问题
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 ??)
回答1:
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 toto/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
makeglob()
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, butglob()
outputs paths liketo/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")')
来源:https://stackoverflow.com/questions/13902188/how-to-get-directory-names-under-a-path-in-vim-script