Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append text to a file with vim script?

Tags:

vim

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?

like image 394
René Nyffenegger Avatar asked Apr 15 '14 16:04

René Nyffenegger


People also ask

Which command is used to append some text at the end of some file?

Append Text Using >> Operator For example, you can use the echo command to append the text to the end of the file as shown. Alternatively, you can use the printf command (do not forget to use \n character to add the next line).


1 Answers

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
like image 173
benjifisher Avatar answered Oct 12 '22 01:10

benjifisher