如何在Vim脚本中的路径下获取目录名? [英] how to get directory names under a path in Vim script?

查看:687
本文介绍了如何在Vim脚本中的路径下获取目录名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的解决方案来获取vim脚本中路径下的目录名。

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

这是我尝试的方法:代码。 https://gist.github.com/4307744
功能在L84行。

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

我将此函数用作input()的完整函数。
所以这个函数需要返回一个路径下的目录名称列表。
例如

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/

我想获得 a b

我试图用找到vim内部函数:help functions 。只发现 globpath(),但它将返回完整路径。

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

有没有人有一个简单的解决方案?
(BTW,为什么很难在Vim中的路径下获取目录名?)

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

推荐答案

不知道是否是有意的,但是 glob()仅限于具有路径的目录,如果模式以 /

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

。一些解释:


  • fnameescape()转义top_directory(应该设置为 to / path 在示例中),以防止其中的特殊字符自己扩展(我曾经使用名为 *的目录* )。

  • {,。} 是必要的,因为在unix vim不会列出以点默认。请注意,通常。* 模式匹配特殊 .. 目录,然后删除,但由于某些原因 {,。} * 不匹配。

  • ,1,1 make glob() ignore 'suffixes''wildignore'选项(第一个)并返回列表(第二个,需要最新的vim)。

  • 最后(第二行)只有您要求的目录名称。通常:h:t 将只返回父目录名称,但 glob()输出路径,如到/ path / a / :h 因此只删除尾部斜杠。 :t strips目录路径(返回尾随路径组件)。没有:h 剥离斜杠尾随路径组件将为空字符串。

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

这篇关于如何在Vim脚本中的路径下获取目录名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆