Vim Tips Wiki
Advertisement

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created March 28, 2010 · complexity basic · author Broofa · version 7.0

After using Ryan Fabella's JavaScript Indent script for a few weeks, I noticed several issues with how it wasn't properly balancing indents with outdents. I believe you'll find the following script does a better job of maintaining consistent indentation for a variety of javascript code styles.

To install, save the following script into the appropriate runtime/indent/javascript.vim file:

" Vim indent file
" Language:	JavaScript
" Author:	Robert Kieffer
" URL:		-
" Last Change:  2010-03-27 (Happy Birthday, Dash!)
"
" 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>,=*/

" Already run this?
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 =~ '[{[(]$'
    return ind + &sw
  elseif line =~ '^[}\])]'
    return ind - &sw
  endif
  " '/*' comments
  if pline =~ '^/\*.*\*/'
    return ind
  elseif pline =~ '^/\*'
    return ind + 1
  elseif pline =~ '^\*/'
    return ind - 1
  endif
  return ind
endfunction

Comments

We will discuss this at 201003, but that may take a while so I want to indicate now that tips like this are difficult for the wiki, although we do have another example (JavaFX indent plugin) that was put here specifically to get feedback. If a plugin has a problem, the author should be notified to fix it. A quick look at vim72/indent/javascript.vim indicates there is no official plugin, so if this tip has a working solution, it should be sent to Bram (after testing). Perhaps post on the vim_use mailing list to alert people to help with testing? JohnBot 06:14, March 30, 2010 (UTC)

Advertisement