github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/markup/goldmark/codeblocks/transform.go (about)

     1  package codeblocks
     2  
     3  import (
     4  	"github.com/yuin/goldmark/ast"
     5  	"github.com/yuin/goldmark/parser"
     6  	"github.com/yuin/goldmark/text"
     7  )
     8  
     9  // KindCodeBlock is the kind of an Hugo code block.
    10  var KindCodeBlock = ast.NewNodeKind("HugoCodeBlock")
    11  
    12  // Its raw contents are the plain text of the code block.
    13  type codeBlock struct {
    14  	ast.BaseBlock
    15  	ordinal int
    16  	b       *ast.FencedCodeBlock
    17  }
    18  
    19  func (*codeBlock) Kind() ast.NodeKind { return KindCodeBlock }
    20  
    21  func (*codeBlock) IsRaw() bool { return true }
    22  
    23  func (b *codeBlock) Dump(src []byte, level int) {
    24  }
    25  
    26  type Transformer struct{}
    27  
    28  // Transform transforms the provided Markdown AST.
    29  func (*Transformer) Transform(doc *ast.Document, reader text.Reader, pctx parser.Context) {
    30  	var codeBlocks []*ast.FencedCodeBlock
    31  
    32  	ast.Walk(doc, func(node ast.Node, enter bool) (ast.WalkStatus, error) {
    33  		if !enter {
    34  			return ast.WalkContinue, nil
    35  		}
    36  
    37  		cb, ok := node.(*ast.FencedCodeBlock)
    38  		if !ok {
    39  			return ast.WalkContinue, nil
    40  		}
    41  
    42  		codeBlocks = append(codeBlocks, cb)
    43  
    44  		return ast.WalkContinue, nil
    45  	})
    46  
    47  	for i, cb := range codeBlocks {
    48  		b := &codeBlock{b: cb, ordinal: i}
    49  		parent := cb.Parent()
    50  		if parent != nil {
    51  			parent.ReplaceChild(parent, cb, b)
    52  		}
    53  	}
    54  }