2 // showdown.js -- A javascript port of Markdown.
 
   4 // Copyright (c) 2007 John Fraser.
 
   6 // Original Markdown Copyright (c) 2004-2005 John Gruber
 
   7 //   <http://daringfireball.net/projects/markdown/>
 
   9 // The full source distribution is at:
 
  15 //   <http://www.attacklab.net/>
 
  19 // Wherever possible, Showdown is a straight, line-by-line port
 
  20 // of the Perl version of Markdown.
 
  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.
 
  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.
 
  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.
 
  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
 
  49 //   var text = "Markdown *rocks*.";
 
  51 //   var converter = new Attacklab.showdown.converter();
 
  52 //   var html = converter.makeHtml(text);
 
  56 // Note: move the sample code to the bottom of this
 
  57 // file before uncommenting it.
 
  62 // Attacklab namespace
 
  64 var Attacklab = Attacklab || {}
 
  69 Attacklab.showdown = Attacklab.showdown || {}
 
  74 // Wraps all "globals" so that the only thing
 
  75 // exposed is makeHtml().
 
  77 Attacklab.showdown.converter = function() {
 
  80 // g_urls and g_titles allow arbitrary user-entered strings as keys. This
 
  81 // caused an exception (and hence stopped the rendering) when the user entered
 
  82 // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this
 
  83 // (since no builtin property starts with "s_"). See
 
  84 // http://meta.stackoverflow.com/questions/64655/strange-wmd-bug
 
  85 // (granted, switching from Array() to Object() alone would have left only __proto__
 
  87 var SaveHash = function () {
 
  88     this.set = function (key, value) {
 
  89         this["s_" + key] = value;
 
  91     this.get = function (key) {
 
  92         return this["s_" + key];
 
 100 // Global hashes, used by various utility routines
 
 105 // Used to track when we're inside an ordered or unordered list
 
 106 // (see _ProcessListItems() for details):
 
 107 var g_list_level = 0;
 
 110 this.makeHtml = function(text) {
 
 112 // Main function. The order in which other subs are called here is
 
 113 // essential. Link and image substitutions need to happen before
 
 114 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
 
 115 // and <img> tags get encoded.
 
 117     text = html_sanitize(text, function(url) {return url;}, function(id) {return id;});
 
 119         // Clear the global hashes. If we don't clear these, you get conflicts
 
 120         // from other articles when generating a page which contains more than
 
 121         // one article (e.g. an index page that shows the N most recent
 
 123     g_urls = new SaveHash();
 
 124     g_titles = new SaveHash();
 
 125         g_html_blocks = new Array();
 
 127         // attacklab: Replace ~ with ~T
 
 128         // This lets us use tilde as an escape char to avoid md5 hashes
 
 129         // The choice of character is arbitray; anything that isn't
 
 130     // magic in Markdown will work.
 
 131         text = text.replace(/~/g,"~T");
 
 133         // attacklab: Replace $ with ~D
 
 134         // RegExp interprets $ as a special character
 
 135         // when it's in a replacement string
 
 136         text = text.replace(/\$/g,"~D");
 
 138         // Standardize line endings
 
 139         text = text.replace(/\r\n/g,"\n"); // DOS to Unix
 
 140         text = text.replace(/\r/g,"\n"); // Mac to Unix
 
 142         // Make sure text begins and ends with a couple of newlines:
 
 143         text = "\n\n" + text + "\n\n";
 
 145         // Convert all tabs to spaces.
 
 148         // Strip any lines consisting only of spaces and tabs.
 
 149         // This makes subsequent regexen easier to write, because we can
 
 150         // match consecutive blank lines with /\n+/ instead of something
 
 151         // contorted like /[ \t]*\n+/ .
 
 152         text = text.replace(/^[ \t]+$/mg,"");
 
 154         // Turn block-level HTML blocks into hash entries
 
 155         text = _HashHTMLBlocks(text);
 
 157         // Strip link definitions, store in hashes.
 
 158         text = _StripLinkDefinitions(text);
 
 160         text = _RunBlockGamut(text);
 
 162         text = _UnescapeSpecialChars(text);
 
 164         // attacklab: Restore dollar signs
 
 165         text = text.replace(/~D/g,"$$");
 
 167         // attacklab: Restore tildes
 
 168         text = text.replace(/~T/g,"~");
 
 170         text = text.replace(/&lt;/g,"<");
 
 171         text = text.replace(/&gt;/g,">");
 
 176 var _StripLinkDefinitions = function(text) {
 
 178 // Strips link definitions from text, stores the URLs and titles in
 
 182         // Link defs are in the form: ^[id]: url "optional title"
 
 185                 var text = text.replace(/
 
 186                                 ^[ ]{0,3}\[(.+)\]:  // id = $1  attacklab: g_tab_width - 1
 
 188                                   \n?                           // maybe *one* newline
 
 190                                 <?(\S+?)>?                      // url = $2
 
 191                 (?=\s|$)            // lookahead for whitespace instead of the lookbehind removed below
 
 193                                   \n?                           // maybe one newline
 
 195                                 (                   // (potential) title = $3
 
 196                                   (\n*)                         // any lines skipped = $4 attacklab: lookbehind removed
 
 202                                 )?                                      // title is optional
 
 207         var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
 
 208                 function (wholeMatch,m1,m2,m3,m4,m5) {
 
 209                         m1 = m1.toLowerCase();
 
 210                         g_urls.set(m1, _EncodeAmpsAndAngles(m2));  // Link IDs are case-insensitive
 
 212                                 // Oops, found blank lines, so it's not a title.
 
 213                                 // Put back the parenthetical statement we stole.
 
 216                                 g_titles.set(m1, m5.replace(/"/g,"""));
 
 219                         // Completely remove the definition from the text
 
 227 var _HashHTMLBlocks = function(text) {
 
 229         // Hashify HTML blocks:
 
 230         // We only want to do this for block-level HTML tags, such as headers,
 
 231         // lists, and tables. That's because we still want to wrap <p>s around
 
 232         // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
 
 233         // phrase emphasis, and spans. The list of tags we're looking for is
 
 235         var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
 
 236         var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
 
 238         // First, look for nested blocks, e.g.:
 
 241         //     tags for inner block must be indented.
 
 245         // The outermost tags must start at the left margin for this to match, and
 
 246         // the inner nested divs must be indented.
 
 247         // We need to do this before the next, more liberal match, because the next
 
 248         // match will start at the first `<div>` and stop at the first `</div>`.
 
 250         // attacklab: This regex can be expensive when it fails.
 
 252                 var text = text.replace(/
 
 254                         ^                                       // start of line  (with /m)
 
 255                         <($block_tags_a)        // start tag = $2
 
 257                                                                 // attacklab: hack around khtml/pcre bug...
 
 258                         [^\r]*?\n                       // any number of lines, minimally matching
 
 259                         </\2>                           // the matching end tag
 
 260                         [ \t]*                          // trailing spaces/tabs
 
 261                         (?=\n+)                         // followed by a newline
 
 262                 )                                               // attacklab: there are sentinel newlines at end of document
 
 263                 /gm,function(){...}};
 
 265         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);
 
 268         // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
 
 272                 var text = text.replace(/
 
 274                         ^                                       // start of line  (with /m)
 
 275                         <($block_tags_b)        // start tag = $2
 
 277                                                                 // attacklab: hack around khtml/pcre bug...
 
 278                         [^\r]*?                         // any number of lines, minimally matching
 
 279                         .*</\2>                         // the matching end tag
 
 280                         [ \t]*                          // trailing spaces/tabs
 
 281                         (?=\n+)                         // followed by a newline
 
 282                 )                                               // attacklab: there are sentinel newlines at end of document
 
 283                 /gm,function(){...}};
 
 285         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);
 
 287         // Special case just for <hr />. It was easier to make a special case than
 
 288         // to make the other regex more complicated.  
 
 291                 text = text.replace(/
 
 292                 \n                                  // Starting after a blank line
 
 295                         (<(hr)                          // start tag = $2
 
 298                         \/?>)                           // the matching end tag
 
 300                         (?=\n{2,})                      // followed by a blank line
 
 304         text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
 
 306         // Special case for standalone HTML comments:
 
 309                 text = text.replace(/
 
 310                 \n\n                            // Starting after a blank line
 
 311                 [ ]{0,3}                        // attacklab: g_tab_width - 1
 
 314                         (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)    // see http://www.w3.org/TR/html-markup/syntax.html#comments
 
 317                         (?=\n{2,})                      // followed by a blank line
 
 321         text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
 
 323         // PHP and ASP-style processor instructions (<?...?> and <%...%>)
 
 326                 text = text.replace(/
 
 328                         \n\n                            // Starting after a blank line
 
 331                         [ ]{0,3}                        // attacklab: g_tab_width - 1
 
 338                         (?=\n{2,})                      // followed by a blank line
 
 342         text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
 
 347 var hashElement = function(wholeMatch,m1) {
 
 351         blockText = blockText.replace(/^\n+/,"");
 
 353         // strip trailing blank lines
 
 354         blockText = blockText.replace(/\n+$/g,"");
 
 356         // Replace the element text with a marker ("~KxK" where x is its key)
 
 357         blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
 
 362 var _RunBlockGamut = function(text, doNotUnhash) {
 
 364 // These are all the transformations that form block-level
 
 365 // tags like paragraphs, headers, and list items.
 
 367         text = _DoHeaders(text);
 
 369         // Do Horizontal Rules:
 
 370         var key = hashBlock("<hr />");
 
 371         text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
 
 372         text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key);
 
 373         text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key);
 
 375         text = _DoLists(text);
 
 376         text = _DoCodeBlocks(text);
 
 377         text = _DoBlockQuotes(text);
 
 379         // We already ran _HashHTMLBlocks() before, in Markdown(), but that
 
 380         // was to escape raw HTML in the original Markdown source. This time,
 
 381         // we're escaping the markup we've just created, so that we don't wrap
 
 382         // <p> tags around block-level tags.
 
 383         text = _HashHTMLBlocks(text);
 
 384     text = _FormParagraphs(text, doNotUnhash);
 
 390 var _RunSpanGamut = function(text) {
 
 392 // These are all the transformations that occur *within* block-level
 
 393 // tags like paragraphs, headers, and list items.
 
 396         text = _DoCodeSpans(text);
 
 397         text = _EscapeSpecialCharsWithinTagAttributes(text);
 
 398         text = _EncodeBackslashEscapes(text);
 
 400         // Process anchor and image tags. Images must come first,
 
 401         // because ![foo][f] looks like an anchor.
 
 402         text = _DoImages(text);
 
 403         text = _DoAnchors(text);
 
 405         // Make links out of things like `<http://example.com/>`
 
 406         // Must come after _DoAnchors(), because you can use < and >
 
 407         // delimiters in inline links like [this](<url>).
 
 408         text = _DoAutoLinks(text);
 
 409         text = _EncodeAmpsAndAngles(text);
 
 410         text = _DoItalicsAndBold(text);
 
 413         text = text.replace(/  +\n/g," <br />\n");
 
 418 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
 
 420 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
 
 421 // don't conflict with their use in Markdown for code, italics and strong.
 
 424         // Build a regex to find HTML tags and comments.  See Friedl's 
 
 425     // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
 
 427     // SE: changed the comment part of the regex
 
 429     var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
 
 431         text = text.replace(regex, function(wholeMatch) {
 
 432                 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
 
 433                 tag = escapeCharacters(tag,"\\`*_");
 
 440 var _DoAnchors = function(text) {
 
 442 // Turn Markdown link shortcuts into XHTML <a> tags.
 
 445         // First, handle reference-style links: [link text] [id]
 
 449                 text = text.replace(/
 
 450                 (                                                       // wrap whole match in $1
 
 454                                         \[[^\]]*\]              // allow brackets nested one level
 
 456                                         [^\[]                   // or anything else
 
 461                         [ ]?                                    // one optional space
 
 462                         (?:\n[ ]*)?                             // one optional newline followed by spaces
 
 467                 )()()()()                                       // pad remaining backreferences
 
 468                 /g,_DoAnchors_callback);
 
 470         text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
 
 473         // Next, inline-style links: [link text](url "optional title")
 
 477                 text = text.replace(/
 
 478                 (                                               // wrap whole match in $1
 
 482                                                 \[[^\]]*\]      // allow brackets nested one level
 
 484                                             [^\[\]]             // or anything else
 
 490                         ()                                              // no id, so leave $3 empty
 
 493                     \([^)]*\)       // allow one level of (correctly nested) parens (think MSDN)
 
 500                                 (['"])                          // quote char = $6
 
 503                                 [ \t]*                          // ignore any spaces/tabs between closing quote and )
 
 504                         )?                                              // title is optional
 
 510         text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
 
 513         // Last, handle reference-style shortcuts: [link text]
 
 514         // These must come last in case you've also got [link test][1]
 
 515         // or [link test](/foo)
 
 519                 text = text.replace(/
 
 520                 (                                                       // wrap whole match in $1
 
 522                         ([^\[\]]+)                              // link text = $2; can't contain '[' or ']'
 
 524                 )()()()()()                                     // pad rest of backreferences
 
 527         text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
 
 532 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
 
 533         if (m7 == undefined) m7 = "";
 
 534         var whole_match = m1;
 
 536         var link_id      = m3.toLowerCase();
 
 542                         // lower-case and turn embedded newlines into spaces
 
 543                         link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
 
 547                 if (g_urls.get(link_id) != undefined) {
 
 548                         url = g_urls.get(link_id);
 
 549                         if (g_titles.get(link_id) != undefined) {
 
 550                                 title = g_titles.get(link_id);
 
 554                         if (whole_match.search(/\(\s*\)$/m)>-1) {
 
 555                                 // Special case for explicit empty url
 
 563         url = escapeCharacters(url,"*_");
 
 564         var result = "<a href=\"" + url + "\"";
 
 567                 title = title.replace(/"/g,""");
 
 568                 title = escapeCharacters(title,"*_");
 
 569                 result +=  " title=\"" + title + "\"";
 
 572         result += ">" + link_text + "</a>";
 
 578 var _DoImages = function(text) {
 
 580 // Turn Markdown image shortcuts into <img> tags.
 
 584         // First, handle reference-style labeled images: ![alt text][id]
 
 588                 text = text.replace(/
 
 589                 (                                               // wrap whole match in $1
 
 591                         (.*?)                           // alt text = $2
 
 594                         [ ]?                            // one optional space
 
 595                         (?:\n[ ]*)?                     // one optional newline followed by spaces
 
 600                 )()()()()                               // pad rest of backreferences
 
 603         text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
 
 606         // Next, handle inline images:  
 
 607         // Don't forget: encode * and _
 
 610                 text = text.replace(/
 
 611                 (                                               // wrap whole match in $1
 
 613                         (.*?)                           // alt text = $2
 
 615                         \s?                                     // One optional whitespace character
 
 618                         ()                                      // no id, so leave $3 empty
 
 619                         <?(\S+?)>?                      // src url = $4
 
 622                                 (['"])                  // quote char = $6
 
 626                         )?                                      // title is optional
 
 631         text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
 
 636 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
 
 637         var whole_match = m1;
 
 639         var link_id      = m3.toLowerCase();
 
 643         if (!title) title = "";
 
 647                         // lower-case and turn embedded newlines into spaces
 
 648                         link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
 
 652                 if (g_urls.get(link_id) != undefined) {
 
 653                         url = g_urls.get(link_id);
 
 654                         if (g_titles.get(link_id) != undefined) {
 
 655                                 title = g_titles.get(link_id);
 
 663         alt_text = alt_text.replace(/"/g,""");
 
 664         url = escapeCharacters(url,"*_");
 
 665         var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
 
 667         // attacklab: Markdown.pl adds empty title attributes to images.
 
 668         // Replicate this bug.
 
 671                 title = title.replace(/"/g,""");
 
 672                 title = escapeCharacters(title,"*_");
 
 673                 result +=  " title=\"" + title + "\"";
 
 682 var _DoHeaders = function(text) {
 
 684         // Setext-style headers:
 
 691         text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
 
 692                 function(wholeMatch,m1){return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n";});
 
 694         text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
 
 695                 function(matchFound,m1){return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n";});
 
 697         // atx-style headers:
 
 700         //  ## Header 2 with closing hashes ##
 
 706                 text = text.replace(/
 
 707                         ^(\#{1,6})                              // $1 = string of #'s
 
 709                         (.+?)                                   // $2 = Header text
 
 711                         \#*                                             // optional closing #'s (not counted)
 
 713                 /gm, function() {...});
 
 716         text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
 
 717                 function(wholeMatch,m1,m2) {
 
 718                         var h_level = m1.length;
 
 719                         return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
 
 725 // This declaration keeps Dojo compressor from outputting garbage:
 
 726 var _ProcessListItems;
 
 728 var _DoLists = function(text) {
 
 730 // Form HTML ordered (numbered) and unordered (bulleted) lists.
 
 733         // attacklab: add sentinel to hack around khtml/safari bug:
 
 734         // http://bugs.webkit.org/show_bug.cgi?id=11231
 
 737         // Re-usable pattern to match any entirel ul or ol list:
 
 743                                 [ ]{0,3}                                        // attacklab: g_tab_width - 1
 
 744                                 ([*+-]|\d+[.])                          // $3 = first list item marker
 
 749                                 ~0                                                      // sentinel for workaround; should be $
 
 753                                 (?!                                                     // Negative lookahead for another list item marker
 
 755                                         (?:[*+-]|\d+[.])[ \t]+
 
 760         var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
 
 763                 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
 
 765                         var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
 
 767                         var result = _ProcessListItems(list, list_type);
 
 769                         // Trim any trailing whitespace, to put the closing `</$list_type>`
 
 770                         // up on the preceding line, to get it past the current stupid
 
 771                         // HTML block parser. This is a hack to work around the terrible
 
 772                         // hack that is the HTML block parser.
 
 773                         result = result.replace(/\s+$/,"");
 
 774                         result = "<"+list_type+">" + result + "</"+list_type+">\n";
 
 778                 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
 
 779                 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
 
 783                         var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
 
 784                         var result = _ProcessListItems(list, list_type);
 
 785                         result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";   
 
 790         // attacklab: strip sentinel
 
 791         text = text.replace(/~0/,"");
 
 796 var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
 
 798 _ProcessListItems = function(list_str, list_type) {
 
 800 //  Process the contents of a single ordered or unordered list, splitting it
 
 801 //  into individual list items.
 
 803 //  list_type is either "ul" or "ol".
 
 805         // The $g_list_level global keeps track of when we're inside a list.
 
 806         // Each time we enter a list, we increment it; when we leave a list,
 
 807         // we decrement. If it's zero, we're not in a list anymore.
 
 809         // We do this because when we're not inside a list, we want to treat
 
 810         // something like this:
 
 812         //    I recommend upgrading to version
 
 813         //    8. Oops, now this line is treated
 
 816         // As a single paragraph, despite the fact that the second line starts
 
 817         // with a digit-period-space sequence.
 
 819         // Whereas when we're inside a list (or sub-list), that line will be
 
 820         // treated as the start of a sub-list. What a kludge, huh? This is
 
 821         // an aspect of Markdown's syntax that's hard to parse perfectly
 
 822         // without resorting to mind-reading. Perhaps the solution is to
 
 823         // change the syntax rules such that sub-lists must start with a
 
 824         // starting cardinal number; e.g. "1." or "a.".
 
 828         // trim trailing blank lines:
 
 829         list_str = list_str.replace(/\n{2,}$/,"\n");
 
 831         // attacklab: add sentinel to emulate \z
 
 834         // In the original attacklab WMD, list_type was not given to this function, and anything
 
 835         // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
 
 837     //  Markdown          rendered by WMD        rendered by MarkdownSharp
 
 838         //  ------------------------------------------------------------------
 
 839         //  1. first          1. first               1. first
 
 840         //  2. second         2. second              2. second
 
 841         //  - third           3. third                   * third
 
 843         // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
 
 844     // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
 
 846                 list_str = list_str.replace(/
 
 847                         (^[ \t]*)                                               // leading whitespace = $1
 
 848                         ({MARKER}) [ \t]+                       // list marker = $2
 
 849                         ([^\r]+?                                                // list item text   = $3
 
 851                         (?= (~0 | \2 ({MARKER}) [ \t]+))
 
 852                 /gm, function(){...});
 
 855     var marker = _listItemMarkers[list_type];
 
 856     var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
 
 857     var last_item_had_a_double_newline = false;
 
 858         list_str = list_str.replace(re,
 
 859                 function(wholeMatch,m1,m2,m3){
 
 861                         var leading_space = m1;
 
 862             var ends_with_double_newline = /\n\n$/.test(item);
 
 863                         var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/)>-1;
 
 865                         if (contains_double_newline || last_item_had_a_double_newline) {
 
 866                                 item =  _RunBlockGamut(_Outdent(item), /* doNotUnhash = */ true);
 
 869                                 // Recursion for sub-lists:
 
 870                                 item = _DoLists(_Outdent(item));
 
 871                                 item = item.replace(/\n$/,""); // chomp(item)
 
 872                                 item = _RunSpanGamut(item);
 
 874             last_item_had_a_double_newline = ends_with_double_newline;
 
 875                         return  "<li>" + item + "</li>\n";
 
 879         // attacklab: strip sentinel
 
 880         list_str = list_str.replace(/~0/g,"");
 
 887 var _DoCodeBlocks = function(text) {
 
 889 //  Process Markdown `<pre><code>` blocks.
 
 893                 text = text.replace(text,
 
 895                         (                                                               // $1 = the code block -- one or more lines, starting with a space/tab
 
 897                                         (?:[ ]{4}|\t)                   // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
 
 901                         (\n*[ ]{0,3}[^ \t\n]|(?=~0))    // attacklab: g_tab_width
 
 905         // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
 
 908         text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
 
 909                 function(wholeMatch,m1,m2) {
 
 913                         codeblock = _EncodeCode( _Outdent(codeblock));
 
 914                         codeblock = _Detab(codeblock);
 
 915                         codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
 
 916                         codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
 
 918                         codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
 
 920                         return "\n\n" + codeblock + "\n\n" + nextChar;
 
 924         // attacklab: strip sentinel
 
 925         text = text.replace(/~0/,"");
 
 930 var hashBlock = function(text) {
 
 931         text = text.replace(/(^\n+|\n+$)/g,"");
 
 932         return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
 
 936 var _DoCodeSpans = function(text) {
 
 938 //   *  Backtick quotes are used for <code></code> spans.
 
 940 //   *  You can use multiple backticks as the delimiters if you want to
 
 941 //       include literal backticks in the code span. So, this input:
 
 943 //               Just type ``foo `bar` baz`` at the prompt.
 
 945 //         Will translate to:
 
 947 //               <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
 
 949 //      There's no arbitrary limit to the number of backticks you
 
 950 //      can use as delimters. If you need three consecutive backticks
 
 951 //      in your code, use four for delimiters, etc.
 
 953 //  *  You can use spaces to get literal backticks at the edges:
 
 955 //               ... type `` `bar` `` ...
 
 959 //               ... type <code>`bar`</code> ...
 
 963                 text = text.replace(/
 
 964                         (^|[^\\])                                       // Character before opening ` can't be a backslash
 
 965                         (`+)                                            // $2 = Opening run of `
 
 966                         (                                                       // $3 = The code block
 
 968                                 [^`]                                    // attacklab: work around lack of lookbehind
 
 970                         \2                                                      // Matching closer
 
 972                 /gm, function(){...});
 
 975         text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
 
 976                 function(wholeMatch,m1,m2,m3,m4) {
 
 978                         c = c.replace(/^([ \t]*)/g,""); // leading whitespace
 
 979                         c = c.replace(/[ \t]*$/g,"");   // trailing whitespace
 
 981                         return m1+"<code>"+c+"</code>";
 
 988 var _EncodeCode = function(text) {
 
 990 // Encode/escape certain characters inside Markdown code runs.
 
 991 // The point is that in code, these characters are literals,
 
 992 // and lose their special Markdown meanings.
 
 994         // Encode all ampersands; HTML entities are not
 
 995         // entities within a Markdown code span.
 
 996         text = text.replace(/&/g,"&");
 
 998         // Do the angle bracket song and dance:
 
 999         text = text.replace(/</g,"<");
 
1000         text = text.replace(/>/g,">");
 
1002         // Now, escape characters that are magic in Markdown:
 
1003         text = escapeCharacters(text,"\*_{}[]\\",false);
 
1005 // jj the line above breaks this:
 
1019 var _DoItalicsAndBold = function(text) {
 
1021         // <strong> must go first:
 
1022         text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g,
 
1023                 "<strong>$2</strong>");
 
1025         text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
 
1032 var _DoBlockQuotes = function(text) {
 
1035                 text = text.replace(/
 
1036                 (                                                               // Wrap whole match in $1
 
1038                                 ^[ \t]*>[ \t]?                  // '>' at the start of a line
 
1039                                 .+\n                                    // rest of the first line
 
1040                                 (.+\n)*                                 // subsequent consecutive lines
 
1044                 /gm, function(){...});
 
1047         text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
 
1048                 function(wholeMatch,m1) {
 
1051                         // attacklab: hack around Konqueror 3.5.4 bug:
 
1052                         // "----------bug".replace(/^-/g,"") == "bug"
 
1054                         bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0");       // trim one level of quoting
 
1056                         // attacklab: clean up hack
 
1057                         bq = bq.replace(/~0/g,"");
 
1059                         bq = bq.replace(/^[ \t]+$/gm,"");               // trim whitespace-only lines
 
1060                         bq = _RunBlockGamut(bq);                                // recurse
 
1062                         bq = bq.replace(/(^|\n)/g,"$1  ");
 
1063                         // These leading spaces screw with <pre> content, so we need to fix that:
 
1065                                         /(\s*<pre>[^\r]+?<\/pre>)/gm,
 
1066                                 function(wholeMatch,m1) {
 
1068                                         // attacklab: hack around Konqueror 3.5.4 bug:
 
1069                                         pre = pre.replace(/^  /mg,"~0");
 
1070                                         pre = pre.replace(/~0/g,"");
 
1074                         return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
 
1080 var _FormParagraphs = function(text, doNotUnhash) {
 
1083 //    $text - string to process with html <p> tags
 
1086         // Strip leading and trailing lines:
 
1087         text = text.replace(/^\n+/g,"");
 
1088         text = text.replace(/\n+$/g,"");
 
1090         var grafs = text.split(/\n{2,}/g);
 
1091         var grafsOut = new Array();
 
1096         var end = grafs.length;
 
1097         for (var i=0; i<end; i++) {
 
1100                 // if this is an HTML marker, copy it
 
1101                 if (str.search(/~K(\d+)K/g) >= 0) {
 
1104                 else if (str.search(/\S/) >= 0) {
 
1105                         str = _RunSpanGamut(str);
 
1106                         str = str.replace(/^([ \t]*)/g,"<p>");
 
1113         // Unhashify HTML blocks
 
1116         end = grafsOut.length;
 
1117             for (var i=0; i<end; i++) {
 
1118                     // if this is a marker for an html block...
 
1119                     while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
 
1120                             var blockText = g_html_blocks[RegExp.$1];
 
1121                             blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
 
1122                             grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
 
1126         return grafsOut.join("\n\n");
 
1130 var _EncodeAmpsAndAngles = function(text) {
 
1131 // Smart processing for ampersands and angle brackets that need to be encoded.
 
1133         // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
 
1134         //   http://bumppo.net/projects/amputator/
 
1135         text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
 
1138         text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
 
1144 var _EncodeBackslashEscapes = function(text) {
 
1146 //   Parameter:  String.
 
1147 //   Returns:   The string, with after processing the following backslash
 
1148 //                         escape sequences.
 
1151         // attacklab: The polite way to do this is with the new
 
1152         // escapeCharacters() function:
 
1154         //      text = escapeCharacters(text,"\\",true);
 
1155         //      text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
 
1157         // ...but we're sidestepping its use of the (slow) RegExp constructor
 
1158         // as an optimization for Firefox.  This function gets called a LOT.
 
1160         text = text.replace(/\\(\\)/g,escapeCharacters_callback);
 
1161         text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
 
1166 var _DoAutoLinks = function(text) {
 
1168         text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
 
1170         // Email addresses: <address@domain.foo>
 
1173                 text = text.replace(/
 
1179                                 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
 
1182                 /gi, _DoAutoLinks_callback());
 
1184         text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
 
1185                 function(wholeMatch,m1) {
 
1186                         return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
 
1194 var _EncodeEmailAddress = function(addr) {
 
1196 //  Input: an email address, e.g. "foo@example.com"
 
1198 //  Output: the email address as a mailto link, with each character
 
1199 //      of the address encoded as either a decimal or hex entity, in
 
1200 //      the hopes of foiling most address harvesting spam bots. E.g.:
 
1202 //      <a href="mailto:foo@e
 
1203 //         xample.com">foo
 
1204 //         @example.com</a>
 
1206 //  Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
 
1207 //  mailing list: <http://tinyurl.com/yu7ue>
 
1210         // attacklab: why can't javascript speak hex?
 
1211         function char2hex(ch) {
 
1212                 var hexDigits = '0123456789ABCDEF';
 
1213                 var dec = ch.charCodeAt(0);
 
1214                 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
 
1218                 function(ch){return "&#"+ch.charCodeAt(0)+";";},
 
1219                 function(ch){return "&#x"+char2hex(ch)+";";},
 
1220                 function(ch){return ch;}
 
1223         addr = "mailto:" + addr;
 
1225         addr = addr.replace(/./g, function(ch) {
 
1227                         // this *must* be encoded. I insist.
 
1228                         ch = encode[Math.floor(Math.random()*2)](ch);
 
1229                 } else if (ch !=":") {
 
1230                         // leave ':' alone (to spot mailto: later)
 
1231                         var r = Math.random();
 
1232                         // roughly 10% raw, 45% hex, 45% dec
 
1234                                         r > .9  ?       encode[2](ch)   :
 
1235                                         r > .45 ?       encode[1](ch)   :
 
1242         addr = "<a href=\"" + addr + "\">" + addr + "</a>";
 
1243         addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
 
1249 var _UnescapeSpecialChars = function(text) {
 
1251 // Swap back in all the special characters we've hidden.
 
1253         text = text.replace(/~E(\d+)E/g,
 
1254                 function(wholeMatch,m1) {
 
1255                         var charCodeToReplace = parseInt(m1);
 
1256                         return String.fromCharCode(charCodeToReplace);
 
1263 var _Outdent = function(text) {
 
1265 // Remove one level of line-leading tabs or spaces
 
1268         // attacklab: hack around Konqueror 3.5.4 bug:
 
1269         // "----------bug".replace(/^-/g,"") == "bug"
 
1271         text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
 
1273         // attacklab: clean up hack
 
1274         text = text.replace(/~0/g,"")
 
1279 var _Detab = function (text) {
 
1280         if (!/\t/.test(text))
 
1283         var spaces = ["    ", "   ", "  ", " "],
 
1287         return text.replace(/[\n\t]/g, function (match, offset) {
 
1288                 if (match === "\n") {
 
1292                 v = (offset - skew) % 4;
 
1299 //  attacklab: Utility functions
 
1303 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
 
1304         // First we have to escape the escape characters so that
 
1305         // we can build a character class out of them
 
1306         var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
 
1308         if (afterBackslash) {
 
1309                 regexString = "\\\\" + regexString;
 
1312         var regex = new RegExp(regexString,"g");
 
1313         text = text.replace(regex,escapeCharacters_callback);
 
1319 var escapeCharacters_callback = function(wholeMatch,m1) {
 
1320         var charCodeToEscape = m1.charCodeAt(0);
 
1321         return "~E"+charCodeToEscape+"E";
 
1324 } // end of Attacklab.showdown.converter
 
1327 // Version 0.9 used the Showdown namespace instead of Attacklab.showdown
 
1328 // The old namespace is deprecated, but we'll support it for now:
 
1329 var Showdown = Attacklab.showdown;
 
1331 // If anyone's interested, tell the world that this file's been loaded
 
1332 if (Attacklab.fileLoaded) {
 
1333         Attacklab.fileLoaded("showdown.js");