[英]How do I append text to a file with vim script?
I want a function to append text to a file (not a buffer) in vim.我想要一个函数将文本附加到 vim 中的文件(不是缓冲区)。 As far as I can see, there is no appendfile()
.据我所知,没有appendfile()
。 But the desired functionality can be emulated with readfile()
and writefile()
:但是可以使用readfile()
和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.由于my.log
可能会变得非常大,当我想添加一行时,我宁愿不读取和写入整个文件。 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.这按预期工作(在 Windows 上)。 Yet, when I invoke TQ84_log()
, that cmd.exe
window pops up for a short time.然而,当我调用TQ84_log()
,那个cmd.exe
窗口会弹出一小段时间。 This is a bit distracting.这有点让人分心。
Is there a better solution for my problem?我的问题有更好的解决方案吗?
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.) (好吧,也许不完全是。例如,它具有将my.log
备用文件的my.log
,如果您打算使用:e#
或其他东西,它可能会让您一团糟。)
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.如果您已经在一个变量中有日志消息,那么您可以打开一个临时缓冲区,使用append()
或:put
将行添加到您的临时缓冲区,然后:w >> my.log
并关闭暂存缓冲区。
: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.有改进的余地:如果您有拆分窗口, :new
和:q
的组合可能无法恢复布局,并且:put
在空缓冲区上:put
您留下一个您可能不想要的空行。
function! Mylog(message, file)
new
setlocal buftype=nofile bufhidden=hide noswapfile nobuflisted
put=a:message
execute 'w >>' a:file
q
endfun
According to :help writefile()
:根据: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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.