Skip to content

Commit

Permalink
More predictible parsing with escape_raw_string
Browse files Browse the repository at this point in the history
Due to the initial parsing of the string before the macro sees it,
followed by the use of `unescape_string`, you currently need to double
up trailing backslashes. We can fix this by calling escape_raw_string in
advance.

This change may cause undesirable side-effects with less comply used
macro forms (e.g. `@styled_str "\\"`), but we'll deal with that if and
when it comes up.
vtjnash authored and tecosaur committed Feb 10, 2024
1 parent 57619c2 commit 0625bce
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/stylemacro.jl
Original file line number Diff line number Diff line change
@@ -84,9 +84,11 @@ inheritval = whitespace, ':'?, symbol ;
```
"""
macro styled_str(raw_content::String)
#------------------
# Helper functions
#------------------
# First undo the transforms of the parser, (assuming the input was entered
# with single `styled""` markers so this transform is unambiguously
# reversible and not as `@styled_str "."` or `styled"""."""`), since the
# `unescape_string` transforms will be a superset of those transforms
raw_content = Base.escape_raw_string(raw_content)

# If this were a module, I'd define the following struct.

@@ -128,6 +130,10 @@ macro styled_str(raw_content::String)
"grey", "gray", "bright_black", "bright_red", "bright_green", "bright_yellow",
"bright_blue", "bright_magenta", "bright_cyan", "bright_white")

#------------------
# Helper functions
#------------------

function styerr!(state, message, position::Union{Nothing, Int}=nothing, hint::String="around here")
if !isnothing(position) && position < 0
position = prevind(
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -207,6 +207,14 @@ end
@macroexpand styled"{(foreground=$color):val}"
end

# Trailing (and non-trailing) Backslashes
@test String(styled"\\") == "\\"
@test String(styled"\\\\") == "\\\\"
@test String(styled"\\\\\\") == "\\\\\\"
@test String(styled".\\") == ".\\"
@test String(styled".\\\\") == ".\\\\"
@test String(styled".\\\\\\") == ".\\\\\\"

# newlines
normal = "abc\
def"

0 comments on commit 0625bce

Please sign in to comment.