展开包含文件的相对路径wrt

时间:2014-04-04 10:38:31

标签: vim

我正在使用Vimscript阅读配置文件foo.yml。此文件包含一个参数,该参数是目录的相对路径。此pathfoo.yml文件相关,而不是我当前的工作目录。

我需要将此相对路径扩展为绝对路径。

我尝试过使用fnamemodify(path, ':p')expand(path)但没有运气。我认为这些函数似乎很混乱,因为从当前工作目录中相对路径无效。所以它保持原样。

有没有办法让Vim在解析相对路径时使用foo.yml作为参考点?或任何其他可以做同样的功能?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

为了相对于文件目录进行扩展,最简单地:cd进入该目录。这是为当前文件(%)执行此操作的示例代码;你必须调整它以使用传递的文件规范。

if expand('%:h') !=# '.'
    " Need to change into the file's directory first to get glob results
    " relative to the file.
    let l:save_cwd = getcwd()
    let l:chdirCommand = (haslocaldir() ? 'lchdir!' : 'chdir!')
    execute l:chdirCommand '%:p:h'
endif
try
    " Get the full path to a:filespec, relative to the current file's directory.
    let l:absoluteFilespec = fnamemodify(a:filespec, ':p')
finally
    if exists('l:save_cwd')
        execute l:chdirCommand fnameescape(l:save_cwd)
    endif
endtry

答案 1 :(得分:1)

怎么样

:let dir = expand('%:p:h')
:let absolute_path = dir . '/' . path

如果您希望它在Windows上运行,您将不得不更加努力。

:help expand()
:help filename-modifiers
:help file-functions
相关问题