Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim calling command on save

Tags:

vim

I am trying to call this autoformatting plugin on save

Here is my autocommand:

autocmd BufWrite *.css,*.html,*.js,*.py :Autoformat<CR>

When I save nothing happens, if I manually call :Autoformat then the autoformatter runs.

What am I doing wrong?

like image 694
Lee Avatar asked Jun 08 '26 23:06

Lee


2 Answers

You've already found the solution - here's the explanation:

The <CR> is for mappings, which work like a recorded sequence of typed keys, so you need to start command-line mode with : and conclude with <CR>. An autocmd takes an Ex command, so the <CR> is taken as an (invalid) argument. You also don't need the :, but that doesn't do harm.

As :help BufWrite shows, this is a synonym for BufWritePre.

  BufWrite or BufWritePre     Before writing the whole buffer to a file.

So, this is the recommended form:

autocmd BufWritePre *.css,*.html,*.js,*.py Autoformat
like image 131
Ingo Karkat Avatar answered Jun 10 '26 18:06

Ingo Karkat


From what I've experienced, you sometimes need to surround it in an augroup

augroup autoFormat
    autocmd BufWrite *.css,*.html,*.js,*.py :Autoformat<CR>
augroup END

I don't know why but it works for me! Technically just the autocmd should work on its own but sometimes it doesn't. Also, on the GitHub page it says to use :Autoformat<CR><CR>, maybe try that.

like image 41
texasflood Avatar answered Jun 10 '26 20:06

texasflood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!