8
votes

I'd like to set up a function that does the equivalent of marking the whole buffer, and running C-u M-| to prompt for a command, pipe the buffer to the command and replace the buffer with the output. Then maybe set it to shift-f5 or something.

I've only got as far as this:

(defun shell-command-on-buffer ()
  (interactive)
  (mark-whole-buffer))

How can I do the rest?

3

3 Answers

6
votes

This works for me:

(defun shell-command-on-buffer (command)
  (interactive "sShell command on buffer: ")
  (shell-command-on-region (point-min) (point-max) command t))
4
votes

This one has the advantage of using the "shell command" minibuffer history instead of the general minibuffer history.

(defun shell-command-on-buffer ()
  (interactive)
  (shell-command-on-region (point-min) (point-max) (read-shell-command "Shell command on buffer: ") t))
0
votes

An incremental improvement on @killdash9's answer, that:

  1. does indeed replace the buffer content (and does not append the output to the head of the buffer)
  2. makes an effort to restore the cursor position.

Tested with emacs 27.1

(defun shell-command-on-buffer ()
  (interactive)
  (let ((line (line-number-at-pos)))
    ;; replace buffer with output of shell command
    (shell-command-on-region (point-min) (point-max) (read-shell-command "Shell command on buffer: ") nil t)
    ;; restore cursor position
    (goto-line line)
    (recenter-top-bottom)))