两个递归子目录函数的比较: Difference between revisions

From 清冽之泉
Jump to navigation Jump to search
Created page with "== ManateeLazycat 版 == <syntaxhighlight lang="bash" line> (require 'cl-lib) (defun add-subdirs-to-load-path (search-dir) (interactive) (let* ((dir (file-name-as-directory search-dir))) (dolist (subdir ;; 过滤出不必要的目录,提升Emacs启动速度 (cl-remove-if #'(lambda (subdir) (or ;; 不是目录的文件都移除 (not (file-directory-p (concat dir subd..."
 
No edit summary
Line 1: Line 1:
让 Emacs 自动把某个目录的子目录递归,还挺有意义的,免去手写 add-to-list 的麻烦。
== ManateeLazycat 版 ==
== ManateeLazycat 版 ==
<syntaxhighlight lang="bash" line>
<syntaxhighlight lang="bash" line>

Revision as of 00:31, 19 July 2026

让 Emacs 自动把某个目录的子目录递归,还挺有意义的,免去手写 add-to-list 的麻烦。

ManateeLazycat 版

(require 'cl-lib)

(defun add-subdirs-to-load-path (search-dir)
  (interactive)
  (let* ((dir (file-name-as-directory search-dir)))
    (dolist (subdir
             ;; 过滤出不必要的目录,提升Emacs启动速度
             (cl-remove-if
              #'(lambda (subdir)
                  (or
                   ;; 不是目录的文件都移除
                   (not (file-directory-p (concat dir subdir)))
                   ;; 父目录、 语言相关和版本控制目录都移除
                   (member subdir '("." ".." 
                                    "dist" "node_modules" "__pycache__" 
                                    "RCS" "CVS" "rcs" "cvs" ".git" ".github")))) 
              (directory-files dir)))
      (let ((subdir-path (concat dir (file-name-as-directory subdir))))
        ;; 目录下有 .el .so .dll 文件的路径才添加到 `load-path' 中,提升Emacs启动速度
        (when (cl-some #'(lambda (subdir-file)
                           (and (file-regular-p (concat subdir-path subdir-file))
                                ;; .so .dll 文件指非Elisp语言编写的Emacs动态库
                                (member (file-name-extension subdir-file) '("el" "so" "dll"))))
                       (directory-files subdir-path))

          ;; 注意:`add-to-list' 函数的第三个参数必须为 t ,表示加到列表末尾
          ;; 这样Emacs会从父目录到子目录的顺序搜索Elisp插件,顺序反过来会导致Emacs无法正常启动
          (add-to-list 'load-path subdir-path t))

        ;; 继续递归搜索子目录
        (add-subdirs-to-load-path subdir-path)))))

(add-subdirs-to-load-path (expand-file-name "travel" user-emacs-directory))

Emacs 原生版

(let ((dir (locate-user-emacs-file "travel")))
  (make-directory dir t)
  (add-to-list 'load-path dir)
  (let ((default-directory dir))
    (normal-top-level-add-subdirs-to-load-path)))

比较