I can\'t seem to get inline Javascript indenting properly in Vim. Consider the following:
$(document).ready(function() {
// Closing brace correctly inde
maybe some combination of these settings should be in your VIMRC file.
syntax on
set syn=auto
set showmatch
filetype on
filetype plugin on
filetype indent on
set tabstop=4
set softtabstop=4
set shiftwidth=4
set expandtab
Assuming the syntax file has good indenting for java script, visually highlight the block and press =. This works for java so I would expect it to do something half decent for java script. The results probably also depend on the settings of tabstop, expandtab and maybe shiftwidth.
gq is useful too, it formats lines rather than indents them.
Use JavaScript Indent: Javascript indenter (HTML indent is included) by Preston Koprivica. Thanks for the heads-up from oligofren - give him an up-vote.
You don't have to install plugins specialised for Javascript, you can learn the built-in Vim options for indentation. Vim has quite a few options, and some of the indenting styles like cindent
, smartindent
and indentexpr
have options of their own.
To check whether you are using cindent
or smartindent
or indentexpr
, run:
:set cindent?
:set smartindent?
:set indentexpr?
Despite the name, cindent
doesn't just apply to C programs, it can apply to a bunch of programming languages that share roughly the same syntax, including Javascript. Have a look at :help C-indenting for documentation about this. You can adjust the settings particularly with a line like this one, see :help 'cinoptions' and :help cinoptions-values. Here's an example configuration:
:au FileType js,javascript setlocal shiftwidth=2 softtabstop=2 cinoptions=j1,J1,(1s " see help cino-j cino-J cino-(
The scripts mentioned above do not format the closure-syntax often used in jQuery correctly:
$(function() {
// only one level of indentation, not two
});
This script works better for me: http://www.vim.org/scripts/script.php?script_id=2765
In case someone comes here please note the vim-javascript
by pangloss
at https://github.com/pangloss/vim-javascript helped me so far, i.e. Vim 7.4. And the above solutions from oligofren and Charles Roper didn't.