ux/Showdown.js
[roojs1] / ux / Showdown.js
1 //
2  /**
3  * marked - a markdown parser
4  * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
5  * https://github.com/chjj/marked
6  */
7
8
9 //
10 // Showdown usage:
11 // 
12 //   alert( Roo.ux.Showdown.toHtml("Markdown *rocks*.") );
13 // 
14 // Note: move the sample code to the bottom of this
15 // file before uncommenting it.
16 //
17
18
19 //
20 // Showdown namespace
21 //
22 Roo.namespace('Roo.ux'); 
23 Roo.ux.Showdown = {};
24 Roo.ux.Showdown.toHtml = function(text) {
25     
26     var c = new Roo.ux.Showdown.marked.setOptions({
27             renderer: new Roo.ux.Showdown.marked.Renderer(),
28             gfm: true,
29             tables: true,
30             breaks: false,
31             pedantic: false,
32             sanitize: false,
33             smartLists: true,
34             smartypants: false
35           });
36
37     return Roo.ux.Showdown.marked(text);
38 };
39 //
40 // converter
41 //
42 // Wraps all "globals" so that the only thing
43 // exposed is makeHtml().
44 //
45 (function() {
46     
47     /**
48      * Block-Level Grammar
49      */
50     
51     var block = {
52       newline: /^\n+/,
53       code: /^( {4}[^\n]+\n*)+/,
54       fences: noop,
55       hr: /^( *[-*_]){3,} *(?:\n+|$)/,
56       heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
57       nptable: noop,
58       lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
59       blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
60       list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
61       html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
62       def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
63       table: noop,
64       paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
65       text: /^[^\n]+/
66     };
67     
68     block.bullet = /(?:[*+-]|\d+\.)/;
69     block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
70     block.item = replace(block.item, 'gm')
71       (/bull/g, block.bullet)
72       ();
73     
74     block.list = replace(block.list)
75       (/bull/g, block.bullet)
76       ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
77       ('def', '\\n+(?=' + block.def.source + ')')
78       ();
79     
80     block.blockquote = replace(block.blockquote)
81       ('def', block.def)
82       ();
83     
84     block._tag = '(?!(?:'
85       + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
86       + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
87       + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
88     
89     block.html = replace(block.html)
90       ('comment', /<!--[\s\S]*?-->/)
91       ('closed', /<(tag)[\s\S]+?<\/\1>/)
92       ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
93       (/tag/g, block._tag)
94       ();
95     
96     block.paragraph = replace(block.paragraph)
97       ('hr', block.hr)
98       ('heading', block.heading)
99       ('lheading', block.lheading)
100       ('blockquote', block.blockquote)
101       ('tag', '<' + block._tag)
102       ('def', block.def)
103       ();
104     
105     /**
106      * Normal Block Grammar
107      */
108     
109     block.normal = merge({}, block);
110     
111     /**
112      * GFM Block Grammar
113      */
114     
115     block.gfm = merge({}, block.normal, {
116       fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
117       paragraph: /^/,
118       heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
119     });
120     
121     block.gfm.paragraph = replace(block.paragraph)
122       ('(?!', '(?!'
123         + block.gfm.fences.source.replace('\\1', '\\2') + '|'
124         + block.list.source.replace('\\1', '\\3') + '|')
125       ();
126     
127     /**
128      * GFM + Tables Block Grammar
129      */
130     
131     block.tables = merge({}, block.gfm, {
132       nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
133       table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
134     });
135     
136     /**
137      * Block Lexer
138      */
139     
140     function Lexer(options) {
141       this.tokens = [];
142       this.tokens.links = {};
143       this.options = options || marked.defaults;
144       this.rules = block.normal;
145     
146       if (this.options.gfm) {
147         if (this.options.tables) {
148           this.rules = block.tables;
149         } else {
150           this.rules = block.gfm;
151         }
152       }
153     }
154     
155     /**
156      * Expose Block Rules
157      */
158     
159     Lexer.rules = block;
160     
161     /**
162      * Static Lex Method
163      */
164     
165     Lexer.lex = function(src, options) {
166       var lexer = new Lexer(options);
167       return lexer.lex(src);
168     };
169     
170     /**
171      * Preprocessing
172      */
173     
174     Lexer.prototype.lex = function(src) {
175       src = src
176         .replace(/\r\n|\r/g, '\n')
177         .replace(/\t/g, '    ')
178         .replace(/\u00a0/g, ' ')
179         .replace(/\u2424/g, '\n');
180     
181       return this.token(src, true);
182     };
183     
184     /**
185      * Lexing
186      */
187     
188     Lexer.prototype.token = function(src, top, bq) {
189       var src = src.replace(/^ +$/gm, '')
190         , next
191         , loose
192         , cap
193         , bull
194         , b
195         , item
196         , space
197         , i
198         , l;
199     
200       while (src) {
201         // newline
202         if (cap = this.rules.newline.exec(src)) {
203           src = src.substring(cap[0].length);
204           if (cap[0].length > 1) {
205             this.tokens.push({
206               type: 'space'
207             });
208           }
209         }
210     
211         // code
212         if (cap = this.rules.code.exec(src)) {
213           src = src.substring(cap[0].length);
214           cap = cap[0].replace(/^ {4}/gm, '');
215           this.tokens.push({
216             type: 'code',
217             text: !this.options.pedantic
218               ? cap.replace(/\n+$/, '')
219               : cap
220           });
221           continue;
222         }
223     
224         // fences (gfm)
225         if (cap = this.rules.fences.exec(src)) {
226           src = src.substring(cap[0].length);
227           this.tokens.push({
228             type: 'code',
229             lang: cap[2],
230             text: cap[3] || ''
231           });
232           continue;
233         }
234     
235         // heading
236         if (cap = this.rules.heading.exec(src)) {
237           src = src.substring(cap[0].length);
238           this.tokens.push({
239             type: 'heading',
240             depth: cap[1].length,
241             text: cap[2]
242           });
243           continue;
244         }
245     
246         // table no leading pipe (gfm)
247         if (top && (cap = this.rules.nptable.exec(src))) {
248           src = src.substring(cap[0].length);
249     
250           item = {
251             type: 'table',
252             header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
253             align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
254             cells: cap[3].replace(/\n$/, '').split('\n')
255           };
256     
257           for (i = 0; i < item.align.length; i++) {
258             if (/^ *-+: *$/.test(item.align[i])) {
259               item.align[i] = 'right';
260             } else if (/^ *:-+: *$/.test(item.align[i])) {
261               item.align[i] = 'center';
262             } else if (/^ *:-+ *$/.test(item.align[i])) {
263               item.align[i] = 'left';
264             } else {
265               item.align[i] = null;
266             }
267           }
268     
269           for (i = 0; i < item.cells.length; i++) {
270             item.cells[i] = item.cells[i].split(/ *\| */);
271           }
272     
273           this.tokens.push(item);
274     
275           continue;
276         }
277     
278         // lheading
279         if (cap = this.rules.lheading.exec(src)) {
280           src = src.substring(cap[0].length);
281           this.tokens.push({
282             type: 'heading',
283             depth: cap[2] === '=' ? 1 : 2,
284             text: cap[1]
285           });
286           continue;
287         }
288     
289         // hr
290         if (cap = this.rules.hr.exec(src)) {
291           src = src.substring(cap[0].length);
292           this.tokens.push({
293             type: 'hr'
294           });
295           continue;
296         }
297     
298         // blockquote
299         if (cap = this.rules.blockquote.exec(src)) {
300           src = src.substring(cap[0].length);
301     
302           this.tokens.push({
303             type: 'blockquote_start'
304           });
305     
306           cap = cap[0].replace(/^ *> ?/gm, '');
307     
308           // Pass `top` to keep the current
309           // "toplevel" state. This is exactly
310           // how markdown.pl works.
311           this.token(cap, top, true);
312     
313           this.tokens.push({
314             type: 'blockquote_end'
315           });
316     
317           continue;
318         }
319     
320         // list
321         if (cap = this.rules.list.exec(src)) {
322           src = src.substring(cap[0].length);
323           bull = cap[2];
324     
325           this.tokens.push({
326             type: 'list_start',
327             ordered: bull.length > 1
328           });
329     
330           // Get each top-level item.
331           cap = cap[0].match(this.rules.item);
332     
333           next = false;
334           l = cap.length;
335           i = 0;
336     
337           for (; i < l; i++) {
338             item = cap[i];
339     
340             // Remove the list item's bullet
341             // so it is seen as the next token.
342             space = item.length;
343             item = item.replace(/^ *([*+-]|\d+\.) +/, '');
344     
345             // Outdent whatever the
346             // list item contains. Hacky.
347             if (~item.indexOf('\n ')) {
348               space -= item.length;
349               item = !this.options.pedantic
350                 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
351                 : item.replace(/^ {1,4}/gm, '');
352             }
353     
354             // Determine whether the next list item belongs here.
355             // Backpedal if it does not belong in this list.
356             if (this.options.smartLists && i !== l - 1) {
357               b = block.bullet.exec(cap[i + 1])[0];
358               if (bull !== b && !(bull.length > 1 && b.length > 1)) {
359                 src = cap.slice(i + 1).join('\n') + src;
360                 i = l - 1;
361               }
362             }
363     
364             // Determine whether item is loose or not.
365             // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
366             // for discount behavior.
367             loose = next || /\n\n(?!\s*$)/.test(item);
368             if (i !== l - 1) {
369               next = item.charAt(item.length - 1) === '\n';
370               if (!loose) loose = next;
371             }
372     
373             this.tokens.push({
374               type: loose
375                 ? 'loose_item_start'
376                 : 'list_item_start'
377             });
378     
379             // Recurse.
380             this.token(item, false, bq);
381     
382             this.tokens.push({
383               type: 'list_item_end'
384             });
385           }
386     
387           this.tokens.push({
388             type: 'list_end'
389           });
390     
391           continue;
392         }
393     
394         // html
395         if (cap = this.rules.html.exec(src)) {
396           src = src.substring(cap[0].length);
397           this.tokens.push({
398             type: this.options.sanitize
399               ? 'paragraph'
400               : 'html',
401             pre: !this.options.sanitizer
402               && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
403             text: cap[0]
404           });
405           continue;
406         }
407     
408         // def
409         if ((!bq && top) && (cap = this.rules.def.exec(src))) {
410           src = src.substring(cap[0].length);
411           this.tokens.links[cap[1].toLowerCase()] = {
412             href: cap[2],
413             title: cap[3]
414           };
415           continue;
416         }
417     
418         // table (gfm)
419         if (top && (cap = this.rules.table.exec(src))) {
420           src = src.substring(cap[0].length);
421     
422           item = {
423             type: 'table',
424             header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
425             align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
426             cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
427           };
428     
429           for (i = 0; i < item.align.length; i++) {
430             if (/^ *-+: *$/.test(item.align[i])) {
431               item.align[i] = 'right';
432             } else if (/^ *:-+: *$/.test(item.align[i])) {
433               item.align[i] = 'center';
434             } else if (/^ *:-+ *$/.test(item.align[i])) {
435               item.align[i] = 'left';
436             } else {
437               item.align[i] = null;
438             }
439           }
440     
441           for (i = 0; i < item.cells.length; i++) {
442             item.cells[i] = item.cells[i]
443               .replace(/^ *\| *| *\| *$/g, '')
444               .split(/ *\| */);
445           }
446     
447           this.tokens.push(item);
448     
449           continue;
450         }
451     
452         // top-level paragraph
453         if (top && (cap = this.rules.paragraph.exec(src))) {
454           src = src.substring(cap[0].length);
455           this.tokens.push({
456             type: 'paragraph',
457             text: cap[1].charAt(cap[1].length - 1) === '\n'
458               ? cap[1].slice(0, -1)
459               : cap[1]
460           });
461           continue;
462         }
463     
464         // text
465         if (cap = this.rules.text.exec(src)) {
466           // Top-level should never reach here.
467           src = src.substring(cap[0].length);
468           this.tokens.push({
469             type: 'text',
470             text: cap[0]
471           });
472           continue;
473         }
474     
475         if (src) {
476           throw new
477             Error('Infinite loop on byte: ' + src.charCodeAt(0));
478         }
479       }
480     
481       return this.tokens;
482     };
483     
484     /**
485      * Inline-Level Grammar
486      */
487     
488     var inline = {
489       escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
490       autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
491       url: noop,
492       tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
493       link: /^!?\[(inside)\]\(href\)/,
494       reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
495       nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
496       strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
497       em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
498       code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
499       br: /^ {2,}\n(?!\s*$)/,
500       del: noop,
501       text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
502     };
503     
504     inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
505     inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
506     
507     inline.link = replace(inline.link)
508       ('inside', inline._inside)
509       ('href', inline._href)
510       ();
511     
512     inline.reflink = replace(inline.reflink)
513       ('inside', inline._inside)
514       ();
515     
516     /**
517      * Normal Inline Grammar
518      */
519     
520     inline.normal = merge({}, inline);
521     
522     /**
523      * Pedantic Inline Grammar
524      */
525     
526     inline.pedantic = merge({}, inline.normal, {
527       strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
528       em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
529     });
530     
531     /**
532      * GFM Inline Grammar
533      */
534     
535     inline.gfm = merge({}, inline.normal, {
536       escape: replace(inline.escape)('])', '~|])')(),
537       url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
538       del: /^~~(?=\S)([\s\S]*?\S)~~/,
539       text: replace(inline.text)
540         (']|', '~]|')
541         ('|', '|https?://|')
542         ()
543     });
544     
545     /**
546      * GFM + Line Breaks Inline Grammar
547      */
548     
549     inline.breaks = merge({}, inline.gfm, {
550       br: replace(inline.br)('{2,}', '*')(),
551       text: replace(inline.gfm.text)('{2,}', '*')()
552     });
553     
554     /**
555      * Inline Lexer & Compiler
556      */
557     
558     function InlineLexer(links, options) {
559       this.options = options || marked.defaults;
560       this.links = links;
561       this.rules = inline.normal;
562       this.renderer = this.options.renderer || new Renderer;
563       this.renderer.options = this.options;
564     
565       if (!this.links) {
566         throw new
567           Error('Tokens array requires a `links` property.');
568       }
569     
570       if (this.options.gfm) {
571         if (this.options.breaks) {
572           this.rules = inline.breaks;
573         } else {
574           this.rules = inline.gfm;
575         }
576       } else if (this.options.pedantic) {
577         this.rules = inline.pedantic;
578       }
579     }
580     
581     /**
582      * Expose Inline Rules
583      */
584     
585     InlineLexer.rules = inline;
586     
587     /**
588      * Static Lexing/Compiling Method
589      */
590     
591     InlineLexer.output = function(src, links, options) {
592       var inline = new InlineLexer(links, options);
593       return inline.output(src);
594     };
595     
596     /**
597      * Lexing/Compiling
598      */
599     
600     InlineLexer.prototype.output = function(src) {
601       var out = ''
602         , link
603         , text
604         , href
605         , cap;
606     
607       while (src) {
608         // escape
609         if (cap = this.rules.escape.exec(src)) {
610           src = src.substring(cap[0].length);
611           out += cap[1];
612           continue;
613         }
614     
615         // autolink
616         if (cap = this.rules.autolink.exec(src)) {
617           src = src.substring(cap[0].length);
618           if (cap[2] === '@') {
619             text = cap[1].charAt(6) === ':'
620               ? this.mangle(cap[1].substring(7))
621               : this.mangle(cap[1]);
622             href = this.mangle('mailto:') + text;
623           } else {
624             text = escape(cap[1]);
625             href = text;
626           }
627           out += this.renderer.link(href, null, text);
628           continue;
629         }
630     
631         // url (gfm)
632         if (!this.inLink && (cap = this.rules.url.exec(src))) {
633           src = src.substring(cap[0].length);
634           text = escape(cap[1]);
635           href = text;
636           out += this.renderer.link(href, null, text);
637           continue;
638         }
639     
640         // tag
641         if (cap = this.rules.tag.exec(src)) {
642           if (!this.inLink && /^<a /i.test(cap[0])) {
643             this.inLink = true;
644           } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
645             this.inLink = false;
646           }
647           src = src.substring(cap[0].length);
648           out += this.options.sanitize
649             ? this.options.sanitizer
650               ? this.options.sanitizer(cap[0])
651               : escape(cap[0])
652             : cap[0]
653           continue;
654         }
655     
656         // link
657         if (cap = this.rules.link.exec(src)) {
658           src = src.substring(cap[0].length);
659           this.inLink = true;
660           out += this.outputLink(cap, {
661             href: cap[2],
662             title: cap[3]
663           });
664           this.inLink = false;
665           continue;
666         }
667     
668         // reflink, nolink
669         if ((cap = this.rules.reflink.exec(src))
670             || (cap = this.rules.nolink.exec(src))) {
671           src = src.substring(cap[0].length);
672           link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
673           link = this.links[link.toLowerCase()];
674           if (!link || !link.href) {
675             out += cap[0].charAt(0);
676             src = cap[0].substring(1) + src;
677             continue;
678           }
679           this.inLink = true;
680           out += this.outputLink(cap, link);
681           this.inLink = false;
682           continue;
683         }
684     
685         // strong
686         if (cap = this.rules.strong.exec(src)) {
687           src = src.substring(cap[0].length);
688           out += this.renderer.strong(this.output(cap[2] || cap[1]));
689           continue;
690         }
691     
692         // em
693         if (cap = this.rules.em.exec(src)) {
694           src = src.substring(cap[0].length);
695           out += this.renderer.em(this.output(cap[2] || cap[1]));
696           continue;
697         }
698     
699         // code
700         if (cap = this.rules.code.exec(src)) {
701           src = src.substring(cap[0].length);
702           out += this.renderer.codespan(escape(cap[2], true));
703           continue;
704         }
705     
706         // br
707         if (cap = this.rules.br.exec(src)) {
708           src = src.substring(cap[0].length);
709           out += this.renderer.br();
710           continue;
711         }
712     
713         // del (gfm)
714         if (cap = this.rules.del.exec(src)) {
715           src = src.substring(cap[0].length);
716           out += this.renderer.del(this.output(cap[1]));
717           continue;
718         }
719     
720         // text
721         if (cap = this.rules.text.exec(src)) {
722           src = src.substring(cap[0].length);
723           out += this.renderer.text(escape(this.smartypants(cap[0])));
724           continue;
725         }
726     
727         if (src) {
728           throw new
729             Error('Infinite loop on byte: ' + src.charCodeAt(0));
730         }
731       }
732     
733       return out;
734     };
735     
736     /**
737      * Compile Link
738      */
739     
740     InlineLexer.prototype.outputLink = function(cap, link) {
741       var href = escape(link.href)
742         , title = link.title ? escape(link.title) : null;
743     
744       return cap[0].charAt(0) !== '!'
745         ? this.renderer.link(href, title, this.output(cap[1]))
746         : this.renderer.image(href, title, escape(cap[1]));
747     };
748     
749     /**
750      * Smartypants Transformations
751      */
752     
753     InlineLexer.prototype.smartypants = function(text) {
754       if (!this.options.smartypants) return text;
755       return text
756         // em-dashes
757         .replace(/---/g, '\u2014')
758         // en-dashes
759         .replace(/--/g, '\u2013')
760         // opening singles
761         .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
762         // closing singles & apostrophes
763         .replace(/'/g, '\u2019')
764         // opening doubles
765         .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
766         // closing doubles
767         .replace(/"/g, '\u201d')
768         // ellipses
769         .replace(/\.{3}/g, '\u2026');
770     };
771     
772     /**
773      * Mangle Links
774      */
775     
776     InlineLexer.prototype.mangle = function(text) {
777       if (!this.options.mangle) return text;
778       var out = ''
779         , l = text.length
780         , i = 0
781         , ch;
782     
783       for (; i < l; i++) {
784         ch = text.charCodeAt(i);
785         if (Math.random() > 0.5) {
786           ch = 'x' + ch.toString(16);
787         }
788         out += '&#' + ch + ';';
789       }
790     
791       return out;
792     };
793     
794     /**
795      * Renderer
796      */
797     
798     function Renderer(options) {
799       this.options = options || {};
800     }
801     
802     Renderer.prototype.code = function(code, lang, escaped) {
803       if (this.options.highlight) {
804         var out = this.options.highlight(code, lang);
805         if (out != null && out !== code) {
806           escaped = true;
807           code = out;
808         }
809       }
810       escaped = true;
811     
812       if (!lang) {
813         return '<pre><code>'
814           + (escaped ? code : escape(code, true))
815           + '\n</code></pre>';
816       }
817     
818       return '<pre><code class="'
819         + this.options.langPrefix
820         + escape(lang, true)
821         + '">'
822         + (escaped ? code : escape(code, true))
823         + '\n</code></pre>\n';
824     };
825     
826     Renderer.prototype.blockquote = function(quote) {
827       return '<blockquote>\n' + quote + '</blockquote>\n';
828     };
829     
830     Renderer.prototype.html = function(html) {
831       return html;
832     };
833     
834     Renderer.prototype.heading = function(text, level, raw) {
835       return '<h'
836         + level
837         + ' id="'
838         + this.options.headerPrefix
839         + raw.toLowerCase().replace(/[^\w]+/g, '-')
840         + '">'
841         + text
842         + '</h'
843         + level
844         + '>\n';
845     };
846     
847     Renderer.prototype.hr = function() {
848       return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
849     };
850     
851     Renderer.prototype.list = function(body, ordered) {
852       var type = ordered ? 'ol' : 'ul';
853       return '<' + type + '>\n' + body + '</' + type + '>\n';
854     };
855     
856     Renderer.prototype.listitem = function(text) {
857       return '<li>' + text + '</li>\n';
858     };
859     
860     Renderer.prototype.paragraph = function(text) {
861       return '<p>' + text + '</p>\n';
862     };
863     
864     Renderer.prototype.table = function(header, body) {
865       return '<table>\n'
866         + '<thead>\n'
867         + header
868         + '</thead>\n'
869         + '<tbody>\n'
870         + body
871         + '</tbody>\n'
872         + '</table>\n';
873     };
874     
875     Renderer.prototype.tablerow = function(content) {
876       return '<tr>\n' + content + '</tr>\n';
877     };
878     
879     Renderer.prototype.tablecell = function(content, flags) {
880       var type = flags.header ? 'th' : 'td';
881       var tag = flags.align
882         ? '<' + type + ' style="text-align:' + flags.align + '">'
883         : '<' + type + '>';
884       return tag + content + '</' + type + '>\n';
885     };
886     
887     // span level renderer
888     Renderer.prototype.strong = function(text) {
889       return '<strong>' + text + '</strong>';
890     };
891     
892     Renderer.prototype.em = function(text) {
893       return '<em>' + text + '</em>';
894     };
895     
896     Renderer.prototype.codespan = function(text) {
897       return '<code>' + text + '</code>';
898     };
899     
900     Renderer.prototype.br = function() {
901       return this.options.xhtml ? '<br/>' : '<br>';
902     };
903     
904     Renderer.prototype.del = function(text) {
905       return '<del>' + text + '</del>';
906     };
907     
908     Renderer.prototype.link = function(href, title, text) {
909       if (this.options.sanitize) {
910         try {
911           var prot = decodeURIComponent(unescape(href))
912             .replace(/[^\w:]/g, '')
913             .toLowerCase();
914         } catch (e) {
915           return '';
916         }
917         if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
918           return '';
919         }
920       }
921       var out = '<a href="' + href + '"';
922       if (title) {
923         out += ' title="' + title + '"';
924       }
925       out += '>' + text + '</a>';
926       return out;
927     };
928     
929     Renderer.prototype.image = function(href, title, text) {
930       var out = '<img src="' + href + '" alt="' + text + '"';
931       if (title) {
932         out += ' title="' + title + '"';
933       }
934       out += this.options.xhtml ? '/>' : '>';
935       return out;
936     };
937     
938     Renderer.prototype.text = function(text) {
939       return text;
940     };
941     
942     /**
943      * Parsing & Compiling
944      */
945     
946     function Parser(options) {
947       this.tokens = [];
948       this.token = null;
949       this.options = options || marked.defaults;
950       this.options.renderer = this.options.renderer || new Renderer;
951       this.renderer = this.options.renderer;
952       this.renderer.options = this.options;
953     }
954     
955     /**
956      * Static Parse Method
957      */
958     
959     Parser.parse = function(src, options, renderer) {
960       var parser = new Parser(options, renderer);
961       return parser.parse(src);
962     };
963     
964     /**
965      * Parse Loop
966      */
967     
968     Parser.prototype.parse = function(src) {
969       this.inline = new InlineLexer(src.links, this.options, this.renderer);
970       this.tokens = src.reverse();
971     
972       var out = '';
973       while (this.next()) {
974         out += this.tok();
975       }
976     
977       return out;
978     };
979     
980     /**
981      * Next Token
982      */
983     
984     Parser.prototype.next = function() {
985       return this.token = this.tokens.pop();
986     };
987     
988     /**
989      * Preview Next Token
990      */
991     
992     Parser.prototype.peek = function() {
993       return this.tokens[this.tokens.length - 1] || 0;
994     };
995     
996     /**
997      * Parse Text Tokens
998      */
999     
1000     Parser.prototype.parseText = function() {
1001       var body = this.token.text;
1002     
1003       while (this.peek().type === 'text') {
1004         body += '\n' + this.next().text;
1005       }
1006     
1007       return this.inline.output(body);
1008     };
1009     
1010     /**
1011      * Parse Current Token
1012      */
1013     
1014     Parser.prototype.tok = function() {
1015       switch (this.token.type) {
1016         case 'space': {
1017           return '';
1018         }
1019         case 'hr': {
1020           return this.renderer.hr();
1021         }
1022         case 'heading': {
1023           return this.renderer.heading(
1024             this.inline.output(this.token.text),
1025             this.token.depth,
1026             this.token.text);
1027         }
1028         case 'code': {
1029           return this.renderer.code(this.token.text,
1030             this.token.lang,
1031             this.token.escaped);
1032         }
1033         case 'table': {
1034           var header = ''
1035             , body = ''
1036             , i
1037             , row
1038             , cell
1039             , flags
1040             , j;
1041     
1042           // header
1043           cell = '';
1044           for (i = 0; i < this.token.header.length; i++) {
1045             flags = { header: true, align: this.token.align[i] };
1046             cell += this.renderer.tablecell(
1047               this.inline.output(this.token.header[i]),
1048               { header: true, align: this.token.align[i] }
1049             );
1050           }
1051           header += this.renderer.tablerow(cell);
1052     
1053           for (i = 0; i < this.token.cells.length; i++) {
1054             row = this.token.cells[i];
1055     
1056             cell = '';
1057             for (j = 0; j < row.length; j++) {
1058               cell += this.renderer.tablecell(
1059                 this.inline.output(row[j]),
1060                 { header: false, align: this.token.align[j] }
1061               );
1062             }
1063     
1064             body += this.renderer.tablerow(cell);
1065           }
1066           return this.renderer.table(header, body);
1067         }
1068         case 'blockquote_start': {
1069           var body = '';
1070     
1071           while (this.next().type !== 'blockquote_end') {
1072             body += this.tok();
1073           }
1074     
1075           return this.renderer.blockquote(body);
1076         }
1077         case 'list_start': {
1078           var body = ''
1079             , ordered = this.token.ordered;
1080     
1081           while (this.next().type !== 'list_end') {
1082             body += this.tok();
1083           }
1084     
1085           return this.renderer.list(body, ordered);
1086         }
1087         case 'list_item_start': {
1088           var body = '';
1089     
1090           while (this.next().type !== 'list_item_end') {
1091             body += this.token.type === 'text'
1092               ? this.parseText()
1093               : this.tok();
1094           }
1095     
1096           return this.renderer.listitem(body);
1097         }
1098         case 'loose_item_start': {
1099           var body = '';
1100     
1101           while (this.next().type !== 'list_item_end') {
1102             body += this.tok();
1103           }
1104     
1105           return this.renderer.listitem(body);
1106         }
1107         case 'html': {
1108           var html = !this.token.pre && !this.options.pedantic
1109             ? this.inline.output(this.token.text)
1110             : this.token.text;
1111           return this.renderer.html(html);
1112         }
1113         case 'paragraph': {
1114           return this.renderer.paragraph(this.inline.output(this.token.text));
1115         }
1116         case 'text': {
1117           return this.renderer.paragraph(this.parseText());
1118         }
1119       }
1120     };
1121     
1122     /**
1123      * Helpers
1124      */
1125     
1126     function escape(html, encode) {
1127       return html
1128         .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
1129         .replace(/</g, '&lt;')
1130         .replace(/>/g, '&gt;')
1131         .replace(/"/g, '&quot;')
1132         .replace(/'/g, '&#39;');
1133     }
1134     
1135     function unescape(html) {
1136         // explicitly match decimal, hex, and named HTML entities 
1137       return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
1138         n = n.toLowerCase();
1139         if (n === 'colon') return ':';
1140         if (n.charAt(0) === '#') {
1141           return n.charAt(1) === 'x'
1142             ? String.fromCharCode(parseInt(n.substring(2), 16))
1143             : String.fromCharCode(+n.substring(1));
1144         }
1145         return '';
1146       });
1147     }
1148     
1149     function replace(regex, opt) {
1150       regex = regex.source;
1151       opt = opt || '';
1152       return function self(name, val) {
1153         if (!name) return new RegExp(regex, opt);
1154         val = val.source || val;
1155         val = val.replace(/(^|[^\[])\^/g, '$1');
1156         regex = regex.replace(name, val);
1157         return self;
1158       };
1159     }
1160     
1161     function noop() {}
1162     noop.exec = noop;
1163     
1164     function merge(obj) {
1165       var i = 1
1166         , target
1167         , key;
1168     
1169       for (; i < arguments.length; i++) {
1170         target = arguments[i];
1171         for (key in target) {
1172           if (Object.prototype.hasOwnProperty.call(target, key)) {
1173             obj[key] = target[key];
1174           }
1175         }
1176       }
1177     
1178       return obj;
1179     }
1180     
1181     
1182     /**
1183      * Marked
1184      */
1185     
1186     function marked(src, opt, callback) {
1187       if (callback || typeof opt === 'function') {
1188         if (!callback) {
1189           callback = opt;
1190           opt = null;
1191         }
1192     
1193         opt = merge({}, marked.defaults, opt || {});
1194     
1195         var highlight = opt.highlight
1196           , tokens
1197           , pending
1198           , i = 0;
1199     
1200         try {
1201           tokens = Lexer.lex(src, opt)
1202         } catch (e) {
1203           return callback(e);
1204         }
1205     
1206         pending = tokens.length;
1207     
1208         var done = function(err) {
1209           if (err) {
1210             opt.highlight = highlight;
1211             return callback(err);
1212           }
1213     
1214           var out;
1215     
1216           try {
1217             out = Parser.parse(tokens, opt);
1218           } catch (e) {
1219             err = e;
1220           }
1221     
1222           opt.highlight = highlight;
1223     
1224           return err
1225             ? callback(err)
1226             : callback(null, out);
1227         };
1228     
1229         if (!highlight || highlight.length < 3) {
1230           return done();
1231         }
1232     
1233         delete opt.highlight;
1234     
1235         if (!pending) return done();
1236     
1237         for (; i < tokens.length; i++) {
1238           (function(token) {
1239             if (token.type !== 'code') {
1240               return --pending || done();
1241             }
1242             return highlight(token.text, token.lang, function(err, code) {
1243               if (err) return done(err);
1244               if (code == null || code === token.text) {
1245                 return --pending || done();
1246               }
1247               token.text = code;
1248               token.escaped = true;
1249               --pending || done();
1250             });
1251           })(tokens[i]);
1252         }
1253     
1254         return;
1255       }
1256       try {
1257         if (opt) opt = merge({}, marked.defaults, opt);
1258         return Parser.parse(Lexer.lex(src, opt), opt);
1259       } catch (e) {
1260         e.message += '\nPlease report this to https://github.com/chjj/marked.';
1261         if ((opt || marked.defaults).silent) {
1262           return '<p>An error occured:</p><pre>'
1263             + escape(e.message + '', true)
1264             + '</pre>';
1265         }
1266         throw e;
1267       }
1268     }
1269     
1270     /**
1271      * Options
1272      */
1273     
1274     marked.options =
1275     marked.setOptions = function(opt) {
1276       merge(marked.defaults, opt);
1277       return marked;
1278     };
1279     
1280     marked.defaults = {
1281       gfm: true,
1282       tables: true,
1283       breaks: false,
1284       pedantic: false,
1285       sanitize: false,
1286       sanitizer: null,
1287       mangle: true,
1288       smartLists: false,
1289       silent: false,
1290       highlight: null,
1291       langPrefix: 'lang-',
1292       smartypants: false,
1293       headerPrefix: '',
1294       renderer: new Renderer,
1295       xhtml: false
1296     };
1297     
1298     /**
1299      * Expose
1300      */
1301     
1302     marked.Parser = Parser;
1303     marked.parser = Parser.parse;
1304     
1305     marked.Renderer = Renderer;
1306     
1307     marked.Lexer = Lexer;
1308     marked.lexer = Lexer.lex;
1309     
1310     marked.InlineLexer = InlineLexer;
1311     marked.inlineLexer = InlineLexer.output;
1312     
1313     marked.parse = marked;
1314     
1315     Roo.ux.Showdown.marked = marked;
1316
1317 })();