如何快速在文件和具有相同主模式的* scratch *缓冲区之间切换?


24

有时在处理代码时,快速打开* scratch *缓冲区以粘贴该代码文件中的代码片段很有用。

如果我正在使用Perl脚本,我想使用in快速打开一个* scratch *缓冲区cperl-mode。快速跳回到我最初使用的代码缓冲区也将是很好的。

Answers:


26

将以下功能绑定到您选择的键绑定将很方便。如果您当前正在使用FILE缓冲区,则调用下面的函数将在调用的FILE特定于主要模式的* scratch *缓冲区*scratch-MAJOR-MODE*和该FILE缓冲区之间切换。

给出问题的示例,如果我正在使用Perl脚本myperl.pl,则调用此函数将在myperl.pl和之间切换*scratch-cperl-mode*

(defun modi/switch-to-scratch-and-back (&optional arg)
  "Toggle between *scratch-MODE* buffer and the current buffer.
If a scratch buffer does not exist, create it with the major mode set to that
of the buffer from where this function is called.

        COMMAND -> Open/switch to a scratch buffer in the current buffer's major mode
    C-0 COMMAND -> Open/switch to a scratch buffer in `fundamental-mode'
    C-u COMMAND -> Open/switch to a scratch buffer in `org-mode'
C-u C-u COMMAND -> Open/switch to a scratch buffer in `emacs-elisp-mode'

Even if the current major mode is a read-only mode (derived from `special-mode'
or `dired-mode'), we would want to be able to write in the scratch buffer. So
the scratch major mode is set to `org-mode' for such cases.

Return the scratch buffer opened."
  (interactive "p")
  (if (and (or (null arg)               ; no prefix
               (= arg 1))
           (string-match-p "\\*scratch" (buffer-name)))
      (switch-to-buffer (other-buffer))
    (let* ((mode-str (cl-case arg
                       (0  "fundamental-mode") ; C-0
                       (4  "org-mode") ; C-u
                       (16 "emacs-lisp-mode") ; C-u C-u
                       ;; If the major mode turns out to be a `special-mode'
                       ;; derived mode, a read-only mode like `help-mode', open
                       ;; an `org-mode' scratch buffer instead.
                       (t (if (or (derived-mode-p 'special-mode) ; no prefix
                                  (derived-mode-p 'dired-mode))
                              "org-mode"
                            (format "%s" major-mode)))))
           (buf (get-buffer-create (concat "*scratch-" mode-str "*"))))
      (switch-to-buffer buf)
      (funcall (intern mode-str))   ; http://stackoverflow.com/a/7539787/1219634
      buf)))

如何排除此功能的Dired模式,term模式和其他不可编辑模式?
godblessfq '16

@godblessfq我刚刚在配置中解决了这个问题。现在,您可以从那里获取该版本。上电脑后,我将更新此答案。
Kaushal Modi

@godblessfq我已经更新了答案。试试看,看看是否适合您。
Kaushal Modi

奇迹般有效!
godblessfq '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.