Advertisement
mark-naylor-1701

elisp preserve & restore kill-ring

Apr 12th, 2025
1,007
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 2.26 KB | None | 0 0
  1. (defvar mwn/kill-ring-file
  2.   "~/.emacs.d/kill-ring"
  3.   "Path of the file used to save the contents of `kill-ring' between sessions.")
  4.  
  5. (defun mwn/get-file-buffer-status (file-name)
  6.   "Return a data structure associated with the FILE-NAME and boolean value
  7. indicating if the buffer was open before the function call. Creates a
  8. new buffer if needed. First value is the buffer associated with
  9. `kill-ring' content. Second value is t if the buffer was already open,
  10. nil if it is a new buffer."
  11.   (let ((has-buffer (not (null (get-file-buffer file-name)))))
  12.     (cl-values (find-file-noselect file-name t)
  13.                has-buffer)))
  14.  
  15. (defun mwn/save-kill-ring ()
  16.   "Stores the contents of the `kill-ring' to a file for later retrieval."
  17.   (interactive)
  18.   (cl-multiple-value-bind
  19.       (buffer open)
  20.       (mwn/get-file-buffer-status mwn/kill-ring-file)
  21.     (with-current-buffer buffer
  22.       (erase-buffer)
  23.       (print kill-ring buffer)
  24.       (save-buffer))
  25.     (unless open
  26.       (kill-buffer buffer))))
  27.  
  28. (defun mwn/restore-kill-ring ()
  29.   "Reads in the contents of the kill ring file, if any, and sets the value of `kill-ring'."
  30.   (interactive)
  31.   (cl-multiple-value-bind
  32.       (buffer open)
  33.       (mwn/get-file-buffer-status mwn/kill-ring-file)
  34.     (with-current-buffer buffer
  35.       (unless (zerop (buffer-size))
  36.         (goto-char 1)
  37.         (setq kill-ring (read (current-buffer)))))
  38.     (unless open
  39.       (kill-buffer buffer))))
  40.  
  41. ;; Automatically preserve the kill-ring when terminating the current emacs process.
  42. (add-hook 'kill-emacs-hook #'mwn/save-kill-ring)
  43.  
  44. (defun mwn/no-kill-ring-terminate (&optional restart)
  45.   "Core function for killing/restarting emacs. This version will NOT save the
  46. `kill-ring' in the defined kill-ring preservation file."
  47.   (let ((old-hook (cl-copy-list kill-emacs-hook)))
  48.     (remove-hook 'kill-emacs-hook #'mwn/save-kill-ring)
  49.     (unless (save-buffers-kill-emacs nil restart)
  50.       (setq kill-emacs-hook old-hook))))
  51.  
  52. (defun mwn/kill-emacs-no-kill-ring ()
  53.   "End the current emacs session w/o saving the `kill-ring'."
  54.   (interactive)
  55.   (mwn/no-kill-ring-terminate))
  56.  
  57. (defun mwn/restart-emacs-no-kill-ring ()
  58.   "Restart the current emacs session w/o saving the `kill-ring'."
  59.   (interactive)
  60.   (mwn/no-kill-ring-terminate t))
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement