ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial
Web Hosting by 1&1

Emacs Lisp Wrapper for Perl/Python/Ruby Scripts

Xah Lee, , …,

This page shows you how you can write a text processing script in your favorite language, then make it available in emacs as a command.

Problem Description

If you are new to emacs lisp, it may take several months for you to become productive. However, you are probably familiar with Perl, Python, Ruby, PHP. You can use your existing knowledge to write many text processing scripts and make them available in emacs as commands, so that you can just select text, press a key, then the selected text will be transformed according to your script.

Solution

Your shell script will need to:

Let's assume your script is the unix program “wc”. (the “wc” command counts the number of words, lines, chars in the text.) For example, try this in shell: cat ‹file name› | wc.

You need a elisp command that:

  1. Grab the current region.
  2. Pass the text to a external program.
  3. Take the output from Stdout.
  4. Replace the current region by that text.

Lucky for us, the elisp function shell-command-on-region does this exactly.

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 (scriptName)
    (setq scriptName "/usr/bin/wc") ; full path to your script
    (shell-command-on-region startPos endPos scriptName nil t nil t)
    ))

Put the above code in your emacs init file and restart emacs. Or, just select the lisp code and call eval-region. 〔☛ Emacs: How to Evaluate Emacs Lisp Code

To use your command, first make a text selection, then call the command by name. You can give it a key. 〔☛ Emacs: How to Define Keys

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

emacs ♥

blog comments powered by Disqus