jueves, 11 de abril de 2013

Running a shell command on current file

Before being an emacs evangelist, I was a vim evangelist for a few years (next month sublime text), and one feature that I missed in emacs was having a way to reference the current file when executing a command.

In vim, it's pretty common to run commands like

:!gcc %

It's pretty simple and the syntax is really easy to remember, ":" for command mode, "!" to run something, and in the command "%" will be replaced by your filename.

I haven't found anything similar to "%" for emacs, so let's write some elisp to fix it.


(defun shell-execute ()
  (interactive)
  (let ((file-buffer (or (buffer-file-name) ""))
        (command (read-shell-command "Shell command: " nil nil nil)))
    (shell-command (replace-regexp-in-string "%" file-buffer command))))

(global-set-key (kbd "M-!") 'shell-execute)

2 comentarios:

David dijo...

I use '!' on dired (it is provided by dired-aux). You can execute a command the marked files.

Anónimo dijo...

See also http://stackoverflow.com/questions/10121944/passing-emacs-variables-to-minibuffer-shell-commands