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