ux/Showdown.js
[roojs1] / ux / Showdown.js
1 //
2 // showdown.js -- A javascript port of Markdown.
3 //
4 // Copyright (c) 2007 John Fraser.
5 //
6 // Original Markdown Copyright (c) 2004-2005 John Gruber
7 //   <http://daringfireball.net/projects/markdown/>
8 //
9 // Redistributable under a BSD-style open source license.
10 // See license.txt for more information.
11 //
12 // The full source distribution is at:
13 //
14 //                              A A L
15 //                              T C A
16 //                              T K B
17 //
18 //   <http://www.attacklab.net/>
19 //
20
21 //
22 // Wherever possible, Showdown is a straight, line-by-line port
23 // of the Perl version of Markdown.
24 //
25 // This is not a normal parser design; it's basically just a
26 // series of string substitutions.  It's hard to read and
27 // maintain this way,  but keeping Showdown close to the original
28 // design makes it easier to port new features.
29 //
30 // More importantly, Showdown behaves like markdown.pl in most
31 // edge cases.  So web applications can do client-side preview
32 // in Javascript, and then build identical HTML on the server.
33 //
34 // This port needs the new RegExp functionality of ECMA 262,
35 // 3rd Edition (i.e. Javascript 1.5).  Most modern web browsers
36 // should do fine.  Even with the new regular expression features,
37 // We do a lot of work to emulate Perl's regex functionality.
38 // The tricky changes in this file mostly have the "attacklab:"
39 // label.  Major or self-explanatory changes don't.
40 //
41 // Smart diff tools like Araxis Merge will be able to match up
42 // this file with markdown.pl in a useful way.  A little tweaking
43 // helps: in a copy of markdown.pl, replace "#" with "//" and
44 // replace "$text" with "text".  Be sure to ignore whitespace
45 // and line endings.
46 //
47
48
49 //
50 // Showdown usage:
51 // 
52 //   alert( Roo.ux.Showdown.toHtml("Markdown *rocks*.") );
53 // 
54 // Note: move the sample code to the bottom of this
55 // file before uncommenting it.
56 //
57
58
59 //
60 // Showdown namespace
61 //
62 Roo.namespace('Roo.ux'); 
63 Roo.ux.Showdown = {};
64 Roo.ux.Showdown.toHtml = function(text) {
65     var c = new Roo.ux.Showdown.converter();
66     return c.makeHtml(text);
67 };
68 //
69 // converter
70 //
71 // Wraps all "globals" so that the only thing
72 // exposed is makeHtml().
73 //
74 Roo.ux.Showdown.converter = function() {
75     
76     //
77     // Globals:
78     //
79     
80     // Global hashes, used by various utility routines
81     var g_urls;
82     var g_titles;
83     var g_html_blocks;
84     
85     // Used to track when we're inside an ordered or unordered list
86     // (see _ProcessListItems() for details):
87     var g_list_level = 0;
88     
89     
90     this.makeHtml = function(_text) {
91     //
92     // Main function. The order in which other subs are called here is
93     // essential. Link and image substitutions need to happen before
94     // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
95     // and <img> tags get encoded.
96     //v
97             var text = '' + _text;
98             // Clear the global hashes. If we don't clear these, you get conflicts
99             // from other articles when generating a page which contains more than
100             // one article (e.g. an index page that shows the N most recent
101             // articles):
102             g_urls = new Array();
103             g_titles = new Array();
104             g_html_blocks = new Array();
105     
106             // attacklab: Replace ~ with ~T
107             // This lets us use tilde as an escape char to avoid md5 hashes
108             // The choice of character is arbitray; anything that isn't
109         // magic in Markdown will work.
110             text = text.replace(/~/g,"~T");
111     
112             // attacklab: Replace $ with ~D
113             // RegExp interprets $ as a special character
114             // when it's in a replacement string
115             text = text.replace(/\$/g,"~D");
116     
117             // Standardize line endings
118             text = text.replace(/\r\n/g,"\n"); // DOS to Unix
119             text = text.replace(/\r/g,"\n"); // Mac to Unix
120     
121             // Make sure text begins and ends with a couple of newlines:
122             text = "\n\n" + text + "\n\n";
123     
124             // Convert all tabs to spaces.
125             text = _Detab(text);
126     
127             // Strip any lines consisting only of spaces and tabs.
128             // This makes subsequent regexen easier to write, because we can
129             // match consecutive blank lines with /\n+/ instead of something
130             // contorted like /[ \t]*\n+/ .
131             text = text.replace(/^[ \t]+$/mg,"");
132     
133             text = _DoCodeBlocks(text);
134     
135             // Turn block-level HTML blocks into hash entries
136             text = _HashHTMLBlocks(text);
137     
138             // Strip link definitions, store in hashes.
139             text = _StripLinkDefinitions(text);
140     
141             text = _RunBlockGamut(text);
142     
143             text = _UnescapeSpecialChars(text);
144     
145             // attacklab: Restore dollar signs
146             text = text.replace(/~D/g,"$$");
147     
148             // attacklab: Restore tildes
149             text = text.replace(/~T/g,"~");
150     
151             return text;
152     }
153     
154     
155     var _StripLinkDefinitions = function(text) {
156     //
157     // Strips link definitions from text, stores the URLs and titles in
158     // hash references.
159     //
160     
161             // Link defs are in the form: ^[id]: url "optional title"
162     
163             /*
164                     var text = text.replace(/
165                                     ^[ ]{0,3}\[(.+)\]:  // id = $1  attacklab: g_tab_width - 1
166                                       [ \t]*
167                                       \n?                               // maybe *one* newline
168                                       [ \t]*
169                                     <?(\S+?)>?                  // url = $2
170                                       [ \t]*
171                                       \n?                               // maybe one newline
172                                       [ \t]*
173                                     (?:
174                                       (\n*)                             // any lines skipped = $3 attacklab: lookbehind removed
175                                       ["(]
176                                       (.+?)                             // title = $4
177                                       [")]
178                                       [ \t]*
179                                     )?                                  // title is optional
180                                     (?:\n+|$)
181                               /gm,
182                               function(){...});
183             */
184             text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
185                     function (wholeMatch,m1,m2,m3,m4) {
186                             m1 = m1.toLowerCase();
187                             g_urls[m1] = _EncodeAmpsAndAngles(m2);  // Link IDs are case-insensitive
188                             if (m3) {
189                                     // Oops, found blank lines, so it's not a title.
190                                     // Put back the parenthetical statement we stole.
191                                     return m3+m4;
192                             } else if (m4) {
193                                     g_titles[m1] = m4.replace(/"/g,"&quot;");
194                             }
195                             
196                             // Completely remove the definition from the text
197                             return "";
198                     }
199             );
200     
201             return text;
202     }
203     
204     
205     var _HashHTMLBlocks = function(text) {
206             // attacklab: Double up blank lines to reduce lookaround
207             text = text.replace(/\n/g,"\n\n");
208     
209             // Hashify HTML blocks:
210             // We only want to do this for block-level HTML tags, such as headers,
211             // lists, and tables. That's because we still want to wrap <p>s around
212             // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
213             // phrase emphasis, and spans. The list of tags we're looking for is
214             // hard-coded:
215             var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
216             var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
217     
218             // First, look for nested blocks, e.g.:
219             //   <div>
220             //     <div>
221             //     tags for inner block must be indented.
222             //     </div>
223             //   </div>
224             //
225             // The outermost tags must start at the left margin for this to match, and
226             // the inner nested divs must be indented.
227             // We need to do this before the next, more liberal match, because the next
228             // match will start at the first `<div>` and stop at the first `</div>`.
229     
230             // attacklab: This regex can be expensive when it fails.
231             /*
232                     var text = text.replace(/
233                     (                                           // save in $1
234                             ^                                   // start of line  (with /m)
235                             <($block_tags_a)    // start tag = $2
236                             \b                                  // word break
237                                                                     // attacklab: hack around khtml/pcre bug...
238                             [^\r]*?\n                   // any number of lines, minimally matching
239                             </\2>                               // the matching end tag
240                             [ \t]*                              // trailing spaces/tabs
241                             (?=\n+)                             // followed by a newline
242                     )                                           // attacklab: there are sentinel newlines at end of document
243                     /gm,function(){...}};
244             */
245             text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
246     
247             //
248             // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
249             //
250     
251             /*
252                     var text = text.replace(/
253                     (                                           // save in $1
254                             ^                                   // start of line  (with /m)
255                             <($block_tags_b)    // start tag = $2
256                             \b                                  // word break
257                                                                     // attacklab: hack around khtml/pcre bug...
258                             [^\r]*?                             // any number of lines, minimally matching
259                             .*</\2>                             // the matching end tag
260                             [ \t]*                              // trailing spaces/tabs
261                             (?=\n+)                             // followed by a newline
262                     )                                           // attacklab: there are sentinel newlines at end of document
263                     /gm,function(){...}};
264             */
265             text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
266     
267             // Special case just for <hr />. It was easier to make a special case than
268             // to make the other regex more complicated.  
269     
270             /*
271                     text = text.replace(/
272                     (                                           // save in $1
273                             \n\n                                // Starting after a blank line
274                             [ ]{0,3}
275                             (<(hr)                              // start tag = $2
276                             \b                                  // word break
277                             ([^<>])*?                   // 
278                             \/?>)                               // the matching end tag
279                             [ \t]*
280                             (?=\n{2,})                  // followed by a blank line
281                     )
282                     /g,hashElement);
283             */
284             text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
285     
286             // Special case for standalone HTML comments:
287     
288             /*
289                     text = text.replace(/
290                     (                                           // save in $1
291                             \n\n                                // Starting after a blank line
292                             [ ]{0,3}                    // attacklab: g_tab_width - 1
293                             <!
294                             (--[^\r]*?--\s*)+
295                             >
296                             [ \t]*
297                             (?=\n{2,})                  // followed by a blank line
298                     )
299                     /g,hashElement);
300             */
301             text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
302     
303             // PHP and ASP-style processor instructions (<?...?> and <%...%>)
304     
305             /*
306                     text = text.replace(/
307                     (?:
308                             \n\n                                // Starting after a blank line
309                     )
310                     (                                           // save in $1
311                             [ ]{0,3}                    // attacklab: g_tab_width - 1
312                             (?:
313                                     <([?%])                     // $2
314                                     [^\r]*?
315                                     \2>
316                             )
317                             [ \t]*
318                             (?=\n{2,})                  // followed by a blank line
319                     )
320                     /g,hashElement);
321             */
322             text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
323     
324             // attacklab: Undo double lines (see comment at top of this function)
325             text = text.replace(/\n\n/g,"\n");
326             return text;
327     }
328     
329     var hashElement = function(wholeMatch,m1) {
330             var blockText = m1;
331     
332             // Undo double lines
333             blockText = blockText.replace(/\n\n/g,"\n");
334             blockText = blockText.replace(/^\n/,"");
335             
336             // strip trailing blank lines
337             blockText = blockText.replace(/\n+$/g,"");
338             
339             // Replace the element text with a marker ("~KxK" where x is its key)
340             blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
341             
342             return blockText;
343     };
344     
345     var _RunBlockGamut = function(text) {
346     //
347     // These are all the transformations that form block-level
348     // tags like paragraphs, headers, and list items.
349     //
350             // code blocks first... so content does not get translated..
351             text = _DoCodeBlocks(text);
352             
353             text = _DoHeaders(text);
354     
355             // Do Horizontal Rules:
356             var key = hashBlock("<hr />");
357             text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
358             text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
359             text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
360     
361             text = _DoLists(text);
362      
363             // We already ran _HashHTMLBlocks() before, in Markdown(), but that
364             // was to escape raw HTML in the original Markdown source. This time,
365             // we're escaping the markup we've just created, so that we don't wrap
366             // <p> tags around block-level tags.
367            
368             text = _FormParagraphs(text);
369             text = _HashHTMLBlocks(text);
370             return text;
371     }
372     
373     
374     var _RunSpanGamut = function(text) {
375     //
376     // These are all the transformations that occur *within* block-level
377     // tags like paragraphs, headers, and list items.
378     //
379     
380             text = _DoCodeSpans(text);
381             text = _EscapeSpecialCharsWithinTagAttributes(text);
382             text = _EncodeBackslashEscapes(text);
383     
384             // Process anchor and image tags. Images must come first,
385             // because ![foo][f] looks like an anchor.
386             text = _DoImages(text);
387             text = _DoAnchors(text);
388     
389             // Make links out of things like `<http://example.com/>`
390             // Must come after _DoAnchors(), because you can use < and >
391             // delimiters in inline links like [this](<url>).
392             text = _DoAutoLinks(text);
393             text = _EncodeAmpsAndAngles(text);
394             text = _DoItalicsAndBold(text);
395     
396             // Do hard breaks:
397             text = text.replace(/  +\n/g," <br />\n");
398     
399             return text;
400     }
401     
402     var _EscapeSpecialCharsWithinTagAttributes = function(text) {
403     //
404     // Within tags -- meaning between < and > -- encode [\ ` * _] so they
405     // don't conflict with their use in Markdown for code, italics and strong.
406     //
407     
408             // Build a regex to find HTML tags and comments.  See Friedl's 
409             // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
410             var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
411     
412             text = text.replace(regex, function(wholeMatch) {
413                     var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
414                     tag = escapeCharacters(tag,"\\`*_");
415                     return tag;
416             });
417     
418             return text;
419     }
420     
421     var _DoAnchors = function(text) {
422     //
423     // Turn Markdown link shortcuts into XHTML <a> tags.
424     //
425             //
426             // First, handle reference-style links: [link text] [id]
427             //
428     
429             /*
430                     text = text.replace(/
431                     (                                                   // wrap whole match in $1
432                             \[
433                             (
434                                     (?:
435                                             \[[^\]]*\]          // allow brackets nested one level
436                                             |
437                                             [^\[]                       // or anything else
438                                     )*
439                             )
440                             \]
441     
442                             [ ]?                                        // one optional space
443                             (?:\n[ ]*)?                         // one optional newline followed by spaces
444     
445                             \[
446                             (.*?)                                       // id = $3
447                             \]
448                     )()()()()                                   // pad remaining backreferences
449                     /g,_DoAnchors_callback);
450             */
451             text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
452     
453             //
454             // Next, inline-style links: [link text](url "optional title")
455             //
456     
457             /*
458                     text = text.replace(/
459                             (                                           // wrap whole match in $1
460                                     \[
461                                     (
462                                             (?:
463                                                     \[[^\]]*\]  // allow brackets nested one level
464                                             |
465                                             [^\[\]]                     // or anything else
466                                     )
467                             )
468                             \]
469                             \(                                          // literal paren
470                             [ \t]*
471                             ()                                          // no id, so leave $3 empty
472                             <?(.*?)>?                           // href = $4
473                             [ \t]*
474                             (                                           // $5
475                                     (['"])                              // quote char = $6
476                                     (.*?)                               // Title = $7
477                                     \6                                  // matching quote
478                                     [ \t]*                              // ignore any spaces/tabs between closing quote and )
479                             )?                                          // title is optional
480                             \)
481                     )
482                     /g,writeAnchorTag);
483             */
484             text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
485     
486             //
487             // Last, handle reference-style shortcuts: [link text]
488             // These must come last in case you've also got [link test][1]
489             // or [link test](/foo)
490             //
491     
492             /*
493                     text = text.replace(/
494                     (                                                   // wrap whole match in $1
495                             \[
496                             ([^\[\]]+)                          // link text = $2; can't contain '[' or ']'
497                             \]
498                     )()()()()()                                 // pad rest of backreferences
499                     /g, writeAnchorTag);
500             */
501             text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
502     
503             return text;
504     }
505     
506     var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
507             if (m7 == undefined) m7 = "";
508             var whole_match = m1;
509             var link_text   = m2;
510             var link_id  = m3.toLowerCase();
511             var url             = m4;
512             var title   = m7;
513             
514             if (url == "") {
515                     if (link_id == "") {
516                             // lower-case and turn embedded newlines into spaces
517                             link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
518                     }
519                     url = "#"+link_id;
520                     
521                     if (g_urls[link_id] != undefined) {
522                             url = g_urls[link_id];
523                             if (g_titles[link_id] != undefined) {
524                                     title = g_titles[link_id];
525                             }
526                     }
527                     else {
528                             if (whole_match.search(/\(\s*\)$/m)>-1) {
529                                     // Special case for explicit empty url
530                                     url = "";
531                             } else {
532                                     return whole_match;
533                             }
534                     }
535             }   
536             
537             url = escapeCharacters(url,"*_");
538             var result = "<a href=\"" + url + "\"";
539             
540             if (title != "") {
541                     title = title.replace(/"/g,"&quot;");
542                     title = escapeCharacters(title,"*_");
543                     result +=  " title=\"" + title + "\"";
544             }
545             
546             result += ">" + link_text + "</a>";
547             
548             return result;
549     }
550     
551     
552     var _DoImages = function(text) {
553     //
554     // Turn Markdown image shortcuts into <img> tags.
555     //
556     
557             //
558             // First, handle reference-style labeled images: ![alt text][id]
559             //
560     
561             /*
562                     text = text.replace(/
563                     (                                           // wrap whole match in $1
564                             !\[
565                             (.*?)                               // alt text = $2
566                             \]
567     
568                             [ ]?                                // one optional space
569                             (?:\n[ ]*)?                 // one optional newline followed by spaces
570     
571                             \[
572                             (.*?)                               // id = $3
573                             \]
574                     )()()()()                           // pad rest of backreferences
575                     /g,writeImageTag);
576             */
577             text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
578     
579             //
580             // Next, handle inline images:  ![alt text](url "optional title")
581             // Don't forget: encode * and _
582     
583             /*
584                     text = text.replace(/
585                     (                                           // wrap whole match in $1
586                             !\[
587                             (.*?)                               // alt text = $2
588                             \]
589                             \s?                                 // One optional whitespace character
590                             \(                                  // literal paren
591                             [ \t]*
592                             ()                                  // no id, so leave $3 empty
593                             <?(\S+?)>?                  // src url = $4
594                             [ \t]*
595                             (                                   // $5
596                                     (['"])                      // quote char = $6
597                                     (.*?)                       // title = $7
598                                     \6                          // matching quote
599                                     [ \t]*
600                             )?                                  // title is optional
601                     \)
602                     )
603                     /g,writeImageTag);
604             */
605             text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
606     
607             return text;
608     }
609     
610     var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
611             var whole_match = m1;
612             var alt_text   = m2;
613             var link_id  = m3.toLowerCase();
614             var url             = m4;
615             var title   = m7;
616     
617             if (!title) title = "";
618             
619             if (url == "") {
620                     if (link_id == "") {
621                             // lower-case and turn embedded newlines into spaces
622                             link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
623                     }
624                     url = "#"+link_id;
625                     
626                     if (g_urls[link_id] != undefined) {
627                             url = g_urls[link_id];
628                             if (g_titles[link_id] != undefined) {
629                                     title = g_titles[link_id];
630                             }
631                     }
632                     else {
633                             return whole_match;
634                     }
635             }   
636             
637             alt_text = alt_text.replace(/"/g,"&quot;");
638             url = escapeCharacters(url,"*_");
639             var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
640     
641             // attacklab: Markdown.pl adds empty title attributes to images.
642             // Replicate this bug.
643     
644             //if (title != "") {
645                     title = title.replace(/"/g,"&quot;");
646                     title = escapeCharacters(title,"*_");
647                     result +=  " title=\"" + title + "\"";
648             //}
649             
650             result += " />";
651             
652             return result;
653     }
654     
655     
656     var _DoHeaders = function(text) {
657     
658             // Setext-style headers:
659             //  Header 1
660             //  ========
661             //  
662             //  Header 2
663             //  --------
664             //
665             text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
666                     function(wholeMatch,m1){return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");});
667     
668             text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
669                     function(matchFound,m1){return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");});
670     
671             // atx-style headers:
672             //  # Header 1
673             //  ## Header 2
674             //  ## Header 2 with closing hashes ##
675             //  ...
676             //  ###### Header 6
677             //
678     
679             /*
680                     text = text.replace(/
681                             ^(\#{1,6})                          // $1 = string of #'s
682                             [ \t]*
683                             (.+?)                                       // $2 = Header text
684                             [ \t]*
685                             \#*                                         // optional closing #'s (not counted)
686                             \n+
687                     /gm, function() {...});
688             */
689     
690             text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
691                     function(wholeMatch,m1,m2) {
692                             var h_level = m1.length;
693                             return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
694                     });
695     
696             function headerId(m) {
697                     return m.replace(/[^\w]/g, '').toLowerCase();
698             }
699             return text;
700     }
701     
702     // This declaration keeps Dojo compressor from outputting garbage:
703     var _ProcessListItems;
704     
705     var _DoLists = function(text) {
706     //
707     // Form HTML ordered (numbered) and unordered (bulleted) lists.
708     //
709     
710             // attacklab: add sentinel to hack around khtml/safari bug:
711             // http://bugs.webkit.org/show_bug.cgi?id=11231
712             text += "~0";
713     
714             // Re-usable pattern to match any entirel ul or ol list:
715     
716             /*
717                     var whole_list = /
718                     (                                                                   // $1 = whole list
719                             (                                                           // $2
720                                     [ ]{0,3}                                    // attacklab: g_tab_width - 1
721                                     ([*+-]|\d+[.])                              // $3 = first list item marker
722                                     [ \t]+
723                             )
724                             [^\r]+?
725                             (                                                           // $4
726                                     ~0                                                  // sentinel for workaround; should be $
727                             |
728                                     \n{2,}
729                                     (?=\S)
730                                     (?!                                                 // Negative lookahead for another list item marker
731                                             [ \t]*
732                                             (?:[*+-]|\d+[.])[ \t]+
733                                     )
734                             )
735                     )/g
736             */
737             var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
738     
739             if (g_list_level) {
740                     text = text.replace(whole_list,function(wholeMatch,m1,m2) {
741                             var list = m1;
742                             var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
743     
744                             // Turn double returns into triple returns, so that we can make a
745                             // paragraph for the last item in a list, if necessary:
746                             list = list.replace(/\n{2,}/g,"\n\n\n");;
747                             var result = _ProcessListItems(list);
748             
749                             // Trim any trailing whitespace, to put the closing `</$list_type>`
750                             // up on the preceding line, to get it past the current stupid
751                             // HTML block parser. This is a hack to work around the terrible
752                             // hack that is the HTML block parser.
753                             result = result.replace(/\s+$/,"");
754                             result = "<"+list_type+">" + result + "</"+list_type+">\n";
755                             return result;
756                     });
757             } else {
758                     whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
759                     text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
760                             var runup = m1;
761                             var list = m2;
762     
763                             var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
764                             // Turn double returns into triple returns, so that we can make a
765                             // paragraph for the last item in a list, if necessary:
766                             var list = list.replace(/\n{2,}/g,"\n\n\n");;
767                             var result = _ProcessListItems(list);
768                             result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";       
769                             return result;
770                     });
771             }
772     
773             // attacklab: strip sentinel
774             text = text.replace(/~0/,"");
775     
776             return text;
777     }
778     
779     _ProcessListItems = function(list_str) {
780     //
781     //  Process the contents of a single ordered or unordered list, splitting it
782     //  into individual list items.
783     //
784             // The $g_list_level global keeps track of when we're inside a list.
785             // Each time we enter a list, we increment it; when we leave a list,
786             // we decrement. If it's zero, we're not in a list anymore.
787             //
788             // We do this because when we're not inside a list, we want to treat
789             // something like this:
790             //
791             //    I recommend upgrading to version
792             //    8. Oops, now this line is treated
793             //    as a sub-list.
794             //
795             // As a single paragraph, despite the fact that the second line starts
796             // with a digit-period-space sequence.
797             //
798             // Whereas when we're inside a list (or sub-list), that line will be
799             // treated as the start of a sub-list. What a kludge, huh? This is
800             // an aspect of Markdown's syntax that's hard to parse perfectly
801             // without resorting to mind-reading. Perhaps the solution is to
802             // change the syntax rules such that sub-lists must start with a
803             // starting cardinal number; e.g. "1." or "a.".
804     
805             g_list_level++;
806     
807             // trim trailing blank lines:
808             list_str = list_str.replace(/\n{2,}$/,"\n");
809     
810             // attacklab: add sentinel to emulate \z
811             list_str += "~0";
812     
813             /*
814                     list_str = list_str.replace(/
815                             (\n)?                                                       // leading line = $1
816                             (^[ \t]*)                                           // leading whitespace = $2
817                             ([*+-]|\d+[.]) [ \t]+                       // list marker = $3
818                             ([^\r]+?                                            // list item text   = $4
819                             (\n{1,2}))
820                             (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
821                     /gm, function(){...});
822             */
823             list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
824                     function(wholeMatch,m1,m2,m3,m4){
825                             var item = m4;
826                             var leading_line = m1;
827                             var leading_space = m2;
828     
829                             if (leading_line || (item.search(/\n{2,}/)>-1)) {
830                                     item = _RunBlockGamut(_Outdent(item));
831                             }
832                             else {
833                                     // Recursion for sub-lists:
834                                     item = _DoLists(_Outdent(item));
835                                     item = item.replace(/\n$/,""); // chomp(item)
836                                     item = _RunSpanGamut(item);
837                             }
838     
839                             return  "<li>" + item + "</li>\n";
840                     }
841             );
842     
843             // attacklab: strip sentinel
844             list_str = list_str.replace(/~0/g,"");
845     
846             g_list_level--;
847             return list_str;
848     }
849     
850     
851     var _DoCodeBlocks = function(text) {
852     //
853     //  Process Markdown `<pre><code>` blocks.
854     //  
855     
856             /*
857                     text = text.replace(text,
858                             /(?:\n\n|^)
859                             (                                                           // $1 = the code block -- one or more lines, starting with a space/tab
860                                     (?:
861                                             (?:[ ]{4}|\t)                       // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
862                                             .*\n+
863                                     )+
864                             )
865                             (\n*[ ]{0,3}[^ \t\n]|(?=~0))        // attacklab: g_tab_width
866                     /g,function(){...});
867             */
868     
869             // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
870             text = text.replace(/~0/,"");
871             text += "~0";
872             
873             text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
874                     function(wholeMatch,m1,m2) {
875                             var codeblock = m1;
876                             var nextChar = m2;
877                     
878                             codeblock = _EncodeCode( _Outdent(codeblock));
879                             codeblock = _Detab(codeblock);
880                             codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
881                             codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
882     
883                             codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
884     
885                             return hashBlock(codeblock) + nextChar;
886                     }
887             );
888     
889             // attacklab: strip sentinel
890             text = text.replace(/~0/,"");
891     
892     
893       
894             text += '~0';
895           
896             text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
897                     var end =  '\n';
898                 
899                     // First parse the github code block
900                     codeblock =  _EncodeCode( codeblock); 
901                     codeblock =  _Detab(codeblock);
902                     codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
903                     codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
904                 
905                     codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
906                 
907                     return hashBlock(codeblock) ;
908             });
909           
910             // attacklab: strip sentinel
911             text = text.replace(/~0/, '');
912
913           
914             return text;
915     }
916     
917     var hashBlock = function(text) {
918             text = text.replace(/(^\n+|\n+$)/g,"");
919             return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
920     }
921     
922     
923     var _DoCodeSpans = function(text) {
924     //
925     //   *  Backtick quotes are used for <code></code> spans.
926     // 
927     //   *  You can use multiple backticks as the delimiters if you want to
928     //   include literal backticks in the code span. So, this input:
929     //   
930     //           Just type ``foo `bar` baz`` at the prompt.
931     //   
932     //     Will translate to:
933     //   
934     //           <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
935     //   
936     //  There's no arbitrary limit to the number of backticks you
937     //  can use as delimters. If you need three consecutive backticks
938     //  in your code, use four for delimiters, etc.
939     //
940     //  *  You can use spaces to get literal backticks at the edges:
941     //   
942     //           ... type `` `bar` `` ...
943     //   
944     //     Turns to:
945     //   
946     //           ... type <code>`bar`</code> ...
947     //
948     
949             /*
950                     text = text.replace(/
951                             (^|[^\\])                                   // Character before opening ` can't be a backslash
952                             (`+)                                                // $2 = Opening run of `
953                             (                                                   // $3 = The code block
954                                     [^\r]*?
955                                     [^`]                                        // attacklab: work around lack of lookbehind
956                             )
957                             \2                                                  // Matching closer
958                             (?!`)
959                     /gm, function(){...});
960             */
961     
962             text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
963                     function(wholeMatch,m1,m2,m3,m4) {
964                             var c = m3;
965                             c = c.replace(/^([ \t]*)/g,"");     // leading whitespace
966                             c = c.replace(/[ \t]*$/g,"");       // trailing whitespace
967                             c = _EncodeCode(c);
968                             return m1+"<code>"+c+"</code>";
969                     });
970     
971             return text;
972     }
973     
974     
975     var _EncodeCode = function(text) {
976     //
977     // Encode/escape certain characters inside Markdown code runs.
978     // The point is that in code, these characters are literals,
979     // and lose their special Markdown meanings.
980     
981     // REMOVED - Data going into markdown should be encoded before it enters..
982     
983     //
984             // Encode all ampersands; HTML entities are not
985             // entities within a Markdown code span.
986             
987             
988             //text = text.replace(/&/g,"&amp;");
989     
990             // Do the angle bracket song and dance:
991             //text = text.replace(/</g,"&lt;");
992             //text = text.replace(/>/g,"&gt;");
993     
994             // Now, escape characters that are magic in Markdown:
995             text = escapeCharacters(text,"\*_{}[]\\",false);
996     
997     // jj the line above breaks this:
998     //---
999     
1000     //* Item
1001     
1002     //   1. Subitem
1003     
1004     //            special char: *
1005     //---
1006     
1007             return text;
1008     }
1009     
1010     
1011     var _DoItalicsAndBold = function(text) {
1012     
1013             // <strong> must go first:
1014             text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
1015                     "<strong>$2</strong>");
1016     
1017             text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1018                     "<em>$2</em>");
1019     
1020             return text;
1021     }
1022     
1023     
1024     var _DoBlockQuotes = function(text) {
1025     
1026             /*
1027                     text = text.replace(/
1028                     (                                                           // Wrap whole match in $1
1029                             (
1030                                     ^[ \t]*>[ \t]?                      // '>' at the start of a line
1031                                     .+\n                                        // rest of the first line
1032                                     (.+\n)*                                     // subsequent consecutive lines
1033                                     \n*                                         // blanks
1034                             )+
1035                     )
1036                     /gm, function(){...});
1037             */
1038     
1039             text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1040                     function(wholeMatch,m1) {
1041                             var bq = m1;
1042     
1043                             // attacklab: hack around Konqueror 3.5.4 bug:
1044                             // "----------bug".replace(/^-/g,"") == "bug"
1045     
1046                             bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0");   // trim one level of quoting
1047     
1048                             // attacklab: clean up hack
1049                             bq = bq.replace(/~0/g,"");
1050     
1051                             bq = bq.replace(/^[ \t]+$/gm,"");           // trim whitespace-only lines
1052                             bq = _RunBlockGamut(bq);                            // recurse
1053                             
1054                             bq = bq.replace(/(^|\n)/g,"$1  ");
1055                             // These leading spaces screw with <pre> content, so we need to fix that:
1056                             bq = bq.replace(
1057                                             /(\s*<pre>[^\r]+?<\/pre>)/gm,
1058                                     function(wholeMatch,m1) {
1059                                             var pre = m1;
1060                                             // attacklab: hack around Konqueror 3.5.4 bug:
1061                                             pre = pre.replace(/^  /mg,"~0");
1062                                             pre = pre.replace(/~0/g,"");
1063                                             return pre;
1064                                     });
1065                             
1066                             return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1067                     });
1068             return text;
1069     }
1070     
1071     
1072     var _FormParagraphs = function(text) {
1073     //
1074     //  Params:
1075     //    $text - string to process with html <p> tags
1076     //
1077     
1078             // Strip leading and trailing lines:
1079             text = text.replace(/^\n+/g,"");
1080             text = text.replace(/\n+$/g,"");
1081     
1082             var grafs = text.split(/\n{2,}/g);
1083             var grafsOut = new Array();
1084     
1085             //
1086             // Wrap <p> tags.
1087             //
1088             var end = grafs.length;
1089             for (var i=0; i<end; i++) {
1090                     var str = grafs[i];
1091     
1092                     // if this is an HTML marker, copy it
1093                     if (str.search(/~K(\d+)K/g) >= 0) {
1094                             grafsOut.push(str);
1095                     }
1096                     else if (str.search(/\S/) >= 0) {
1097                             str = _RunSpanGamut(str);
1098                             str = str.replace(/^([ \t]*)/g,"<p>");
1099                             str += "</p>"
1100                             grafsOut.push(str);
1101                     }
1102     
1103             }
1104     
1105             //
1106             // Unhashify HTML blocks
1107             //
1108             end = grafsOut.length;
1109             for (var i=0; i<end; i++) {
1110                     // if this is a marker for an html block...
1111                     while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1112                             var blockText = g_html_blocks[RegExp.$1];
1113                             blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1114                             grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1115                     }
1116             }
1117     
1118             return grafsOut.join("\n\n");
1119     }
1120     
1121     
1122     var _EncodeAmpsAndAngles = function(text) {
1123     // Smart processing for ampersands and angle brackets that need to be encoded.
1124             
1125             // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1126             //   http://bumppo.net/projects/amputator/
1127             text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
1128             
1129             // Encode naked <'s
1130             text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
1131             
1132             return text;
1133     }
1134     
1135     
1136     var _EncodeBackslashEscapes = function(text) {
1137     //
1138     //   Parameter:  String.
1139     //   Returns:       The string, with after processing the following backslash
1140     //                     escape sequences.
1141     //
1142     
1143             // attacklab: The polite way to do this is with the new
1144             // escapeCharacters() function:
1145             //
1146             //  text = escapeCharacters(text,"\\",true);
1147             //  text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1148             //
1149             // ...but we're sidestepping its use of the (slow) RegExp constructor
1150             // as an optimization for Firefox.  This function gets called a LOT.
1151     
1152             text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1153             text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1154             return text;
1155     }
1156     
1157     
1158     var _DoAutoLinks = function(text) {
1159     
1160             text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1161     
1162             // Email addresses: <address@domain.foo>
1163     
1164             /*
1165                     text = text.replace(/
1166                             <
1167                             (?:mailto:)?
1168                             (
1169                                     [-.\w]+
1170                                     \@
1171                                     [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1172                             )
1173                             >
1174                     /gi, _DoAutoLinks_callback());
1175             */
1176             text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1177                     function(wholeMatch,m1) {
1178                             return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1179                     }
1180             );
1181     
1182             return text;
1183     }
1184     
1185     
1186     var _EncodeEmailAddress = function(addr) {
1187     //
1188     //  Input: an email address, e.g. "foo@example.com"
1189     //
1190     //  Output: the email address as a mailto link, with each character
1191     //  of the address encoded as either a decimal or hex entity, in
1192     //  the hopes of foiling most address harvesting spam bots. E.g.:
1193     //
1194     //  <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
1195     //     x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
1196     //     &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
1197     //
1198     //  Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1199     //  mailing list: <http://tinyurl.com/yu7ue>
1200     //
1201     
1202             // attacklab: why can't javascript speak hex?
1203             function char2hex(ch) {
1204                     var hexDigits = '0123456789ABCDEF';
1205                     var dec = ch.charCodeAt(0);
1206                     return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1207             }
1208     
1209             var encode = [
1210                     function(ch){return "&#"+ch.charCodeAt(0)+";";},
1211                     function(ch){return "&#x"+char2hex(ch)+";";},
1212                     function(ch){return ch;}
1213             ];
1214     
1215             addr = "mailto:" + addr;
1216     
1217             addr = addr.replace(/./g, function(ch) {
1218                     if (ch == "@") {
1219                             // this *must* be encoded. I insist.
1220                             ch = encode[Math.floor(Math.random()*2)](ch);
1221                     } else if (ch !=":") {
1222                             // leave ':' alone (to spot mailto: later)
1223                             var r = Math.random();
1224                             // roughly 10% raw, 45% hex, 45% dec
1225                             ch =  (
1226                                             r > .9  ?   encode[2](ch)   :
1227                                             r > .45 ?   encode[1](ch)   :
1228                                                                     encode[0](ch)
1229                                     );
1230                     }
1231                     return ch;
1232             });
1233     
1234             addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1235             addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1236     
1237             return addr;
1238     }
1239     
1240     
1241     var _UnescapeSpecialChars = function(text) {
1242     //
1243     // Swap back in all the special characters we've hidden.
1244     //
1245             text = text.replace(/~E(\d+)E/g,
1246                     function(wholeMatch,m1) {
1247                             var charCodeToReplace = parseInt(m1);
1248                             return String.fromCharCode(charCodeToReplace);
1249                     }
1250             );
1251             return text;
1252     }
1253     
1254     
1255     var _Outdent = function(text) {
1256     //
1257     // Remove one level of line-leading tabs or spaces
1258     //
1259     
1260             // attacklab: hack around Konqueror 3.5.4 bug:
1261             // "----------bug".replace(/^-/g,"") == "bug"
1262     
1263             text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1264     
1265             // attacklab: clean up hack
1266             text = text.replace(/~0/g,"");
1267     
1268             return text;
1269     }
1270     
1271     var _Detab = function(text) {
1272     // attacklab: Detab's completely rewritten for speed.
1273     // In perl we could fix it by anchoring the regexp with \G.
1274     // In javascript we're less fortunate.
1275     
1276             // expand first n-1 tabs
1277             text = text.replace(/\t(?=\t)/g,"    "); // attacklab: g_tab_width
1278     
1279             // replace the nth with two sentinels
1280             text = text.replace(/\t/g,"~A~B");
1281     
1282             // use the sentinel to anchor our regex so it doesn't explode
1283             text = text.replace(/~B(.+?)~A/g,
1284                     function(wholeMatch,m1,m2) {
1285                             var leadingText = m1;
1286                             var numSpaces = 4 - leadingText.length % 4;  // attacklab: g_tab_width
1287     
1288                             // there *must* be a better way to do this:
1289                             for (var i=0; i<numSpaces; i++) leadingText+=" ";
1290     
1291                             return leadingText;
1292                     }
1293             );
1294     
1295             // clean up sentinels
1296             text = text.replace(/~A/g,"    ");  // attacklab: g_tab_width
1297             text = text.replace(/~B/g,"");
1298     
1299             return text;
1300     }
1301     
1302     
1303     //
1304     //  attacklab: Utility functions
1305     //
1306     
1307     
1308     var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1309             // First we have to escape the escape characters so that
1310             // we can build a character class out of them
1311             var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1312     
1313             if (afterBackslash) {
1314                     regexString = "\\\\" + regexString;
1315             }
1316     
1317             var regex = new RegExp(regexString,"g");
1318             text = text.replace(regex,escapeCharacters_callback);
1319     
1320             return text;
1321     }
1322     
1323     
1324     var escapeCharacters_callback = function(wholeMatch,m1) {
1325             var charCodeToEscape = m1.charCodeAt(0);
1326             return "~E"+charCodeToEscape+"E";
1327     }
1328
1329 } // end of Showdown.converter
1330
1331 // export
1332 //if (typeof exports != 'undefined') exports.Showdown = Showdown;