Search code examples
colorsluahexhighlightneovim

Programmatically Lighten or Darken a hex color in lua - nvim highlight colors


The goal is to programmatically change a hex colors brightness in lua.

This post contains several nice examples for js: Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I tried my luck to convert one of these functions, but I'm still pretty new to lua programming. It just needs to work with hex values, rgb or other variants are not needed. Therefore, I thought the "simpler" answers could serve as inspiration, but I still had no luck with it.

Eventually it shall be used to manipulate highlight colors in nvim. I'm getting the colorcodes with a function I wrote:

local function get_color(synID, what)
    local command = 'echo synIDattr(hlID("' .. synID .. '"),' .. '"' .. what .. '"' .. ')'
    return vim.api.nvim_command_output(command)
end

Solution

  • I wouldn't resort to bit ops in Lua 5.2 and lower, especially as Lua 5.1 lacks them (LuaJIT however does provide them); use multiplication, floor division & mod instead, and take care to clamp your values:

    local function clamp(component)
      return math.min(math.max(component, 0), 255)
    end
    function LightenDarkenColor(col, amt)
      local num = tonumber(col, 16)
      local r = math.floor(num / 0x10000) + amt
      local g = (math.floor(num / 0x100) % 0x100) + amt
      local b = (num % 0x100) + amt
      return string.format("%#x", clamp(r) * 0x10000 + clamp(g) * 0x100 + clamp(b))
    end