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