Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix incorrect inline Javascript indentation in Vim?

Tags:

javascript

vim

I can't seem to get inline Javascript indenting properly in Vim. Consider the following:

  $(document).ready(function() {    // Closing brace correctly indented     $("input").focus(function() {       $(this).closest("li").addClass("cur-focus");     }); // <-- I had to manually unindent this    // Closing brace incorrectly indented     $("input").blur(function() {       $(this).closest("li").removeClass("cur-focus");       }); // <-- This is what it does by default. Argh!    }); 

Vim seems to insist on automatically indenting the closing brace shown in the second case there. It does the same if I re-indent the whole file. How do I get it to automatically indent using the more standard JS indenting style seen in the first case?

like image 370
Charles Roper Avatar asked Mar 06 '09 20:03

Charles Roper


People also ask

How do you indent a line in JavaScript?

Lines should never be longer than 100 characters in JavaScript, and many developers aim at 80 characters as the line character limit. When any line is longer than 100 characters, break it into two lines by pressing Enter after an operator and reindenting the line.

Does JavaScript indentation matter?

Indentation and extra spaces are not significant in small scripts. For code in development, readability should be preferred. Larger production scripts should be minified.

How do I indent Vim?

To indent the current line, or a visual block: ctrl-t, ctrl-d - indent current line forward, backwards (insert mode) visual > or < - indent block by sw (repeat with . )


2 Answers

The most comprehensive and bug-free Javascript indentation script is the one by Preston Koprivica. The so called OOP script that is in the proposed answer has severe bugs, and does not indent code properly that has square brackets.

like image 182
oligofren Avatar answered Sep 19 '22 12:09

oligofren


Use JavaScript Indent: Javascript indenter (HTML indent is included) by Preston Koprivica. Thanks for the heads-up from oligofren - give him an up-vote.

like image 38
Charles Roper Avatar answered Sep 21 '22 12:09

Charles Roper