github.com/ashishbhate/mattermost-server@v5.11.1+incompatible/utils/markdown/inspect.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package markdown
     5  
     6  // Inspect traverses the markdown tree in depth-first order. If f returns true, Inspect invokes f
     7  // recursively for each child of the block or inline, followed by a call of f(nil).
     8  func Inspect(markdown string, f func(interface{}) bool) {
     9  	document, referenceDefinitions := Parse(markdown)
    10  	InspectBlock(document, func(block Block) bool {
    11  		if !f(block) {
    12  			return false
    13  		}
    14  		switch v := block.(type) {
    15  		case *Paragraph:
    16  			for _, inline := range MergeInlineText(v.ParseInlines(referenceDefinitions)) {
    17  				InspectInline(inline, func(inline Inline) bool {
    18  					return f(inline)
    19  				})
    20  			}
    21  		}
    22  		return true
    23  	})
    24  }
    25  
    26  // InspectBlock traverses the blocks in depth-first order, starting with block. If f returns true,
    27  // InspectBlock invokes f recursively for each child of the block, followed by a call of f(nil).
    28  func InspectBlock(block Block, f func(Block) bool) {
    29  	if !f(block) {
    30  		return
    31  	}
    32  	switch v := block.(type) {
    33  	case *Document:
    34  		for _, child := range v.Children {
    35  			InspectBlock(child, f)
    36  		}
    37  	case *List:
    38  		for _, child := range v.Children {
    39  			InspectBlock(child, f)
    40  		}
    41  	case *ListItem:
    42  		for _, child := range v.Children {
    43  			InspectBlock(child, f)
    44  		}
    45  	case *BlockQuote:
    46  		for _, child := range v.Children {
    47  			InspectBlock(child, f)
    48  		}
    49  	}
    50  	f(nil)
    51  }
    52  
    53  // InspectInline traverses the blocks in depth-first order, starting with block. If f returns true,
    54  // InspectInline invokes f recursively for each child of the block, followed by a call of f(nil).
    55  func InspectInline(inline Inline, f func(Inline) bool) {
    56  	if !f(inline) {
    57  		return
    58  	}
    59  	switch v := inline.(type) {
    60  	case *InlineImage:
    61  		for _, child := range v.Children {
    62  			InspectInline(child, f)
    63  		}
    64  	case *InlineLink:
    65  		for _, child := range v.Children {
    66  			InspectInline(child, f)
    67  		}
    68  	case *ReferenceImage:
    69  		for _, child := range v.Children {
    70  			InspectInline(child, f)
    71  		}
    72  	case *ReferenceLink:
    73  		for _, child := range v.Children {
    74  			InspectInline(child, f)
    75  		}
    76  	}
    77  	f(nil)
    78  }