3

How do I cancel the write in the BufWritePre/FileWritePre auto command?

I already looked at this question and the proposed solution, throw, displays error messages, and I don't want that. It should be transparent to the user that nothing got written, since I am displaying my own error message.

Community
  • 1
  • 1
mk12
  • 25,873
  • 32
  • 98
  • 137
  • 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

1 Answers1

3

Just throw your own error message, then. I don't think there's another way around this; after all, the user expects the buffer to be written after issuing a :w, so only an exception can prevent this.

You might work around this by using a BufWriteCmd hook and :setl buftype=acwrite, and write the buffer entirely on your own, but that's a lot of (error-prone) effort, and if you intend to issue an error, anyway, go with the exception.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • Can I prevent it from showing `Error detected while processing function …` and the line number some how, at least? That is annoying and makes it seem like the script wasn't supposed to do this. – mk12 Jul 28 '12 at 18:21
  • 4
    One addition about `acwrite` and error-prone effort: if one is not going to use built-in `:w` he is going to take care about `'fileencoding'`, `'fileformat'`, `'binary'`+`'endofline'` options (and maybe also `'charconvert'` if this is possible at all): just to emulate `:w` behavior. More, he is going to take care about `v:cmdarg` where these options can be overriden: to emulate `:w ++opt`. Also he should be sure he uses a pattern: `au BufWriteCmd ` has a problem of taking care about almost all buffer writes, including `:w another-file-name` (but not including `:w !shell-command`). – ZyX Jul 28 '12 at 18:36
  • 1
    You're calling a function from the autocmd; instead, have the function return a success flag, and throw directly in the autocmd: `autocmd BufWritePre if !MyFunc() | throw "error" | endif`; that's only slightly better; I'm afraid, though. – Ingo Karkat Jul 28 '12 at 18:51