gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:50:19 25 4
gpt4 key购买 nike

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

/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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com