Thomas Browne
Thomas Browne

Reputation: 24898

How do I activate a colorscheme when I load a specific file in vim

I have a number of R and Python files, all of which I work on at the same time. I prefer to have different colorschemes, not only for different filetypes, but for different files even of the same type. This is so that I can locate them easily on my screen, and quickly shift my mind from one piece of code to another. Can I do this automatically in my vimrc? The filetype variable is not what I am looking for as there are already several answers to that particular question. I want to change colorschemes based on file*name*.

For example, one file could be called bbg.r, whereas another might be called fx.r. Note that it's not the extension I'm interested in changing the colorscheme for, it is for the individuals files, so the above two files should invoke different color schemes.

Upvotes: 1

Views: 316

Answers (2)

romainl
romainl

Reputation: 196516

You have two general mechanisms for setting specific things for specific filetypes:

  • autocommands, see :help autocmd,

  • ftplugins, see :help ftplugin.

However, they won't be of any help, here, because

Vim can only have one colorscheme active at a time.

On the other hand, if you use separate instances, you can perfectly have different colorschemes. If that's the case, you can do something like:

function! FTColors()
    if &filetype == "python"
        colorscheme foo
    elseif &filetype == "r"
        colorscheme bar
    else
        colorschem baz
    endif
endfunction

autocmd BufNew,BufEnter * call FTColors()

or:

autocmd BufNew,BufEnter * colorscheme baz
autocmd BufNew,BufEnter *.py colorscheme foo
autocmd BufNew,BufEnter *.r colorscheme bar

(not thoroughly tested)

Upvotes: 1

FDinoff
FDinoff

Reputation: 31419

Color schemes are loaded for all buffers but if you just want to load a certain color scheme when the buffer is loaded for sagb.r you could use the following colorscheme.

autocmd BufEnter sagb.r colorscheme <colorscheme_name>

And then if you wanted to reset the colorscheme to the default one when you leave the buffer you could use

autocmd BufLeave sagb.r colorscheme <default_colorscheme>

In general

autocmd BufEnter <filename> colorscheme <colorscheme_for_file>
autocmd BufLeave <filename> colorscheme <default_colorscheme>

Upvotes: 2

Related Questions