Elisp:在当前文件上调用命令

11

我希望在emacs中设置一个键,以便在缓冲区中执行shell命令,并在不提示的情况下还原缓冲区。 shell命令是:p4 edit 'currentfilename.ext'

(global-set-key [\C-E] (funcall 'revert-buffer 1 1 1)) 
;; my attempt above to call revert-buffer with a non-nil 
;; argument (ignoring the shell command for now) -- get an init error:
;; Error in init file: error: "Buffer does not seem to be associated with any file"

我完全不了解elisp。从emacs手册中,这是revert-buffer的定义:

Command: revert-buffer &optional ignore-auto noconfirm preserve-modes

谢谢!


你想还原缓冲区是因为它已经被编辑过了,还是因为shell命令覆盖了缓冲区的内容? - zwol
因为它将缓冲区从只读更改为可写,并将其添加到版本控制中。 - atp
2个回答

9

您实际看到的错误是由于您错误地指定了global-set-key,即函数调用。您想要的是:

(global-set-key (kbd "C-S-e") '(lambda () (revert-buffer t t t)))

你的.emacs文件在加载时调用了funcall,导致了错误。
然后,你可以创建一个类似这样的命令来获取所有内容:
(defun call-something-on-current-buffers-file ()
  "run a command on the current file and revert the buffer"
  (interactive)
  (shell-command 
   (format "/home/tjackson/bin/dummy.sh %s" 
       (shell-quote-argument (buffer-file-name))))
  (revert-buffer t t t))
(global-set-key (kbd "C-S-e") 'call-something-on-current-buffers-file)

显然,如果你希望的话,可以自定义命令,并添加错误检查。

1
你需要以某种方式引用shell的文件名... comint-quote-filename 看起来可以完成这个任务,但不幸的是,它只有在你已经在shell缓冲区中时才能使用。这就是我所做到的。 - zwol
@Zack 添加了 comint-quote-filename 调用。 - Trey Jackson
谢谢您的回复。我收到了一个错误信息:Symbol's function definition is void: comint-quote-filename。我将其替换为 shell-quote-argument,然后它就正常工作了。顺便提一下,Emacs 手册中指出:“应避免使用的按键组合是 [Ctrl] + [Shift] + [字母]。在文本终端中,无法区分这种组合的大小写版本。如果您总是在图形用户界面中使用 Emacs,则不会有问题。”因此,我将它更改为 <f5>,并且 Emacs 能够识别该键。 - atp
@Jasie 我知道一定有内置的引用方式,我已经更新了答案,使用了 shell-quote-argument。(为了修复空函数定义错误,你可以添加 (require 'comint)),但是 shell-quote-argument 更好。 - Trey Jackson
@TreyJackson 这很不错,如果我需要输出弹出在一个窗口中,并且可以通过按“q”键关闭该窗口,我需要做什么? - zinking

0

也许使用次要模式“auto-revert-mode”是一个选项。 只需在当前缓冲区启用它:

M-x "auto-revert-mode"

在执行外部命令之前,始终确保缓冲区已保存。


这很好,但默认的自动重载模式时间是5秒(太慢了)。如果我将其更改为1秒,它将每秒检查每个缓冲区,这是不必要的。 - atp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接