In Elisp, how to get path string with slash properly inserted?

后端 未结 6 865
闹比i
闹比i 2021-01-02 05:46

I am manually constructing path strings in Elisp by concatenating partial paths and directory names. Unfortunately sometimes the paths end with slash, sometimes not. Theref

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 06:44

    (file-name-as-directory dir) will return directory path dir with a trailing slash, adding one if necessary, and not otherwise.

    If you had your sequence of partial paths in a list, you could do something like:

    (let ((directory-list '("/foo" "bar/" "p/q/" "x/y"))
          (file-name "some_file.el"))
      (concat
       (mapconcat 'file-name-as-directory directory-list "")
       file-name))
    
    "/foo/bar/p/q/x/y/some_file.el"
    

    or as an alternative, if you wanted to include the file name in the list, you could utilise directory-file-name which does the opposite of file-name-as-directory:

    (let ((path-list '("/foo" "bar/" "p/q/" "x/y/some_file.el")))
      (mapconcat 'directory-file-name path-list "/"))
    
    "/foo/bar/p/q/x/y/some_file.el"
    

    (Someone please correct me if using directory-file-name on a non-directory is not portable?)

提交回复
热议问题