Emacs lisp regex从buffer-file-name中提取当前相对路径



我试图从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将给定的文件名转换为相对于该目录的文件名。

相关内容

  • 没有找到相关文章

最新更新