Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to join multiple path components into a single complete path in emacs lisp?

Suppose I have variables dir and file containing strings representing a directory and a filename, respectively . What is the proper way in emacs lisp to join them into a full path to the file?

For example, if dir is "/usr/bin" and file is "ls", then I want "/usr/bin/ls". But if instead dir is "/usr/bin/", I still want the same thing, with no repeated slash.

like image 663
Ryan C. Thompson Avatar asked Oct 19 '10 01:10

Ryan C. Thompson


2 Answers

Reading through the manual for Directory Names, you'll find the answer:

Given a directory name, you can combine it with a relative file name using concat:

 (concat dirname relfile)

Be sure to verify that the file name is relative before doing that. If you use an absolute file name, the results could be syntactically invalid or refer to the wrong file.

If you want to use a directory file name in making such a combination, you must first convert it to a directory name using file-name-as-directory:

 (concat (file-name-as-directory dirfile) relfile) 

Don't try concatenating a slash by hand, as in

 ;;; Wrong!
 (concat dirfile "/" relfile) 

because this is not portable. Always use file-name-as-directory.

Other commands that are useful are: file-name-directory, file-name-nondirectory, and others in the File Name Components section.

like image 62
Trey Jackson Avatar answered Nov 15 '22 14:11

Trey Jackson


You can use expand-file-name for this:

(expand-file-name "ls" "/usr/bin")
"/usr/bin/ls"
(expand-file-name "ls" "/usr/bin/")
"/usr/bin/ls"

Edit: this only works with absolute directory names. I think Trey's answer is the preferable solution.

like image 32
Hugh Avatar answered Nov 15 '22 16:11

Hugh