Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 42 additions & 8 deletions src/styledmarkup.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

module StyledMarkup

using Base: AnnotatedString, annotatedstring
using Base: AnnotatedString, annotations, annotatedstring
using ..StyledStrings: Face, SimpleColor

export @styled_str, styled
Expand Down Expand Up @@ -97,7 +97,7 @@ function addpart!(state::State, stop::Int)
range = (start - state.point[]):(stop - state.point[] + state.offset[] + 1)
push!(styles, tupl(range, annot))
end
sort!(state.pending_styles, by = (r -> (first(r), -last(r))) ∘ first) # see `Base._annot_sortkey`
sort!(state.pending_styles, by = (r -> (first(r), -last(r))) ∘ first) # Prioritise the most specific styles
for (range, annot) in state.pending_styles
if !isempty(range)
push!(styles, tupl(range .- state.point[], annot))
Expand Down Expand Up @@ -135,11 +135,15 @@ function addpart!(state::State, start::Int, expr, stop::Int)
else
push!(state.parts,
:(let $str = string($expr)
if isempty($str)
""
$len = ncodeunits($str) # Used in `annots`.
if $str isa AnnotatedString && !isempty($str)
AnnotatedString(String($str), vcat($annots, annotations($str)))
else
$len = ncodeunits($str)
AnnotatedString($str, $annots)
if isempty($str)
""
else
AnnotatedString($str, $annots)
end
end
end))
end
Expand Down Expand Up @@ -641,6 +645,36 @@ function run_state_machine!(state::State)
end
end

"""
annotatedstring_optimize!(str::AnnotatedString)

Merge contiguous identical annotations in `str`.
"""
function annotatedstring_optimize!(s::AnnotatedString)
last_seen = Dict{Pair{Symbol, Any}, Int}()
i = 1
while i <= length(s.annotations)
region, keyval = s.annotations[i]
prev = get(last_seen, keyval, 0)
if prev > 0
lregion, _ = s.annotations[prev]
if last(lregion) + 1 == first(region)
s.annotations[prev] =
setindex(s.annotations[prev],
first(lregion):last(region),
1)
deleteat!(s.annotations, i)
else
delete!(last_seen, keyval)
end
else
last_seen[keyval] = i
i += 1
end
end
s
end

"""
@styled_str -> AnnotatedString

Expand Down Expand Up @@ -740,7 +774,7 @@ macro styled_str(raw_content::String)
elseif state.interpolated[]
:(annotatedstring($(state.parts...)))
else
annotatedstring(map(Base.Fix1(hygienic_eval, state), state.parts)...) |> Base.annotatedstring_optimize!
annotatedstring(map(Base.Fix1(hygienic_eval, state), state.parts)...) |> annotatedstring_optimize!
end
end

Expand All @@ -762,7 +796,7 @@ function styled(content::AbstractString)
if !isempty(state.errors)
throw(MalformedStylingMacro(state.content, state.errors))
else
annotatedstring(state.parts...) |> Base.annotatedstring_optimize!
annotatedstring(state.parts...) |> annotatedstring_optimize!
end
end

Expand Down