On Mon, Mar 27, 2023 at 02:56:01PM +0100, Richard Copley wrote: > On Mon, 27 Mar 2023 at 10:21, Michael Maurer wrote: > > > > Hello, > > > > I wrote the following function to copy the kill-ring to the scratch > > buffer, but it only gets initialized sometimes at the start of emacs, > > sometimes not. Why? > > > > (defun copy-to-scratch-on-kill > > () > > "Copy every kill (delete or yank) to *scratch* buffer." > > (let > > ((cur-kill-string > > (current-kill 0 t))) > > (when > > (and > > (not > > (equal cur-kill-string "")) > > (not > > (equal cur-kill-string prev-kill-string)) > > (get-buffer "*scratch*")) > > (with-current-buffer "*scratch*" > > (goto-char > > (point-max)) > > (insert cur-kill-string "\n") > > (goto-char > > (point-max)))) > > (setq prev-kill-string cur-kill-string))) > > > > (add-hook 'post-command-hook #'copy-to-scratch-on-kill) > > > > If an error propagates from the hook function (most likely "Kill ring > is empty", signalled by `current-kill`) then Emacs removes the > function from the hook. See the docstring for variable > `post-command-hook`. There's more: where does the variable `prev-kill-string' come from? - if nobody has set it previously, this will be the error killing your hook (this is my hunch) - if somebody has, you are lucky if that somebody was you (otherwise you are into an entertaining debugging session If you are using a global variable like that, it makes sense to declare, document and perhaps initialize it with `defvar' Another possibility would be to hide it away in a closure [1] (you are using lexical binding, aren't you?). Just ask around here if the concept is unfamiliar to you. Cheers -- t