I'd like to automatically format html and js code when I exit insert mode. Currently I have ctrlf mapped to format the current file in my .vimrc:

map <c-f> :call JSBeautify()<cr>

Is there a way I can trigger this command each time I exit insert mode?

  • 2
    Really ? Each time you leave insert mode?
    – romainl
    Commented Oct 6, 2015 at 16:14
  • @romainl I guess it's a quick way to tidy things up. For example, if I paste code into vim from my system clipboard the formatting may not be quite right
    – alidrongo
    Commented Oct 6, 2015 at 16:45
  • 2
    @alidrongo Note that to paste code from your system to vim you are not necessarily in insert mode (e.g. "+p in normal mode). A solution could be to trigger the command only when you write the buffer to the file.
    – statox
    Commented Oct 6, 2015 at 19:29

1 Answer 1


You can use the InsertLeave autocommand event to do what you want. You can add something like that in your .vimrc to create commands for html and js files:

autocmd! InsertLeave *.html,*.js call JSBeautify
  • InsertLeave will trigger the event each time you exit insert mode.
  • *.html,*.js to do that only on html and js files.
  • call JSBeautify is the call you want to do.

Also you could be interested in the BufWritePre event which will trigger the command just before writing the buffer to the file. Using the command each time you leave insert mode may be not that comfortable I think.

Relevant help topic:

Edit In the comments OP asks how to use different function for different filetypes. The easiest solution I see is using an augroup:

    autocmd! InsertLeave *.js   call JSBeautify
    autocmd! InsertLeave *.html call HTMLBeautify
    autocmd! InsertLeave *.css  call CSSBeautify
augroup END
  • augroup allows to group autocommands.
  • autocmd! purges the group when you need to re-source your .vimrc
  • the 3 autocommands are pretty similar to the first one excepted they are triggered for only one filetype.

More related topics:

  • Great stuff. One further question (I'm pretty early on my vim journey): I have some logic that selects the kind of beautification based on the file type: map <c-f> :call JsBeautify()<cr> " or autocmd FileType javascript noremap <buffer> <c-f> :call JsBeautify()<cr> " for html autocmd FileType html noremap <buffer> <c-f> :call HtmlBeautify()<cr> " for css or scss autocmd FileType css noremap <buffer> <c-f> :call CSSBeautify()<cr> Is there a way I can do this also automatically? Many thanks!
    – alidrongo
    Commented Oct 7, 2015 at 9:45
  • @alidrongo: I edited my answer I think the best way to do what you want is to use an augroup containing one autocommand by function to call.
    – statox
    Commented Oct 7, 2015 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.