kyle-n / HighlightedTextEditor

A SwiftUI view for dynamically highlighting user input
MIT License
726 stars 69 forks source link

HighlightRules colorize the same text #43

Closed thelonious closed 3 years ago

thelonious commented 3 years ago

I have two patterns on macOS:

let commentPattern = try! NSRegularExpression(pattern: "//.*", options: [])
let keywordPattern = try! NSRegularExpression(pattern: "(?:constant|void)\\b", options: [])

The first is used to colorize comments. The second is for colorizing keywords. If a keyword is in a comment, it's highlighted as a keyword.

image

I expect that once a pattern has matched, all following matches at that position will be aborted and matching will restart but after the last character in the successful match. So, in the above image, I would expect "constant" to be grey like the rest of the comment.

I'm probably missing a setting or some subtlety here

kyle-n commented 3 years ago

I spun up a test project and reproduced this. It's less a bug and more a defect. You're not missing anything, it's just that HLTE is not designed super well to handle this problem.

Short term workaround: HLTE processes HighlightRules in order. Move the HighlightRule targeting keywordPattern before the one targeting commentPattern in the array passed to highlightRules.

Longer term, I'll think about this. HighlightRules know nothing about each other, for simplicity. I'm not sure how the library should handle conflicts.

thelonious commented 3 years ago

Thanks @kyle-n. FWIW, what I've used in the past is either a) longest wins or b) first wins. Both of these still preserve HighlightRules being independent from one another