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