【问题标题】:Walk up the directory tree向上走目录树
【发布时间】:2012-12-30 22:10:02
【问题描述】:

文件树如下:

- foo
  - lorem
    - ipsum <-
  - baz <-
- bar
- baz

当前访问的文件是ipsum。现在我想找到第一个 baz 和它所在的目录。我如何从树上走 ipsum 在 elisp 中?

【问题讨论】:

  • "First" 是模棱两可的,不是在这个例子中,而是一般情况下。如果有多个,我们应该选择一个子节点、父节点还是兄弟节点之一?

标签: elisp


【解决方案1】:

你想要locate-dominating-file

【讨论】:

  • 看起来不错,只是它似乎不接受通配符。我正在寻找具有给定扩展名的文件。
  • 实际上,在最近的 Emacs 版本中,它接受一个函数作为参数,所以它可以肯定地做通配符的事情(通过directory-files)。
  • (locate-dominating-file DIR (lambda (parent) (directory-files parent nil "\\(GNU\\)?[Mm]akefile")))
【解决方案2】:
(defun parent-directory (dir)
  (unless (equal "/" dir)
    (file-name-directory (directory-file-name dir))))

(defun find-file-in-heirarchy (current-dir fname)
  "Search for a file named FNAME upwards through the directory hierarchy, starting from CURRENT-DIR" 
  (let ((file (concat current-dir fname))
        (parent (parent-directory (expand-file-name current-dir))))
    (if (file-exists-p file)
        file
      (when parent
        (find-file-in-heirarchy parent fname)))))

如果结果不是 nil,你可以使用 file-name-directory 提取文件的目录,如下所示:

(let ((file (find-file-in-heirarchy (buffer-file-name) "baz")))
  (when file
    (file-name-directory file)))

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2021-07-13
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多