r-lib / prettycode

Syntax highlight R code in the terminal
https://r-lib.github.io/prettycode/
Other
101 stars 9 forks source link

Fix handling of long strings and symbols in highlight() #21

Closed moodymudskipper closed 1 year ago

moodymudskipper commented 1 year ago

Closes #20

We implement get_parse_data() as an alternative to getParseDate(, includeText = NA)

for strings and symbols we consider the text from the parent if :

New behaviour:

x <- paste0("fun('", strrep("-", 1000), "')")
prettycode::highlight(x)
#> [1] "fun('----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------')"

Created on 2022-11-10 with reprex v2.0.2

There are still corner cases unfortunately, see below in the parse data how the expression combines children so cannot be used as is.

I didn't go through the rabbit hole for those, they're unlikely to be encountered in practice. we keep the previous behavior.

code <- sprintf("b$'%s'", strrep("a", 1000))
pd <- getParseData(parse(text=code), includeText = TRUE)
pd$text <- substr(pd$text,1, 30)
pd
#>   line1 col1 line2 col2 id parent     token terminal
#> 5     1    1     1 1004  5      0      expr    FALSE
#> 1     1    1     1    1  1      3    SYMBOL     TRUE
#> 3     1    1     1    1  3      5      expr    FALSE
#> 2     1    2     1    2  2      5       '$'     TRUE
#> 4     1    3     1 1004  4      5 STR_CONST     TRUE
#>                             text
#> 5 b$'aaaaaaaaaaaaaaaaaaaaaaaaaaa
#> 1                              b
#> 3                              b
#> 2                              $
#> 4   [1000 chars quoted with ''']
prettycode::highlight(code)
#> [1] "b$[1000 chars quoted with ''']"

Created on 2022-11-10 with reprex v2.0.2

gaborcsardi commented 1 year ago

Thanks, looks great! Can you please add an entry to the NEWS file?

moodymudskipper commented 1 year ago

Done, thanks!

gaborcsardi commented 1 year ago

Great, thank you!