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