Emacs - 无法获得缓冲提供 - 保存工作

时间:2010-03-01 17:56:11

标签: emacs elisp emacs23

我想让Emacs问我是否要保存修改后的缓冲区,当缓冲区与文件没有关联时。要打开一个新的缓冲区(不访问文件),我的.emacs文件中有以下功能:

;; Creates a new empty buffer
(defun new-empty-buffer ()
  "Opens a new empty buffer."
  (interactive)
  (let ((buf (generate-new-buffer "untitled")))
    (switch-to-buffer buf)
    (funcall (and default-major-mode))
    (setq buffer-offer-save t)))

我认为将“缓冲 - 提供 - 保存”设置为不是零的东西会成功。但每当我使用“kill-this-buffer”杀死缓冲区时,它会立即被杀死而不会有任何问题。

这发生在GNU Emacs 23.1.1

有什么想法吗?

谢谢, w ^

3 个答案:

答案 0 :(得分:2)

已编辑添加buffers-offer-save 的使用。注意:变量buffer-offer-save is only used upon exiting Emacs

您可以从此代码开始,并根据需要对其进行自定义:

(add-to-list 'kill-buffer-query-functions 'ask-me-first)
(defun ask-me-first ()
  "prompt when killing a buffer"
  (if (or buffer-offer-save 
          (eq this-command 'kill-this-buffer)
          (and (buffer-modified-p) (not (buffer-file-name))))
      (y-or-n-p (format "Do you want to kill %s without saving? " (buffer-name)))
    t))

经过进一步的反思,这有点笨拙,因为系统会提示您输入所有缓冲区,并且Emacs通常会使用许多临时缓冲区。如果您只是想在交互式杀死缓冲区(与文件无关)时收到提示。

您可以使用此建议,该建议仅在您以交互方式尝试杀死缓冲区时提示您:

(defadvice kill-buffer (around kill-buffer-ask-first activate)
  "if called interactively, prompt before killing"
  (if (and (or buffer-offer-save (interactive-p))
           (buffer-modified-p)
           (not (buffer-file-name)))
      (let ((answ (completing-read
                   (format "Buffer '%s' modified and not associated with a file, what do you want to do? (k)ill (s)ave (a)bort? " (buffer-name))
                   '("k" "s" "a")
                   nil
                   t)))
        (when (cond ((string-match answ "k")
                     ;; kill
                     t)
                    ((string-match answ "s")
                     ;; write then kill
                     (call-interactively 'write-file)
                     t)
                    (nil))
          ad-do-it)

        t)
    ;; not prompting, just do it
    ad-do-it))

答案 1 :(得分:1)

修改'new-empty-buffer似乎使我的工作与Trey的defadvice一样。

;; Creates a new empty buffer
(defun new-empty-buffer ()
 "Opens a new empty buffer."
 (interactive)
 (let ((buf (generate-new-buffer "untitled")))
   (switch-to-buffer buf)
   (funcall (and default-major-mode))
   (put 'buffer-offer-save 'permanent-local t)
   (setq buffer-offer-save t)))

这使得buffer-offer-save在我们的新缓冲区中永久本地化,因此在切换主要模式时不会被其余的局部变量杀死。

答案 2 :(得分:1)

buffer-offer-save要求退出Emacs而不是手动关闭缓冲区没有意义,为什么不“扩大”它的职责呢?

(defadvice kill-buffer (around kill-buffer-ask activate)
  "If `buffer-offer-save' is non-nil and a buffer is modified,
prompt before closing."
  (if (and buffer-offer-save (buffer-modified-p))
      (when (yes-or-no-p "The document isn't saved. Quit? ")
        ad-do-it)
    ad-do-it))

如果新创建untitled缓冲区,则不会提示。如果您使用Elisp的kill-buffer,则不会提示。它不会在像*Messages*这样的Emacs系统缓冲区上提示。但它会提示你是否创建了一个空缓冲区并在其中写了一些内容。

另见my answer on creating an empty buffer