How do I append text to a file with vim script?
According to :help writefile()
:
When {flags} contains "a" then append mode is used, lines are
appended to the file: >
:call writefile(["foo"], "event.log", "a")
:call writefile(["bar"], "event.log", "a")
If you have a range of lines in your current buffer that you want to append to the log file, then
:[range]w >> my.log
does exactly what you want. (Well, maybe not exactly. For example, it has the side effect of making my.log
the alternate file, and if you plan to use :e#
or something, it may mess you up.)
If you already have the log message in a variable, then you could open up a scratch buffer, use append()
or :put
to add the line(s) to your scratch buffer, then :w >> my.log
and close the scratch buffer.
:help special-buffers
:help :put
:help :w
Here is a complete log function. There is room for improvement: the combination of :new
and :q
may not restore the layout if you have split windows, and :put
on an empty buffer leaves you with a blank line that you probably do not want.
function! Mylog(message, file)
new
setlocal buftype=nofile bufhidden=hide noswapfile nobuflisted
put=a:message
execute 'w >>' a:file
q
endfun