File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
commonmark/src/test/java/org/commonmark/test Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -130,6 +130,31 @@ class WordCountVisitor extends AbstractVisitor {
130130}
131131```
132132
133+ #### Source positions
134+
135+ If you want to know where a parsed ` Node ` appeared in the input source text,
136+ you can request the parser to return source positions like this:
137+
138+ ``` java
139+ var parser = Parser . builder(). includeSourceSpans(IncludeSourceSpans . BLOCKS_AND_INLINES ). build();
140+ ```
141+
142+ Then parse nodes and inspect source positions:
143+
144+ ``` java
145+ var source = " foo\n\n bar *baz*" ;
146+ var doc = parser. parse(source);
147+ var emphasis = doc. getLastChild(). getLastChild();
148+ var s = emphasis. getSourceSpans(). get(0 );
149+ s. getLineIndex(); // 2 (third line)
150+ s. getColumnIndex(); // 4 (fifth column)
151+ s. getInputIndex(); // 9 (string index 9)
152+ s. getLength(); // 5
153+ source. substring(s. getInputIndex(), s. getInputIndex() + s. getLength()); // "*baz*"
154+ ```
155+
156+ If you're only interested in blocks and not inlines, use ` IncludeSourceSpans.BLOCKS ` .
157+
133158#### Add or change attributes of HTML elements
134159
135160Sometimes you might want to customize how HTML is rendered. If all you
Original file line number Diff line number Diff line change 11package org .commonmark .test ;
22
33import org .commonmark .node .*;
4+ import org .commonmark .parser .IncludeSourceSpans ;
45import org .commonmark .parser .Parser ;
56import org .commonmark .renderer .NodeRenderer ;
67import org .commonmark .renderer .html .*;
@@ -58,6 +59,21 @@ public void visitor() {
5859 assertEquals (4 , visitor .wordCount );
5960 }
6061
62+ @ Test
63+ public void sourcePositions () {
64+ var parser = Parser .builder ().includeSourceSpans (IncludeSourceSpans .BLOCKS_AND_INLINES ).build ();
65+
66+ var source = "foo\n \n bar *baz*" ;
67+ var doc = parser .parse (source );
68+ var emphasis = doc .getLastChild ().getLastChild ();
69+ var s = emphasis .getSourceSpans ().get (0 );
70+ assertEquals (2 , s .getLineIndex ());
71+ assertEquals (4 , s .getColumnIndex ());
72+ assertEquals (9 , s .getInputIndex ());
73+ assertEquals (5 , s .getLength ());
74+ assertEquals ("*baz*" , source .substring (s .getInputIndex (), s .getInputIndex () + s .getLength ()));
75+ }
76+
6177 @ Test
6278 public void addAttributes () {
6379 Parser parser = Parser .builder ().build ();
You can’t perform that action at this time.
0 commit comments