Håkon Hægland
Håkon Hægland

Reputation: 40738

Emacs lisp regex to extract current relative path from buffer-file-name

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

Answers (2)

user355252
user355252

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

abo-abo
abo-abo

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

Related Questions