使用Vim将文件内容替换为外部命令的输出。

huangapple go评论72阅读模式
英文:

Vim replace content from file with output from external command

问题

我正在编写Go代码,我想用一个快捷键运行gofmt命令,并用gofmt的输出替换当前源文件的内容。

我在我的vimrc文件中定义了以下映射:
map <C-r> :r ! gofmt %<CR>,但这只是将输出追加到当前文件中。有没有办法覆盖它?

英文:

I am programming go and I want to run gofmt with a shortcut and replace the content of the current source file with the output of gofmt.

I have the following mapping defined in my vimrc:
map &lt;C-r&gt; :r ! gofmt %&lt;CR&gt; but this does simply append the output to the current file. Is there a way to override it?

答案1

得分: 6

你正在使用错误的命令::read会将行追加到缓冲区中(使用! {cmd}可以从外部命令读取)。相反,你想要通过外部命令对当前缓冲区内容进行过滤。可以使用:help :range!来实现这一点。当没有传递文件时,gofmt命令会从标准输入读取(其他一些命令可以使用特殊的-参数)。因此,你可以这样做:

:nnoremap <C-r> :%! gofmt<CR>

注意事项

  • 你应该使用:noremap;它可以防止映射被重新映射和递归调用。
  • 我将映射限制在了正常模式下;我认为直接从可视模式或操作等待模式启动这个命令是不必要的。
  • 如评论中所提到的,可能已经有一个插件可以直接提供这个功能。
英文:

You're using the wrong command: :read appends lines to the buffer (with ! {cmd}: from an external command). Instead, you want to filter the current buffer contents through an external command. This is done via :help :range!. The gofmt command reads from stdin when no file is passed (some other commands take a special - argument for that. Ergo:

:nnoremap &lt;C-r&gt; :%! gofmt&lt;CR&gt;

Notes

  • You should use :noremap; it makes the mapping immune to remapping and recursion.
  • I've limited the mapping to normal mode; I don't think is necessary to directly launch this from visual mode or operator-pending mode.
  • As mentioned in the comments, there's probably a plugin that already provides this out of the box.

答案2

得分: 5

gofmt标志-w将覆盖它正在修复的文件的内容。

英文:

The gofmt flag -w will overwrite the contents of the file it's fixing

huangapple
  • 本文由 发表于 2017年7月31日 06:50:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/45405468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定