github.com/ashishbhate/mattermost-server@v5.11.1+incompatible/utils/markdown/indented_code.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  import (
     7  	"strings"
     8  )
     9  
    10  type IndentedCodeLine struct {
    11  	Indentation int
    12  	Range       Range
    13  }
    14  
    15  type IndentedCode struct {
    16  	blockBase
    17  	markdown string
    18  
    19  	RawCode []IndentedCodeLine
    20  }
    21  
    22  func (b *IndentedCode) Code() (result string) {
    23  	for _, code := range b.RawCode {
    24  		result += strings.Repeat(" ", code.Indentation) + b.markdown[code.Range.Position:code.Range.End]
    25  	}
    26  	return
    27  }
    28  
    29  func (b *IndentedCode) Continuation(indentation int, r Range) *continuation {
    30  	if indentation >= 4 {
    31  		return &continuation{
    32  			Indentation: indentation - 4,
    33  			Remaining:   r,
    34  		}
    35  	}
    36  	s := b.markdown[r.Position:r.End]
    37  	if strings.TrimSpace(s) == "" {
    38  		return &continuation{
    39  			Remaining: r,
    40  		}
    41  	}
    42  	return nil
    43  }
    44  
    45  func (b *IndentedCode) AddLine(indentation int, r Range) bool {
    46  	b.RawCode = append(b.RawCode, IndentedCodeLine{
    47  		Indentation: indentation,
    48  		Range:       r,
    49  	})
    50  	return true
    51  }
    52  
    53  func (b *IndentedCode) Close() {
    54  	for {
    55  		last := b.RawCode[len(b.RawCode)-1]
    56  		s := b.markdown[last.Range.Position:last.Range.End]
    57  		if strings.TrimRight(s, "\r\n") == "" {
    58  			b.RawCode = b.RawCode[:len(b.RawCode)-1]
    59  		} else {
    60  			break
    61  		}
    62  	}
    63  }
    64  
    65  func (b *IndentedCode) AllowsBlockStarts() bool {
    66  	return false
    67  }
    68  
    69  func indentedCodeStart(markdown string, indentation int, r Range, matchedBlocks, unmatchedBlocks []Block) []Block {
    70  	if len(unmatchedBlocks) > 0 {
    71  		if _, ok := unmatchedBlocks[len(unmatchedBlocks)-1].(*Paragraph); ok {
    72  			return nil
    73  		}
    74  	} else if len(matchedBlocks) > 0 {
    75  		if _, ok := matchedBlocks[len(matchedBlocks)-1].(*Paragraph); ok {
    76  			return nil
    77  		}
    78  	}
    79  
    80  	if indentation < 4 {
    81  		return nil
    82  	}
    83  
    84  	s := markdown[r.Position:r.End]
    85  	if strings.TrimSpace(s) == "" {
    86  		return nil
    87  	}
    88  
    89  	return []Block{
    90  		&IndentedCode{
    91  			markdown: markdown,
    92  			RawCode: []IndentedCodeLine{{
    93  				Indentation: indentation - 4,
    94  				Range:       r,
    95  			}},
    96  		},
    97  	}
    98  }