I want a simple solution to get directory names under a path in vim script.

Here is my tried ways: the code. https://gist.github.com/4307744 Function is at line L84.

I use this function as complete function for input(). So this function need to return a list of directory names under a path. e.g.

to/path/
        - a/
        - b/

I want to get a and b.

I tried to find vim internal functions with :help functions. only found globpath(), but it will return full path.

So does anyone have a simple solution ? (BTW, why it is so hard to get directory names under a path in Vim ??)

share|improve this question
    
What do you want to do with those names? You can always do a substitute to trim those full paths. – romainl Dec 16 '12 at 15:42
2  
@romainl Don’t do substitute() for path manipulations, it is hard to get it right, simple and portable at the same time. There is fnamemodify() for this. – ZyX Dec 17 '12 at 4:33
up vote 7 down vote accepted

I don’t know whether it was intentional or not, but glob() limits directories only to those with paths if pattern ends with /:

let directories=glob(fnameescape(top_directory).'/{,.}*/', 1, 1)
call map(directories, 'fnamemodify(v:val, ":h:t")')

. Some explanations:

  • fnameescape() escapes top_directory (it should be set to to/path in the example) in order to prevent special characters in it from being expanded on their own (I once used to have directory named *.*).
  • {,.} is necessary because on unix vim won’t list files starting with dot by default. Note that normally .* pattern matches special . and .. directories that are then removed, but due to some reason {,.}* does not match them.
  • , 1, 1 make glob() ignore 'suffixes' and 'wildignore' options (first) and return a list (second, requires most recent vim).
  • Last (second) line is for keeping only directory names as you requested. Normally :h:t would return only parent directory name, but glob() outputs paths like to/path/a/ and :h thus removes only the trailing slash. :t strips directory path (returns trailing path component). Without :h stripping slash trailing path component would be empty string.

You can join everything into one line:

let directories=map(glob(fnameescape(top_directory).'/{,.}*/', 1, 1), 'fnamemodify(v:val, ":h:t")')
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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