【发布时间】:2012-01-13 21:38:55
【问题描述】:
当我在 emacs 中使用 dired 模式时,我可以通过输入 !xxx 来运行 shell 命令,但是如何绑定一个键来运行这个命令呢? 例如,我想在一个文件上按 O,然后 dired 将运行 'cygstart' 来打开这个文件。
【问题讨论】:
当我在 emacs 中使用 dired 模式时,我可以通过输入 !xxx 来运行 shell 命令,但是如何绑定一个键来运行这个命令呢? 例如,我想在一个文件上按 O,然后 dired 将运行 'cygstart' 来打开这个文件。
【问题讨论】:
您可以使用shell-command 函数。例如:
(defun ls ()
"Lists the contents of the current directory."
(interactive)
(shell-command "ls"))
(global-set-key (kbd "C-x :") 'ls); Or whatever key you want...
要在单个缓冲区中定义命令,您可以使用local-set-key。实际上,您可以使用dired-file-name-at-point 获取文件名。所以,完全按照你的要求去做:
(defun cygstart-in-dired ()
"Uses the cygstart command to open the file at point."
(interactive)
(shell-command (concat "cygstart " (dired-file-name-at-point))))
(add-hook 'dired-mode-hook '(lambda ()
(local-set-key (kbd "O") 'cygstart-in-dired)))
【讨论】:
M-! 上使用C-h k 得到了shell-command 的名称;我得到了dired-file-name-at-point,首先猜测它是一个dired- 函数,然后使用C-h f 和tab 来自动完成名称。您还可以像这样轻松找出 Emacs 函数名称和效果——毕竟,它是一个 自文档化 编辑器!这只是它很棒的众多方式之一。
;; this will output ls
(global-set-key (kbd "C-x :") (lambda () (interactive) (shell-command "ls")))
;; this is bonus and not directly related to the question
;; will insert the current date into active buffer
(global-set-key (kbd "C-x :") (lambda () (interactive) (insert (shell-command-to-string "date"))))
lambda 定义了一个匿名函数。这样您就不必定义将在另一个步骤中绑定到键的辅助函数。
lambda 是关键字,如果需要的话,下一个括号对包含您的参数。 Rest 类似于任何常规函数定义。
【讨论】: