Elisp: Write Emacs Commands Using Python, Ruby, …
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
to the path of your script. You can include arguments as part of the command string.
Your script will need to:
- take input from Stdin.
- output to Stdout.
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." (interactive) (let ((cmdStr (format "/usr/bin/python /home/jane/pythonscriptxyz %s" (buffer-file-name)))) (shell-command-on-region (region-beginning) (region-end) cmdStr nil "REPLACE" nil t)))
thanks to Jordan Greenberg for python tips.