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