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