I didn't know if it was implemented in emacs and got to working on it and one hour later I produced this emacs lisp script:
(defun command-on-buffer (command)
(interactive "MEnter command: ")
(shell-command-on-region (point-min) (point-max) command (current-buffer)))
(global-set-key "\C-c\C-s" 'command-on-buffer)
I was initially bent on using call-process-region but somehow it gave errors when I was running interpreted python or perl code. I remember the python code giving syntax error at reading stdin. I don't know whether it thought there was no stdin at all or if it was empty. However normal commands like "cat" worked without any problems.
So, I was looking for other programs which used call-process-region and since I was editing a python file (which was what I was testing the elisp function on), I recognized that the python-mode must use something like that for sending the buffer to the python shell.
I grep'd for a while in python-mode files and found out that shell-command-on-region is like call-process-region but it could execute shell commands and looked for its documentation (in emacs itself - it IS the best editor in the world after all). And yes, it did exactly what I wanted - it gave arbitrary text in the buffer to the shell command and could put the output in any buffer I chose. Writing the function then was very simple as you can see.
It doesn't give selected text to the command yet. I do plan to implement that too - but only when I have a real need or inspiration and if I find that emacs indeed doesn't have any functions to do what I want. For that I need a way to see if any text is selected, get the selected text and then ask shell-command-on-region to replace only the selected text. I don't think shell-command-on-region does that and if that is the case, I'll have to put that in a buffer and insert its contents into the selected region.
No comments:
Post a Comment