Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to add a directory and all its subdirectories to load-path in Emacs

Tags:

emacs

lisp

elisp

The question is similar to one.

However, it differs in putting all subdirectories achievable in the folder too.

Jouni's code which puts first level folders achievable

(let ((base "~/Projects/emacs"))
  (add-to-list 'load-path base)
  (dolist (f (directory-files base))
    (let ((name (concat base "/" f)))
      (when (and (file-directory-p name) 
                 (not (equal f ".."))
                 (not (equal f ".")))
        (add-to-list 'load-path name)))))

How can you put a directory and all its subdirectories to load-path in Emacs?

like image 628
Léo Léopold Hertz 준영 Avatar asked Apr 26 '09 23:04

Léo Léopold Hertz 준영


2 Answers

My answer in the other question does handle multiple levels of subdirectories.

The code for reference

(let* ((my-lisp-dir "~/.elisp/")
       (default-directory my-lisp-dir)
       (orig-load-path load-path))
  (setq load-path (cons my-lisp-dir nil))
  (normal-top-level-add-subdirs-to-load-path)
  (nconc load-path orig-load-path))
like image 131
Nicholas Riley Avatar answered Sep 19 '22 12:09

Nicholas Riley


Here's an adaptation of Jouni's answer that uses a helper function that you can tailor.

One advantage of the helper function is that you can trace it when it does something unexpected, because it's a pure function, so doesn't side-effect into your load-path. I tried using the normal-top-level-add-subdirs-to-load-path, but everything in it is so side-effecting and dependent on unpredictable special variables, that it was just easier to write something fresh that was clean. Note that my answer does not use inodes, so may be less efficient.

A second advantage of this approach is that it lets you tailor what files you would like to ignore.

(defun add-to-load-path-with-subdirs (directory &optional endp)
  (let ((newdirs (lp-subdir-list directory)))
    (if endp (setq load-path (append load-path newdirs))
      (setq load-path (nconc newdirs load-path)))))

(defconst +lp-ignore-list+
  (list "CVS" ".git" ".svn" ".." "."))

(defun lp-subdir-list (base &optional ignore)
  (unless ignore
    (setq ignore +lp-ignore-list+))
  (let ((pending (list base))
 (retval nil))
    (while pending
      (let ((dir (pop pending)))
 (push dir retval)
 (dolist (f (directory-files dir))
   (let ((name (concat dir "/" f)))
     (when (and (not (member f ignore))
         (file-directory-p name))
       (push name pending)
       (push name retval))))))
    (reverse retval)))
like image 40
Robert P. Goldman Avatar answered Sep 18 '22 12:09

Robert P. Goldman