9

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 Answers 3

8

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))
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, I tried it. This opens up a new buffer for me -- ideally I'd like it to replace the current buffer, as C-u M-| does.
Ah, sorry, my initial suggestion has the same C-u behaviour as shell-command-on-region. Edited to better answer your request
No luck I'm afraid - it prompts me for the command but gives an error of wrong number of arguments.
Odd.. I just started a new emacs without customization (-q) and it works for me. What version of emacs?
24.2.1. The full error is: Wrong number of arguments: (lambda nil (interactive "sShell command on buffer: ") (shell-command-on-region (point-min) (point-max) command t)), 1
|
4

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

1 Comment

Please note that read-shell-command was introduce to GNU Emacs in version 23.1. If you need to be compatible with older versions, then you will not want to use this, or you will need to add code that checks for the presence of read-shell-command before trying to call it.
1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.