cwonrails
10/11/2013 - 6:46 PM

Vim Javascript indentation via esformatter. Idea insired by http://yieldthedog.github.io/blog/2013/03/01/invoke-js-beautify-in-vim/

Vim Javascript indentation via esformatter. Idea insired by http://yieldthedog.github.io/blog/2013/03/01/invoke-js-beautify-in-vim/

nnoremap <silent> <leader>e :call JSFormat()<cr>

function! JSFormat()
  " Preparation: save last search, and cursor position.
  let l:win_view = winsaveview()
  let l:last_search = getreg('/')
  let fileWorkingDirectory = expand('%:p:h')
  let currentWorkingDirectory = getcwd()
  execute ':lcd' . fileWorkingDirectory
  execute ':silent' . '%!esformatter'
  if v:shell_error
    undo
    "echo "esformatter error, using builtin vim formatter"
    " use internal formatting command
    execute ":silent normal! gg=G<cr>"
  endif
  " Clean up: restore previous search history, and cursor position
  execute ':lcd' . currentWorkingDirectory
  call winrestview(l:win_view)
  call setreg('/', l:last_search)
endfunction

You can configure esformatter by changing ~/.esformatter See the esformatter default https://github.com/millermedeiros/esformatter/blob/master/lib/preset/default.json for configuration examples.

You will need the esformatter binary available in your path to run the indent command

npm install -g esformatter