Skip to content

Commit fe34ea5

Browse files
authored
Merge pull request #460 from cbednarski/b-ast-block-text
Add Text() retrieval for BaseBlock types
2 parents 15ade8a + e367755 commit fe34ea5

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

ast/ast_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package ast
22

33
import (
4+
"bytes"
45
"reflect"
56
"testing"
7+
8+
"github.com/yuin/goldmark/text"
69
)
710

811
func TestRemoveChildren(t *testing.T) {
@@ -73,3 +76,48 @@ func node(n Node, children ...Node) Node {
7376
}
7477
return n
7578
}
79+
80+
func TestBaseBlock_Text(t *testing.T) {
81+
source := []byte(`# Heading
82+
83+
code block here
84+
and also here
85+
86+
A paragraph
87+
88+
` + "```" + `somelang
89+
fenced code block
90+
` + "```" + `
91+
92+
The end`)
93+
94+
t.Run("fetch text from code block", func(t *testing.T) {
95+
block := NewCodeBlock()
96+
block.lines = text.NewSegments()
97+
block.lines.Append(text.Segment{Start: 15, Stop: 31})
98+
block.lines.Append(text.Segment{Start: 32, Stop: 46})
99+
100+
expected := []byte("code block here\nand also here\n")
101+
if !bytes.Equal(expected, block.Text(source)) {
102+
t.Errorf("Expected: %q, got: %q", string(expected), string(block.Text(source)))
103+
}
104+
})
105+
106+
t.Run("fetch text from fenced code block", func(t *testing.T) {
107+
block := NewFencedCodeBlock(&Text{
108+
Segment: text.Segment{Start: 63, Stop: 71},
109+
})
110+
block.lines = text.NewSegments()
111+
block.lines.Append(text.Segment{Start: 72, Stop: 90})
112+
113+
expectedLang := []byte("somelang")
114+
if !bytes.Equal(expectedLang, block.Language(source)) {
115+
t.Errorf("Expected: %q, got: %q", string(expectedLang), string(block.Language(source)))
116+
}
117+
118+
expected := []byte("fenced code block\n")
119+
if !bytes.Equal(expected, block.Text(source)) {
120+
t.Errorf("Expected: %q, got: %q", string(expected), string(block.Text(source)))
121+
}
122+
})
123+
}

ast/block.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package ast
22

33
import (
4+
"bytes"
45
"fmt"
56
"strings"
67

@@ -47,6 +48,14 @@ func (b *BaseBlock) SetLines(v *textm.Segments) {
4748
b.lines = v
4849
}
4950

51+
func (b *BaseBlock) Text(source []byte) []byte {
52+
var buf bytes.Buffer
53+
for _, line := range b.Lines().Sliced(0, b.Lines().Len()) {
54+
buf.Write(line.Value(source))
55+
}
56+
return buf.Bytes()
57+
}
58+
5059
// A Document struct is a root node of Markdown text.
5160
type Document struct {
5261
BaseBlock

0 commit comments

Comments
 (0)