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     
811       if (!lang) {
812         return '<pre><code>'
813           + (escaped ? code : escape(code, true))
814           + '\n</code></pre>';
815       }
816     
817       return '<pre><code class="'
818         + this.options.langPrefix
819         + escape(lang, true)
820         + '">'
821         + (escaped ? code : escape(code, true))
822         + '\n</code></pre>\n';
823     };
824     
825     Renderer.prototype.blockquote = function(quote) {
826       return '<blockquote>\n' + quote + '</blockquote>\n';
827     };
828     
829     Renderer.prototype.html = function(html) {
830       return html;
831     };
832     
833     Renderer.prototype.heading = function(text, level, raw) {
834       return '<h'
835         + level
836         + ' id="'
837         + this.options.headerPrefix
838         + raw.toLowerCase().replace(/[^\w]+/g, '-')
839         + '">'
840         + text
841         + '</h'
842         + level
843         + '>\n';
844     };
845     
846     Renderer.prototype.hr = function() {
847       return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
848     };
849     
850     Renderer.prototype.list = function(body, ordered) {
851       var type = ordered ? 'ol' : 'ul';
852       return '<' + type + '>\n' + body + '</' + type + '>\n';
853     };
854     
855     Renderer.prototype.listitem = function(text) {
856       return '<li>' + text + '</li>\n';
857     };
858     
859     Renderer.prototype.paragraph = function(text) {
860       return '<p>' + text + '</p>\n';
861     };
862     
863     Renderer.prototype.table = function(header, body) {
864       return '<table>\n'
865         + '<thead>\n'
866         + header
867         + '</thead>\n'
868         + '<tbody>\n'
869         + body
870         + '</tbody>\n'
871         + '</table>\n';
872     };
873     
874     Renderer.prototype.tablerow = function(content) {
875       return '<tr>\n' + content + '</tr>\n';
876     };
877     
878     Renderer.prototype.tablecell = function(content, flags) {
879       var type = flags.header ? 'th' : 'td';
880       var tag = flags.align
881         ? '<' + type + ' style="text-align:' + flags.align + '">'
882         : '<' + type + '>';
883       return tag + content + '</' + type + '>\n';
884     };
885     
886     // span level renderer
887     Renderer.prototype.strong = function(text) {
888       return '<strong>' + text + '</strong>';
889     };
890     
891     Renderer.prototype.em = function(text) {
892       return '<em>' + text + '</em>';
893     };
894     
895     Renderer.prototype.codespan = function(text) {
896       return '<code>' + text + '</code>';
897     };
898     
899     Renderer.prototype.br = function() {
900       return this.options.xhtml ? '<br/>' : '<br>';
901     };
902     
903     Renderer.prototype.del = function(text) {
904       return '<del>' + text + '</del>';
905     };
906     
907     Renderer.prototype.link = function(href, title, text) {
908       if (this.options.sanitize) {
909         try {
910           var prot = decodeURIComponent(unescape(href))
911             .replace(/[^\w:]/g, '')
912             .toLowerCase();
913         } catch (e) {
914           return '';
915         }
916         if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
917           return '';
918         }
919       }
920       var out = '<a href="' + href + '"';
921       if (title) {
922         out += ' title="' + title + '"';
923       }
924       out += '>' + text + '</a>';
925       return out;
926     };
927     
928     Renderer.prototype.image = function(href, title, text) {
929       var out = '<img src="' + href + '" alt="' + text + '"';
930       if (title) {
931         out += ' title="' + title + '"';
932       }
933       out += this.options.xhtml ? '/>' : '>';
934       return out;
935     };
936     
937     Renderer.prototype.text = function(text) {
938       return text;
939     };
940     
941     /**
942      * Parsing & Compiling
943      */
944     
945     function Parser(options) {
946       this.tokens = [];
947       this.token = null;
948       this.options = options || marked.defaults;
949       this.options.renderer = this.options.renderer || new Renderer;
950       this.renderer = this.options.renderer;
951       this.renderer.options = this.options;
952     }
953     
954     /**
955      * Static Parse Method
956      */
957     
958     Parser.parse = function(src, options, renderer) {
959       var parser = new Parser(options, renderer);
960       return parser.parse(src);
961     };
962     
963     /**
964      * Parse Loop
965      */
966     
967     Parser.prototype.parse = function(src) {
968       this.inline = new InlineLexer(src.links, this.options, this.renderer);
969       this.tokens = src.reverse();
970     
971       var out = '';
972       while (this.next()) {
973         out += this.tok();
974       }
975     
976       return out;
977     };
978     
979     /**
980      * Next Token
981      */
982     
983     Parser.prototype.next = function() {
984       return this.token = this.tokens.pop();
985     };
986     
987     /**
988      * Preview Next Token
989      */
990     
991     Parser.prototype.peek = function() {
992       return this.tokens[this.tokens.length - 1] || 0;
993     };
994     
995     /**
996      * Parse Text Tokens
997      */
998     
999     Parser.prototype.parseText = function() {
1000       var body = this.token.text;
1001     
1002       while (this.peek().type === 'text') {
1003         body += '\n' + this.next().text;
1004       }
1005     
1006       return this.inline.output(body);
1007     };
1008     
1009     /**
1010      * Parse Current Token
1011      */
1012     
1013     Parser.prototype.tok = function() {
1014       switch (this.token.type) {
1015         case 'space': {
1016           return '';
1017         }
1018         case 'hr': {
1019           return this.renderer.hr();
1020         }
1021         case 'heading': {
1022           return this.renderer.heading(
1023             this.inline.output(this.token.text),
1024             this.token.depth,
1025             this.token.text);
1026         }
1027         case 'code': {
1028           return this.renderer.code(this.token.text,
1029             this.token.lang,
1030             this.token.escaped);
1031         }
1032         case 'table': {
1033           var header = ''
1034             , body = ''
1035             , i
1036             , row
1037             , cell
1038             , flags
1039             , j;
1040     
1041           // header
1042           cell = '';
1043           for (i = 0; i < this.token.header.length; i++) {
1044             flags = { header: true, align: this.token.align[i] };
1045             cell += this.renderer.tablecell(
1046               this.inline.output(this.token.header[i]),
1047               { header: true, align: this.token.align[i] }
1048             );
1049           }
1050           header += this.renderer.tablerow(cell);
1051     
1052           for (i = 0; i < this.token.cells.length; i++) {
1053             row = this.token.cells[i];
1054     
1055             cell = '';
1056             for (j = 0; j < row.length; j++) {
1057               cell += this.renderer.tablecell(
1058                 this.inline.output(row[j]),
1059                 { header: false, align: this.token.align[j] }
1060               );
1061             }
1062     
1063             body += this.renderer.tablerow(cell);
1064           }
1065           return this.renderer.table(header, body);
1066         }
1067         case 'blockquote_start': {
1068           var body = '';
1069     
1070           while (this.next().type !== 'blockquote_end') {
1071             body += this.tok();
1072           }
1073     
1074           return this.renderer.blockquote(body);
1075         }
1076         case 'list_start': {
1077           var body = ''
1078             , ordered = this.token.ordered;
1079     
1080           while (this.next().type !== 'list_end') {
1081             body += this.tok();
1082           }
1083     
1084           return this.renderer.list(body, ordered);
1085         }
1086         case 'list_item_start': {
1087           var body = '';
1088     
1089           while (this.next().type !== 'list_item_end') {
1090             body += this.token.type === 'text'
1091               ? this.parseText()
1092               : this.tok();
1093           }
1094     
1095           return this.renderer.listitem(body);
1096         }
1097         case 'loose_item_start': {
1098           var body = '';
1099     
1100           while (this.next().type !== 'list_item_end') {
1101             body += this.tok();
1102           }
1103     
1104           return this.renderer.listitem(body);
1105         }
1106         case 'html': {
1107           var html = !this.token.pre && !this.options.pedantic
1108             ? this.inline.output(this.token.text)
1109             : this.token.text;
1110           return this.renderer.html(html);
1111         }
1112         case 'paragraph': {
1113           return this.renderer.paragraph(this.inline.output(this.token.text));
1114         }
1115         case 'text': {
1116           return this.renderer.paragraph(this.parseText());
1117         }
1118       }
1119     };
1120     
1121     /**
1122      * Helpers
1123      */
1124     
1125     function escape(html, encode) {
1126       return html
1127         .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
1128         .replace(/</g, '&lt;')
1129         .replace(/>/g, '&gt;')
1130         .replace(/"/g, '&quot;')
1131         .replace(/'/g, '&#39;');
1132     }
1133     
1134     function unescape(html) {
1135         // explicitly match decimal, hex, and named HTML entities 
1136       return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
1137         n = n.toLowerCase();
1138         if (n === 'colon') return ':';
1139         if (n.charAt(0) === '#') {
1140           return n.charAt(1) === 'x'
1141             ? String.fromCharCode(parseInt(n.substring(2), 16))
1142             : String.fromCharCode(+n.substring(1));
1143         }
1144         return '';
1145       });
1146     }
1147     
1148     function replace(regex, opt) {
1149       regex = regex.source;
1150       opt = opt || '';
1151       return function self(name, val) {
1152         if (!name) return new RegExp(regex, opt);
1153         val = val.source || val;
1154         val = val.replace(/(^|[^\[])\^/g, '$1');
1155         regex = regex.replace(name, val);
1156         return self;
1157       };
1158     }
1159     
1160     function noop() {}
1161     noop.exec = noop;
1162     
1163     function merge(obj) {
1164       var i = 1
1165         , target
1166         , key;
1167     
1168       for (; i < arguments.length; i++) {
1169         target = arguments[i];
1170         for (key in target) {
1171           if (Object.prototype.hasOwnProperty.call(target, key)) {
1172             obj[key] = target[key];
1173           }
1174         }
1175       }
1176     
1177       return obj;
1178     }
1179     
1180     
1181     /**
1182      * Marked
1183      */
1184     
1185     function marked(src, opt, callback) {
1186       if (callback || typeof opt === 'function') {
1187         if (!callback) {
1188           callback = opt;
1189           opt = null;
1190         }
1191     
1192         opt = merge({}, marked.defaults, opt || {});
1193     
1194         var highlight = opt.highlight
1195           , tokens
1196           , pending
1197           , i = 0;
1198     
1199         try {
1200           tokens = Lexer.lex(src, opt)
1201         } catch (e) {
1202           return callback(e);
1203         }
1204     
1205         pending = tokens.length;
1206     
1207         var done = function(err) {
1208           if (err) {
1209             opt.highlight = highlight;
1210             return callback(err);
1211           }
1212     
1213           var out;
1214     
1215           try {
1216             out = Parser.parse(tokens, opt);
1217           } catch (e) {
1218             err = e;
1219           }
1220     
1221           opt.highlight = highlight;
1222     
1223           return err
1224             ? callback(err)
1225             : callback(null, out);
1226         };
1227     
1228         if (!highlight || highlight.length < 3) {
1229           return done();
1230         }
1231     
1232         delete opt.highlight;
1233     
1234         if (!pending) return done();
1235     
1236         for (; i < tokens.length; i++) {
1237           (function(token) {
1238             if (token.type !== 'code') {
1239               return --pending || done();
1240             }
1241             return highlight(token.text, token.lang, function(err, code) {
1242               if (err) return done(err);
1243               if (code == null || code === token.text) {
1244                 return --pending || done();
1245               }
1246               token.text = code;
1247               token.escaped = true;
1248               --pending || done();
1249             });
1250           })(tokens[i]);
1251         }
1252     
1253         return;
1254       }
1255       try {
1256         if (opt) opt = merge({}, marked.defaults, opt);
1257         return Parser.parse(Lexer.lex(src, opt), opt);
1258       } catch (e) {
1259         e.message += '\nPlease report this to https://github.com/chjj/marked.';
1260         if ((opt || marked.defaults).silent) {
1261           return '<p>An error occured:</p><pre>'
1262             + escape(e.message + '', true)
1263             + '</pre>';
1264         }
1265         throw e;
1266       }
1267     }
1268     
1269     /**
1270      * Options
1271      */
1272     
1273     marked.options =
1274     marked.setOptions = function(opt) {
1275       merge(marked.defaults, opt);
1276       return marked;
1277     };
1278     
1279     marked.defaults = {
1280       gfm: true,
1281       tables: true,
1282       breaks: false,
1283       pedantic: false,
1284       sanitize: false,
1285       sanitizer: null,
1286       mangle: true,
1287       smartLists: false,
1288       silent: false,
1289       highlight: null,
1290       langPrefix: 'lang-',
1291       smartypants: false,
1292       headerPrefix: '',
1293       renderer: new Renderer,
1294       xhtml: false
1295     };
1296     
1297     /**
1298      * Expose
1299      */
1300     
1301     marked.Parser = Parser;
1302     marked.parser = Parser.parse;
1303     
1304     marked.Renderer = Renderer;
1305     
1306     marked.Lexer = Lexer;
1307     marked.lexer = Lexer.lex;
1308     
1309     marked.InlineLexer = InlineLexer;
1310     marked.inlineLexer = InlineLexer.output;
1311     
1312     marked.parse = marked;
1313     
1314     Roo.ux.Showdown.marked = marked;
1315
1316 })();