I want to use get with the environment variable namespace, so instead of this in the global namespace:

let vim_data_dir = get(g:, 'vim_data_dir', "default value if not set")

Something like this, in the $ or environment variable namespace:

let $VIM_DATA_DIR = get($, 'VIM_DATA_DIR', "default value if not set")

The help says that the first parameter to get is a list. How do I get all environment variables as a list?


In that case, you could simply use the good old exists()

:let foo = exists('$FOO') ? $FOO : 'default'

There is also empty(), IMO it only makes sense if you want to undefine environment variables from within Vim. Indeed, as :unlet $FOO isn't possible, yet, we have to use :let $FOO=''

To obtain all environment variables, you could use getcompletion() on recent vim versions. The latest version of my obtain-whatever function looks like this:

" Function: lh#command#matching_askvim(what, lead) {{{3
if exists('*getcompletion')
  function! lh#command#matching_askvim(what, lead) abort
    return getcompletion(a:lead, a:what)
  function! lh#command#matching_askvim(what, lead) abort
    let cleanup = lh#on#exit()
          \.register('delcom LHAskVimMatchingCompletion')
      exe 'command! -complete='.a:what.' -nargs=* LHAskVimMatchingCompletion :echo "<args>"'
      if exists('*getcmdline')
        call cleanup
              \.restore_buffer_mapping('?', 'c')
              \.restore_mapping_and_clear_now('<c-a>', 'c')
        cnoremap <buffer> <expr> ? s:register()
        function! s:register()
          let g:cmds = split(getcmdline(), ' ')[1:]
          return ''
        silent! exe "norm :LHAskVimMatchingCompletion ".a:lead."\<c-a>?"
        return g:cmds
        " The following may lead to problem with unescaped quotes => use
        " getcmdline() when available
        silent! exe "norm! :LHAskVimMatchingCompletion ".a:lead."\<c-a>\"\<home>let\ cmds=\"\<cr>"
        return split(cmds, ' ')[1:]
      call cleanup.finalize()

(It's complex in order to support mappings as well)

To obtain all environment variables, you can then use: echo lh#command#matching_askvim('environment', '')

| improve this answer | |

$VIM_DATA_DIR already gives you the environment variable, so you can do

let $VIM_DATA_DIR = !empty($VIM_DATA_DIR) ? $VIM_DATA_DIR : "default"

If you really need all environment variables take a look at this answer on stackoverflow:

function! Env()
    redir => s
    sil! exe "norm!:ec$\<c-a>'\<c-b>\<right>\<right>\<del>'\<cr>"
    redir END
    return split(s)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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