Reputation: 40738
I am trying to extract the current directory relative to the home directory from the buffer-file-name
variable. Consider:
(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)))))))
Here I would like to get ${HOME}/dir1/dir2/
but instead I get ${HOME}/
. What am I missing here?
Upvotes: 2
Views: 689
Reputation:
Use file-relative-name
:
(concat "$HOME/" (file-relative-name (buffer-file-name) (expand-file-name "~")))
(expand-file-name "~")
gives the home directory of the current user. file-relative-name
then converts the given file name into a file name relative this directory.
Upvotes: 2
Reputation: 20342
Try this:
(let ((str "/home/user/dir1/dir2/file.txt"))
(when (string-match "^.*?/user/" str)
(file-name-directory (replace-match "${HOME}/" nil nil str))))
Upvotes: 2