Mac – In emacs dired, how can I run a command on multiple marked files

emacs

I have several files marked in dired-mode, and I'd like to run a command on (say (delete-trailing-whitespace) on each of them.

Is there a built-in way to do this, or do I need to write it myself?

Basically I want to do something like (dired-do-shell-command) but I want to eval an emacs expression rather than a shell command. I want to do this within emacs on the files I have marked, so I can't use -batch.

Best Answer

I wrote something to do what I want, in case anyone else finds it useful:

Update: Updated this solution with a more general purpose command.

(defun mrc-dired-do-command (command)
  "Run COMMAND on marked files. Any files not already open will be opened.
After this command has been run, any buffers it's modified will remain
open and unsaved."
  (interactive "CRun on marked files M-x ")
  (save-window-excursion
    (mapc (lambda (filename)
            (find-file filename)
            (call-interactively command))
          (dired-get-marked-files))))

Now M-x mrc-dired-do-command delete-trailing-whitespace does what I want.

I would be delighted if someone would point out to me that I didn't have to do this, and I overlooked an obvious command like dired-do-command.

Related Question