Skip to content

Commit

Permalink
README: Add source positions section
Browse files Browse the repository at this point in the history
  • Loading branch information
robinst committed Oct 21, 2024
1 parent 4e42065 commit c5c9547
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,31 @@ class WordCountVisitor extends AbstractVisitor {
}
```

#### Source positions

If you want to know where a parsed `Node` appeared in the input source text,
you can request the parser to return source positions like this:

```java
var parser = Parser.builder().includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES).build();
```

Then parse nodes and inspect source positions:

```java
var source = "foo\n\nbar *baz*";
var doc = parser.parse(source);
var emphasis = doc.getLastChild().getLastChild();
var s = emphasis.getSourceSpans().get(0);
s.getLineIndex(); // 2 (third line)
s.getColumnIndex(); // 4 (fifth column)
s.getInputIndex(); // 9 (string index 9)
s.getLength(); // 5
source.substring(s.getInputIndex(), s.getInputIndex() + s.getLength()); // "*baz*"
```

If you're only interested in blocks and not inlines, use `IncludeSourceSpans.BLOCKS`.

#### Add or change attributes of HTML elements

Sometimes you might want to customize how HTML is rendered. If all you
Expand Down
16 changes: 16 additions & 0 deletions commonmark/src/test/java/org/commonmark/test/UsageExampleTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.commonmark.test;

import org.commonmark.node.*;
import org.commonmark.parser.IncludeSourceSpans;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.*;
Expand Down Expand Up @@ -58,6 +59,21 @@ public void visitor() {
assertEquals(4, visitor.wordCount);
}

@Test
public void sourcePositions() {
var parser = Parser.builder().includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES).build();

var source = "foo\n\nbar *baz*";
var doc = parser.parse(source);
var emphasis = doc.getLastChild().getLastChild();
var s = emphasis.getSourceSpans().get(0);
assertEquals(2, s.getLineIndex());
assertEquals(4, s.getColumnIndex());
assertEquals(9, s.getInputIndex());
assertEquals(5, s.getLength());
assertEquals("*baz*", source.substring(s.getInputIndex(), s.getInputIndex() + s.getLength()));
}

@Test
public void addAttributes() {
Parser parser = Parser.builder().build();
Expand Down

0 comments on commit c5c9547

Please sign in to comment.