7

I'd like to write the modified buffer I'm currently editing to a temporary file periodically. In the background I could then, for example, use external tools to analyze the file.

I don't want to write the file to it real location in this process - I want the user to be in charge of that through the normal :w command.

How can I do this in a vimscript called by the CursorHold autocommand? Vim 7.4 and up is fine.

1
  • You can run external tools directly on the content (or parts) of your buffer with :[range]w !command.
    – romainl
    Mar 20, 2015 at 16:04

1 Answer 1

8

This is rather simple:

:autocmd CursorHold *
\   let save_modified = &modified |
\       silent! execute 'write' fnameescape(tempname()) |
\   let &modified = save_modified

However, this has the side effect of naming a :new buffer on the first triggering. (It doesn't affect existing files; this is the difference between :write and :saveas.) You can either add another check (empty(bufname(''))) and undo that via :0file, or move to lower-level functions altogether:

:autocmd CursorHold * call writefile(getline(1, '$'), tempname())

The caveat of this approach is that the file contents will always be persisted

  • with Vim's 'encoding' setting, i.e. you lose any custom 'fileencoding' of the original buffer, and
  • with Unix (LF) line endings (which you could restore with a map() over the list returned by getline()).

Your Answer

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

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