Search code examples
vimcolor-scheme

Vim: How to assign a colorscheme at random from a selected list?


I have some colorschemes that I really like. I also find changing between them adds some freshness to my work. I've been changing manually for a while, but would love to automate this.

I'd like to put a line in my .vimrc that assigns a random colorscheme from a pre-defined allowlist. I googled around and didn't find obvious answers, and even some debate about whether there's even a random function in vimscript.

I don't know much vimscript, and though I've read the basics here and there over the years, I don't have a working knowledge of it because I rarely use it. So I thought I'd reach out to the community. I tried to do this myself after some reasearch, but the following code fails:

let my_colorschemes = ['torte', 'Dark2' , 'ubloh']
colorscheme my_colorschemes[rand() % (len(my_colorschemes) - 1 ) ]
Cannot find color scheme 'my_colorschemes[rand() % (len(my_colorschemes)+ 1 ) ]'

Can anyone help me get this right? There seems to be some fundamental concepts I'm missing in vimscript...

Thanks!

-------- UPDATE ---------

For posterity, after the correct answer below, the code that works for me is:

let my_colorschemes = ['torte', 'Dark2' , 'ubloh', 'znake']
execute 'colorscheme' my_colorschemes[rand() % (len(my_colorschemes) - 1 ) ]

I guess I was close, but there's no way I would have come up with what was wrong on my own.


Solution

  • Vim bits are explained in User Manual (:h user-manual). The relevant chapter 41 "Write a Vim script" (:h usr_41.txt), section 41.5 (:h 41.5).

    To put it short, only few commands accept expressions, while others accept only literal arguments (btw. this is the reason one writes :colo torte and not :colo "torte"). Therefore to compose a command dynamically one needs both to build a string representation of a command and to re-evaluate it.

    So it becomes :execute 'colo' my_colors[rand() % len(my_colors)]