我试图从buffer-file-name
变量中提取相对于主目录的当前目录。考虑:
(defun test ()
(interactive)
(let ((fn "/home/user/dir1/dir2/file.txt"))
(when (string-match "^.*?/user/" fn)
(let ((temp (replace-match "${HOME}/" nil nil fn)))
(when (string-match "/.*?$" temp)
(message (replace-match "/" nil nil temp)))))))
这里我想得到${HOME}/dir1/dir2/
,但我得到了${HOME}/
。我遗漏了什么?
试试这个:
(let ((str "/home/user/dir1/dir2/file.txt"))
(when (string-match "^.*?/user/" str)
(file-name-directory (replace-match "${HOME}/" nil nil str))))
使用file-relative-name
:
(concat "$HOME/" (file-relative-name (buffer-file-name) (expand-file-name "~")))
(expand-file-name "~")
给出了当前用户的主目录。然后file-relative-name
将给定的文件名转换为相对于该目录的文件名。