Elisp: Write Emacs Commands Using Python, Ruby, …

By Xah Lee. Date: . Last updated: .

Write a script in your favorite language and make it into a emacs command!

Here's the elisp wrapper:

;; emacs wrapper to a script in python, ruby, etc.

(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 scritpt 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/jane/pythonscriptxyz %s"
    (shell-command-on-region (region-beginning) (region-end) cmdStr nil "REPLACE" nil t)))

thanks to Jordan Greenberg for python tips.

Simple Example with JavaScript node.js

Elisp: Calling External Command to Decode URL Percent Encoding

Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.