【发布时间】:2011-07-09 19:36:47
【问题描述】:
我正在寻找以下 vi 命令的等效项
:! %
这在当前打开的文件上运行 nl 命令
什么是emacs检测打开文件名的方法?
M-X shell-commnad nl
我无法找到当前打开/缓冲区和替换的确定值。 谢谢/马赫什
【问题讨论】:
我正在寻找以下 vi 命令的等效项
:! %
这在当前打开的文件上运行 nl 命令
什么是emacs检测打开文件名的方法?
M-X shell-commnad nl
我无法找到当前打开/缓冲区和替换的确定值。 谢谢/马赫什
【问题讨论】:
我用这个:
(defun my-shell-command-on-current-file (command &optional output-buffer error-buffer)
"Run a shell command on the current file (or marked dired files).
In the shell command, the file(s) will be substituted wherever a '%' is."
(interactive (list (read-from-minibuffer "Shell command: "
nil nil nil 'shell-command-history)
current-prefix-arg
shell-command-default-error-buffer))
(cond ((buffer-file-name)
(setq command (replace-regexp-in-string "%" (buffer-file-name) command nil t)))
((and (equal major-mode 'dired-mode) (save-excursion (dired-move-to-filename)))
(setq command (replace-regexp-in-string "%" (mapconcat 'identity (dired-get-marked-files) " ") command nil t))))
(shell-command command output-buffer error-buffer))
(global-set-key (kbd "M-!") 'my-shell-command-on-current-file)
然后你可以做 M-! nl %
【讨论】:
如果您总是希望为 shell 命令插入缓冲区的文件名,您可以使用以下建议:
(defadvice read-shell-command (before read-shell-command-with-filename activate)
"force the initial contents to contain the buffer's filename"
(if (and (null (ad-get-arg 1))
buffer-file-name)
(ad-set-arg 1 buffer-file-name)))
添加上述代码后,M-x shell-command 将始终以缓冲区的文件名开头,因此您可以在命令中使用它。
【讨论】:
编辑:将您的问题误读为想要将该更改应用于您正在处理的文件。如果只想对缓冲区运行 shell 命令,可以使用shell-command-on-region,它通常绑定到M-|。
如果您只是想获取特定的行号,M-x goto-line 可以。我通过将(define-key global-map "\C-x\C-l" 'goto-line) 放入我的~/.emacs 将其绑定到C-x C-l。
试试这个(在您的~/.emacs 文件中):
;;; Run a shell command on all text between the mark and the point and
;;; replace with the output.
(defun shell-command-in-region (start end command &optional flag interactive)
"Execute shell-command-on-region and replace the region with the output
of the shell command."
(interactive (list (region-beginning) (region-end)
(read-from-minibuffer "Shell command in region: "
nil nil nil 'shell-command-history)
current-prefix-arg
(prefix-numeric-value current-prefix-arg)))
(shell-command-on-region (point) (mark) command t)
)
(define-key esc-map "#" 'shell-command-in-region)
通过选择您要操作的区域然后执行M-#来调用它。
【讨论】:
save-buffer,否则无法保证磁盘上的文件与缓冲区中的文件匹配。 (与vi 相同。)