Re-open *scratch* buffer in Emacs?

后端 未结 16 1340
北海茫月
北海茫月 2020-12-12 10:29

If I accidentally closed the scratch buffer in Emacs, how do I create a new scratch buffer?

16条回答
  •  鱼传尺愫
    2020-12-12 11:10

    I have combined the solutions posted so far into one function:

    (defun --scratch-buffer(&optional reset)
      "Get the *scratch* buffer object.
    Make new scratch buffer unless it exists. 
    If RESET is non-nil arrange it that it can't be killed."
      (let ((R (get-buffer "*scratch*")))
        (unless R
          (message "Creating new *scratch* buffer")
          (setq R (get-buffer-create "*scratch*") reset t))
            (when reset
              (save-excursion
                (set-buffer R)
                (lisp-interaction-mode)
                (make-local-variable 'kill-buffer-query-functions)
                (add-hook 'kill-buffer-query-functions '(lambda()(bury-buffer) nil)
              )))
        R))
    

    To apply this function in your .emacs use:

    (--scratch-buffer t)
    (run-with-idle-timer 3 t '--scratch-buffer)
    

    This will make the scratch buffer indestructible in the first place, and if saved it will be recreated. Additionally we can use a shortcut function scratch to bring up the buffer quickly:

    (defun scratch()
      "Switch to *scratch*.  With prefix-arg delete its contents."
      (interactive)
      (switch-to-buffer (--scratch-buffer))
      (if current-prefix-arg
          (delete-region (point-min) (point-max))
        (goto-char (point-max))))
    

    In the past it has proven useful to know the original startup-directory from which Emacs was started. This is either the value of desktop-dirname or the default-directory local variable of the scratch-buffer:

    (defvar --scratch-directory
      (save-excursion (set-buffer "*scratch*") default-directory)
      "The `default-directory' local variable of the *scratch* buffer.")
    
    (defconst --no-desktop (member "--no-desktop" command-line-args)
      "True when no desktop file is loaded (--no-desktop command-line switch set).")
    
    (defun --startup-directory ()
      "Return directory from which Emacs was started: `desktop-dirname' or the `--scratch-directory'.
    Note also `default-minibuffer-frame'."
      (if (and (not --no-desktop) desktop-dirname) 
          desktop-dirname
        --scratch-directory))
    

    So --startup-directory will always return the base directory of your makefile, TODO-file etc. In case there is no desktop (--no-desktop commandline-switch or no desktop-file) the --scratch-directory variable will hold directory Emacs was once started under.

提交回复
热议问题