Skip to content

Instantly share code, notes, and snippets.

@nisaacson
Last active December 9, 2019 01:17
Show Gist options
  • Save nisaacson/6939960 to your computer and use it in GitHub Desktop.
Save nisaacson/6939960 to your computer and use it in GitHub Desktop.
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
@millermedeiros
Copy link

right now I'm doing just the basic:

" --- format visually selected JavaScript using esformatter --
vnoremap <silent> <leader>es :! esformatter<CR>

and to format whole code:

:%!esformatter

would also be good if you could execute esformatter without the need of the .sh file.

I'm having issue with the trailing line as well. I will try to find a fix for it so you don't need to use awk. (see: millermedeiros/esformatter#91)

@millermedeiros
Copy link

one benefit of wrapping into a vimscript function is that you can filter the error (like you already did). we have plans to support local/global settings for the CLI, so you wouldn't need the extra logic as well.

@millermedeiros
Copy link

I fixed the trailing line break on v0.0.9 (just pushed to npm) so you don't need awk anymore. cheers.

@millermedeiros
Copy link

I just added option to set/override options through the CLI and also added support for local/global config files.

@nisaacson
Copy link
Author

Thanks for the fixes!

@nisaacson
Copy link
Author

I updated the gist to call esformatter directly without the shell script

@millermedeiros
Copy link

I improved this plugin and created a repository for it that way it's going to be easier to install and update: https://github.com/millermedeiros/vim-esformatter - cheers!

@razzius
Copy link

razzius commented Aug 1, 2015

Using this and http://stackoverflow.com/questions/10969366/vim-automatically-formatting-golang-source-code-when-saving I made formatting automatic on write:

augroup filetype_javascript
  autocmd!
  autocmd FileType javascript autocmd BufWritePre <buffer> :call JSFormat()
augroup END

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment