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,"~");
173 var _StripLinkDefinitions = function(text) {
175 // Strips link definitions from text, stores the URLs and titles in
179 // Link defs are in the form: ^[id]: url "optional title"
182 var text = text.replace(/
183 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
185 \n? // maybe *one* newline
187 <?(\S+?)>? // url = $2
188 (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
190 \n? // maybe one newline
192 ( // (potential) title = $3
193 (\n*) // any lines skipped = $4 attacklab: lookbehind removed
199 )? // title is optional
204 var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
205 function (wholeMatch,m1,m2,m3,m4,m5) {
206 m1 = m1.toLowerCase();
207 g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
209 // Oops, found blank lines, so it's not a title.
210 // Put back the parenthetical statement we stole.
213 g_titles.set(m1, m5.replace(/"/g,"""));
216 // Completely remove the definition from the text
224 var _HashHTMLBlocks = function(text) {
226 // Hashify HTML blocks:
227 // We only want to do this for block-level HTML tags, such as headers,
228 // lists, and tables. That's because we still want to wrap <p>s around
229 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
230 // phrase emphasis, and spans. The list of tags we're looking for is
232 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
233 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
235 // First, look for nested blocks, e.g.:
238 // tags for inner block must be indented.
242 // The outermost tags must start at the left margin for this to match, and
243 // the inner nested divs must be indented.
244 // We need to do this before the next, more liberal match, because the next
245 // match will start at the first `<div>` and stop at the first `</div>`.
247 // attacklab: This regex can be expensive when it fails.
249 var text = text.replace(/
251 ^ // start of line (with /m)
252 <($block_tags_a) // start tag = $2
254 // attacklab: hack around khtml/pcre bug...
255 [^\r]*?\n // any number of lines, minimally matching
256 </\2> // the matching end tag
257 [ \t]* // trailing spaces/tabs
258 (?=\n+) // followed by a newline
259 ) // attacklab: there are sentinel newlines at end of document
260 /gm,function(){...}};
262 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);
265 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
269 var text = text.replace(/
271 ^ // start of line (with /m)
272 <($block_tags_b) // start tag = $2
274 // attacklab: hack around khtml/pcre bug...
275 [^\r]*? // any number of lines, minimally matching
276 .*</\2> // the matching end tag
277 [ \t]* // trailing spaces/tabs
278 (?=\n+) // followed by a newline
279 ) // attacklab: there are sentinel newlines at end of document
280 /gm,function(){...}};
282 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);
284 // Special case just for <hr />. It was easier to make a special case than
285 // to make the other regex more complicated.
288 text = text.replace(/
289 \n // Starting after a blank line
292 (<(hr) // start tag = $2
295 \/?>) // the matching end tag
297 (?=\n{2,}) // followed by a blank line
301 text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
303 // Special case for standalone HTML comments:
306 text = text.replace(/
307 \n\n // Starting after a blank line
308 [ ]{0,3} // attacklab: g_tab_width - 1
311 (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments
314 (?=\n{2,}) // followed by a blank line
318 text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
320 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
323 text = text.replace(/
325 \n\n // Starting after a blank line
328 [ ]{0,3} // attacklab: g_tab_width - 1
335 (?=\n{2,}) // followed by a blank line
339 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
344 var hashElement = function(wholeMatch,m1) {
348 blockText = blockText.replace(/^\n+/,"");
350 // strip trailing blank lines
351 blockText = blockText.replace(/\n+$/g,"");
353 // Replace the element text with a marker ("~KxK" where x is its key)
354 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
359 var _RunBlockGamut = function(text, doNotUnhash) {
361 // These are all the transformations that form block-level
362 // tags like paragraphs, headers, and list items.
364 text = _DoHeaders(text);
366 // Do Horizontal Rules:
367 var key = hashBlock("<hr />");
368 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
369 text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key);
370 text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key);
372 text = _DoLists(text);
373 text = _DoCodeBlocks(text);
374 text = _DoBlockQuotes(text);
376 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
377 // was to escape raw HTML in the original Markdown source. This time,
378 // we're escaping the markup we've just created, so that we don't wrap
379 // <p> tags around block-level tags.
380 text = _HashHTMLBlocks(text);
381 text = _FormParagraphs(text, doNotUnhash);
387 var _RunSpanGamut = function(text) {
389 // These are all the transformations that occur *within* block-level
390 // tags like paragraphs, headers, and list items.
393 text = _DoCodeSpans(text);
394 text = _EscapeSpecialCharsWithinTagAttributes(text);
395 text = _EncodeBackslashEscapes(text);
397 // Process anchor and image tags. Images must come first,
398 // because ![foo][f] looks like an anchor.
399 text = _DoImages(text);
400 text = _DoAnchors(text);
402 // Make links out of things like `<http://example.com/>`
403 // Must come after _DoAnchors(), because you can use < and >
404 // delimiters in inline links like [this](<url>).
405 text = _DoAutoLinks(text);
406 text = _EncodeAmpsAndAngles(text);
407 text = _DoItalicsAndBold(text);
410 text = text.replace(/ +\n/g," <br />\n");
415 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
417 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
418 // don't conflict with their use in Markdown for code, italics and strong.
421 // Build a regex to find HTML tags and comments. See Friedl's
422 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
424 // SE: changed the comment part of the regex
426 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
428 text = text.replace(regex, function(wholeMatch) {
429 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
430 tag = escapeCharacters(tag,"\\`*_");
437 var _DoAnchors = function(text) {
439 // Turn Markdown link shortcuts into XHTML <a> tags.
442 // First, handle reference-style links: [link text] [id]
446 text = text.replace(/
447 ( // wrap whole match in $1
451 \[[^\]]*\] // allow brackets nested one level
453 [^\[] // or anything else
458 [ ]? // one optional space
459 (?:\n[ ]*)? // one optional newline followed by spaces
464 )()()()() // pad remaining backreferences
465 /g,_DoAnchors_callback);
467 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
470 // Next, inline-style links: [link text](url "optional title")
474 text = text.replace(/
475 ( // wrap whole match in $1
479 \[[^\]]*\] // allow brackets nested one level
481 [^\[\]] // or anything else
487 () // no id, so leave $3 empty
490 \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
497 (['"]) // quote char = $6
500 [ \t]* // ignore any spaces/tabs between closing quote and )
501 )? // title is optional
507 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
510 // Last, handle reference-style shortcuts: [link text]
511 // These must come last in case you've also got [link test][1]
512 // or [link test](/foo)
516 text = text.replace(/
517 ( // wrap whole match in $1
519 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
521 )()()()()() // pad rest of backreferences
524 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
529 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
530 if (m7 == undefined) m7 = "";
531 var whole_match = m1;
533 var link_id = m3.toLowerCase();
539 // lower-case and turn embedded newlines into spaces
540 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
544 if (g_urls.get(link_id) != undefined) {
545 url = g_urls.get(link_id);
546 if (g_titles.get(link_id) != undefined) {
547 title = g_titles.get(link_id);
551 if (whole_match.search(/\(\s*\)$/m)>-1) {
552 // Special case for explicit empty url
560 url = escapeCharacters(url,"*_");
561 var result = "<a href=\"" + url + "\"";
564 title = title.replace(/"/g,""");
565 title = escapeCharacters(title,"*_");
566 result += " title=\"" + title + "\"";
569 result += ">" + link_text + "</a>";
575 var _DoImages = function(text) {
577 // Turn Markdown image shortcuts into <img> tags.
581 // First, handle reference-style labeled images: ![alt text][id]
585 text = text.replace(/
586 ( // wrap whole match in $1
588 (.*?) // alt text = $2
591 [ ]? // one optional space
592 (?:\n[ ]*)? // one optional newline followed by spaces
597 )()()()() // pad rest of backreferences
600 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
603 // Next, handle inline images: ![alt text](url "optional title")
604 // Don't forget: encode * and _
607 text = text.replace(/
608 ( // wrap whole match in $1
610 (.*?) // alt text = $2
612 \s? // One optional whitespace character
615 () // no id, so leave $3 empty
616 <?(\S+?)>? // src url = $4
619 (['"]) // quote char = $6
623 )? // title is optional
628 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
633 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
634 var whole_match = m1;
636 var link_id = m3.toLowerCase();
640 if (!title) title = "";
644 // lower-case and turn embedded newlines into spaces
645 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
649 if (g_urls.get(link_id) != undefined) {
650 url = g_urls.get(link_id);
651 if (g_titles.get(link_id) != undefined) {
652 title = g_titles.get(link_id);
660 alt_text = alt_text.replace(/"/g,""");
661 url = escapeCharacters(url,"*_");
662 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
664 // attacklab: Markdown.pl adds empty title attributes to images.
665 // Replicate this bug.
668 title = title.replace(/"/g,""");
669 title = escapeCharacters(title,"*_");
670 result += " title=\"" + title + "\"";
679 var _DoHeaders = function(text) {
681 // Setext-style headers:
688 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
689 function(wholeMatch,m1){return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n";});
691 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
692 function(matchFound,m1){return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n";});
694 // atx-style headers:
697 // ## Header 2 with closing hashes ##
703 text = text.replace(/
704 ^(\#{1,6}) // $1 = string of #'s
706 (.+?) // $2 = Header text
708 \#* // optional closing #'s (not counted)
710 /gm, function() {...});
713 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
714 function(wholeMatch,m1,m2) {
715 var h_level = m1.length;
716 return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
722 // This declaration keeps Dojo compressor from outputting garbage:
723 var _ProcessListItems;
725 var _DoLists = function(text) {
727 // Form HTML ordered (numbered) and unordered (bulleted) lists.
730 // attacklab: add sentinel to hack around khtml/safari bug:
731 // http://bugs.webkit.org/show_bug.cgi?id=11231
734 // Re-usable pattern to match any entirel ul or ol list:
740 [ ]{0,3} // attacklab: g_tab_width - 1
741 ([*+-]|\d+[.]) // $3 = first list item marker
746 ~0 // sentinel for workaround; should be $
750 (?! // Negative lookahead for another list item marker
752 (?:[*+-]|\d+[.])[ \t]+
757 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
760 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
762 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
764 var result = _ProcessListItems(list, list_type);
766 // Trim any trailing whitespace, to put the closing `</$list_type>`
767 // up on the preceding line, to get it past the current stupid
768 // HTML block parser. This is a hack to work around the terrible
769 // hack that is the HTML block parser.
770 result = result.replace(/\s+$/,"");
771 result = "<"+list_type+">" + result + "</"+list_type+">\n";
775 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
776 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
780 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
781 var result = _ProcessListItems(list, list_type);
782 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
787 // attacklab: strip sentinel
788 text = text.replace(/~0/,"");
793 var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
795 _ProcessListItems = function(list_str, list_type) {
797 // Process the contents of a single ordered or unordered list, splitting it
798 // into individual list items.
800 // list_type is either "ul" or "ol".
802 // The $g_list_level global keeps track of when we're inside a list.
803 // Each time we enter a list, we increment it; when we leave a list,
804 // we decrement. If it's zero, we're not in a list anymore.
806 // We do this because when we're not inside a list, we want to treat
807 // something like this:
809 // I recommend upgrading to version
810 // 8. Oops, now this line is treated
813 // As a single paragraph, despite the fact that the second line starts
814 // with a digit-period-space sequence.
816 // Whereas when we're inside a list (or sub-list), that line will be
817 // treated as the start of a sub-list. What a kludge, huh? This is
818 // an aspect of Markdown's syntax that's hard to parse perfectly
819 // without resorting to mind-reading. Perhaps the solution is to
820 // change the syntax rules such that sub-lists must start with a
821 // starting cardinal number; e.g. "1." or "a.".
825 // trim trailing blank lines:
826 list_str = list_str.replace(/\n{2,}$/,"\n");
828 // attacklab: add sentinel to emulate \z
831 // In the original attacklab WMD, list_type was not given to this function, and anything
832 // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
834 // Markdown rendered by WMD rendered by MarkdownSharp
835 // ------------------------------------------------------------------
836 // 1. first 1. first 1. first
837 // 2. second 2. second 2. second
838 // - third 3. third * third
840 // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
841 // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
843 list_str = list_str.replace(/
844 (^[ \t]*) // leading whitespace = $1
845 ({MARKER}) [ \t]+ // list marker = $2
846 ([^\r]+? // list item text = $3
848 (?= (~0 | \2 ({MARKER}) [ \t]+))
849 /gm, function(){...});
852 var marker = _listItemMarkers[list_type];
853 var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
854 var last_item_had_a_double_newline = false;
855 list_str = list_str.replace(re,
856 function(wholeMatch,m1,m2,m3){
858 var leading_space = m1;
859 var ends_with_double_newline = /\n\n$/.test(item);
860 var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/)>-1;
862 if (contains_double_newline || last_item_had_a_double_newline) {
863 item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */ true);
866 // Recursion for sub-lists:
867 item = _DoLists(_Outdent(item));
868 item = item.replace(/\n$/,""); // chomp(item)
869 item = _RunSpanGamut(item);
871 last_item_had_a_double_newline = ends_with_double_newline;
872 return "<li>" + item + "</li>\n";
876 // attacklab: strip sentinel
877 list_str = list_str.replace(/~0/g,"");
884 var _DoCodeBlocks = function(text) {
886 // Process Markdown `<pre><code>` blocks.
890 text = text.replace(text,
892 ( // $1 = the code block -- one or more lines, starting with a space/tab
894 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
898 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
902 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
905 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
906 function(wholeMatch,m1,m2) {
910 codeblock = _EncodeCode( _Outdent(codeblock));
911 codeblock = _Detab(codeblock);
912 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
913 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
915 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
917 return "\n\n" + codeblock + "\n\n" + nextChar;
921 // attacklab: strip sentinel
922 text = text.replace(/~0/,"");
927 var hashBlock = function(text) {
928 text = text.replace(/(^\n+|\n+$)/g,"");
929 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
933 var _DoCodeSpans = function(text) {
935 // * Backtick quotes are used for <code></code> spans.
937 // * You can use multiple backticks as the delimiters if you want to
938 // include literal backticks in the code span. So, this input:
940 // Just type ``foo `bar` baz`` at the prompt.
942 // Will translate to:
944 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
946 // There's no arbitrary limit to the number of backticks you
947 // can use as delimters. If you need three consecutive backticks
948 // in your code, use four for delimiters, etc.
950 // * You can use spaces to get literal backticks at the edges:
952 // ... type `` `bar` `` ...
956 // ... type <code>`bar`</code> ...
960 text = text.replace(/
961 (^|[^\\]) // Character before opening ` can't be a backslash
962 (`+) // $2 = Opening run of `
963 ( // $3 = The code block
965 [^`] // attacklab: work around lack of lookbehind
967 \2 // Matching closer
969 /gm, function(){...});
972 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
973 function(wholeMatch,m1,m2,m3,m4) {
975 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
976 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
978 return m1+"<code>"+c+"</code>";
985 var _EncodeCode = function(text) {
987 // Encode/escape certain characters inside Markdown code runs.
988 // The point is that in code, these characters are literals,
989 // and lose their special Markdown meanings.
991 // Encode all ampersands; HTML entities are not
992 // entities within a Markdown code span.
993 text = text.replace(/&/g,"&");
995 // Do the angle bracket song and dance:
996 text = text.replace(/</g,"<");
997 text = text.replace(/>/g,">");
999 // Now, escape characters that are magic in Markdown:
1000 text = escapeCharacters(text,"\*_{}[]\\",false);
1002 // jj the line above breaks this:
1016 var _DoItalicsAndBold = function(text) {
1018 // <strong> must go first:
1019 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g,
1020 "<strong>$2</strong>");
1022 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1029 var _DoBlockQuotes = function(text) {
1032 text = text.replace(/
1033 ( // Wrap whole match in $1
1035 ^[ \t]*>[ \t]? // '>' at the start of a line
1036 .+\n // rest of the first line
1037 (.+\n)* // subsequent consecutive lines
1041 /gm, function(){...});
1044 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1045 function(wholeMatch,m1) {
1048 // attacklab: hack around Konqueror 3.5.4 bug:
1049 // "----------bug".replace(/^-/g,"") == "bug"
1051 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1053 // attacklab: clean up hack
1054 bq = bq.replace(/~0/g,"");
1056 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1057 bq = _RunBlockGamut(bq); // recurse
1059 bq = bq.replace(/(^|\n)/g,"$1 ");
1060 // These leading spaces screw with <pre> content, so we need to fix that:
1062 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1063 function(wholeMatch,m1) {
1065 // attacklab: hack around Konqueror 3.5.4 bug:
1066 pre = pre.replace(/^ /mg,"~0");
1067 pre = pre.replace(/~0/g,"");
1071 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1077 var _FormParagraphs = function(text, doNotUnhash) {
1080 // $text - string to process with html <p> tags
1083 // Strip leading and trailing lines:
1084 text = text.replace(/^\n+/g,"");
1085 text = text.replace(/\n+$/g,"");
1087 var grafs = text.split(/\n{2,}/g);
1088 var grafsOut = new Array();
1093 var end = grafs.length;
1094 for (var i=0; i<end; i++) {
1097 // if this is an HTML marker, copy it
1098 if (str.search(/~K(\d+)K/g) >= 0) {
1101 else if (str.search(/\S/) >= 0) {
1102 str = _RunSpanGamut(str);
1103 str = str.replace(/^([ \t]*)/g,"<p>");
1110 // Unhashify HTML blocks
1113 end = grafsOut.length;
1114 for (var i=0; i<end; i++) {
1115 // if this is a marker for an html block...
1116 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1117 var blockText = g_html_blocks[RegExp.$1];
1118 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1119 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1123 return grafsOut.join("\n\n");
1127 var _EncodeAmpsAndAngles = function(text) {
1128 // Smart processing for ampersands and angle brackets that need to be encoded.
1130 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1131 // http://bumppo.net/projects/amputator/
1132 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1135 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1141 var _EncodeBackslashEscapes = function(text) {
1143 // Parameter: String.
1144 // Returns: The string, with after processing the following backslash
1145 // escape sequences.
1148 // attacklab: The polite way to do this is with the new
1149 // escapeCharacters() function:
1151 // text = escapeCharacters(text,"\\",true);
1152 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1154 // ...but we're sidestepping its use of the (slow) RegExp constructor
1155 // as an optimization for Firefox. This function gets called a LOT.
1157 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1158 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1163 var _DoAutoLinks = function(text) {
1165 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1167 // Email addresses: <address@domain.foo>
1170 text = text.replace(/
1176 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1179 /gi, _DoAutoLinks_callback());
1181 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1182 function(wholeMatch,m1) {
1183 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1191 var _EncodeEmailAddress = function(addr) {
1193 // Input: an email address, e.g. "foo@example.com"
1195 // Output: the email address as a mailto link, with each character
1196 // of the address encoded as either a decimal or hex entity, in
1197 // the hopes of foiling most address harvesting spam bots. E.g.:
1199 // <a href="mailto:foo@e
1200 // xample.com">foo
1201 // @example.com</a>
1203 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1204 // mailing list: <http://tinyurl.com/yu7ue>
1207 // attacklab: why can't javascript speak hex?
1208 function char2hex(ch) {
1209 var hexDigits = '0123456789ABCDEF';
1210 var dec = ch.charCodeAt(0);
1211 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1215 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1216 function(ch){return "&#x"+char2hex(ch)+";";},
1217 function(ch){return ch;}
1220 addr = "mailto:" + addr;
1222 addr = addr.replace(/./g, function(ch) {
1224 // this *must* be encoded. I insist.
1225 ch = encode[Math.floor(Math.random()*2)](ch);
1226 } else if (ch !=":") {
1227 // leave ':' alone (to spot mailto: later)
1228 var r = Math.random();
1229 // roughly 10% raw, 45% hex, 45% dec
1231 r > .9 ? encode[2](ch) :
1232 r > .45 ? encode[1](ch) :
1239 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1240 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1246 var _UnescapeSpecialChars = function(text) {
1248 // Swap back in all the special characters we've hidden.
1250 text = text.replace(/~E(\d+)E/g,
1251 function(wholeMatch,m1) {
1252 var charCodeToReplace = parseInt(m1);
1253 return String.fromCharCode(charCodeToReplace);
1260 var _Outdent = function(text) {
1262 // Remove one level of line-leading tabs or spaces
1265 // attacklab: hack around Konqueror 3.5.4 bug:
1266 // "----------bug".replace(/^-/g,"") == "bug"
1268 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1270 // attacklab: clean up hack
1271 text = text.replace(/~0/g,"")
1276 var _Detab = function (text) {
1277 if (!/\t/.test(text))
1280 var spaces = [" ", " ", " ", " "],
1284 return text.replace(/[\n\t]/g, function (match, offset) {
1285 if (match === "\n") {
1289 v = (offset - skew) % 4;
1296 // attacklab: Utility functions
1300 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1301 // First we have to escape the escape characters so that
1302 // we can build a character class out of them
1303 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1305 if (afterBackslash) {
1306 regexString = "\\\\" + regexString;
1309 var regex = new RegExp(regexString,"g");
1310 text = text.replace(regex,escapeCharacters_callback);
1316 var escapeCharacters_callback = function(wholeMatch,m1) {
1317 var charCodeToEscape = m1.charCodeAt(0);
1318 return "~E"+charCodeToEscape+"E";
1321 } // end of Attacklab.showdown.converter
1324 // Version 0.9 used the Showdown namespace instead of Attacklab.showdown
1325 // The old namespace is deprecated, but we'll support it for now:
1326 var Showdown = Attacklab.showdown;
1328 // If anyone's interested, tell the world that this file's been loaded
1329 if (Attacklab.fileLoaded) {
1330 Attacklab.fileLoaded("showdown.js");