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