I have a problem similar that for which nnoremap was conceived, but for the BufWrite aucmd.

I have a code formatter which isn't very well-behaved. Gnatpp demands to read a file directly rather than be fed stdin and output stdout as is the norm for code formatters.

First I tried this:

autocmd BufWrite *.ad[sb] Autoformat

But the problem is that, while 'Autoformat' itself works fine, it reads the file contents before writing. Hence, it makes it impossible to change any Ada source files anymore! How can I prepend an operation to this to 'write but without executing this autocmd' ?

As suggested, I have also tried BufWritePost instead, which allows one to change the file, but not I need to do :w twice - the first time, the buffer is changed after writing the file, and the second write will write the formatting changes.

  • Thanks for the suggestion; autocmd BufWritePost *.ad[sb] Autoformat fails on the other side; it reads the file I modified by hand fine, but it fails to then write again afterwards (without triggering itself) – TamaMcGlinn Mar 21 at 20:24
  • Whether I use BufWrite or BufWritePost doesn't matter here; the point is that the file needs to be written twice when I do :w, without triggering itself. Hence, that is the question. – TamaMcGlinn Mar 21 at 20:25
  • What's really confusing me is the use of "itself" (in the title and your comment). "The file needs to be written twice...without triggering itself". It in that sentence is the file. "Make a bufwrite bound command save...without calling itself". It in this case is the command. What exactly is calling itself. – B Layer Mar 21 at 20:28
  • 1
    Do you mean :w triggers the autocommand and Autowrite is also doing :w which triggers the autocommand again? (IOW, nothing is actually calling itself...it's just a circular series of events.) – B Layer Mar 21 at 20:41

You could write the file again in BufWritePost but without triggering the autocmd using noautocmd. For example, if I open a file called tmp and do:

autocmd BufWritePost * call append(0, "foo")

Each time the file is saved, "foo" is added after the file is written to disk, so opening up a terminal separately and issuing cat tmp will show the pre-appended state. However, doing:

autocmd BufWritePost * call append(0, "foo") | noautocmd write

will write the file and then trigger BufWritePost, during which the file is modified and then written to disk again.

Thus, for your use case, you might try:

autocmd BufWritePost *.ad[sb] Autoformat | noautocmd write

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.