Vim Tips Wiki
Advertisement

This tip is deprecated for the following reasons:

This script is not maintained and does not have much informative value. The plugins mentioned below do a better job anyway. The original script author, Broofa, recommends script 3227 below.

Similar plugins

Original content

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>,=*/

" 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

  " '/*' comments
  if pline =~ '^/\*.*\*/'
    " no indent for single-line form
  elseif pline =~ '^/\*'
    let ind += 1
  elseif pline =~ '^\*/'
    let 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