emacs - 在项目中查找文件的相对路径

标签 emacs elisp

我的项目文件设置为这种格式:

/home/user/proj/source
/home/user/proj/source/src1
/home/user/proj/source/src1
/home/user/proj/header ...etc

查看任何源文件时我都有办法找到项目路径

"/home/user/proj"

另外,(buffer-file-name) 给出给定源文件的完整绝对路径。

如何编写一个lisp函数来提取源文件的相对路径?

意思是,如果我正在查看

/home/user/proj/source/src1/file.c

我想要路径

"source/src1/file.c"

以下函数为我提供了项目路径:

(defun upward-find-file (filename &optional startdir)
  (let ((dirname (expand-file-name
          (if startdir startdir ".")))
    (found nil) ; found is set as a flag to leave loop if we find it
    (top nil))  ; top is set when we get
            ; to / so that we only check it once
    ; While we've neither been at the top last time nor have we found
    ; the file.
    (while (not (or found top))
      ; If we're at / set top flag.
      (if (string= (expand-file-name dirname) "/")
      (setq top t))
      ; Check for the file
      (if (file-exists-p (expand-file-name filename dirname))
      (setq found t)
    ; If not, move up a directory
    (setq dirname (expand-file-name ".." dirname))))
    ; return statement
    (if found (concat dirname "/") nil)))

我在主项目文件夹中总是有“Makefile”,所以

(setq dirname (upward-find-file "Makefile" startdir))

照顾它。

最佳答案

试试 locate-domination-filefile-relative-name

(let ((fname (buffer-file-name)))
  (file-relative-name fname (locate-dominating-file fname "Makefile")))

注意locate-dominiating-file 如果找不到任何东西,则返回 nil

关于emacs - 在项目中查找文件的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18366839/

相关文章:

emacs - 如何用Emacs Calendar在Lisp中实现二十四节气

emacs - 将行号与linum-mode对齐?

elisp - 使用带引号的符号调用 defmacro

git - 在 git 中查看区域历史

emacs - 为有抱负的 Lisp 新手设置一个工作的 Common Lisp 环境

emacs - 为 emacs lisp 注册点击事件

emacs - Lisp:解码通用时间无效

emacs - Emacs中embedded-buffer-list frame参数的作用是什么

emacs - 在 emacs 或 org-mode 中打开 http 链接的键盘快捷键

python-3.x - 将 emacs python 模式解释器更改为 python3.5