Elisp: Call Shell Command on Region

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 input from stdin and output to stdout. Then, use a emacs lisp wrapper function to call it.

shell-command-on-region

shell-command-on-region

(shell-command-on-region START END COMMAND &optional OUTPUT-BUFFER REPLACE ERROR-BUFFER DISPLAY-ERROR-BUFFER REGION-NONCONTIGUOUS-P)

Call a shell command, feed the emacs region to stdin, and take the stdout optionally replacing the region text.

# 2024-11-18
# read from stdin
# print capitalize version to stdout
# file name: xupcase.py

import sys
xx = sys.stdin.read()
print( xx.upper().strip())
(defun my-do-region (Begin End)
  "call command at ~/xupcase.py
with text selection as stdin, and replace the region with its output.
version: 2024-11-18"
  (interactive (list (region-beginning) (region-end)))
  (let (xcmdStr)
    (setq xcmdStr (concat "python " (expand-file-name "~/xupcase.py")))
    (shell-command-on-region Begin End xcmdStr nil t nil t)))

Elisp, Call Shell Command