Search code examples
emacselisp

How to pipe output from one external process into another?


I’ve written a function which takes the contents of the selected region and then runs it through two external processes. Effectively the behaviour I want to replicate is M-| smartypants -2 | ascii2uni -a D -q.

The following function works, but requires two calls to call-process-region and temporarily storing the output of the first process in a buffer. Is there a better way to do this?

(defun convert-ascii-to-unicode (&optional b e)
  "Converts ascii punctuation marks (quotes, dashes, and ellipses) into their unicode equivilents."
  (interactive "r")
  (let ((output-buffer (generate-new-buffer "*ASCII to Unicode Output*")))
    (call-process-region b e "smartypants" nil output-buffer nil "-2")
    (set-buffer output-buffer)
    (call-process-region (point-min) (point-max) "ascii2uni" t output-buffer nil "-a" "D" "-q")
    (switch-to-buffer-other-window output-buffer)))

Solution

  • Just pipe within shell command, the following should do what you want:

    (defun convert-ascii-to-unicode (beg end)
      (interactive "r")
      (shell-command
       (format "smartypants -2 %s | ascii2uni -a D -q"
               (shell-quote-argument (buffer-substring beg end)))))
    

    Switch to *Shell Command Output* to view the output.