atx_heading.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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, _ 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(
  122. segment.Start+start+1-segment.Padding,
  123. segment.Start+closureOpen-segment.Padding))
  124. }
  125. }
  126. }
  127. if !parsed {
  128. start = origstart
  129. stop := len(line) - util.TrimRightSpaceLength(line)
  130. if stop <= start { // empty headings like '##[space]'
  131. stop = start
  132. } else {
  133. i = stop - 1
  134. for ; line[i] == '#' && i >= start; i-- {
  135. }
  136. if i != stop-1 && !util.IsSpace(line[i]) {
  137. i = stop - 1
  138. }
  139. i++
  140. stop = i
  141. }
  142. if len(util.TrimRight(line[start:stop], []byte{'#'})) != 0 { // empty heading like '### ###'
  143. node.Lines().Append(text.NewSegment(segment.Start+start-segment.Padding, segment.Start+stop-segment.Padding))
  144. }
  145. }
  146. return node, NoChildren
  147. }
  148. func (b *atxHeadingParser) Continue(node ast.Node, reader text.Reader, pc Context) State {
  149. return Close
  150. }
  151. func (b *atxHeadingParser) Close(node ast.Node, reader text.Reader, pc Context) {
  152. if b.Attribute {
  153. _, ok := node.AttributeString("id")
  154. if !ok {
  155. parseLastLineAttributes(node, reader, pc)
  156. }
  157. }
  158. if b.AutoHeadingID {
  159. id, ok := node.AttributeString("id")
  160. if !ok {
  161. generateAutoHeadingID(node.(*ast.Heading), reader, pc)
  162. } else {
  163. pc.IDs().Put(id.([]byte))
  164. }
  165. }
  166. }
  167. func (b *atxHeadingParser) CanInterruptParagraph() bool {
  168. return true
  169. }
  170. func (b *atxHeadingParser) CanAcceptIndentedLine() bool {
  171. return false
  172. }
  173. func generateAutoHeadingID(node *ast.Heading, reader text.Reader, pc Context) {
  174. var line []byte
  175. lastIndex := node.Lines().Len() - 1
  176. if lastIndex > -1 {
  177. lastLine := node.Lines().At(lastIndex)
  178. line = lastLine.Value(reader.Source())
  179. }
  180. headingID := pc.IDs().Generate(line, ast.KindHeading)
  181. node.SetAttribute(attrNameID, headingID)
  182. }
  183. func parseLastLineAttributes(node ast.Node, reader text.Reader, pc Context) {
  184. lastIndex := node.Lines().Len() - 1
  185. if lastIndex < 0 { // empty headings
  186. return
  187. }
  188. lastLine := node.Lines().At(lastIndex)
  189. line := lastLine.Value(reader.Source())
  190. lr := text.NewReader(line)
  191. var attrs Attributes
  192. var ok bool
  193. var start text.Segment
  194. var sl int
  195. var end text.Segment
  196. for {
  197. c := lr.Peek()
  198. if c == text.EOF {
  199. break
  200. }
  201. if c == '\\' {
  202. lr.Advance(1)
  203. if lr.Peek() == '{' {
  204. lr.Advance(1)
  205. }
  206. continue
  207. }
  208. if c == '{' {
  209. sl, start = lr.Position()
  210. attrs, ok = ParseAttributes(lr)
  211. _, end = lr.Position()
  212. lr.SetPosition(sl, start)
  213. }
  214. lr.Advance(1)
  215. }
  216. if ok && util.IsBlank(line[end.Start:]) {
  217. for _, attr := range attrs {
  218. node.SetAttribute(attr.Name, attr.Value)
  219. }
  220. lastLine.Stop = lastLine.Start + start.Start
  221. node.Lines().Set(lastIndex, lastLine)
  222. }
  223. }