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.

2
  • 6
    shell-command-on-region.
    – Dan
    Commented Jan 26, 2017 at 19:19
  • 2
    @Dan: Please consider posting that as an answer.
    – Drew
    Commented Jan 27, 2017 at 3:03

1 Answer 1

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

3
  • 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
    Commented Jan 28, 2017 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
    Commented Jan 29, 2017 at 10:20
  • 1
    This doesn't replace the selection.
    – ideasman42
    Commented Aug 14, 2017 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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