Skip to content

Instantly share code, notes, and snippets.

@eev2
Last active July 15, 2025 14:47
Show Gist options
  • Save eev2/52edbfdb645e26aefec19226c0ca7ad0 to your computer and use it in GitHub Desktop.
Save eev2/52edbfdb645e26aefec19226c0ca7ad0 to your computer and use it in GitHub Desktop.
Create a new scratch buffer in emacs
(defun create-scratch-buffer (&optional nomode)
"Create a new scratch buffer and switch to it. If the region is active, then
paste the contents of the region in the new buffer. The new buffer inherits
the mode of the original buffer unless nomode is set.
Return the buffer."
(interactive "P")
(let ((bufname (get-buffer-create (generate-new-buffer-name "*scratch*")))
(mjmode (if nomode 'fundamental-mode (major-mode-remap major-mode))))
(when (use-region-p)
(insert-into-buffer bufname (point) (mark t))
(deactivate-mark))
(switch-to-buffer bufname)
(goto-char (point-min))
(funcall mjmode)
(get-buffer bufname)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment