Skip to content

Commit

Permalink
Merge pull request #460 from cbednarski/b-ast-block-text
Browse files Browse the repository at this point in the history
Add Text() retrieval for BaseBlock types
  • Loading branch information
yuin authored Oct 12, 2024
2 parents 15ade8a + e367755 commit fe34ea5
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
48 changes: 48 additions & 0 deletions ast/ast_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package ast

import (
"bytes"
"reflect"
"testing"

"github.com/yuin/goldmark/text"
)

func TestRemoveChildren(t *testing.T) {
Expand Down Expand Up @@ -73,3 +76,48 @@ func node(n Node, children ...Node) Node {
}
return n
}

func TestBaseBlock_Text(t *testing.T) {
source := []byte(`# Heading
code block here
and also here
A paragraph
` + "```" + `somelang
fenced code block
` + "```" + `
The end`)

t.Run("fetch text from code block", func(t *testing.T) {
block := NewCodeBlock()
block.lines = text.NewSegments()
block.lines.Append(text.Segment{Start: 15, Stop: 31})
block.lines.Append(text.Segment{Start: 32, Stop: 46})

expected := []byte("code block here\nand also here\n")
if !bytes.Equal(expected, block.Text(source)) {
t.Errorf("Expected: %q, got: %q", string(expected), string(block.Text(source)))
}
})

t.Run("fetch text from fenced code block", func(t *testing.T) {
block := NewFencedCodeBlock(&Text{
Segment: text.Segment{Start: 63, Stop: 71},
})
block.lines = text.NewSegments()
block.lines.Append(text.Segment{Start: 72, Stop: 90})

expectedLang := []byte("somelang")
if !bytes.Equal(expectedLang, block.Language(source)) {
t.Errorf("Expected: %q, got: %q", string(expectedLang), string(block.Language(source)))
}

expected := []byte("fenced code block\n")
if !bytes.Equal(expected, block.Text(source)) {
t.Errorf("Expected: %q, got: %q", string(expected), string(block.Text(source)))
}
})
}
9 changes: 9 additions & 0 deletions ast/block.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ast

import (
"bytes"
"fmt"
"strings"

Expand Down Expand Up @@ -47,6 +48,14 @@ func (b *BaseBlock) SetLines(v *textm.Segments) {
b.lines = v
}

func (b *BaseBlock) Text(source []byte) []byte {

Check failure on line 51 in ast/block.go

View workflow job for this annotation

GitHub Actions / test (1.21.x, ubuntu-latest)

exported: exported method BaseBlock.Text should have comment or be unexported (revive)

Check failure on line 51 in ast/block.go

View workflow job for this annotation

GitHub Actions / test (1.22.x, ubuntu-latest)

exported: exported method BaseBlock.Text should have comment or be unexported (revive)
var buf bytes.Buffer
for _, line := range b.Lines().Sliced(0, b.Lines().Len()) {
buf.Write(line.Value(source))
}
return buf.Bytes()
}

// A Document struct is a root node of Markdown text.
type Document struct {
BaseBlock
Expand Down

0 comments on commit fe34ea5

Please sign in to comment.