2

There is a nice example of how to open neotree in the project root
see: https://www.emacswiki.org/emacs/NeoTree (find-file-in-project and Projectile sections).

However, I'd like to toggle neotree, so I can easily open and close it, while having the root set to the project path.

Is this possible?

3

It's now 2020 and you can open neotree in the current directory using neotree-show instead of neotree-toggle.

neotree-show does exactly what the orignal op required, without the need for the elaborate function.

3
  • 1
    Thanks I tried this but found this still not quite as good as neotree-toggle snippet. As it doesn't show a tree for the paths leading up to the current file. Also, looking at the code, it doesn't support find-file-in-project or vc methods of finding the root.
    – ideasman42
    Apr 5 '20 at 1:17
  • This works perfectly for me, on neotree v 0.5.1. The definition of neotree-open has built-in integration with projectile, and it is wrapped by neotree-toggle which answers the original question.
    – hraban
    Jun 1 '21 at 13:45
  • @ideasman42 I have opened a PR adding the built-in project integration: github.com/jaypei/emacs-neotree/pull/343 -- thanks for your comment. Jun 24 '21 at 13:51
3

Using a slightly modified version of this post, I managed to get this working:

(defun my-neotree-project-dir-toggle ()
  "Open NeoTree using the project root, using projectile, find-file-in-project,
or the current buffer directory."
  (interactive)
  (require 'neotree)
  (let* ((filepath (buffer-file-name))
         (project-dir
          (with-demoted-errors
              (cond
               ((featurep 'projectile)
                (projectile-project-root))
               ((featurep 'find-file-in-project)
                (ffip-project-root))
               (t ;; Fall back to version control root.
                (if filepath
                    (vc-call-backend
                     (vc-responsible-backend filepath) 'root filepath)
                  nil)))))
         (neo-smart-open t))

    (if (and (fboundp 'neo-global--window-exists-p)
             (neo-global--window-exists-p))
        (neotree-hide)
      (neotree-show)
      (when project-dir
        (neotree-dir project-dir))
      (when filepath
        (neotree-find filepath)))))

Key binding to toggle, example:

(define-key global-map (kbd "M-e") 'my-neotree-project-dir-toggle)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.