assertcarl
assertcarl

Reputation: 87

Vim BufWritePost not taking effect until vimrc is sourced manually on startup

Using a minimal vimrc to remove trailing whitespace.

set list                            " show invisible characters
set listchars=trail:·               " display extra whitespace

autocmd BufWritePost <buffer> :%s/\s\+$//e

When I open a project and start working on a file with trailing white space when I save the file I expect it to be removed, but it doesn't get removed.

When I source .vimrc manually and save the file it suddenly works.

What is causing this and how do I solve it?

Upvotes: 0

Views: 444

Answers (2)

user202729
user202729

Reputation: 3965

From Vim documentation:

7. Buffer-local autocommands    *autocmd-buflocal* *autocmd-buffer-local*
                    *<buffer=N>* *<buffer=abuf>* *E680*

Buffer-local autocommands are attached to a specific buffer.  They are useful
if the buffer does not have a name and when the name does not match a specific
pattern.  But it also means they must be explicitly added to each buffer.

Instead of a pattern buffer-local autocommands use one of these forms:
    <buffer>    current buffer
    <buffer=99> buffer number 99
    <buffer=abuf>   using <abuf> (only when executing autocommands)
            |<abuf>|

Of course .vimrc is only ever sourced once when vim starts, at that time the current buffer is not your file.

Solution: replace <buffer> with *.

Upvotes: 0

phd
phd

Reputation: 94716

BufWritePost is executed after writing. You don't need to source .vimrc — you can just write the second time.

But to really fix the problem use BufWritePre.

Upvotes: 1

Related Questions