0

Something I've found useful in other editors is the ability to:

  • take the selected text
  • run an external command and pass the selection to its stdin
  • take the external commands stdout and replace the current selection with it.

This way you can write useful text tools which operate on the selection using any language that can do basic io.

How can this be done with emacs using the selection? ... a single character, word, paragraph... etc.

(Directly in the command line, or via a key binding?)


Note

The reason I'm asking this question is because I would like to operate on the selection. (i.e., the text that would be removed if x was pressed). In evil-mode !sort for example only works on a line-level.

Drew
  • 75,699
  • 9
  • 109
  • 225
ideasman42
  • 8,375
  • 1
  • 28
  • 105

1 Answers1

2

You can use the function shell-command-on-region to pipe some text into an external command. For example, the following simple command will give you a word count of the active region by sending the selected text to the shell command wc:

(defun wc-region (beg end)
  "Count words in the active region."
  (interactive "*r")
  (if (region-active-p)
      (shell-command-on-region beg end "wc -w")
    (message "No active region")))

You can adapt other members of the shell-command family as necessary if you're not interested in using the region (e.g., if you'd like to use thing-at-point).

Dan
  • 32,584
  • 6
  • 98
  • 168
  • The OP asks for replacing the selected text with shell command output, you could show the use of the *replace* arg to `shell-command-on-region` for that. – JeanPierre Jan 28 '17 at 09:25
  • The replace selected region by the stdout of the shell command operating on it (what Dan and Jean-Pierre describe in Code) is mapped to ```C-u M-|``` in the standard key map. – dfeich Jan 29 '17 at 10:20
  • 1
    This doesn't replace the selection. – ideasman42 Aug 14 '17 at 04:04