From 0625bcefb47385112da88af9390e0daf3a2fb5cb Mon Sep 17 00:00:00 2001 From: Jameson Nash Date: Mon, 5 Feb 2024 16:28:24 -0500 Subject: [PATCH] More predictible parsing with escape_raw_string 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. --- src/stylemacro.jl | 12 +++++++++--- test/runtests.jl | 8 ++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/stylemacro.jl b/src/stylemacro.jl index b0305690..f6b551fa 100644 --- a/src/stylemacro.jl +++ b/src/stylemacro.jl @@ -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( diff --git a/test/runtests.jl b/test/runtests.jl index c0a44107..f5a7a4d9 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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"