Emacs Dired: View (and edit) file contents without opening a file

Some files open fast, others slower. It may depend on the file viewer too. But in Emacs Dired it is possible to extract file contents without opening the file. The inbuilt function for it is insert-file-contents.

In Dired (Emacs file manager), the m key marks the file at point. Mark some file or files in Dired and look at them. Instead of opening them, how to extract their contents into an arbitrary buffer? Here’s a function that prompts for a buffer:

(defun dired-append-marked (bufname)
  "In Dired or Ibuffer, open the contents of all marked
  buffers in a new buffer. Prompt for the name of the new buffer."
  (interactive "BAppend to buffer: ")
  (cond ((equal major-mode 'ibuffer-mode)
         (let ((mfiles (ibuffer-get-marked-buffers)))
           (switch-to-buffer (get-buffer-create bufname))
           (mapc 'insert-buffer-substring mfiles)))
        ((equal major-mode 'dired-mode)
         (let ((mfiles (dired-get-marked-files)))
           (switch-to-buffer (get-buffer-create bufname))
           (mapc 'insert-file-contents mfiles)))))

The function first tests whether Dired is in focus. If Dired is not in focus, nothing will happen. If Dired is in focus, the function extracts the (entire!) contents of marked files into a selected buffer. If nothing is marked, nothing will happen.

To create a new buffer to extract the file contents to, write a new random buffer name when the prompt appears.

As a bonus, this function will also work in Ibuffer the same way. Ibuffer provides marking (of buffers listed in Ibuffer) as well.

Additionally, there is an automatic preview for Dired available at https://protesilaos.com/emacs/dired-preview which opens file contents instantly into a new buffer when point is on the filename in Dired. The buffers go into buffer list and can be switched to through List-buffers, Ibuffer, or Buffer-show normally for editing.

Leave a Reply

Your email address will not be published. Required fields are marked *