Emacs Lisp: switch-to-scratch and return back to previous buffer

Emacs Lisp: switch-to-scratch and return back to previous buffer

This function is using register 100 to switch-to-scratch and remembers where to return back. Global key binding is Hyper key and 8 and once in the *scratch* buffer, the local key binding is to return back to previous buffer.

I could not make it without using registers. The local binding would not remember the buffer, but as registers are global so I am using it. I could as well use some global variable.

(defun switch-to-scratch ()
  "Moves to scratch and remembers how to move back by using registers"
  (interactive)
  (set-register 100 (current-buffer))
  (persistent-scratch-restore)
  (switch-to-buffer "*scratch*")
  (local-set-key (kbd "s-8") (lambda () (interactive)
                   (switch-to-buffer (get-register 100)))))

(global-set-key (kbd "s-8") 'switch-to-scratch)

There are many ways to switch to buffer and return back. *scratch* buffer with emacs-lisp-mode is used on my side very often for calculations and estimates, new functions and similar. This function is using persistent-scratch package and it would restore the *scratch* if it does not exist. If you do not have the persistent-scratch then simple remove the line above.

Leave Your Comment or Contact GNU.Support

Contact GNU.Support now. There is a simple rule at GNU.Support: if we can help you, we do, whenever and wherever necessary, and it's the way we've been doing business since 2002, and the only way we know


Full name:


E-mail:


Message: