# How to use on save action for file type in vim

vim

I am using vim-jsbeautify and I think it is awesome.

However I would like to add the reformatting on the save action. At the moment I have to press Ctrlf each time I want to reformat. I tried

 autocmd FileType html AutoFormatBuffer :call HtmlBeautify()<cr>


but somehow that command is wrong, could someone please clarify?

### Update

Just as @Ingo Karkat mentioned. For this case create a file in

~/.vim/ftplugin/html/main.vim


and add the line into the file

autocmd BufWritePre <buffer> call HtmlBeautify()


Your command (call HtmlBeautify()) needs to be triggered before saving. :help autocmd-events lists all available ones; BufWritePre is the one you want. The {cmd} for :autocmd is an Ex command, so you can drop the : (that switches from normal mode to command-line mode), and have to drop the <CR> (this is for mappings only):

autocmd BufWritePre <buffer> call HtmlBeautify()


Now, you want that trigger installed for every opened HTML file. The way you tried this is by using another :autocmd on the FileType event:

autocmd FileType html autocmd BufWritePre <buffer> call HtmlBeautify()


But this is what filetype plugins are for:

I would recommend putting any settings, mappings, and filetype-specific autocmds (such as this) into ~/.vim/ftplugin/{filetype}_whatever.vim (or {filetype}/whatever.vim; cp. :help ftplugin-name) instead of defining lots of :autocmd FileType {filetype}; it's cleaner and scales better; requires that you have :filetype plugin on, though.