Emacs:如何在暂存屏幕中加载文件内容

Emacs : how to load file content in scratch screen

我想在启动时加载 scratch 缓冲区中的“~/todo.org”文件内容。

我试过:

(setq initial-buffer-choice "~/todo.org")

但它会在新缓冲区中打开文件(不是 scratch)。

我也试过:

(setq initial-scratch-message "~/todo.org")

但它在 scratch 缓冲区中打印文件路径,我想要它的内容。

我也想将 scratch 缓冲区的模式更改为组织模式。

我试过:

(setq initial-major-mode org-mode)

但是我有一个初始化错误

Symbol's value as variable is void: org-mode

最后,我会这样做:

(condition-case err
  (when (get-buffer "*scratch*")
    (with-current-buffer "*scratch*"
      (erase-buffer)
      (insert-file-contents "~/todo.org")
      (org-mode)
    )
  )
(error (message "%s" error-message-string err)))

您可以通过在 init file:

中输入一些 Lisp 代码来达到预期的效果
(condition-case err
    (with-current-buffer "*scratch*"
      (let ((min (point-min))
            (max (point-max))
        (goto-char max)
        (insert-file-contents "~/todo.org")
        (delete-region min max)
        (org-mode)))
  (error (message "%s" error-message-string err)))

但是正如@phils 在对您的问题的评论中指出的那样,*scratch* 缓冲区可能不是用于此功能的最佳缓冲区。因此,我建议考虑以下替代方案:

(condition-case err
    (let ((buffer (get-buffer-create "*todo*")))
      (with-current-buffer buffer
        (insert-file-contents "~/todo.org")
        (org-mode))
      (setq initial-buffer-choice buffer))
  (error (message "%s" error-message-string err)))

通过使用此版本,您可以单独保留 *scratch* 缓冲区。您的 .org 文件将被插入到名为 *todo* 的单独缓冲区中。此缓冲区与您的 ~/todo.org 文件无关,因此当您第一次尝试保存它时,您必须指定一个文件名。