Emacs Lisp: How to add a folder and all its first level sub-folders to the load-path

99封情书 提交于 2019-11-28 20:40:48
(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)))))

Here's something I use in my .emacs:

(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))

If you look at the description for normal-top-level-add-subdirs-to-load-path, it's somewhat smart about picking which directories to exclude.

I suggest you to use subdirs.el

This is my hacked up version :P

(defun add-to-list-with-subdirs (base exclude-list include-list)
  (dolist (f (directory-files base))
 (let ((name (concat base "/" f)))
   (when (and (file-directory-p name)
     (not (member f exclude-list)))
  (add-to-list 'load-path name)
  (when (member f include-list)
   (add-to-list-with-subdirs name exclude-list include-list)))))
  (add-to-list 'load-path base))

This will add all first level dirs from base and exclude the ones in exclude-list, while for the dirs in include-list, it will add all the first level dirs of that dir too.

(add-to-list-with-subdirs "~/.emacs.d" '("." ".." "backup") '("vendor" "my-lisp"))

This function will map over first level sub-folders and files in BASE-PATH and add it to the LOAD-LIST if it's a directory (excluding directories "." and "..").

(defun add-subdirs-to-load-path (base-path)
  "Adds first level subfolders to LOAD-PATH.
BASE-PATH must not end with a '/'"
  (mapc (lambda (attr)
          (let ((name (car attr))
                (folder-p (cadr attr)))
            (unless (or (not folder-p)
                        (equal name ".")
                        (equal name ".."))
              (add-to-list 'load-path (concat base-path "/" name)))))
        (directory-files-and-attributes base-path)))

Install dash and f third-party libraries. Your needed function is f-directories:

(f-directories "~/YOURDIR") ; return only immediate directories
(f-directories "~/YOURDIR" nil t) ; all directories recursively

Then use --each to add each found directory to load-path. This whole operation works in O(n²), but as load-path is usually super-small, who cares.

(add-to-list 'load-path "~/YOURDIR") ; your parent folder itself
(--each (f-directories "~/YOURDIR") (add-to-list 'load-path it))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!