通过Emacs中的shell命令筛选文本
在vi[m]中,通过一个shell命令(如sort或indent)将过滤后的文本返回缓冲区。emacs中是否有类似的版本?后期编辑:尽管我非常感谢投票结果,但Jurta的答案是正确的。格雷格的黑客比我的更整洁 我会把剩下的留在这里,因为它可能值点钱,但是通过Emacs中的shell命令筛选文本,emacs,text-editor,elisp,Emacs,Text Editor,Elisp,在vi[m]中,通过一个shell命令(如sort或indent)将过滤后的文本返回缓冲区。emacs中是否有类似的版本?后期编辑:尽管我非常感谢投票结果,但Jurta的答案是正确的。格雷格的黑客比我的更整洁 我会把剩下的留在这里,因为它可能值点钱,但是 区域上的M-x shell命令,默认情况下,该命令似乎绑定到M-| 我看到这并没有完全符合Rohit的要求。在区域上使用C-h f shell命令可以显示所需的行为在命令的非交互版本中可用(通过将参数replace设置为非nil)。我们应该
区域上的M-x shell命令
,默认情况下,该命令似乎绑定到M-|
我看到这并没有完全符合Rohit的要求。在区域上使用
C-h f shell命令可以显示所需的行为在命令的非交互版本中可用(通过将参数replace
设置为非nil)。我们应该能够编写一个包装器来实现这一点
尝试此操作(将其加载到*scratch*
并运行M-x eval buffer
,如果可以,请将其复制到.emacs文件中):
请注意,正如我在评论中所说,这不是一件非常令人沮丧的事情。但我认为它是有效的
对于不知道如何选择区域的读者:
将“点”(当前光标位置)移动到区域的一端,并使用C-space
激活“标记”
将点移动到区域的另一端
完成后,调用命令
您可以选择一个区域并键入“C-u M-| command RET”,由于区域上的shell命令的交互前缀参数,它将该区域替换为同一缓冲区中的命令输出 几年前我写了这篇文章,它可能会帮助你:
(defun generalized-shell-command (command arg)
"Unifies `shell-command' and `shell-command-on-region'. If no region is
selected, run a shell command just like M-x shell-command (M-!). If
no region is selected and an argument is a passed, run a shell command
and place its output after the mark as in C-u M-x `shell-command' (C-u
M-!). If a region is selected pass the text of that region to the
shell and replace the text in that region with the output of the shell
command as in C-u M-x `shell-command-on-region' (C-u M-|). If a region
is selected AND an argument is passed (via C-u) send output to another
buffer instead of replacing the text in region."
(interactive (list (read-from-minibuffer "Shell command: " nil nil nil 'shell-command-history)
current-prefix-arg))
(let ((p (if mark-active (region-beginning) 0))
(m (if mark-active (region-end) 0)))
(if (= p m)
;; No active region
(if (eq arg nil)
(shell-command command)
(shell-command command t))
;; Active region
(if (eq arg nil)
(shell-command-on-region p m command t t)
(shell-command-on-region p m command)))))
我发现这个函数非常有用。如果您觉得它也很有用,我建议将其绑定到某个功能键以方便使用,我个人使用的是F3
:
(global-set-key [f3] 'generalized-shell-command)
谢谢,我知道这一点,但它给了我一个单独的缓冲区过滤文本;它不能取代原来的。我知道你想要的vi行为。仍然在寻找。有趣的是,这不仅仅是一个常见问题。我一直在vi(或vim)中使用这个功能;没有它的编辑会变成。。。不太有趣。我在vi中也使用了这种行为,但这不是emacs的方式,它可能是定义一种知道您想要什么并让它自动发生的模式。我将使用jurta建议的方式:)jurta获胜。向上投票。我发誓,每当我开始了解这个程序时,总会有人来告诉我我是一个一流的初学者。通常当你需要Emacs中的一个功能时,它很可能早就已经实现了。因此,最好的做法是先阅读文档,而不是开始重新发明轮子;)谢谢你,尤塔。不幸的是,我找不到有关此功能的任何文档。Rohit,您可以通过打开Emacs手册(C-h I d m Emacs RET')并在区域RET上的index-
I shell命令中查找命令名,在Emacs中找到它的文档。这对于使用“perl pie”很有用当Emacs Regexp不能很好地进行正则表达式搜索和替换时C-u M-| perl-pi-e's/pattern/replace/g'RET
。邪恶也支持Vim命令来执行此操作(:%!perl-pi-e…RET
)。非常好。这就像joe的“C-k/”pipe through shell命令一样。只是有点偏离正切,我认为Vim没有Emacs的M-|等价物,Vim只能用shell输出替换区域;除非您为它编写自定义命令,否则我有点失望。
(global-set-key [f3] 'generalized-shell-command)