Jumping directories in eshell

A quick note that I thought might be interesting to document.

As befits a shell written in elisp, eshell is extremely easy to modify to your use. There are a few packages floating around that add autojump/fasd/z type functionality to eshell. These let you jump quickly to any previously visited directory. As it turns out it’s very easy to implement a more powerful version of this by piggybacking off of consult-dir.

Here’s a z command that lets you jump to any previously visited directory, as well as any bookmark, project or emacs-wide recent directory:

It’s a single function:

(defun eshell/z (&optional regexp)
    "Navigate to a previously visited directory in eshell, or to
any directory proferred by `consult-dir'."
    (let ((eshell-dirs (delete-dups
                        (mapcar 'abbreviate-file-name
                                (ring-elements eshell-last-dir-ring)))))
      (cond
       ((and (not regexp) (featurep 'consult-dir))
        (let* ((consult-dir--source-eshell `(:name "Eshell"
                                             :narrow ?e
                                             :category file
                                             :face consult-file
                                             :items ,eshell-dirs))
               (consult-dir-sources (cons consult-dir--source-eshell
                                          consult-dir-sources)))
          (eshell/cd (substring-no-properties
                      (consult-dir--pick "Switch directory: ")))))
       (t (eshell/cd (if regexp (eshell-find-previous-directory regexp)
                            (completing-read "cd: " eshell-dirs)))))))

Plus consult-dir, of course.

Note that if you provide input to the command instead, e.g. z doc, it will jump directly to the last matching directory you visited in eshell, i.e. ~/Documents/ or something like it.

The idea is simple, and it should be trivial to write something similar if you’re a Helm or Ivy user, as well as to write one for the comint mode M-x shell.

Add a comment, or comment via email