how to get directory names under a path in Vim script?

淺唱寂寞╮ 提交于 2019-12-22 18:36:32

问题


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 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")')


来源:https://stackoverflow.com/questions/13902188/how-to-get-directory-names-under-a-path-in-vim-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!