Brandon
Brandon

Reputation: 39

How to run a Vimscript (.vim) file from a different directory?

I have created two short .vim files to quickly switch between some configurations and placed them in ~/.vim

If I start vim from ~/.vim and do :run write.vim or :run code.vim, they work fine, but if I start vim from anywhere else (e.g. ~/) and try :run .vim/write.vim (from ~/) or :run ~/.vim/write.vim (from anywhere else), it won't run. Any ideas why?

For completeness' sake, I have put in both .vim files.

write.vim

colorscheme pencil
set background=light
set colorcolumn=0
set wrap
set nonumber

code.vim

colorscheme tomorrow-night-eighties
set background=dark
set colorcolumn=100
highlight ColorColumn ctermbg=darkgrey
set nowrap
set number

Upvotes: 0

Views: 377

Answers (1)

Luc Hermitte
Luc Hermitte

Reputation: 32966

You should read :runtime and 'runtimepath' documentation -> :h :runtime, :h 'runtimepath'.

You'll then see that you actually want to execute either :so ~/.vim/sub/path.vim or :runtime sub/path.vim in your case. See also: What's the difference between ':source file' and ':runtime file' in vim?

Note by the way that ~/.vim/macros/ is best suited for this -- even if nobody uses it any more. Or even better, you could put your definitions in a function and trigger them on a key binding

function! s:toggle_settings() abort
  let s:writing = 1 - get(s:, 'writing', 0)
  if s:writing
    colorscheme pencil
    set background=light
    set colorcolumn=0
    set wrap
    set nonumber
  else
    ...
  endif
endfunction

nnoremap µ :call s:toggle_settings()<cr>

You could also detect that the current &filetype is not related to a programming language, and then use autocommands

  1. to switch the configuration of 'colorcolumn', 'wrap' and 'number' at buffer level (with :setlocal -- you don't want to use :set as you are at the moment).
  2. to toggle the configuration of your colorscheme every time you change windows, if need be. But this way of proceeding can be quite aggressive, switching on demand is probably more ergonomic.

Upvotes: 4

Related Questions