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))))
Scott Weldon
  • 2,695
  • 1
  • 17
  • 31
Madhavan
  • 1,957
  • 12
  • 28

1 Answers1

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)))
Jordon Biondo
  • 12,332
  • 2
  • 41
  • 62
  • 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, http://emacs.stackexchange.com/questions/10900/copy-text-from-emacs-to-os-x-clipboard – Jordon Biondo Jul 31 '15 at 14:35