Not sure whether you mean toggling the last visited dired
buffer or some other dired
buffer.
For the latter you can just use bookmarks. Set a bookmark to a dired
buffer with M-x bookmark-set
, call it my my-dired-buffer
and keep re-bookmarking the same name to different buffers. Bind a key to jump to it:
(define-key global-map (kbd "<f7>")
(lambda () (interactive)
(if (equal (expand-file-name (bookmark-location "my-dired-buffer"))
(expand-file-name default-directory))
(previous-buffer)
(bookmark-jump "my-dired-buffer"))))
If you are already in the bookmarked buffer this will take you back to the last buffer.
For the former, I think you just need to keep track of the last dired
buffer and wrap your dired
jump function with something that updates the tracking variable:
(setq my-last-dired-buffer nil)
(defun my-open-dired-bufer ()
(interactive)
(dired-jump)
(setq my-last-dired-buffer (current-buffer)))
(define-key global-map (kbd "<f7>")
(lambda () (interactive)
(if (equal (current-buffer) my-last-dired-buffer)
(previous-buffer)
(switch-to-buffer my-last-dired-buffer))))
Note this only keeps track of buffers that were opened with my-open-dired-buffer
.
You can also add a setter to set the current buffer as the last buffer:
(defun my-last-dired-buffer-set ()
(interactive)
(setq my-last-dired-buffer-set (current-buffer)))
In fact, you can just use this instead of using bookmarks and just don't wrap the dired-jump
function and set the tracking variable with the setter manually.
You can complicate this quite a bit, but I am not sure it is worth it. It is very easy to change buffers in Emacs especially if you are using Evil mode, maybe with something like Doom Emacs.
Note, I haven't tested the above code heavily. But you get the idea I hope.