Skip to content

Instantly share code, notes, and snippets.

@jfcherng
Last active December 7, 2023 07:27
Show Gist options
  • Save jfcherng/3e2d2acadc91962ded6379ed2884aa7f to your computer and use it in GitHub Desktop.
Save jfcherng/3e2d2acadc91962ded6379ed2884aa7f to your computer and use it in GitHub Desktop.
ColorHelper custom color parsing for .lsx files
// file: Packages/User/color_helper.sublime-settings
{
"user_color_classes": {
"srgb_norm": {
"class": "ColorHelper.custom.srgb_norm.ColorSrgbNorm",
"filters": ["srgb"],
"output": [
{"space": "srgb", "format": {"precision": 6}},
],
},
},
"user_color_rules": [
{
"name": "XML", // overwrites the built-in "XML" color rule
"base_scopes": ["text.xml"],
"color_class": "srgb_norm",
"scanning": [
"text.xml meta.tag",
],
"color_trigger": "(?<=value=\")(?=[\\d.]+\\s+[\\d.]+\\s+[\\d.]+)",
},
],
}
# file: Packages/ColorHelper/custom/srgb_norm.py
import re
from ColorHelper.ch_util import get_base_color
from ..lib.coloraide.spaces.srgb.css import sRGB
MATCH = re.compile(
r"""
(?P<r>\d+(?:\.\d+)?)\s+
(?P<g>\d+(?:\.\d+)?)\s+
(?P<b>\d+(?:\.\d+)?)
""",
re.VERBOSE,
)
class SrgbNorm(sRGB):
@classmethod
def match(cls, string: str, start: int = 0, fullmatch: bool = True):
"""Match and parse a color string."""
m = MATCH.match(string, start)
if not m or (fullmatch and m.end(0) != len(string)):
return None
r, g, b, a = map(float, m.groups()), 1.0
return ((r, g, b), a), m.end(0)
@classmethod
def to_string(cls, parent, *, precision=6):
"""Output color in `R G B` form."""
def handle_coord(val: float):
val = round(val, precision)
return int(val) if val.is_integer() else val
coords = parent.clone().coords(nans=False)
return "{r} {g} {b}".format_map(
dict(
zip(
("r", "g", "b"),
map(handle_coord, coords),
)
)
)
class ColorSrgbNorm(get_base_color()):
pass
ColorSrgbNorm.register(SrgbNorm(), overwrite=True)
@TechRoot
Copy link

TechRoot commented Dec 6, 2023

Hey!

ColorHelper got Updated to cover a solved bug documented on facelessuser/ColorHelper#260
It seems that this code may need also an update?

Thank you so much for your work, your code solved a lot of problem on my end on the last months.

@jfcherng
Copy link
Author

jfcherng commented Dec 7, 2023

ColorHelper got Updated to cover a solved bug documented on facelessuser/ColorHelper#260 It seems that this code may need also an update?

That looks like I don't have to do anything.

@TechRoot
Copy link

TechRoot commented Dec 7, 2023

Issue then must be elsewhere and i should apologize.
I beg you pardon, and thank you again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment