Search code examples
shellemacselispkey-bindings

calling shell from emacs


I have an executable file that can be used from the terminal command line.

$ foo "bar" which returns a single line of text

I would like to be able to call this function while editing files.

I can see that I can do the following

M-! ~/Library/yolo/bin/foo "bar" and I get exactly what I am looking for.

So I am trying to write a function that I can then bind to keys. But I am stumped.

(setq foobar-path "~/Library/yolo/bin/foo ")
(defun foo-bar (func)
  (shell-command (concat foobar-path func)))

(global-set-key (kbd "M-p") foo-bar)

but I know (emacs is telling me) that I am way way off.

What I would ideally end up with is a keybinding that can send a line of code (like evaluate last expression) to the external function and display the return at the bottom of the screen in the message bar.

Any hints?


Solution

  • Your code has two issues:

    • You need to quote the symbol you pass to global-set-key.
    • The function has to be a "command". This is any emacs function marked as interactively callable by containing a top-level interactive form.

    In particular, if you want to pass in the func argument from the minibuffer, you could do this:

    (setq foobar-path "~/Library/yolo/bin/foo ")
    (defun foo-bar (func)
      (interactive "sEnter func: ")
      (shell-command (concat foobar-path func)))
    
    (global-set-key (kbd "M-p") 'foo-bar)