英文:
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 <C-r> :r ! gofmt %<CR>
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 <C-r> :%! gofmt<CR>
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论