atx_heading.go 5.7 KB

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