Skip to content

Commit 42a8655

Browse files
committed
Introduce recolouring hooks
1 parent a05c0d0 commit 42a8655

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

docs/src/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,4 +342,5 @@ StyledStrings.parse(::Type{StyledStrings.SimpleColor}, ::String)
342342
StyledStrings.tryparse(::Type{StyledStrings.SimpleColor}, ::String)
343343
StyledStrings.merge(::StyledStrings.Face, ::StyledStrings.Face)
344344
StyledStrings.blend(::StyledStrings.SimpleColor, ::StyledStrings.SimpleColor, ::Real)
345+
StyledStrings.recolor
345346
```

src/StyledStrings.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ using Base.ScopedValues: ScopedValue, with, @with
99
export AnnotatedString, AnnotatedChar, AnnotatedIOBuffer, annotations, annotate!, annotatedstring
1010

1111
export @styled_str
12-
public Face, addface!, withfaces, styled, SimpleColor, blend
12+
public Face, addface!, withfaces, styled, SimpleColor, blend, recolor
1313

1414
include("faces.jl")
1515
include("io.jl")

src/faces.jl

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,46 @@ function Base.convert(::Type{Face}, spec::Dict{String,Any})
763763
end)
764764
end
765765

766+
## Recolouring ##
767+
768+
const recolor_hooks = Function[]
769+
const recolor_lock = ReentrantLock()
770+
771+
"""
772+
recolor(f::Function)
773+
774+
Register a hook function `f` to be called whenever the colors change.
775+
776+
Usually hooks will be called once after terminal colors have been
777+
determined. These hooks enable dynamic retheming, but are specifically *not* run when faces
778+
are changed. They sit in between the default faces and modifications layered on
779+
top with `loadface!` and user customisations.
780+
"""
781+
function recolor(f::Function)
782+
@lock recolor_lock push!(recolor_hooks, f)
783+
nothing
784+
end
785+
786+
function setcolors!(color::Vector{Pair{Symbol, RGBTuple}})
787+
@lock recolor_lock begin
788+
for (name, rgb) in color
789+
FACES.basecolors[name] = rgb
790+
end
791+
current = FACES.current[]
792+
for (name, _) in FACES.modifications[]
793+
default = get(FACES.default, name, nothing)
794+
isnothing(default) && continue
795+
current[name] = default
796+
end
797+
for hook in recolor_hooks
798+
hook()
799+
end
800+
for (name, face) in FACES.modifications[]
801+
current[name] = merge(current[name], face)
802+
end
803+
end
804+
end
805+
766806
## Color utils ##
767807

768808
"""

0 commit comments

Comments
 (0)