Skip to content

Commit c5c9547

Browse files
committed
README: Add source positions section
1 parent 4e42065 commit c5c9547

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff 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\nbar *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

135160
Sometimes you might want to customize how HTML is rendered. If all you

commonmark/src/test/java/org/commonmark/test/UsageExampleTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.commonmark.test;
22

33
import org.commonmark.node.*;
4+
import org.commonmark.parser.IncludeSourceSpans;
45
import org.commonmark.parser.Parser;
56
import org.commonmark.renderer.NodeRenderer;
67
import 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\nbar *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();

0 commit comments

Comments
 (0)