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.

1

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).

  • 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 9: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
  • This doesn't replace the selection. – ideasman42 Aug 14 '17 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.