Filtering text through a shell command in Emacs

后端 未结 3 654
庸人自扰
庸人自扰 2020-12-12 14:11

In vi[m] there is the ! command which lets me pipe text through a shell command -- like sort or indent -- and get the filtered text back into the buffer. Is there an equival

3条回答
  •  天命终不由人
    2020-12-12 14:41

    Late edit: As much as I appreciate the upvotes, Jurta's answer is the way to go. And Greg's hack is neater than mine.

    I'll leave the rest of this here because it might be worth something, but...


    M-x shell-command-on-region, which appears to be bound to M-| by default.


    I see that this does not do exactly what Rohit asked for. Using C-h f shell-command-on-region reveals that the desired behavior is available in the non-interactive version of the command (by setting the argument replace to non-nil). We should be able to write a wrapper to do this.

    Try this (load it into *scratch* and run M-x eval-buffer, if it works, copy it to your .emacs file):

    (defun shell-command-on-region-replace (start end command)
      "Run shell-command-on-region interactivly replacing the region in place"
      (interactive (let (string) 
             (unless (mark)
               (error "The mark is not set now, so there is no region"))
             ;; Do this before calling region-beginning
             ;; and region-end, in case subprocess output
             ;; relocates them while we are in the minibuffer.
             ;; call-interactively recognizes region-beginning and
             ;; region-end specially, leaving them in the history.
             (setq string (read-from-minibuffer "Shell command on region: "
                                nil nil nil
                                'shell-command-history))
             (list (region-beginning) (region-end)
                   string)))
      (shell-command-on-region start end command t t)
      )
    

    And note as I say in the comments that this is not a very emacsy thing to do. But I think it works.


    For any readers who don't know how to select a region:

    1. Move the "point" (current cursor position) to one end of the region, and use C-space to activate the "mark"
    2. Move the point to the other end of the region
    3. Your done, invoke the command

提交回复
热议问题