Pulse to Highlight Yanked Text in Vanilla Emacs
I somehow found Abin Simon’s post about how he made pasting text in his Emacs “pulse”, aka temporarily highlight the pasted region.
In Emacs parlance, pasting is called “yanking”. His post sadly covers only one use case: Emacs with evil-mode
, which adds vim keybindings and apparently also adds a special evil-yank
command in place of the regular yank
.
Update 2020-12-21: Abin pointed out to me that “yanking” in vim parlance means the exact opposite – copying! What is happening in this world?! Anyway, he pointed me towards goggles.el, a package that does the same effect as the code below, and then some. Check it out!
The evil Emacs version is easier to make pulse-to-highlight because its function parameter already define the beginning and end position of the yanked text. These two parameters are then passed on to pulse-momentary-highlight-region
. The pulsing highlight is built-in, but to adapt the stuff to work with the regular pasting-aka-yanking, I had to change things up a bit.
For vanilla Emacs yank
, I used the Decorator Pattern (called “advice” in Emacs Lisp) and captured the point (row & column in the text of the insertion point) before and after the paste:
(require 'pulse)
(defun ct/yank-pulse-advice (orig-fn &rest args)
;; Define the variables first
(let (begin end)
;; Initialize `begin` to the current point before pasting
(setq begin (point))
;; Forward to the decorated function (i.e. `yank`)
(apply orig-fn args)
;; Initialize `end` to the current point after pasting
(setq end (point))
;; Pulse to highlight!
(pulse-momentary-highlight-region begin end)))
(advice-add 'yank :around #'ct/yank-pulse-advice))