10

I want to do the same thing as the bash dirname command or python os.path.split()[0] in vimscript for any path string (not necessarily the path of the current file).

Sample desired behaviour:

  • /a/b/ -> /a
  • /a/b -> /a

I have tried fnamemodify() but to me its output seems to depend on whether dirs exist or not:

:ec fnamemodify( '/usr/idontexist', ':p:h')

gives:

/usr

which is good, but:

:ec fnamemodify( '/usr/bin', ':p:h')

gives:

/usr/bin

which is not what I want, and I can't figure out what it is doing.

I hope to find a cross platform solution.

2 Answers 2

20

have you read this part of the description of :h:

 When the file name ends in a path separator, only the path
            separator is removed. Thus ":p:h" on a directory name results
        on the directory name itself (without trailing slash).

that's the reason of:

:ec fnamemodify( '/usr/bin/', ':p:h')  "directory, ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin/', ':h')  "directory, ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin', ':p:h')  "directory, not ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin', ':h')  "directory, not ending with /
-> /usr

so there are two factors to decide the output.

  • if your string ending with separator
  • if you used :p

to achieve your goal, you may remove the last char if the string is ending with / (or \ in win?), then pass to the function without :p

2
  • I think this was not the origin of my problem, but I was asking myself that anyways, so +1. what a complicated behaviour... May 10, 2013 at 16:14
  • take my last comment back, this was the main cause of my problem! using :p is the problem not only because the dir may not exist, but because using :p:h does not do what I want. The fact that :p removed the idontexist part and seemed to do what I wanted falls inside undefined behaviour, and only confused me. May 11, 2013 at 5:33
5
fnamemodify( '/usr/idontexist', ':h')

The :p modifier will expand a path to a full path. Therefore it must be a real path. Just don't use :p if you are not messing with real paths.

See

:h filename-modifiers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.