3

我使用 vim 以非交互方式将单个 C 语言函数写入文件。首先tags使用 ctags 创建一个文件。要将main()函数写入文件func.c,然后我使用

vim -R -U NONE -u NONE -c ":ta main" -c ":.,/^}/w!func.c" -c :q

换句话说,它以非交互方式运行 3 个 vim 命令:

  1. :ta main跳转到 main()
  2. :.,/^}/w!func.c从当前行写入到行首的下一个结束花括号
  3. :q退出

我试图通过不浪费时间读取用户或系统启动文件 ( -U NONE -u NONE) 并避免创建 .swp 文件 ( -R) 来提高效率。

还有两个我无法摆脱的障碍:

  1. 如果这是作为管道的一部分运行的,我会收到Vim: Warning: Output is not to a terminal警告和(显然)一秒钟的延迟。
  2. 如果我保存此命令的标准输出,我仍然会看到许多终端转义序列正在使用,以及"func.c" 58 lines, 1707 characters written正在生成的消息。

有没有办法避免这些?

4

1 回答 1

8

这听起来像静默批处理模式( :help -s-ex) 可能适用于您的用例。否则,您无法绕过完全自动化(您描述的一些缺点)。

静默批处理模式

对于非常简单的文本处理(即像增强的 'sed' 或 'awk' 一样使用 Vim,也许只是受益于:substitute命令中增强的正则表达式),请使用Ex-mode

REM Windows
call vim -N -u NONE -n -i NONE -es -S "commands.ex" "filespec"

注意:静默批处理模式 ( :help -s-ex) 会弄乱 Windows 控制台,因此您可能需要cls在 Vim 运行后进行清理。

# Unix
vim -T dumb --noplugin -n -i NONE -es -S "commands.ex" "filespec"

"commands.ex"注意:如果文件不存在,Vim 会挂起等待输入;最好事先检查它的存在!或者,Vim 可以从标准输入读取命令。如果使用-参数,您还可以使用从标准输入读取的文本填充新缓冲区,并从标准错误读取命令。

全自动

对于涉及多个窗口的更高级处理,以及 Vim 的真正自动化(您可能与用户交互或让 Vim 运行以让用户接管),请使用:

vim -N -u NONE -n -c "set nomore" -S "commands.vim" "filespec"

以下是使用的参数的摘要:

-T dumb           Avoids errors in case the terminal detection goes wrong.
-N -u NONE        Do not load vimrc and plugins, alternatively:
--noplugin        Do not load plugins.
-n                No swapfile.
-i NONE           Ignore the |viminfo| file (to avoid disturbing the
                user's settings).
-es               Ex mode + silent batch mode -s-ex
                Attention: Must be given in that order!
-S ...            Source script.
-c 'set nomore'   Suppress the more-prompt when the screen is filled
                with messages or output to avoid blocking.
于 2015-01-09T13:10:48.947 回答