I would like to wrap kill-ring-save in order to only execute kill-ring-save if text has been highlighted - same as in most text editors.

Sometimes I accidentally hit copy instead of paste and then my clipboard is over written, but I have not selected any text for copying. Personally it's a complete workflow killer.

Something like:

(defun my-kill-ring-save()
  (interactive)
  (if (TEXT IS HIGHLIGHTED)
    (kill-ring-save)))
up vote 3 down vote accepted

I think you simply want to (setq mark-even-if-inactive nil).

Do not worry about the kill ring ("clipboard") being overwritten: you can recover previous kill ring entries by typing C-y M-y (repeat M-y as many times as you need). See Section 12.2.2 of the Emacs manual for more.

If you really want to disable M-w when the region is inactive ("not highlighted"), which I do not recommend, you can probably do something like this (untested):

(defun my-kill-ring-save (beg end &optional region)
  (interactive (mark) (point) (prefix-numeric-value current-prefix-arg))
  (if (region-active-p)
      (kill-ring-save beg end region)
      (error "Eek!")))
  • I use browse-kill-ring but it's one too many keys and I'd rather just disable. – YoungGrandpa Oct 27 '14 at 11:42

As a Mac Os X user, the only regret that I have about emacs is its lack of integration with the rest of the so user-friedly Mac desktop. In particular, I have a mental problem when switching apps, to or from emacs, that is, the change of the copy-and-paste key shortcuts. Even Mac OS X’s Terminal.app understands the M-c and M-v shortcuts, while in emacs, We’re stuck with those ugly M-w and C-y.

As I don’t needed it (I have the “prior page” and “next page” keys on my keyboard) , I quickly replaced my M-v shortcut by a yank :

   (global-set-key (kbd "M-v") 'yank)

But I still had the M-c problem: I could not just bind M-c to kill-ring-save, because I really often use the traditional command bound to M-c: capitalize-word. So I wrote this little function in my .emacs, and it really made my life easier :

   (defun capitalize-word-or-kill-ring-save ()
      (interactive)
      (if mark-active
          (kill-ring-save (region-beginning) (region-end))
        (capitalize-word 1)
        )
    )
(global-set-key (kbd "M-c") 'capitalize-word-or-kill-ring-save)

I posted this a long time ago on the EmacsWiki but an Emacs.SX site is a great home for this trick too !

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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