2

consider the bit of vimscript like:

func! ClangFormatFile()
    silent exec ":! mv % %.old && clang-format %.old >> %"
endfunc

which means I'd like to format the current file with clang-format but keep the old version.

On top of that I'd like to disable the "File has changed, do you want to reload?" prompt, but just reload the file.

Using set autoread, then execute the mv and clang-format, then set noautoread within the function has unfortunately no effect.

2
  • 1
    Why not just add e! % to line 3? Does that solve it for you?
    – DJMcMayhem
    Commented Aug 22, 2016 at 16:22
  • Well, it does in a way. But then all folds are collapsed and the cursor is set to line 1, which in fact is more annoying than the load confirmation. Commented Aug 23, 2016 at 23:11

1 Answer 1

0

clang-format reads from stdin, so you can use %! to filter the entire buffer to it:

func! ClangFormatFile()
    silent exec ":%!clang-format"
endfunc

Of course, you can still make a backup file if you want:

func! ClangFormatFile()
    silent exec ":!mv % %.old"
    silent exec ":%!clang-format"
endfunc

The advantage of this is that it works for any buffer, including those without a filename or with unsaved content. For example, what if someone makes modifications to a buffer, doesn't save, and then runs your version of ClangFormatFile()? Those changes would then be lost.

In general, you should always avoid modifying files directly if possible. If a tool doesn't support this, then it's probably best to make a simple wrapper script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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