2

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.

Community
  • 1
  • 1
Prince Goulash
  • 15,295
  • 2
  • 46
  • 47
  • See also the question "[Prevent saving files with certain names in Vim](http://stackoverflow.com/q/6210946/254635)". – ib. Jul 29 '12 at 04:11

2 Answers2

4

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • This is much simpler than what I concocted. I'm guessing that using `:w!` will force through this error? – intuited Apr 04 '11 at 20:12
  • No, `w!` does not write anyway – sehe Apr 04 '11 at 20:33
  • Thanks! That looks very promising. However, the "error detected" message looks quite ugly... can the error be handled so that it echos a meaningful message, but still leaves the function without saving? I'm not experienced enough in the ways of try/catch/endtry to know if this is possible. – Prince Goulash Apr 04 '11 at 20:52
  • Me neither, Prince! (+1 for the greate screenname, BTW) – sehe Apr 04 '11 at 20:58
1

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

  • disable your BufWriteCmd autocommand
  • :write the file again. I'm not sure if it will let you do this from within the BufWriteCmd handler.
  • re-enable your BufWriteCmd autocommand. You should probably put this in a :finally clause to ensure that it executes even if there are problems with the write.
intuited
  • 23,174
  • 7
  • 66
  • 88