vimvim-plugin

Variables in Vim Plugin


I write a vim plugin to learn some vimscript. I set the variables in the /autoload/plugin.vim like this:

let g:configpath = '~/home/username/.vim/bundle/testplugin/templates/'
let g:config = '/config.h'

Then I want to use it within a function:

function! testplugin#template(...)
    :e g:configpath  . a:1 . g:config   
endfunction

The goal is to open the file behind this path. a:1 is a user-given input because the subfolder is selectable by the user.

When I use echo g:configpath . a:1 . g:config the correct path will be print out to Vim but when I use :e to open the file Vim open a new file with the name:

"g:configpath . a:1 . g:config" [New]

How do I open the template file behind this path?


Solution

  • :help :echo and :help :edit_f handle arguments differently.

    The former expects an expression, which is evaluated at runtime to produce the text that will be echoed:

    :let $FOO = 'foo'
    :let g:bar = 'bar'
    :echo $FOO .. g:bar .. 'baz' .. eval('1+2')
    foobarbaz3
    

    The latter also does some evaluation but it is limited to expanding environment variables and the items documented under :help cmdline-special. Most notably it can't do concatenation:

    :let $DIR = '/path/to/dir'
    :edit $DIR/filename
    :edit %<.stories.ts
    

    If you want to build the filename programmatically, you have two options.

    FWIW, autoloaded scripts don't seem to be the right place for defining global options. They are usually defined in plugin/foo.vim.