Debian Codegraph @

passthrough/passthrough.go

raw symbols SCIP
1 package passthrough
2
3 import (
4 "bytes"
5 "fmt"
6 "strings"
7
8 "github.com/yuin/goldmark"
9 "github.com/yuin/goldmark/ast"
10 "github.com/yuin/goldmark/parser"
11 "github.com/yuin/goldmark/renderer"
12 "github.com/yuin/goldmark/text"
13 "github.com/yuin/goldmark/util"
14 )
15
16 type Delimiters struct {
17 Open string
18 Close string
19 }
20
21 // Determine if a byte array starts with a given string
22 func startsWith(b []byte, s string) bool {
23 if len(b) < len(s) {
24 return false
25 }
26
27 return string(b[:len(s)]) == s
28 }
29
30 // PassthroughInline is a node representing a inline passthrough.
31 type PassthroughInline struct {
32 ast.BaseInline
33
34 // The segment of text that this inline passthrough represents.
35 Segment text.Segment
36
37 // The matched delimiters
38 Delimiters *Delimiters
39 }
40
41 func newPassthroughInline(segment text.Segment, delimiters *Delimiters) *PassthroughInline {
42 return &PassthroughInline{
43 Segment: segment,
44 Delimiters: delimiters,
45 }
46 }
47
48 // Text implements Node.Text.
49 // Deprecated: Goldmark v1.7.8 deprecates Node.Text
50 func (n *PassthroughInline) Text(source []byte) []byte {
51 return n.Segment.Value(source)
52 }
53
54 // Dump implements Node.Dump.
55 func (n *PassthroughInline) Dump(source []byte, level int) {
56 indent := strings.Repeat(" ", level)
57 fmt.Printf("%sPassthroughInline {\n", indent)
58 indent2 := strings.Repeat(" ", level+1)
59 fmt.Printf("%sSegment: \"%s\"\n", indent2, n.Segment.Value(source))
60 fmt.Printf("%s}\n", indent)
61 }
62
63 // KindPassthroughInline is a NodeKind of the PassthroughInline node.
64 var KindPassthroughInline = ast.NewNodeKind("PassthroughInline")
65
66 // Kind implements Node.Kind.
67 func (n *PassthroughInline) Kind() ast.NodeKind {
68 return KindPassthroughInline
69 }
70
71 type inlinePassthroughParser struct {
72 PassthroughDelimiters []Delimiters
73 }
74
75 func newInlinePassthroughParser(ds []Delimiters) parser.InlineParser {
76 return &inlinePassthroughParser{
77 PassthroughDelimiters: ds,
78 }
79 }
80
81 // Determine if the input slice starts with a full valid opening delimiter.
82 // If so, returns the delimiter struct, otherwise returns nil.
83 func getFullOpeningDelimiter(delims []Delimiters, line []byte) *Delimiters {
84 for _, d := range delims {
85 if startsWith(line, d.Open) {
86 return &d
87 }
88 }
89
90 return nil
91 }
92
93 // Return an array of bytes containing the first byte of each opening
94 // delimiter. Used to populate the trigger list for inline and block parsers.
95 // `Parse` will be executed once for each character that is in this list of
96 // allowed trigger characters. Our parse function needs to do some additional
97 // checks because Trigger only works for single-byte delimiters.
98 func openersFirstByte(delims []Delimiters) []byte {
99 var firstBytes []byte
100 containsBackslash := false
101 for _, d := range delims {
102 if d.Open[0] == '\\' {
103 containsBackslash = true
104 }
105 firstBytes = append(firstBytes, d.Open[0])
106 }
107
108 if !containsBackslash {
109 // always trigger on backslash because it can be used to escape the opening
110 // delimiter.
111 firstBytes = append(firstBytes, '\\')
112 }
113 return firstBytes
114 }
115
116 // Determine if the input list of delimiters contains the given delimiter pair
117 func containsDelimiters(delims []Delimiters, toFind *Delimiters) bool {
118 for _, d := range delims {
119 if d.Open == toFind.Open && d.Close == toFind.Close {
120 return true
121 }
122 }
123
124 return false
125 }
126
127 // isInlineContainerNode returns true if n is a block-level node that contains
128 // inline content. Goldmark uses ast.KindParagraph for loose list items and
129 // standalone paragraphs, but ast.KindTextBlock for tight list items. Both need
130 // the same passthrough-splitting logic to ensure block delimiters render in
131 // display mode rather than inline.
132 func isInlineContainerNode(n ast.Node) bool {
133 if n == nil {
134 return false
135 }
136
137 switch n.Kind() {
138 case ast.KindParagraph, ast.KindTextBlock:
139 return true
140 default:
141 return false
142 }
143 }
144
145 func newInlineContainer(kind ast.NodeKind) ast.Node {
146 switch kind {
147 case ast.KindParagraph:
148 return ast.NewParagraph()
149 case ast.KindTextBlock:
150 return ast.NewTextBlock()
151 default:
152 return nil
153 }
154 }
155
156 // trimContainerSpace removes leading or trailing whitespace from text nodes
157 // in a container, modifying the text segment boundaries in place.
158 func trimContainerSpace(container ast.Node, source []byte, leading bool) {
159 if container.ChildCount() == 0 {
160 return
161 }
162
163 var textNode *ast.Text
164 if leading {
165 child := container.FirstChild()
166 if child.Kind() != ast.KindText {
167 return
168 }
169 textNode = child.(*ast.Text)
170 } else {
171 child := container.LastChild()
172 if child.Kind() != ast.KindText {
173 return
174 }
175 textNode = child.(*ast.Text)
176 }
177
178 seg := textNode.Segment
179 value := seg.Value(source)
180 origLen := len(value)
181
182 if leading {
183 value = bytes.TrimLeft(value, " \t")
184 newLen := len(value)
185 if newLen < origLen {
186 textNode.Segment = seg.WithStart(seg.Start + (origLen - newLen))
187 }
188 } else {
189 value = bytes.TrimRight(value, " \t")
190 newLen := len(value)
191 if newLen < origLen {
192 textNode.Segment = seg.WithStop(seg.Stop - (origLen - newLen))
193 }
194 }
195 }
196
197 func (s *inlinePassthroughParser) Trigger() []byte {
198 return openersFirstByte(s.PassthroughDelimiters)
199 }
200
201 func (s *inlinePassthroughParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node {
202 // In order to prevent other parser extensions from operating on the text
203 // between passthrough delimiters, we must process the entire inline
204 // passthrough in one execution of Parse. This means we can't use the style
205 // of multiple triggers with parser.Context state saved between calls.
206 line, startSegment := block.PeekLine()
207
208 fencePair := getFullOpeningDelimiter(s.PassthroughDelimiters, line)
209 // fencePair == nil can happen if only the first byte of an opening delimiter
210 // matches, but it is not the complete opening delimiter. The trigger causes
211 // this Parse function to execute, but the trigger interface is limited to
212 // matching single bytes.
213 // It can also be because the opening delimiter is escaped with a
214 // double-backslash. In this case, we advance and return nil.
215 if fencePair == nil {
216 if len(line) > 2 && line[0] == '\\' && line[1] == '\\' {
217 fencePair = getFullOpeningDelimiter(s.PassthroughDelimiters, line[2:])
218 if fencePair != nil {
219 // Opening delimiter is escaped, return the escaped opener as plain text
220 // So that the characters are not processed again.
221 block.Advance(2 + len(fencePair.Open))
222 return ast.NewTextSegment(startSegment.WithStop(startSegment.Start + len(fencePair.Open) + 2))
223 }
224 }
225 return nil
226 }
227
228 // This roughly follows goldmark/parser/code_span.go
229 block.Advance(len(fencePair.Open))
230 openerSize := len(fencePair.Open)
231 l, pos := block.Position()
232
233 for {
234 line, lineSegment := block.PeekLine()
235 if line == nil {
236 block.SetPosition(l, pos)
237 return ast.NewTextSegment(startSegment.WithStop(startSegment.Start + openerSize))
238 }
239
240 closingDelimiterPos := bytes.Index(line, []byte(fencePair.Close))
241 if closingDelimiterPos == -1 { // no closer on this line
242 block.AdvanceLine()
243 continue
244 }
245
246 // This segment spans from the original starting trigger (including the delimiter)
247 // up to and including the closing delimiter.
248 seg := startSegment.WithStop(lineSegment.Start + closingDelimiterPos + len(fencePair.Close))
249 if seg.Len() == len(fencePair.Open)+len(fencePair.Close) {
250 return nil
251 }
252
253 block.Advance(closingDelimiterPos + len(fencePair.Close))
254 return newPassthroughInline(seg, fencePair)
255 }
256 }
257
258 type passthroughInlineRenderer struct{}
259
260 func (r *passthroughInlineRenderer) renderRawInline(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
261 if entering {
262 n, ok := n.(*PassthroughInline)
263 if !ok {
264 return ast.WalkContinue, nil
265 }
266 w.WriteString(string(n.Segment.Value(source)))
267 }
268 return ast.WalkContinue, nil
269 }
270
271 // A PassthroughBlock struct represents a fenced block of raw text to pass
272 // through unchanged. This is not parsed directly, but emitted by an
273 // ASTTransformer that splits a paragraph at the point of an inline passthrough
274 // with the matching block delimiters.
275 type PassthroughBlock struct {
276 ast.BaseBlock
277 // The matched delimiters
278 Delimiters *Delimiters
279 }
280
281 // Dump implements Node.Dump.
282 func (n *PassthroughBlock) Dump(source []byte, level int) {
283 ast.DumpHelper(n, source, level, nil, nil)
284 }
285
286 // KindPassthroughBlock is a NodeKind of the PassthroughBlock node.
287 var KindPassthroughBlock = ast.NewNodeKind("PassthroughBlock")
288
289 // Kind implements Node.Kind.
290 func (n *PassthroughBlock) Kind() ast.NodeKind {
291 return KindPassthroughBlock
292 }
293
294 // newPassthroughBlock return a new PassthroughBlock node.
295 func newPassthroughBlock(delimiters *Delimiters) *PassthroughBlock {
296 return &PassthroughBlock{
297 Delimiters: delimiters,
298 BaseBlock: ast.BaseBlock{},
299 }
300 }
301
302 type passthroughBlockRenderer struct{}
303
304 func (r *passthroughBlockRenderer) renderRawBlock(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
305 if entering {
306 l := n.Lines().Len()
307 for i := 0; i < l; i++ {
308 line := n.Lines().At(i)
309 w.WriteString(string(line.Value(source)))
310 }
311 w.WriteString("\n")
312 }
313 return ast.WalkSkipChildren, nil
314 }
315
316 // To support the use of passthrough block delimiters in inline contexts, I
317 // wasn't able to get the normal block parser to work. Goldmark seems to only
318 // trigger the inline parser when the trigger is not the first characters in a
319 // block. So instead we hook into the transformer interface, and process an
320 // inline passthrough after it's parsed, looking for nodes whose delimiters
321 // match the block delimiters, and splitting the paragraph at that point.
322 type passthroughInlineTransformer struct {
323 BlockDelimiters []Delimiters
324 }
325
326 var PassthroughInlineTransformer = &passthroughInlineTransformer{}
327
328 const (
329 passthroughMarkedForDeletion = "passthrough_marked_for_deletion"
330 passthroughProcessed = "passthrough_processed"
331 )
332
333 // Note, this transformer destroys the RawText attributes of the paragraph
334 // nodes that it transforms. However, this does not seem to have an impact on
335 // rendering.
336 func (p *passthroughInlineTransformer) Transform(
337 doc *ast.Document, reader text.Reader, pc parser.Context,
338 ) {
339 source := reader.Source()
340 // Goldmark's walking algorithm is simplistic, and doesn't handle the
341 // possibility of replacing the current node being walked with a new node. So
342 // as a workaround, we split the walk in two. The first walk inserts new
343 // nodes, and marks the original nodes for deletion. The second walk deletes
344 // the marked nodes. To avoid an infinite loop, we also need to mark the
345 // newly inserted nodes as "processed" so that they are not re-processed as
346 // the walk continues.
347 ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
348 if !entering || !isInlineContainerNode(n) {
349 return ast.WalkContinue, nil
350 }
351
352 val, found := n.AttributeString(passthroughProcessed)
353 if found && val == "true" {
354 return ast.WalkContinue, nil
355 }
356
357 // If no direct children are passthroughs, skip it.
358 foundInlinePassthrough := false
359 for c := n.FirstChild(); c != nil; c = c.NextSibling() {
360 if c.Kind() == KindPassthroughInline {
361 foundInlinePassthrough = true
362 break
363 }
364 }
365 if !foundInlinePassthrough {
366 return ast.WalkContinue, nil
367 }
368
369 parent := n.Parent()
370 containerKind := n.Kind()
371 currentContainer := newInlineContainer(containerKind)
372 if currentContainer == nil {
373 return ast.WalkContinue, nil
374 }
375 // AppendChild breaks the link between the node and its siblings, so we
376 // need to manually track the current and next node.
377 currentNode := n.FirstChild()
378 insertionPoint := n
379
380 for currentNode != nil {
381 nextNode := currentNode.NextSibling()
382 if currentNode.Kind() != KindPassthroughInline {
383 currentContainer.AppendChild(currentContainer, currentNode)
384 currentNode = nextNode
385 } else if currentNode.Kind() == KindPassthroughInline {
386 inline := currentNode.(*PassthroughInline)
387
388 // Only split into a new block if the delimiters are block delimiters
389 if !containsDelimiters(p.BlockDelimiters, inline.Delimiters) {
390 currentContainer.AppendChild(currentContainer, currentNode)
391 currentNode = nextNode
392 continue
393 }
394
395 newBlock := newPassthroughBlock(inline.Delimiters)
396 newBlock.SetPos(inline.Pos())
397 newBlock.Lines().Append(inline.Segment)
398 if currentContainer.ChildCount() > 0 {
399 // Trim trailing whitespace from text preceding the block in tight lists
400 if containerKind == ast.KindTextBlock {
401 trimContainerSpace(currentContainer, source, false)
402 }
403 // Trim leading whitespace from text following a previous block in tight lists
404 if containerKind == ast.KindTextBlock && insertionPoint.Kind() == KindPassthroughBlock {
405 trimContainerSpace(currentContainer, source, true)
406 }
407 parent.InsertAfter(parent, insertionPoint, currentContainer)
408 // Since we're not removing the original paragraph, we need to ensure
409 // that this paragraph is not re-processed as the walk continues
410 currentContainer.SetAttributeString(passthroughProcessed, "true")
411 insertionPoint = currentContainer
412 }
413 parent.InsertAfter(parent, insertionPoint, newBlock)
414 insertionPoint = newBlock
415 currentContainer = newInlineContainer(containerKind)
416 currentNode = nextNode
417 }
418 }
419
420 if currentContainer.ChildCount() > 0 {
421 // Trim leading whitespace from text following a block in tight lists
422 if containerKind == ast.KindTextBlock && insertionPoint.Kind() == KindPassthroughBlock {
423 trimContainerSpace(currentContainer, source, true)
424 }
425 parent.InsertAfter(parent, insertionPoint, currentContainer)
426 // Since we're not removing the original paragraph, we need to ensure
427 // that this paragraph is not re-processed as the walk continues
428 currentContainer.SetAttributeString(passthroughProcessed, "true")
429 }
430
431 // At this point, we don't remove the original paragraph, but mark it
432 // for removal in the second walk.
433 n.SetAttributeString(passthroughMarkedForDeletion, "true")
434 return ast.WalkContinue, nil
435 })
436
437 // Now delete any marked nodes
438 ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
439 if !entering {
440 return ast.WalkContinue, nil
441 }
442
443 for c := n.FirstChild(); c != nil; {
444 // Have to eagerly fetch this because `c` may be removed from the tree,
445 // destroying its link to the next sibling.
446 next := c.NextSibling()
447 if isInlineContainerNode(c) {
448 val, found := c.AttributeString(passthroughMarkedForDeletion)
449 if found && val == "true" {
450 n.RemoveChild(n, c)
451 }
452 }
453 c = next
454 }
455
456 return ast.WalkContinue, nil
457 })
458 }
459
460 func newPassthroughInlineTransformer(ds []Delimiters) parser.ASTTransformer {
461 return &passthroughInlineTransformer{
462 BlockDelimiters: ds,
463 }
464 }
465
466 // RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
467 func (r *passthroughInlineRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
468 reg.Register(KindPassthroughInline, r.renderRawInline)
469 }
470
471 // RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
472 func (r *passthroughBlockRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
473 reg.Register(KindPassthroughBlock, r.renderRawBlock)
474 }
475
476 // ---- Extension and config ----
477
478 type passthrough struct {
479 InlineDelimiters []Delimiters
480 BlockDelimiters []Delimiters
481 }
482
483 // Config configures this extension.
484 type Config struct {
485 InlineDelimiters []Delimiters
486 BlockDelimiters []Delimiters
487 }
488
489 func New(c Config) goldmark.Extender {
490 // The parser executes in two phases:
491 //
492 // Phase 1: parse the input with all delimiters treated as inline, and block delimiters
493 // taking precedence over inline delimiters.
494 //
495 // Phase 2: transform the parsed AST to split paragraphs at the point of
496 // inline passthroughs with matching block delimiters.
497 combinedDelimiters := make([]Delimiters, len(c.InlineDelimiters)+len(c.BlockDelimiters))
498 copy(combinedDelimiters, c.BlockDelimiters)
499 copy(combinedDelimiters[len(c.BlockDelimiters):], c.InlineDelimiters)
500 return &passthrough{
501 InlineDelimiters: combinedDelimiters,
502 BlockDelimiters: c.BlockDelimiters,
503 }
504 }
505
506 func (e *passthrough) Extend(m goldmark.Markdown) {
507 m.Parser().AddOptions(
508 parser.WithInlineParsers(
509 util.Prioritized(newInlinePassthroughParser(e.InlineDelimiters), 201),
510 ),
511 parser.WithASTTransformers(
512 util.Prioritized(newPassthroughInlineTransformer(e.BlockDelimiters), 0),
513 ),
514 )
515
516 m.Renderer().AddOptions(renderer.WithNodeRenderers(
517 util.Prioritized(&passthroughInlineRenderer{}, 101),
518 util.Prioritized(&passthroughBlockRenderer{}, 99),
519 ))
520 }