Reputation: 15735
I have a function which performs validity checking on the current file (so as to conform to my employer's coding standards). I would like to call this function before saving, i.e. using BufWritePre. However, I would to prevent saving the file if it fails my checking function.
So, is it possible to break out of the BufWritePre autocommand?
I realise that I could accomplish this by re-mapping the :write
command as illustrated here, but I would like to avoid that if at all possible, as it feels somewhat un-subtle.
Thanks in advance for your suggestions.
Upvotes: 2
Views: 887
Reputation: 393547
You can 'simply' force an error:
:autocmd BufWritePre *.txt throw "you may not"
If you wanted to be able to save .txt files again
:autocmd!
:source $MYVIMRC
Upvotes: 4
Reputation: 24054
From :help BufWriteCmd
*BufWriteCmd*
BufWriteCmd Before writing the whole buffer to a file.
Should do the writing of the file and reset
'modified' if successful, unless '+' is in
'cpo' and writing to another file |cpo-+|.
The buffer contents should not be changed.
|Cmd-event|
So it sounds like you could implement that autocommand, and only do the save and reset 'modified'
if the save is allowed.
I'm guessing that you'd have to use something like writefile(getline('^', '$'))
to actually do the writing.
On the other hand, you might be able to do something like
:write
the file again. I'm not sure if it will let you do this from within the BufWriteCmd handler.:finally
clause to ensure that it executes even if there are problems with the write.Upvotes: 1