Emacs, How to copy region, and leave it highlighted

emacs

I'm happy enough with the default M-w as (kill-ring-save) which loses the region's highlighting upon running the command. I don't want to alter its behaviour, but I do want to re-bind <C-insert> to perform a similar action and maintain the region's highlighting.

I've tried (un)setting transient-mark-mode directly and via a function, but the region still loses its highlighting.

Running only (kill-ring-save (region-beginning) (region-end)) in an interactive function works as expected, ie. it loses highlighting.

Running only (exchange-point-and-mark) (exchange-point-and-mark) in an interactive function works as expected, ie. it re-highlights the region and puts/leaves point in its original/correct place.

However when I put them all together in a function, it does not re-highlight the region. Here is non-functioning function and binding:

(defun kill-ring-save-keep-highlight ()
  (interactive)
  (kill-ring-save (region-beginning) (region-end))
  (exchange-point-and-mark) (exchange-point-and-mark)
)
(global-unset-key (kbd "<C-insert>"))
(global-set-key   (kbd "<C-insert>") 'kill-ring-save-keep-highlight)

Using: GNU Emacs 23.1.1 in Ubuntu 10.04.3

Best Answer

Running kill-ring-save doesn't deactivate the mark directly, but merely sets the variable deactivate-mark to t in order for the deactivation to be done afterward. To prevent this, reset deactivate-mark to nil before the deactivation.

(defun kill-ring-save-keep-highlight (beg end)
  "Keep the region active after the kill"
  (interactive "r")
  (prog1 (kill-ring-save beg end)
    (setq deactivate-mark nil)))

(global-set-key (kbd "<C-insert>") 'kill-ring-save-keep-highlight)
Related Question