Support for extending inline parsing with custom inline content parsers #321
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds an API for users/extensions to extend inline parsing (or override some built-in inline parsing), similar to the current support for custom block parsers. Fixes:
See also:
Overview
Since 5790505 we've internally extracted some of the inline parsing logic. This PR turns that into an API. It's currently exported in the
beta
package because it might be subject to change (andScanner
, which this depends on are is inbeta
).The entry point for this is
Parser.Builder#customInlineContentParserFactory
.The registered factory needs to provide one or more "trigger characters". When such a character is encountered during inline parsing, the parser is called with a
Scanner
and it can parse inline content from there. It can decide not to return a result; in that case other parsers (including built-in ones) are tried next.Example
See
InlineContentParserTest
for an example of how to use it. Registering the factory:commonmark-java/commonmark/src/test/java/org/commonmark/parser/InlineContentParserTest.java
Line 20 in f481935
And the factory and parser:
commonmark-java/commonmark/src/test/java/org/commonmark/parser/InlineContentParserTest.java
Lines 56 to 86 in f481935
Design considerations
The trickiest part was deciding on the lifetime of the parser instance. There were a few options:
Some other thoughts:
Set<Character>
for trigger characters instead of just a singlechar
? If link parsing was implemented on top of this, it would require at least[
and]
as trigger characters, so let's allow multiple. There's not really a downside to allowing multiple.Node
? Not with the current API, but we could add that in a backwards-compatible way.Factory
? Not sure what the alternative would be, and we already have the same concept forBlockParserFactory
:).