6

I use clipboard-kill-region to copy contents from Emacs to other programs. But sometimes, it copies the same content twice into the clipboard. It looks like,

/home/user/.emacs/home/user/.emacs

when I copy the filename

/home/user/.emacs

Is there a way I can empty the clipboard contents before calling clipboard-kill-region?

My complete function is shown here; it is a utility function to copy the absolute path of currently opened file in Emacs buffer:

(defun sk-copy-file-name ()
  "Put the current file name on the clipboard"
  (interactive)
  (let ((filename (if (equal major-mode 'dired-mode)
                      default-directory
                    (buffer-file-name))))
    (when filename
      (with-temp-buffer
        (insert filename)
        (clipboard-kill-region (point-min) (point-max)))
      (message filename))))
6

Use kill-new instead of clipboard-kill-region for this. clipboard-kill-region uses kill-region which will append the text to the last kill if the last call was kill-region.

(defun sk-copy-file-name ()
  "Put the current file name on the clipboard"
  (interactive)
  (kill-new (or (buffer-file-name) default-directory)))
  • hi Jordan, it works with emacs gui but not with emacs terminal - emacs --no-window-system – Madhavan Jul 31 '15 at 13:59
  • I believe you'll need to manually interface with the systems clipboard program, you can see how to do it on OSX here, emacs.stackexchange.com/questions/10900/… – Jordon Biondo Jul 31 '15 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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