Posted on :: Tags: , , , ,

I decided I needed a random colorscheme selector for those moments when you want to change things up but don’t want to make a specific choice. LazyVim already has <leader>uC for selecting a colorscheme, but it can be too mentally taxing as it requires you to manually select one. This script simply switches to a random one.

RandomColorScheme returns the name of a random colorscheme after searching through all available paths. SetRandomColorScheme sets the colorscheme to that choice. The keybinding is mapped to <leader>uR.

function RandomColorScheme()
  local color_schemes = vim.fn.globpath(vim.o.rtp, "colors/*.vim", false, true)
  for i, fullpath in ipairs(color_schemes) do
    color_schemes[i] = fullpath:match(".*/(.*).vim$")
  end

  -- Generate a random index
  local index = math.random(#color_schemes)

  local random_color_scheme = color_schemes[index]

  vim.notify("Random Color Scheme: " .. random_color_scheme)
  -- Select a random color scheme
  return random_color_scheme
end

function SetRandomColorScheme()
  vim.cmd("colorscheme " .. RandomColorScheme())
end

vim.api.nvim_set_keymap("n", "<leader>uR", ":lua SetRandomColorScheme()<CR>", { noremap = true, silent = true })