Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using Emacs at the moment and experimenting with it for my Rails development and there is one thing that I do quite regularly in Vim and I'd like to know if an equivalent exists in Emacs, or an alternative workflow to achieve the behavior that I need.

The command in Vim is

:map ;t :!rspec --no-color %<cr>

Essentially this maps a key combination to run a bash/shell command on the file represented by the current buffer (% expands to the filename at runtime, the <cr> is just a carriage return at the end to execute the command).

I map all sorts of random little commands as and when I need them and I really miss the immediacy of this approach.

How can I achieve something similar?

share|improve this question
Do you mean something like shell-command-on-region? You can call this with the whole buffer selected as the region. – Tom Nov 22 '11 at 21:00
kind of, however in most cases I don't want to run the command on the actual region of test but on the file represented by the buffer. for example rspec --no-color spec/some_spec.rb. I love the look of shell-command-on-region though – I can definitely see where that would fit in my workflow – eightbitraptor Nov 22 '11 at 21:31
up vote 3 down vote accepted

this function prompts for a command and runs that on to the current buffer file. if no file is associated to current buffer gives an error

(defun shell-command-on-buffer-file ()
 "prompts for a command and executes that command on to the associated 
 file of current buffer. if no buffer is associated gives an error"
  (or (buffer-file-name) (error "no file is associated file to this buffer"))
  (let* ((my-cmd (read-shell-command "Command to run: "))
         (cmd-to-run (concat my-cmd " " (buffer-file-name))))
   (shell-command cmd-to-run)))

as usual emacs saves history of commands you have given so far, those can be accessed using M-p,M-n

share|improve this answer
wow, that's awesome thanks. – eightbitraptor Nov 23 '11 at 13:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .