summaryrefslogtreecommitdiffstats
path: root/utils/markdown/inspect.go
blob: 80b5bc246427e1cfa7fecbd3a670cf21603c9d39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package markdown

// Inspect traverses the markdown tree in depth-first order. If f returns true, Inspect invokes f
// recursively for each child of the block or inline, followed by a call of f(nil).
func Inspect(markdown string, f func(interface{}) bool) {
	document, referenceDefinitions := Parse(markdown)
	InspectBlock(document, func(block Block) bool {
		if !f(block) {
			return false
		}
		switch v := block.(type) {
		case *Paragraph:
			for _, inline := range MergeInlineText(v.ParseInlines(referenceDefinitions)) {
				InspectInline(inline, func(inline Inline) bool {
					return f(inline)
				})
			}
		}
		return true
	})
}

// InspectBlock traverses the blocks in depth-first order, starting with block. If f returns true,
// InspectBlock invokes f recursively for each child of the block, followed by a call of f(nil).
func InspectBlock(block Block, f func(Block) bool) {
	if !f(block) {
		return
	}
	switch v := block.(type) {
	case *Document:
		for _, child := range v.Children {
			InspectBlock(child, f)
		}
	case *List:
		for _, child := range v.Children {
			InspectBlock(child, f)
		}
	case *ListItem:
		for _, child := range v.Children {
			InspectBlock(child, f)
		}
	case *BlockQuote:
		for _, child := range v.Children {
			InspectBlock(child, f)
		}
	}
	f(nil)
}

// InspectInline traverses the blocks in depth-first order, starting with block. If f returns true,
// InspectInline invokes f recursively for each child of the block, followed by a call of f(nil).
func InspectInline(inline Inline, f func(Inline) bool) {
	if !f(inline) {
		return
	}
	switch v := inline.(type) {
	case *InlineImage:
		for _, child := range v.Children {
			InspectInline(child, f)
		}
	case *InlineLink:
		for _, child := range v.Children {
			InspectInline(child, f)
		}
	case *ReferenceImage:
		for _, child := range v.Children {
			InspectInline(child, f)
		}
	case *ReferenceLink:
		for _, child := range v.Children {
			InspectInline(child, f)
		}
	}
	f(nil)
}