12

I am trying to rewrite adding a string to option with variable. The original string is

set rtp+=~/.vim/bundle/Vundle.vim

The following is the working let way:

let MYVIMDIR='/home/loom/foo'
let &rtp .= ','.expand(MYVIMDIR).'/bundle/Vundle.vim'

I am interested how rewrite it with set. The following code (and some other variations) doesn't work

let MYVIMDIR='/home/loom/foo'
set rtp+=expand(MYVIMDIR).'/bundle/Vundle.vim'

What is the right way to use variables in expression with set?

2 Answers 2

16

You could use :exe, but this is extremely cumbersome to use and you'll need to escape a few things.

I used to use my own path fixing function. It looked like:

exe 'set rtp+='.lh#path#fix(somevariable)
" with standard tools, may be it'd be (untested)
exe 'set rtp+='.escape(somevariable, ' \|,')

let &rtp = expression is really our friend.

But indeed, it doesn't play well with +=. That's why I've came up with lh#path#munge() that relies on another function lh#list#add_if_new(). Strictly speaking set += is emulated by lh#list#add_if_new(). munge() keeps pathnames that do exist, or actually globbing patterns that match things.

" Function: lh#path#munge(pathlist, path) {{{3
function! lh#path#munge(pathlist, path) abort
  if type(a:pathlist) == type('str')
    let pathlist = split(a:pathlist, ',')
    return join(lh#path#munge(pathlist, a:path), ',')
  else
    " if filereadable(a:path) || isdirectory(a:path)
    if ! empty(glob(a:path)) " support '/**' for &tags
      call lh#list#push_if_new(a:pathlist, a:path)
    endif
    return a:pathlist
  endif
endfunction

" Function: lh#list#push_if_new(list, value) {{{3
function! lh#list#push_if_new(list, value) abort
  if index(a:list, a:value) < 0
    call add (a:list, a:value)
  endif
  return a:list
endfunction

They are defined and maintained in lh-vim-lib.

1
  • 1
    you also need to escape commas in the :set call Mar 1, 2018 at 11:46
9

You could use an environment variable defined within your current shell session.

let $myvimdir = '/home/abc/vimfiles'

That way you can use other variables to compose the path as well:

let $myvimdir = $HOME.'/vimfiles'

And set the runtime path:

set rtp+=$myvimdir/bundle/Vundle.vim

More information on environment variables within vim :help expr-env

2
  • 1
    Interesting. But when I try with let $nts | set ts=$nts, vim does not like it.
    – tivn
    Sep 22, 2018 at 13:54
  • It's because environment variables are stored as strings and tabstop is expecting a number.
    – iznav
    Sep 24, 2018 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.