14

I want a function to append text to a file (not a buffer) in vim. As far as I can see, there is no appendfile(). But the desired functionality can be emulated with readfile() and writefile():

fu! TQ84_log (S)

   let l:f = readfile('my.log')
   call add(l:f, a:S)
   call writefile(l:f, 'my.log')

endfu

Since my.log can grow quite large, I'd rather not read and write the entire file when I want to add a line. So, I came up with another "solution":

fu! TQ84_log (S)
   silent execute "!echo " . a:S . ">> my.log"    
endfu

This works (on windows, that is) as expected. Yet, when I invoke TQ84_log(), that cmd.exe window pops up for a short time. This is a bit distracting.

Is there a better solution for my problem?

2
  • If you do not find an alternative, you can avoid the cmd.exe window with shell.vim plugin. Commented Apr 15, 2014 at 17:17
  • 3
    You should use function instead of fu and use more readable variable names. If you don't do that for others at least do that for yourself. Commented Apr 15, 2014 at 18:36

2 Answers 2

18

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect, Now I can write to my FIFO easy peasy. I use a fifo to pass text to another computer via ssh.
9

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")

2 Comments

That was added in 7.4.503, released 2014-11-05 according to github.com/vim/vim/releases/tag/v7.4.503, a few months after my answer. Still, good to know and worth an up-vote.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.