两个递归子目录函数的比较: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
| (2 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
让 Emacs 自动把某个目录的子目录递归,还挺有意义的,免去手写 add-to-list 的麻烦。 | 让 Emacs 自动把某个目录的子目录递归,还挺有意义的,免去手写 add-to-list 的麻烦。 | ||
__TOC__ | |||
== ManateeLazycat 版 == | == ManateeLazycat 版 == | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="elisp" line> | ||
(require 'cl-lib) | (require 'cl-lib) | ||
| Line 41: | Line 41: | ||
== Emacs 原生版 == | == Emacs 原生版 == | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="elisp" line> | ||
(let ((dir (locate-user-emacs-file "travel"))) | (let ((dir (locate-user-emacs-file "travel"))) | ||
(make-directory dir t) | (make-directory dir t) | ||
| Line 52: | Line 52: | ||
{| class="wikitable" | {| class="wikitable" | ||
!功能 | !功能 | ||
! | !<code>add-subdirs-to-load-path</code> | ||
!Emacs 自带 | !Emacs 自带 | ||
|- | |- | ||
Latest revision as of 00:34, 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)))
比较
| 功能 | add-subdirs-to-load-path
|
Emacs 自带 |
|---|---|---|
| 递归扫描子目录 | ✅ | ✅ |
自动加入 load-path
|
✅ | ✅ |
跳过 .git、.github
|
✅ 手写排除 | ✅ 因为只处理字母或数字开头的目录 |
跳过 RCS、CVS
|
✅ | ✅ |
跳过 node_modules
|
✅ | ❌ |
跳过 dist
|
✅ | ❌ |
跳过 __pycache__
|
✅ | ✅ 实际上 _ 开头不会进入
|
只加入含 .el/.so/.dll 的目录
|
✅ | ❌ |
支持 .nosearch 控制不扫描
|
❌ | ✅ |
需要 cl-lib
|
✅ | ❌ |
| 自己维护代码 | ✅ | ❌ |
| Emacs 原生 | ❌ | ✅ |