Lee
Lee

Reputation: 8744

Vim calling command on save

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?

Upvotes: 3

Views: 224

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172738

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

Upvotes: 4

Lee
Lee

Reputation: 8744

For some reason i had to get rid of the carriage return and change to BufWritePre (although the CR is the main issue, the BufWritePre just makes sure it gets changed before the buffer is written instead of after so it gets saved):

autocmd BufWritePre *.css,*.html,*.js,*.py :Autoformat

Why, I don't know?

Upvotes: 1

texasflood
texasflood

Reputation: 1633

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.

Upvotes: 1

Related Questions