I would like to emulate the fonctionnality of xclip in dired. That is, copying file content to clipboard (but without opening it in Emacs).

Sadly, using dired-do-async-shell-command and xclip does not work. Any ideas ? Thanks !

3 Answers 3

    (kill-new (buffer-substring-no-properties (point-min) (point-max)))

@nichijou's answer is fine. But there's no need to actually put the buffer in a window. You can use find-file-noselect to visit a buffer without displaying it.

(defun foo ()
  (let ((buf  (find-file-noselect (dired-get-file-for-visit))))
    (with-current-buffer buf
      (kill-new (buffer-substring-no-properties (point-min) (point-max))))
    (kill-buffer buf)))
  • Could you explain why you have to store the buffer in the "buf" variable ? It looks like it read the file twice. Commented May 24, 2021 at 20:35
  • @alex_reader: Duh; good catch. Fixed. I forgot to replace the sexp by the variable. I added the variable so I could kill the buffer when done.
    – Drew
    Commented May 24, 2021 at 21:09
  • I rejected an edit that added a non-nil RAW arg to the find-file-noselect call. Not sure the rejection was correct (had to reject or accept), but it's not clear to me why the answer to the question calls for non-nil RAW as part of the answer.
    – Drew
    Commented May 25, 2021 at 21:19

I can't reproduce your error, and want to suggest that you're possibly using xclip incorrectly. This answer should also benefit others because no-one needs to create a custom emacs function for this to work.

From a dired buffer, I select a small-sized file, and enter & to get the async dialog. Then I enter xclip -i. That sends the contents of the selected file to the PRIMARY clipboard, one of the three clipboards present in all modern GUI environments (the other two are called SECONDARY and CLIPBOARD). Then, from a terminal emulator outside emacs, I run xclip -o and I do see the contents of that file inserted into the terminal.

If you want xclip to operate on the CLIPBOARD clipboard (I know, it is confusing, I didn't design it), then pass it the arguments -selection clipboard. Personally, I have it defined as a shell alias. There also exists the command-line program xsel, which has shorter option names.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.