Elisp: Write Emacs Command Using Python etc

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 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."
  (interactive)
  (let ((cmdStr
         (format
          "/usr/bin/python /home/joe/pythonscriptxyz %s"
          (buffer-file-name))))
    (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.

Simple Example with JavaScript

Elisp: URL Percent Encode/Decode using JavaScript

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp Examples

Xah Commands

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples

Misc