Closed antfu closed 1 week ago
All modified and coverable lines are covered by tests :white_check_mark:
Project coverage is 96.30%. Comparing base (
603713d
) to head (0953f83
).
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
Cool idea
Motivations
Sometimes, we might want to highlight a partial of the code snippet, which might not necessarily be a full language statement.
For example, if we want to highlight a TypeScript type annotation
Pick<MyObject, string>[]
we might do:We will get the result like this:
This isn't accurate. This is because from the grammar, Shiki doesn't know it's a type annotation already.
Instead, we could append
let a:
to our code to hint that:Which will now render:
While the highlighting is now correct, we have another challenge: removing the "temporary snippet" we just added from the highlighted HTML.
Solutions
This PR introduces a new concept,
GrammarState
, with a few APIs around it.GrammarState
is a special token that holds the grammar context and allows you to highlight from an intermediate grammar state, making it easier to highlight code snippets.For example, you can get the grammar state with the
getLastGrammarState
method, and pass into thegrammarState
option:Now Shiki would highlight correctly as it knows to start as the type annotation. You can keep that grammar state object for multiple uses as well.
For one-off grammar context shifting, we also provide a shorthand by the
grammarContextCode
option:Credits
Thanks to @benjamincanac for the idea and discussions