Search code examples
vim

Suggested way to join filepaths in vim


In python I will often do something like:

os.path.join('/some/path/', 'something', 'file.mov')

Or it can be done using Path(...). What's the suggested way to do this in vim? For example, here is the way I'm currently creating a log file in the same directory as the script:

let log_file = expand('%:p:h') . '/file.log'

Is there a better way to do this?


Solution

  • I've a lh#path#join() function in my library, but honestly... I never use it. In the end, it always comes down to string concatenation, and / always works, even on Windows. When I need to interact with external processes, I have other functions that correctly protect pathnames.

    " Function: lh#path#join(pathparts, {path_separator}) {{{3
    function! lh#path#join(pathparts, ...) abort
      let sep
            \ = (a:0) == 0                       ? '/'
            \ : type(a:1)==type(0) && (a:1) == 0 ? '/'
            \ : (a:1) == 1                       ? '\'
            \ : (a:1) =~ 'shellslash\|ssl'       ? (&ssl ? '\' : '/')
            \ :                                    (a:1)
      return join(a:pathparts, sep)
    endfunction