自定义dired缓冲区的缓冲区名称

时间:2014-05-12 17:20:23

标签: emacs buffer dired

我希望任何时候都有一个单独的可用缓冲区,我希望能够使用特定的热键将它带到前面。但是,为了做到这一点,我需要dired缓冲区始终具有相同的名称。但是每次加载新目录时缓冲区名称都会更改。有没有办法告诉dired不要更改名称?我尝试调整读取和加载钩子,但它没有用。

或者,是否有一个命令来提出现有的dired缓冲区?

谢谢!

2 个答案:

答案 0 :(得分:4)

你可能不想这样做。某些Dired功能取决于与目录关联的缓冲区名称。

更好的方法可能是让一个命令切换到唯一的Dired缓冲区,因为你一次只能有一个。

(defun switch-to-dired-buffer ()
  "..."
  (interactive)
  (let ((dbufs  (cl-remove-if-not
                 (lambda (bf)
                   (with-current-buffer bf
                     (derived-mode-p 'dired-mode)))
                 (buffer-list))))
    (switch-to-buffer (car dbufs))))

如果有多个等待缓冲区,您也可以获得更好的和提示。

答案 1 :(得分:0)

尽管存在可能的缺点,但以下代码可以满足您的需求:

(setq dired-default-buffer-name "*Dired*")

(defun dired-set-default-buffer-name ()
  "Set name of Dired buffer to `dired-default-buffer-name'.

If there already is a buffer with that name, kill it first."
  (when (get-buffer dired-default-buffer-name)
    (kill-buffer (get-buffer dired-default-buffer-name)))
  (rename-buffer dired-default-buffer-name))

(defadvice dired (after dired-set-default-buffer-name activate compile)
  "Set name of Dired buffer to default name when launching Dired."
  (dired-set-default-buffer-name))

(defadvice dired-find-file (after dired-set-default-buffer-name activate compile)
  "Set name of Dired buffer to default name when entering a subdirectory."
  (when (eq major-mode 'dired-mode)
    (dired-set-default-buffer-name)))

(defun dired-switch-to-default-buffer ()
  "Bring up default Dired buffer."
  (interactive)
  (switch-to-buffer dired-default-buffer-name))

;; Set up global key binding for bringing up default Dired buffer:
(global-set-key (kbd "C-c C-d") 'dired-switch-to-default-buffer)

请注意,如果您使用ido-mode,则需要在第一个dired中将ido-dired替换为defadvice。此外,dired-switch-to-default-buffer不会检查您是否已启动Dired;如果你希望它在这种情况下工作,你将不得不稍微修改一下这个功能(例如在某个默认位置打开Dired)。


修改

如果您发现您实际上使用的功能取决于与显示的目录关联的Dired缓冲区的名称,您可以添加:

(setq dired-original-buffer-name nil)

(defun dired-restore-original-name ()
  (rename-buffer dired-original-buffer-name))

(defun dired-toggle-name ()
  (interactive)
  (if (eq (buffer-name) dired-default-buffer-name)
      (dired-restore-original-name)
    (dired-set-default-buffer-name)))

(global-set-key (kbd "C-c C-t") 'dired-toggle-name)

...并修改dired-set-default-buffer-name,如下所示:

(defun dired-set-default-buffer-name ()
  "Set name of Dired buffer to `dired-default-buffer-name'.

If there already is a buffer with that name, kill it first."
  (when (get-buffer dired-default-buffer-name)
    (kill-buffer (get-buffer dired-default-buffer-name)))
  (setq dired-original-buffer-name (buffer-name)) ;; Keep track of original
                                                  ;; buffer name so we can
                                                  ;; restore it
  (rename-buffer dired-default-buffer-name))

这将允许您通过发出相关的键绑定(当前: Cc Ct )在Dired缓冲区的原始名称和默认名称之间切换,但您当然可以修改它以适合您的需要)。