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