Elisp: Call Shell Command

By Xah Lee. Date: . Last updated: .

Emacs Lisp Command Wrapper to Shell

You can write a emacs command using your favorite language such as • JavaScriptPythonRuby .

All you have to do is make your script take the stdin and output in stdout. Then, use a emacs lisp wrapper function to call it.

Here's the elisp wrapper:

(defun do-something-region (startPos endPos)
  "Do some text processing on region.
This command calls the external script “wc”."
  (interactive "r")
  (let (cmdStr)
    (setq cmdStr "/usr/bin/wc") ; full path to your script
    (shell-command-on-region startPos endPos cmdStr nil t nil t)))

In the above, just replace the /usr/bin/wc to the path of your script. You can include arguments as part of the command string.

Your script will need to:

The elisp function shell-command-on-region above, takes a region begin/end position, call your script and passing the text as Stdin, gets the script's Stdout, and replace the region.

With the above, you can write many little text processing scripts in your favorite language, and have them all available in emacs as commands.

Passing Text to STDIN and Command Line Arg

In this example, we also pass a argument to the shell command.

You can simply do that by passing it as part of the command string.

(defun my-call-script-xyz ()
  "example of calling a external command.
passing text of region to its stdin.
and passing current file name to the script as arg.
replace region by its stdout."
  (let ((cmdStr
          "/usr/bin/python /home/joe/pythonscriptxyz %s"
    (shell-command-on-region (region-beginning) (region-end) cmdStr nil "REPLACE" nil t)))

2013-11-29 thanks to https://www.facebook.com/jrdngrnbrg for python tips.

Examples: Command Wrapper Calling External Program

Emacs Wrapper for External Command