...

Source file src/github.com/yuin/goldmark/parser/atx_heading.go

Documentation: github.com/yuin/goldmark/parser

     1  package parser
     2  
     3  import (
     4  	"github.com/yuin/goldmark/ast"
     5  	"github.com/yuin/goldmark/text"
     6  	"github.com/yuin/goldmark/util"
     7  )
     8  
     9  // A HeadingConfig struct is a data structure that holds configuration of the renderers related to headings.
    10  type HeadingConfig struct {
    11  	AutoHeadingID bool
    12  	Attribute     bool
    13  }
    14  
    15  // SetOption implements SetOptioner.
    16  func (b *HeadingConfig) SetOption(name OptionName, _ interface{}) {
    17  	switch name {
    18  	case optAutoHeadingID:
    19  		b.AutoHeadingID = true
    20  	case optAttribute:
    21  		b.Attribute = true
    22  	}
    23  }
    24  
    25  // A HeadingOption interface sets options for heading parsers.
    26  type HeadingOption interface {
    27  	Option
    28  	SetHeadingOption(*HeadingConfig)
    29  }
    30  
    31  // AutoHeadingID is an option name that enables auto IDs for headings.
    32  const optAutoHeadingID OptionName = "AutoHeadingID"
    33  
    34  type withAutoHeadingID struct {
    35  }
    36  
    37  func (o *withAutoHeadingID) SetParserOption(c *Config) {
    38  	c.Options[optAutoHeadingID] = true
    39  }
    40  
    41  func (o *withAutoHeadingID) SetHeadingOption(p *HeadingConfig) {
    42  	p.AutoHeadingID = true
    43  }
    44  
    45  // WithAutoHeadingID is a functional option that enables custom heading ids and
    46  // auto generated heading ids.
    47  func WithAutoHeadingID() HeadingOption {
    48  	return &withAutoHeadingID{}
    49  }
    50  
    51  type withHeadingAttribute struct {
    52  	Option
    53  }
    54  
    55  func (o *withHeadingAttribute) SetHeadingOption(p *HeadingConfig) {
    56  	p.Attribute = true
    57  }
    58  
    59  // WithHeadingAttribute is a functional option that enables custom heading attributes.
    60  func WithHeadingAttribute() HeadingOption {
    61  	return &withHeadingAttribute{WithAttribute()}
    62  }
    63  
    64  type atxHeadingParser struct {
    65  	HeadingConfig
    66  }
    67  
    68  // NewATXHeadingParser return a new BlockParser that can parse ATX headings.
    69  func NewATXHeadingParser(opts ...HeadingOption) BlockParser {
    70  	p := &atxHeadingParser{}
    71  	for _, o := range opts {
    72  		o.SetHeadingOption(&p.HeadingConfig)
    73  	}
    74  	return p
    75  }
    76  
    77  func (b *atxHeadingParser) Trigger() []byte {
    78  	return []byte{'#'}
    79  }
    80  
    81  func (b *atxHeadingParser) Open(parent ast.Node, reader text.Reader, pc Context) (ast.Node, State) {
    82  	line, segment := reader.PeekLine()
    83  	pos := pc.BlockOffset()
    84  	if pos < 0 {
    85  		return nil, NoChildren
    86  	}
    87  	i := pos
    88  	for ; i < len(line) && line[i] == '#'; i++ {
    89  	}
    90  	level := i - pos
    91  	if i == pos || level > 6 {
    92  		return nil, NoChildren
    93  	}
    94  	if i == len(line) { // alone '#' (without a new line character)
    95  		return ast.NewHeading(level), NoChildren
    96  	}
    97  	l := util.TrimLeftSpaceLength(line[i:])
    98  	if l == 0 {
    99  		return nil, NoChildren
   100  	}
   101  	start := i + l
   102  	if start >= len(line) {
   103  		start = len(line) - 1
   104  	}
   105  	origstart := start
   106  	stop := len(line) - util.TrimRightSpaceLength(line)
   107  
   108  	node := ast.NewHeading(level)
   109  	parsed := false
   110  	if b.Attribute { // handles special case like ### heading ### {#id}
   111  		start--
   112  		closureClose := -1
   113  		closureOpen := -1
   114  		for j := start; j < stop; {
   115  			c := line[j]
   116  			if util.IsEscapedPunctuation(line, j) {
   117  				j += 2
   118  			} else if util.IsSpace(c) && j < stop-1 && line[j+1] == '#' {
   119  				closureOpen = j + 1
   120  				k := j + 1
   121  				for ; k < stop && line[k] == '#'; k++ {
   122  				}
   123  				closureClose = k
   124  				break
   125  			} else {
   126  				j++
   127  			}
   128  		}
   129  		if closureClose > 0 {
   130  			reader.Advance(closureClose)
   131  			attrs, ok := ParseAttributes(reader)
   132  			rest, _ := reader.PeekLine()
   133  			parsed = ok && util.IsBlank(rest)
   134  			if parsed {
   135  				for _, attr := range attrs {
   136  					node.SetAttribute(attr.Name, attr.Value)
   137  				}
   138  				node.Lines().Append(text.NewSegment(
   139  					segment.Start+start+1-segment.Padding,
   140  					segment.Start+closureOpen-segment.Padding))
   141  			}
   142  		}
   143  	}
   144  	if !parsed {
   145  		start = origstart
   146  		stop := len(line) - util.TrimRightSpaceLength(line)
   147  		if stop <= start { // empty headings like '##[space]'
   148  			stop = start
   149  		} else {
   150  			i = stop - 1
   151  			for ; line[i] == '#' && i >= start; i-- {
   152  			}
   153  			if i != stop-1 && !util.IsSpace(line[i]) {
   154  				i = stop - 1
   155  			}
   156  			i++
   157  			stop = i
   158  		}
   159  
   160  		if len(util.TrimRight(line[start:stop], []byte{'#'})) != 0 { // empty heading like '### ###'
   161  			node.Lines().Append(text.NewSegment(segment.Start+start-segment.Padding, segment.Start+stop-segment.Padding))
   162  		}
   163  	}
   164  	return node, NoChildren
   165  }
   166  
   167  func (b *atxHeadingParser) Continue(node ast.Node, reader text.Reader, pc Context) State {
   168  	return Close
   169  }
   170  
   171  func (b *atxHeadingParser) Close(node ast.Node, reader text.Reader, pc Context) {
   172  	if b.Attribute {
   173  		_, ok := node.AttributeString("id")
   174  		if !ok {
   175  			parseLastLineAttributes(node, reader, pc)
   176  		}
   177  	}
   178  
   179  	if b.AutoHeadingID {
   180  		id, ok := node.AttributeString("id")
   181  		if !ok {
   182  			generateAutoHeadingID(node.(*ast.Heading), reader, pc)
   183  		} else {
   184  			pc.IDs().Put(id.([]byte))
   185  		}
   186  	}
   187  }
   188  
   189  func (b *atxHeadingParser) CanInterruptParagraph() bool {
   190  	return true
   191  }
   192  
   193  func (b *atxHeadingParser) CanAcceptIndentedLine() bool {
   194  	return false
   195  }
   196  
   197  func generateAutoHeadingID(node *ast.Heading, reader text.Reader, pc Context) {
   198  	var line []byte
   199  	lastIndex := node.Lines().Len() - 1
   200  	if lastIndex > -1 {
   201  		lastLine := node.Lines().At(lastIndex)
   202  		line = lastLine.Value(reader.Source())
   203  	}
   204  	headingID := pc.IDs().Generate(line, ast.KindHeading)
   205  	node.SetAttribute(attrNameID, headingID)
   206  }
   207  
   208  func parseLastLineAttributes(node ast.Node, reader text.Reader, pc Context) {
   209  	lastIndex := node.Lines().Len() - 1
   210  	if lastIndex < 0 { // empty headings
   211  		return
   212  	}
   213  	lastLine := node.Lines().At(lastIndex)
   214  	line := lastLine.Value(reader.Source())
   215  	lr := text.NewReader(line)
   216  	var attrs Attributes
   217  	var ok bool
   218  	var start text.Segment
   219  	var sl int
   220  	var end text.Segment
   221  	for {
   222  		c := lr.Peek()
   223  		if c == text.EOF {
   224  			break
   225  		}
   226  		if c == '\\' {
   227  			lr.Advance(1)
   228  			if lr.Peek() == '{' {
   229  				lr.Advance(1)
   230  			}
   231  			continue
   232  		}
   233  		if c == '{' {
   234  			sl, start = lr.Position()
   235  			attrs, ok = ParseAttributes(lr)
   236  			_, end = lr.Position()
   237  			lr.SetPosition(sl, start)
   238  		}
   239  		lr.Advance(1)
   240  	}
   241  	if ok && util.IsBlank(line[end.Start:]) {
   242  		for _, attr := range attrs {
   243  			node.SetAttribute(attr.Name, attr.Value)
   244  		}
   245  		lastLine.Stop = lastLine.Start + start.Start
   246  		node.Lines().Set(lastIndex, lastLine)
   247  	}
   248  }
   249  

View as plain text