markdown.go (view raw)
1//
2// Blackfriday Markdown Processor
3// Available at http://github.com/russross/blackfriday
4//
5// Copyright © 2011 Russ Ross <russ@russross.com>.
6// Distributed under the Simplified BSD License.
7// See README.md for details.
8//
9
10//
11//
12// Markdown parsing and processing
13//
14//
15
16// Blackfriday markdown processor.
17//
18// Translates plain text with simple formatting rules into HTML or LaTeX.
19package blackfriday
20
21import (
22 "bytes"
23 "fmt"
24 "strings"
25 "unicode/utf8"
26)
27
28const VERSION = "1.4"
29
30type Extensions int
31
32// These are the supported markdown parsing extensions.
33// OR these values together to select multiple extensions.
34const (
35 NoExtensions Extensions = 0
36 NoIntraEmphasis Extensions = 1 << iota // Ignore emphasis markers inside words
37 Tables // Render tables
38 FencedCode // Render fenced code blocks
39 Autolink // Detect embedded URLs that are not explicitly marked
40 Strikethrough // Strikethrough text using ~~test~~
41 LaxHTMLBlocks // Loosen up HTML block parsing rules
42 SpaceHeaders // Be strict about prefix header rules
43 HardLineBreak // Translate newlines into line breaks
44 TabSizeEight // Expand tabs to eight spaces instead of four
45 Footnotes // Pandoc-style footnotes
46 NoEmptyLineBeforeBlock // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block
47 HeaderIDs // specify header IDs with {#id}
48 Titleblock // Titleblock ala pandoc
49 AutoHeaderIDs // Create the header ID from the text
50 BackslashLineBreak // Translate trailing backslashes into line breaks
51 DefinitionLists // Render definition lists
52
53 CommonHtmlFlags HtmlFlags = UseXHTML | UseSmartypants |
54 SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes
55
56 CommonExtensions Extensions = NoIntraEmphasis | Tables | FencedCode |
57 Autolink | Strikethrough | SpaceHeaders | HeaderIDs |
58 BackslashLineBreak | DefinitionLists
59)
60
61var DefaultOptions = Options{
62 Extensions: CommonExtensions,
63}
64
65type LinkType int
66
67// These are the possible flag values for the link renderer.
68// Only a single one of these values will be used; they are not ORed together.
69// These are mostly of interest if you are writing a new output format.
70const (
71 LinkTypeNotAutolink LinkType = iota
72 LinkTypeNormal
73 LinkTypeEmail
74)
75
76type ListType int
77
78// These are the possible flag values for the ListItem renderer.
79// Multiple flag values may be ORed together.
80// These are mostly of interest if you are writing a new output format.
81const (
82 ListTypeOrdered ListType = 1 << iota
83 ListTypeDefinition
84 ListTypeTerm
85
86 ListItemContainsBlock
87 ListItemBeginningOfList
88 ListItemEndOfList
89)
90
91type TableFlags int
92
93// These are the possible flag values for the table cell renderer.
94// Only a single one of these values will be used; they are not ORed together.
95// These are mostly of interest if you are writing a new output format.
96const (
97 TableAlignmentLeft = 1 << iota
98 TableAlignmentRight
99 TableAlignmentCenter = (TableAlignmentLeft | TableAlignmentRight)
100)
101
102// The size of a tab stop.
103const (
104 TabSizeDefault = 4
105 TabSizeDouble = 8
106)
107
108// blockTags is a set of tags that are recognized as HTML block tags.
109// Any of these can be included in markdown text without special escaping.
110var blockTags = map[string]struct{}{
111 "blockquote": struct{}{},
112 "del": struct{}{},
113 "div": struct{}{},
114 "dl": struct{}{},
115 "fieldset": struct{}{},
116 "form": struct{}{},
117 "h1": struct{}{},
118 "h2": struct{}{},
119 "h3": struct{}{},
120 "h4": struct{}{},
121 "h5": struct{}{},
122 "h6": struct{}{},
123 "iframe": struct{}{},
124 "ins": struct{}{},
125 "math": struct{}{},
126 "noscript": struct{}{},
127 "ol": struct{}{},
128 "pre": struct{}{},
129 "p": struct{}{},
130 "script": struct{}{},
131 "style": struct{}{},
132 "table": struct{}{},
133 "ul": struct{}{},
134
135 // HTML5
136 "address": struct{}{},
137 "article": struct{}{},
138 "aside": struct{}{},
139 "canvas": struct{}{},
140 "figcaption": struct{}{},
141 "figure": struct{}{},
142 "footer": struct{}{},
143 "header": struct{}{},
144 "hgroup": struct{}{},
145 "main": struct{}{},
146 "nav": struct{}{},
147 "output": struct{}{},
148 "progress": struct{}{},
149 "section": struct{}{},
150 "video": struct{}{},
151}
152
153// Renderer is the rendering interface.
154// This is mostly of interest if you are implementing a new rendering format.
155//
156// When a byte slice is provided, it contains the (rendered) contents of the
157// element.
158//
159// When a callback is provided instead, it will write the contents of the
160// respective element directly to the output buffer and return true on success.
161// If the callback returns false, the rendering function should reset the
162// output buffer as though it had never been called.
163//
164// Currently Html and Latex implementations are provided
165type Renderer interface {
166 // block-level callbacks
167 BlockCode(text []byte, lang string)
168 BlockQuote(text []byte)
169 BlockHtml(text []byte)
170 BeginHeader(level int, id string)
171 EndHeader(level int, id string, header []byte)
172 HRule()
173 BeginList(flags ListType)
174 EndList(flags ListType)
175 ListItem(text []byte, flags ListType)
176 BeginParagraph()
177 EndParagraph()
178 Table(header []byte, body []byte, columnData []int)
179 TableRow(text []byte)
180 TableHeaderCell(out *bytes.Buffer, text []byte, flags int)
181 TableCell(out *bytes.Buffer, text []byte, flags int)
182 BeginFootnotes()
183 EndFootnotes()
184 FootnoteItem(name, text []byte, flags ListType)
185 TitleBlock(text []byte)
186
187 // Span-level callbacks
188 AutoLink(link []byte, kind LinkType)
189 CodeSpan(text []byte)
190 DoubleEmphasis(text []byte)
191 Emphasis(text []byte)
192 Image(link []byte, title []byte, alt []byte)
193 LineBreak()
194 Link(link []byte, title []byte, content []byte)
195 RawHtmlTag(tag []byte)
196 TripleEmphasis(text []byte)
197 StrikeThrough(text []byte)
198 FootnoteRef(ref []byte, id int)
199
200 // Low-level callbacks
201 Entity(entity []byte)
202 NormalText(text []byte)
203
204 // Header and footer
205 DocumentHeader()
206 DocumentFooter()
207
208 GetFlags() HtmlFlags
209 Write(b []byte) (int, error)
210
211 Render(ast *Node) []byte
212}
213
214// Callback functions for inline parsing. One such function is defined
215// for each character that triggers a response when parsing inline data.
216type inlineParser func(p *parser, data []byte, offset int) int
217
218// Parser holds runtime state used by the parser.
219// This is constructed by the Markdown function.
220type parser struct {
221 refOverride ReferenceOverrideFunc
222 refs map[string]*reference
223 inlineCallback [256]inlineParser
224 flags Extensions
225 nesting int
226 maxNesting int
227 insideLink bool
228
229 // Footnotes need to be ordered as well as available to quickly check for
230 // presence. If a ref is also a footnote, it's stored both in refs and here
231 // in notes. Slice is nil if footnotes not enabled.
232 notes []*reference
233
234 doc *Node
235 tip *Node // = doc
236 oldTip *Node
237 lastMatchedContainer *Node // = doc
238 allClosed bool
239 currBlock *Node // a block node currently being parsed by inline parser
240}
241
242func (p *parser) getRef(refid string) (ref *reference, found bool) {
243 if p.refOverride != nil {
244 r, overridden := p.refOverride(refid)
245 if overridden {
246 if r == nil {
247 return nil, false
248 }
249 return &reference{
250 link: []byte(r.Link),
251 title: []byte(r.Title),
252 noteId: 0,
253 hasBlock: false,
254 text: []byte(r.Text)}, true
255 }
256 }
257 // refs are case insensitive
258 ref, found = p.refs[strings.ToLower(refid)]
259 return ref, found
260}
261
262func (p *parser) finalize(block *Node) {
263 above := block.Parent
264 block.open = false
265 p.tip = above
266}
267
268func (p *parser) addChild(node NodeType, offset uint32) *Node {
269 for !p.tip.canContain(node) {
270 p.finalize(p.tip)
271 }
272 newNode := NewNode(node)
273 newNode.content = []byte{}
274 p.tip.appendChild(newNode)
275 p.tip = newNode
276 return newNode
277}
278
279func (p *parser) closeUnmatchedBlocks() {
280 if !p.allClosed {
281 for p.oldTip != p.lastMatchedContainer {
282 parent := p.oldTip.Parent
283 p.finalize(p.oldTip)
284 p.oldTip = parent
285 }
286 p.allClosed = true
287 }
288}
289
290//
291//
292// Public interface
293//
294//
295
296// Reference represents the details of a link.
297// See the documentation in Options for more details on use-case.
298type Reference struct {
299 // Link is usually the URL the reference points to.
300 Link string
301 // Title is the alternate text describing the link in more detail.
302 Title string
303 // Text is the optional text to override the ref with if the syntax used was
304 // [refid][]
305 Text string
306}
307
308// ReferenceOverrideFunc is expected to be called with a reference string and
309// return either a valid Reference type that the reference string maps to or
310// nil. If overridden is false, the default reference logic will be executed.
311// See the documentation in Options for more details on use-case.
312type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool)
313
314// Options represents configurable overrides and callbacks (in addition to the
315// extension flag set) for configuring a Markdown parse.
316type Options struct {
317 // Extensions is a flag set of bit-wise ORed extension bits. See the
318 // Extensions flags defined in this package.
319 Extensions Extensions
320
321 // ReferenceOverride is an optional function callback that is called every
322 // time a reference is resolved.
323 //
324 // In Markdown, the link reference syntax can be made to resolve a link to
325 // a reference instead of an inline URL, in one of the following ways:
326 //
327 // * [link text][refid]
328 // * [refid][]
329 //
330 // Usually, the refid is defined at the bottom of the Markdown document. If
331 // this override function is provided, the refid is passed to the override
332 // function first, before consulting the defined refids at the bottom. If
333 // the override function indicates an override did not occur, the refids at
334 // the bottom will be used to fill in the link details.
335 ReferenceOverride ReferenceOverrideFunc
336}
337
338// MarkdownBasic is a convenience function for simple rendering.
339// It processes markdown input with no extensions enabled.
340func MarkdownBasic(input []byte) []byte {
341 // set up the HTML renderer
342 htmlFlags := UseXHTML
343 renderer := HtmlRenderer(htmlFlags, "", "")
344
345 // set up the parser
346 return MarkdownOptions(input, renderer, Options{Extensions: 0})
347}
348
349// Call Markdown with most useful extensions enabled
350// MarkdownCommon is a convenience function for simple rendering.
351// It processes markdown input with common extensions enabled, including:
352//
353// * Smartypants processing with smart fractions and LaTeX dashes
354//
355// * Intra-word emphasis suppression
356//
357// * Tables
358//
359// * Fenced code blocks
360//
361// * Autolinking
362//
363// * Strikethrough support
364//
365// * Strict header parsing
366//
367// * Custom Header IDs
368func MarkdownCommon(input []byte) []byte {
369 // set up the HTML renderer
370 renderer := HtmlRenderer(CommonHtmlFlags, "", "")
371 return MarkdownOptions(input, renderer, DefaultOptions)
372}
373
374// Markdown is the main rendering function.
375// It parses and renders a block of markdown-encoded text.
376// The supplied Renderer is used to format the output, and extensions dictates
377// which non-standard extensions are enabled.
378//
379// To use the supplied Html or LaTeX renderers, see HtmlRenderer and
380// LatexRenderer, respectively.
381func Markdown(input []byte, renderer Renderer, extensions Extensions) []byte {
382 return MarkdownOptions(input, renderer, Options{
383 Extensions: extensions})
384}
385
386// MarkdownOptions is just like Markdown but takes additional options through
387// the Options struct.
388func MarkdownOptions(input []byte, renderer Renderer, opts Options) []byte {
389 // no point in parsing if we can't render
390 if renderer == nil {
391 return nil
392 }
393 return renderer.Render(Parse(input, opts))
394}
395
396func Parse(input []byte, opts Options) *Node {
397 extensions := opts.Extensions
398
399 // fill in the render structure
400 p := new(parser)
401 p.flags = extensions
402 p.refOverride = opts.ReferenceOverride
403 p.refs = make(map[string]*reference)
404 p.maxNesting = 16
405 p.insideLink = false
406
407 docNode := NewNode(Document)
408 p.doc = docNode
409 p.tip = docNode
410 p.oldTip = docNode
411 p.lastMatchedContainer = docNode
412 p.allClosed = true
413
414 // register inline parsers
415 p.inlineCallback['*'] = emphasis
416 p.inlineCallback['_'] = emphasis
417 if extensions&Strikethrough != 0 {
418 p.inlineCallback['~'] = emphasis
419 }
420 p.inlineCallback['`'] = codeSpan
421 p.inlineCallback['\n'] = lineBreak
422 p.inlineCallback['['] = link
423 p.inlineCallback['<'] = leftAngle
424 p.inlineCallback['\\'] = escape
425 p.inlineCallback['&'] = entity
426 p.inlineCallback['!'] = maybeImage
427 p.inlineCallback['^'] = maybeInlineFootnote
428
429 if extensions&Autolink != 0 {
430 p.inlineCallback['h'] = maybeAutoLink
431 p.inlineCallback['m'] = maybeAutoLink
432 p.inlineCallback['f'] = maybeAutoLink
433 p.inlineCallback['H'] = maybeAutoLink
434 p.inlineCallback['M'] = maybeAutoLink
435 p.inlineCallback['F'] = maybeAutoLink
436 }
437
438 if extensions&Footnotes != 0 {
439 p.notes = make([]*reference, 0)
440 }
441
442 first := firstPass(p, input)
443 secondPass(p, first)
444 // walk the tree and finish up some of unfinished blocks:
445 for p.tip != nil {
446 p.finalize(p.tip)
447 }
448 ForEachNode(p.doc, func(node *Node, entering bool) {
449 if node.Type == Paragraph || node.Type == Header || node.Type == TableCell {
450 p.currBlock = node
451 p.inline(node.content)
452 node.content = nil
453 }
454 })
455 p.parseRefsToAST()
456 return p.doc
457}
458
459func (p *parser) parseRefsToAST() {
460 if p.flags&Footnotes == 0 || len(p.notes) == 0 {
461 return
462 }
463 p.tip = p.doc
464 finalizeHtmlBlock(p.addBlock(HtmlBlock, []byte(`<div class="footnotes">`)))
465 p.addBlock(HorizontalRule, nil)
466 block := p.addBlock(List, nil)
467 block.ListData = &ListData{ // TODO: fill in the real ListData
468 Flags: ListTypeOrdered,
469 Tight: false,
470 BulletChar: '*',
471 Delimiter: 0,
472 }
473 flags := ListItemBeginningOfList
474 // Note: this loop is intentionally explicit, not range-form. This is
475 // because the body of the loop will append nested footnotes to p.notes and
476 // we need to process those late additions. Range form would only walk over
477 // the fixed initial set.
478 for i := 0; i < len(p.notes); i++ {
479 ref := p.notes[i]
480 block := p.addBlock(Item, nil)
481 block.ListData = &ListData{ // TODO: fill in the real ListData
482 Flags: ListTypeOrdered,
483 Tight: false,
484 BulletChar: '*',
485 Delimiter: 0,
486 RefLink: ref.link,
487 }
488 if ref.hasBlock {
489 flags |= ListItemContainsBlock
490 p.block(ref.title)
491 } else {
492 p.currBlock = block
493 p.inline(ref.title)
494 }
495 flags &^= ListItemBeginningOfList | ListItemContainsBlock
496 }
497 above := block.Parent
498 finalizeList(block)
499 p.tip = above
500 finalizeHtmlBlock(p.addBlock(HtmlBlock, []byte("</div>")))
501 ForEachNode(block, func(node *Node, entering bool) {
502 if node.Type == Paragraph || node.Type == Header {
503 p.currBlock = node
504 p.inline(node.content)
505 node.content = nil
506 }
507 })
508}
509
510// first pass:
511// - extract references
512// - expand tabs
513// - normalize newlines
514// - copy everything else
515func firstPass(p *parser, input []byte) []byte {
516 var out bytes.Buffer
517 tabSize := TabSizeDefault
518 if p.flags&TabSizeEight != 0 {
519 tabSize = TabSizeDouble
520 }
521 beg, end := 0, 0
522 lastFencedCodeBlockEnd := 0
523 for beg < len(input) { // iterate over lines
524 if end = isReference(p, input[beg:], tabSize); end > 0 {
525 beg += end
526 } else { // skip to the next line
527 end = beg
528 for end < len(input) && input[end] != '\n' && input[end] != '\r' {
529 end++
530 }
531
532 if p.flags&FencedCode != 0 {
533 // track fenced code block boundaries to suppress tab expansion
534 // inside them:
535 if beg >= lastFencedCodeBlockEnd {
536 if i := p.fencedCode(input[beg:], false); i > 0 {
537 lastFencedCodeBlockEnd = beg + i
538 }
539 }
540 }
541
542 // add the line body if present
543 if end > beg {
544 if end < lastFencedCodeBlockEnd { // Do not expand tabs while inside fenced code blocks.
545 out.Write(input[beg:end])
546 } else {
547 expandTabs(&out, input[beg:end], tabSize)
548 }
549 }
550 out.WriteByte('\n')
551
552 if end < len(input) && input[end] == '\r' {
553 end++
554 }
555 if end < len(input) && input[end] == '\n' {
556 end++
557 }
558
559 beg = end
560 }
561 }
562
563 // empty input?
564 if out.Len() == 0 {
565 out.WriteByte('\n')
566 }
567
568 return out.Bytes()
569}
570
571// second pass: actual rendering
572func secondPass(p *parser, input []byte) {
573 p.block(input)
574
575 if p.flags&Footnotes != 0 && len(p.notes) > 0 {
576 flags := ListItemBeginningOfList
577 for i := 0; i < len(p.notes); i += 1 {
578 ref := p.notes[i]
579 if ref.hasBlock {
580 flags |= ListItemContainsBlock
581 p.block(ref.title)
582 } else {
583 p.inline(ref.title)
584 }
585 flags &^= ListItemBeginningOfList | ListItemContainsBlock
586 }
587 }
588
589 if p.nesting != 0 {
590 panic("Nesting level did not end at zero")
591 }
592}
593
594//
595// Link references
596//
597// This section implements support for references that (usually) appear
598// as footnotes in a document, and can be referenced anywhere in the document.
599// The basic format is:
600//
601// [1]: http://www.google.com/ "Google"
602// [2]: http://www.github.com/ "Github"
603//
604// Anywhere in the document, the reference can be linked by referring to its
605// label, i.e., 1 and 2 in this example, as in:
606//
607// This library is hosted on [Github][2], a git hosting site.
608//
609// Actual footnotes as specified in Pandoc and supported by some other Markdown
610// libraries such as php-markdown are also taken care of. They look like this:
611//
612// This sentence needs a bit of further explanation.[^note]
613//
614// [^note]: This is the explanation.
615//
616// Footnotes should be placed at the end of the document in an ordered list.
617// Inline footnotes such as:
618//
619// Inline footnotes^[Not supported.] also exist.
620//
621// are not yet supported.
622
623// References are parsed and stored in this struct.
624type reference struct {
625 link []byte
626 title []byte
627 noteId int // 0 if not a footnote ref
628 hasBlock bool
629 text []byte
630}
631
632func (r *reference) String() string {
633 return fmt.Sprintf("{link: %q, title: %q, text: %q, noteId: %d, hasBlock: %v}",
634 r.link, r.title, r.text, r.noteId, r.hasBlock)
635}
636
637// Check whether or not data starts with a reference link.
638// If so, it is parsed and stored in the list of references
639// (in the render struct).
640// Returns the number of bytes to skip to move past it,
641// or zero if the first line is not a reference.
642func isReference(p *parser, data []byte, tabSize int) int {
643 // up to 3 optional leading spaces
644 if len(data) < 4 {
645 return 0
646 }
647 i := 0
648 for i < 3 && data[i] == ' ' {
649 i++
650 }
651
652 noteId := 0
653
654 // id part: anything but a newline between brackets
655 if data[i] != '[' {
656 return 0
657 }
658 i++
659 if p.flags&Footnotes != 0 {
660 if i < len(data) && data[i] == '^' {
661 // we can set it to anything here because the proper noteIds will
662 // be assigned later during the second pass. It just has to be != 0
663 noteId = 1
664 i++
665 }
666 }
667 idOffset := i
668 for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
669 i++
670 }
671 if i >= len(data) || data[i] != ']' {
672 return 0
673 }
674 idEnd := i
675
676 // spacer: colon (space | tab)* newline? (space | tab)*
677 i++
678 if i >= len(data) || data[i] != ':' {
679 return 0
680 }
681 i++
682 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
683 i++
684 }
685 if i < len(data) && (data[i] == '\n' || data[i] == '\r') {
686 i++
687 if i < len(data) && data[i] == '\n' && data[i-1] == '\r' {
688 i++
689 }
690 }
691 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
692 i++
693 }
694 if i >= len(data) {
695 return 0
696 }
697
698 var (
699 linkOffset, linkEnd int
700 titleOffset, titleEnd int
701 lineEnd int
702 raw []byte
703 hasBlock bool
704 )
705
706 if p.flags&Footnotes != 0 && noteId != 0 {
707 linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize)
708 lineEnd = linkEnd
709 } else {
710 linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i)
711 }
712 if lineEnd == 0 {
713 return 0
714 }
715
716 // a valid ref has been found
717
718 ref := &reference{
719 noteId: noteId,
720 hasBlock: hasBlock,
721 }
722
723 if noteId > 0 {
724 // reusing the link field for the id since footnotes don't have links
725 ref.link = data[idOffset:idEnd]
726 // if footnote, it's not really a title, it's the contained text
727 ref.title = raw
728 } else {
729 ref.link = data[linkOffset:linkEnd]
730 ref.title = data[titleOffset:titleEnd]
731 }
732
733 // id matches are case-insensitive
734 id := string(bytes.ToLower(data[idOffset:idEnd]))
735
736 p.refs[id] = ref
737
738 return lineEnd
739}
740
741func scanLinkRef(p *parser, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) {
742 // link: whitespace-free sequence, optionally between angle brackets
743 if data[i] == '<' {
744 i++
745 }
746 linkOffset = i
747 for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
748 i++
749 }
750 if i == len(data) {
751 return
752 }
753 linkEnd = i
754 if data[linkOffset] == '<' && data[linkEnd-1] == '>' {
755 linkOffset++
756 linkEnd--
757 }
758
759 // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' )
760 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
761 i++
762 }
763 if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' {
764 return
765 }
766
767 // compute end-of-line
768 if i >= len(data) || data[i] == '\r' || data[i] == '\n' {
769 lineEnd = i
770 }
771 if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' {
772 lineEnd++
773 }
774
775 // optional (space|tab)* spacer after a newline
776 if lineEnd > 0 {
777 i = lineEnd + 1
778 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
779 i++
780 }
781 }
782
783 // optional title: any non-newline sequence enclosed in '"() alone on its line
784 if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') {
785 i++
786 titleOffset = i
787
788 // look for EOL
789 for i < len(data) && data[i] != '\n' && data[i] != '\r' {
790 i++
791 }
792 if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' {
793 titleEnd = i + 1
794 } else {
795 titleEnd = i
796 }
797
798 // step back
799 i--
800 for i > titleOffset && (data[i] == ' ' || data[i] == '\t') {
801 i--
802 }
803 if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') {
804 lineEnd = titleEnd
805 titleEnd = i
806 }
807 }
808
809 return
810}
811
812// The first bit of this logic is the same as (*parser).listItem, but the rest
813// is much simpler. This function simply finds the entire block and shifts it
814// over by one tab if it is indeed a block (just returns the line if it's not).
815// blockEnd is the end of the section in the input buffer, and contents is the
816// extracted text that was shifted over one tab. It will need to be rendered at
817// the end of the document.
818func scanFootnote(p *parser, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) {
819 if i == 0 || len(data) == 0 {
820 return
821 }
822
823 // skip leading whitespace on first line
824 for i < len(data) && data[i] == ' ' {
825 i++
826 }
827
828 blockStart = i
829
830 // find the end of the line
831 blockEnd = i
832 for i < len(data) && data[i-1] != '\n' {
833 i++
834 }
835
836 // get working buffer
837 var raw bytes.Buffer
838
839 // put the first line into the working buffer
840 raw.Write(data[blockEnd:i])
841 blockEnd = i
842
843 // process the following lines
844 containsBlankLine := false
845
846gatherLines:
847 for blockEnd < len(data) {
848 i++
849
850 // find the end of this line
851 for i < len(data) && data[i-1] != '\n' {
852 i++
853 }
854
855 // if it is an empty line, guess that it is part of this item
856 // and move on to the next line
857 if p.isEmpty(data[blockEnd:i]) > 0 {
858 containsBlankLine = true
859 blockEnd = i
860 continue
861 }
862
863 n := 0
864 if n = isIndented(data[blockEnd:i], indentSize); n == 0 {
865 // this is the end of the block.
866 // we don't want to include this last line in the index.
867 break gatherLines
868 }
869
870 // if there were blank lines before this one, insert a new one now
871 if containsBlankLine {
872 raw.WriteByte('\n')
873 containsBlankLine = false
874 }
875
876 // get rid of that first tab, write to buffer
877 raw.Write(data[blockEnd+n : i])
878 hasBlock = true
879
880 blockEnd = i
881 }
882
883 if data[blockEnd-1] != '\n' {
884 raw.WriteByte('\n')
885 }
886
887 contents = raw.Bytes()
888
889 return
890}
891
892//
893//
894// Miscellaneous helper functions
895//
896//
897
898// Test if a character is a punctuation symbol.
899// Taken from a private function in regexp in the stdlib.
900func ispunct(c byte) bool {
901 for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
902 if c == r {
903 return true
904 }
905 }
906 return false
907}
908
909// Test if a character is a whitespace character.
910func isspace(c byte) bool {
911 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
912}
913
914// Test if a character is letter.
915func isletter(c byte) bool {
916 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
917}
918
919// Test if a character is a letter or a digit.
920// TODO: check when this is looking for ASCII alnum and when it should use unicode
921func isalnum(c byte) bool {
922 return (c >= '0' && c <= '9') || isletter(c)
923}
924
925// Replace tab characters with spaces, aligning to the next TAB_SIZE column.
926// always ends output with a newline
927func expandTabs(out *bytes.Buffer, line []byte, tabSize int) {
928 // first, check for common cases: no tabs, or only tabs at beginning of line
929 i, prefix := 0, 0
930 slowcase := false
931 for i = 0; i < len(line); i++ {
932 if line[i] == '\t' {
933 if prefix == i {
934 prefix++
935 } else {
936 slowcase = true
937 break
938 }
939 }
940 }
941
942 // no need to decode runes if all tabs are at the beginning of the line
943 if !slowcase {
944 for i = 0; i < prefix*tabSize; i++ {
945 out.WriteByte(' ')
946 }
947 out.Write(line[prefix:])
948 return
949 }
950
951 // the slow case: we need to count runes to figure out how
952 // many spaces to insert for each tab
953 column := 0
954 i = 0
955 for i < len(line) {
956 start := i
957 for i < len(line) && line[i] != '\t' {
958 _, size := utf8.DecodeRune(line[i:])
959 i += size
960 column++
961 }
962
963 if i > start {
964 out.Write(line[start:i])
965 }
966
967 if i >= len(line) {
968 break
969 }
970
971 for {
972 out.WriteByte(' ')
973 column++
974 if column%tabSize == 0 {
975 break
976 }
977 }
978
979 i++
980 }
981}
982
983// Find if a line counts as indented or not.
984// Returns number of characters the indent is (0 = not indented).
985func isIndented(data []byte, indentSize int) int {
986 if len(data) == 0 {
987 return 0
988 }
989 if data[0] == '\t' {
990 return 1
991 }
992 if len(data) < indentSize {
993 return 0
994 }
995 for i := 0; i < indentSize; i++ {
996 if data[i] != ' ' {
997 return 0
998 }
999 }
1000 return indentSize
1001}
1002
1003// Create a url-safe slug for fragments
1004func slugify(in []byte) []byte {
1005 if len(in) == 0 {
1006 return in
1007 }
1008 out := make([]byte, 0, len(in))
1009 sym := false
1010
1011 for _, ch := range in {
1012 if isalnum(ch) {
1013 sym = false
1014 out = append(out, ch)
1015 } else if sym {
1016 continue
1017 } else {
1018 out = append(out, '-')
1019 sym = true
1020 }
1021 }
1022 var a, b int
1023 var ch byte
1024 for a, ch = range out {
1025 if ch != '-' {
1026 break
1027 }
1028 }
1029 for b = len(out) - 1; b > 0; b-- {
1030 if out[b] != '-' {
1031 break
1032 }
1033 }
1034 return out[a : b+1]
1035}