github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/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  // Kind 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  		return ast.WalkContinue, nil
    44  	})
    45  
    46  	for i, cb := range codeBlocks {
    47  		b := &codeBlock{b: cb, ordinal: i}
    48  		parent := cb.Parent()
    49  		if parent != nil {
    50  			parent.ReplaceChild(parent, cb, b)
    51  		}
    52  	}
    53  }