Created
August 12, 2010 20:02
-
-
Save aanand/521620 to your computer and use it in GitHub Desktop.
Well-behaved Javascript indentation for vim, with my own addition for multiline var blocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" Vim indent file | |
" Language: JavaScript | |
" Author: Robert Kieffer | |
" URL: - | |
" Last Change: 2010-08-12 | |
" | |
" Improved JavaScript indent script. | |
" Indent script in place for this already? | |
if exists("b:did_indent") | |
finish | |
endif | |
let b:did_indent = 1 | |
setlocal indentexpr=GetJsIndent() | |
setlocal indentkeys=0{,0},0),:,!^F,o,O,e,*<Return>,=*/ | |
" Only define functions once per session | |
if exists("*GetJsIndent") | |
finish | |
endif | |
" Clean up a line of code by removing trailing '//' comments, and trimming | |
" whitespace | |
function! Trim(line) | |
return substitute(substitute(a:line, '// .*', '', ''), '^\s*\|\s*$', '', 'g') | |
endfunction | |
function! GetJsIndent() | |
let num = v:lnum | |
let line = Trim(getline(num)) | |
let pnum = prevnonblank(num - 1) | |
if pnum == 0 | |
return 0 | |
endif | |
let pline = Trim(getline(pnum)) | |
let ind = indent(pnum) | |
" bracket/brace/paren blocks | |
if pline =~ '[{[(]$' | |
let ind += &sw | |
endif | |
if line =~ '^[}\])]' | |
let ind -= &sw | |
endif | |
" multi-line variable declarations | |
if pline =~ '^var\s.*,$' | |
let ind += 4 | |
elseif pnum > 0 && pline =~ '=' && pline !~ ',$' | |
" try to figure out if a declaration block has just ended | |
let varblock = 0 | |
let vpnum = prevnonblank(pnum - 1) | |
let vpline = Trim(getline(vpnum)) | |
while varblock == 0 && vpnum > 0 && vpline =~ ',$' | |
if vpline =~ '^var\s' | |
let varblock = 1 | |
else | |
let vpnum = prevnonblank(vpnum - 1) | |
let vpline = Trim(getline(vpnum)) | |
endif | |
endwhile | |
if varblock == 1 | |
let ind -= 4 | |
end | |
endif | |
" '/*' comments | |
if pline =~ '^/\*.*\*/' | |
" no indent for single-line form | |
elseif pline =~ '^/\*' | |
let ind += 1 | |
elseif pline =~ '^\*/' | |
let ind -= 1 | |
endif | |
return ind | |
endfunction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original: http://vim.wikia.com/wiki/Improved_Javascript_Indent_script_for_Vim