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.
118 // Clear the global hashes. If we don't clear these, you get conflicts
119 // from other articles when generating a page which contains more than
120 // one article (e.g. an index page that shows the N most recent
122 g_urls = new SaveHash();
123 g_titles = new SaveHash();
124 g_html_blocks = new Array();
126 // attacklab: Replace ~ with ~T
127 // This lets us use tilde as an escape char to avoid md5 hashes
128 // The choice of character is arbitray; anything that isn't
129 // magic in Markdown will work.
130 text = text.replace(/~/g,"~T");
132 // attacklab: Replace $ with ~D
133 // RegExp interprets $ as a special character
134 // when it's in a replacement string
135 text = text.replace(/\$/g,"~D");
137 // Standardize line endings
138 text = text.replace(/\r\n/g,"\n"); // DOS to Unix
139 text = text.replace(/\r/g,"\n"); // Mac to Unix
141 // Make sure text begins and ends with a couple of newlines:
142 text = "\n\n" + text + "\n\n";
144 // Convert all tabs to spaces.
147 // Strip any lines consisting only of spaces and tabs.
148 // This makes subsequent regexen easier to write, because we can
149 // match consecutive blank lines with /\n+/ instead of something
150 // contorted like /[ \t]*\n+/ .
151 text = text.replace(/^[ \t]+$/mg,"");
153 // Turn block-level HTML blocks into hash entries
154 text = _HashHTMLBlocks(text);
156 // Strip link definitions, store in hashes.
157 text = _StripLinkDefinitions(text);
159 text = _RunBlockGamut(text);
161 text = _UnescapeSpecialChars(text);
163 // attacklab: Restore dollar signs
164 text = text.replace(/~D/g,"$$");
166 // attacklab: Restore tildes
167 text = text.replace(/~T/g,"~");
172 var _StripLinkDefinitions = function(text) {
174 // Strips link definitions from text, stores the URLs and titles in
178 // Link defs are in the form: ^[id]: url "optional title"
181 var text = text.replace(/
182 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
184 \n? // maybe *one* newline
186 <?(\S+?)>? // url = $2
187 (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
189 \n? // maybe one newline
191 ( // (potential) title = $3
192 (\n*) // any lines skipped = $4 attacklab: lookbehind removed
198 )? // title is optional
203 var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
204 function (wholeMatch,m1,m2,m3,m4,m5) {
205 m1 = m1.toLowerCase();
206 g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
208 // Oops, found blank lines, so it's not a title.
209 // Put back the parenthetical statement we stole.
212 g_titles.set(m1, m5.replace(/"/g,"""));
215 // Completely remove the definition from the text
223 var _HashHTMLBlocks = function(text) {
225 // Hashify HTML blocks:
226 // We only want to do this for block-level HTML tags, such as headers,
227 // lists, and tables. That's because we still want to wrap <p>s around
228 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
229 // phrase emphasis, and spans. The list of tags we're looking for is
231 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
232 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
234 // First, look for nested blocks, e.g.:
237 // tags for inner block must be indented.
241 // The outermost tags must start at the left margin for this to match, and
242 // the inner nested divs must be indented.
243 // We need to do this before the next, more liberal match, because the next
244 // match will start at the first `<div>` and stop at the first `</div>`.
246 // attacklab: This regex can be expensive when it fails.
248 var text = text.replace(/
250 ^ // start of line (with /m)
251 <($block_tags_a) // start tag = $2
253 // attacklab: hack around khtml/pcre bug...
254 [^\r]*?\n // any number of lines, minimally matching
255 </\2> // the matching end tag
256 [ \t]* // trailing spaces/tabs
257 (?=\n+) // followed by a newline
258 ) // attacklab: there are sentinel newlines at end of document
259 /gm,function(){...}};
261 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);
264 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
268 var text = text.replace(/
270 ^ // start of line (with /m)
271 <($block_tags_b) // start tag = $2
273 // attacklab: hack around khtml/pcre bug...
274 [^\r]*? // any number of lines, minimally matching
275 .*</\2> // the matching end tag
276 [ \t]* // trailing spaces/tabs
277 (?=\n+) // followed by a newline
278 ) // attacklab: there are sentinel newlines at end of document
279 /gm,function(){...}};
281 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);
283 // Special case just for <hr />. It was easier to make a special case than
284 // to make the other regex more complicated.
287 text = text.replace(/
288 \n // Starting after a blank line
291 (<(hr) // start tag = $2
294 \/?>) // the matching end tag
296 (?=\n{2,}) // followed by a blank line
300 text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
302 // Special case for standalone HTML comments:
305 text = text.replace(/
306 \n\n // Starting after a blank line
307 [ ]{0,3} // attacklab: g_tab_width - 1
310 (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments
313 (?=\n{2,}) // followed by a blank line
317 text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
319 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
322 text = text.replace(/
324 \n\n // Starting after a blank line
327 [ ]{0,3} // attacklab: g_tab_width - 1
334 (?=\n{2,}) // followed by a blank line
338 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
343 var hashElement = function(wholeMatch,m1) {
347 blockText = blockText.replace(/^\n+/,"");
349 // strip trailing blank lines
350 blockText = blockText.replace(/\n+$/g,"");
352 // Replace the element text with a marker ("~KxK" where x is its key)
353 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
358 var _RunBlockGamut = function(text, doNotUnhash) {
360 // These are all the transformations that form block-level
361 // tags like paragraphs, headers, and list items.
363 text = _DoHeaders(text);
365 // Do Horizontal Rules:
366 var key = hashBlock("<hr />");
367 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
368 text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key);
369 text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key);
371 text = _DoLists(text);
372 text = _DoCodeBlocks(text);
373 text = _DoBlockQuotes(text);
375 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
376 // was to escape raw HTML in the original Markdown source. This time,
377 // we're escaping the markup we've just created, so that we don't wrap
378 // <p> tags around block-level tags.
379 text = _HashHTMLBlocks(text);
380 text = _FormParagraphs(text, doNotUnhash);
386 var _RunSpanGamut = function(text) {
388 // These are all the transformations that occur *within* block-level
389 // tags like paragraphs, headers, and list items.
392 text = _DoCodeSpans(text);
393 text = _EscapeSpecialCharsWithinTagAttributes(text);
394 text = _EncodeBackslashEscapes(text);
396 // Process anchor and image tags. Images must come first,
397 // because ![foo][f] looks like an anchor.
398 text = _DoImages(text);
399 text = _DoAnchors(text);
401 // Make links out of things like `<http://example.com/>`
402 // Must come after _DoAnchors(), because you can use < and >
403 // delimiters in inline links like [this](<url>).
404 text = _DoAutoLinks(text);
405 text = _EncodeAmpsAndAngles(text);
406 text = _DoItalicsAndBold(text);
409 text = text.replace(/ +\n/g," <br />\n");
414 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
416 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
417 // don't conflict with their use in Markdown for code, italics and strong.
420 // Build a regex to find HTML tags and comments. See Friedl's
421 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
423 // SE: changed the comment part of the regex
425 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
427 text = text.replace(regex, function(wholeMatch) {
428 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
429 tag = escapeCharacters(tag,"\\`*_");
436 var _DoAnchors = function(text) {
438 // Turn Markdown link shortcuts into XHTML <a> tags.
441 // First, handle reference-style links: [link text] [id]
445 text = text.replace(/
446 ( // wrap whole match in $1
450 \[[^\]]*\] // allow brackets nested one level
452 [^\[] // or anything else
457 [ ]? // one optional space
458 (?:\n[ ]*)? // one optional newline followed by spaces
463 )()()()() // pad remaining backreferences
464 /g,_DoAnchors_callback);
466 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
469 // Next, inline-style links: [link text](url "optional title")
473 text = text.replace(/
474 ( // wrap whole match in $1
478 \[[^\]]*\] // allow brackets nested one level
480 [^\[\]] // or anything else
486 () // no id, so leave $3 empty
489 \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
496 (['"]) // quote char = $6
499 [ \t]* // ignore any spaces/tabs between closing quote and )
500 )? // title is optional
506 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
509 // Last, handle reference-style shortcuts: [link text]
510 // These must come last in case you've also got [link test][1]
511 // or [link test](/foo)
515 text = text.replace(/
516 ( // wrap whole match in $1
518 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
520 )()()()()() // pad rest of backreferences
523 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
528 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
529 if (m7 == undefined) m7 = "";
530 var whole_match = m1;
532 var link_id = m3.toLowerCase();
538 // lower-case and turn embedded newlines into spaces
539 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
543 if (g_urls.get(link_id) != undefined) {
544 url = g_urls.get(link_id);
545 if (g_titles.get(link_id) != undefined) {
546 title = g_titles.get(link_id);
550 if (whole_match.search(/\(\s*\)$/m)>-1) {
551 // Special case for explicit empty url
559 url = escapeCharacters(url,"*_");
560 var result = "<a href=\"" + url + "\"";
563 title = title.replace(/"/g,""");
564 title = escapeCharacters(title,"*_");
565 result += " title=\"" + title + "\"";
568 result += ">" + link_text + "</a>";
574 var _DoImages = function(text) {
576 // Turn Markdown image shortcuts into <img> tags.
580 // First, handle reference-style labeled images: ![alt text][id]
584 text = text.replace(/
585 ( // wrap whole match in $1
587 (.*?) // alt text = $2
590 [ ]? // one optional space
591 (?:\n[ ]*)? // one optional newline followed by spaces
596 )()()()() // pad rest of backreferences
599 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
602 // Next, handle inline images: ![alt text](url "optional title")
603 // Don't forget: encode * and _
606 text = text.replace(/
607 ( // wrap whole match in $1
609 (.*?) // alt text = $2
611 \s? // One optional whitespace character
614 () // no id, so leave $3 empty
615 <?(\S+?)>? // src url = $4
618 (['"]) // quote char = $6
622 )? // title is optional
627 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
632 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
633 var whole_match = m1;
635 var link_id = m3.toLowerCase();
639 if (!title) title = "";
643 // lower-case and turn embedded newlines into spaces
644 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
648 if (g_urls.get(link_id) != undefined) {
649 url = g_urls.get(link_id);
650 if (g_titles.get(link_id) != undefined) {
651 title = g_titles.get(link_id);
659 alt_text = alt_text.replace(/"/g,""");
660 url = escapeCharacters(url,"*_");
661 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
663 // attacklab: Markdown.pl adds empty title attributes to images.
664 // Replicate this bug.
667 title = title.replace(/"/g,""");
668 title = escapeCharacters(title,"*_");
669 result += " title=\"" + title + "\"";
678 var _DoHeaders = function(text) {
680 // Setext-style headers:
687 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
688 function(wholeMatch,m1){return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n";});
690 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
691 function(matchFound,m1){return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n";});
693 // atx-style headers:
696 // ## Header 2 with closing hashes ##
702 text = text.replace(/
703 ^(\#{1,6}) // $1 = string of #'s
705 (.+?) // $2 = Header text
707 \#* // optional closing #'s (not counted)
709 /gm, function() {...});
712 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
713 function(wholeMatch,m1,m2) {
714 var h_level = m1.length;
715 return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
721 // This declaration keeps Dojo compressor from outputting garbage:
722 var _ProcessListItems;
724 var _DoLists = function(text) {
726 // Form HTML ordered (numbered) and unordered (bulleted) lists.
729 // attacklab: add sentinel to hack around khtml/safari bug:
730 // http://bugs.webkit.org/show_bug.cgi?id=11231
733 // Re-usable pattern to match any entirel ul or ol list:
739 [ ]{0,3} // attacklab: g_tab_width - 1
740 ([*+-]|\d+[.]) // $3 = first list item marker
745 ~0 // sentinel for workaround; should be $
749 (?! // Negative lookahead for another list item marker
751 (?:[*+-]|\d+[.])[ \t]+
756 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
759 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
761 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
763 var result = _ProcessListItems(list, list_type);
765 // Trim any trailing whitespace, to put the closing `</$list_type>`
766 // up on the preceding line, to get it past the current stupid
767 // HTML block parser. This is a hack to work around the terrible
768 // hack that is the HTML block parser.
769 result = result.replace(/\s+$/,"");
770 result = "<"+list_type+">" + result + "</"+list_type+">\n";
774 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
775 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
779 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
780 var result = _ProcessListItems(list, list_type);
781 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
786 // attacklab: strip sentinel
787 text = text.replace(/~0/,"");
792 var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
794 _ProcessListItems = function(list_str, list_type) {
796 // Process the contents of a single ordered or unordered list, splitting it
797 // into individual list items.
799 // list_type is either "ul" or "ol".
801 // The $g_list_level global keeps track of when we're inside a list.
802 // Each time we enter a list, we increment it; when we leave a list,
803 // we decrement. If it's zero, we're not in a list anymore.
805 // We do this because when we're not inside a list, we want to treat
806 // something like this:
808 // I recommend upgrading to version
809 // 8. Oops, now this line is treated
812 // As a single paragraph, despite the fact that the second line starts
813 // with a digit-period-space sequence.
815 // Whereas when we're inside a list (or sub-list), that line will be
816 // treated as the start of a sub-list. What a kludge, huh? This is
817 // an aspect of Markdown's syntax that's hard to parse perfectly
818 // without resorting to mind-reading. Perhaps the solution is to
819 // change the syntax rules such that sub-lists must start with a
820 // starting cardinal number; e.g. "1." or "a.".
824 // trim trailing blank lines:
825 list_str = list_str.replace(/\n{2,}$/,"\n");
827 // attacklab: add sentinel to emulate \z
830 // In the original attacklab WMD, list_type was not given to this function, and anything
831 // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
833 // Markdown rendered by WMD rendered by MarkdownSharp
834 // ------------------------------------------------------------------
835 // 1. first 1. first 1. first
836 // 2. second 2. second 2. second
837 // - third 3. third * third
839 // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
840 // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
842 list_str = list_str.replace(/
843 (^[ \t]*) // leading whitespace = $1
844 ({MARKER}) [ \t]+ // list marker = $2
845 ([^\r]+? // list item text = $3
847 (?= (~0 | \2 ({MARKER}) [ \t]+))
848 /gm, function(){...});
851 var marker = _listItemMarkers[list_type];
852 var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
853 var last_item_had_a_double_newline = false;
854 list_str = list_str.replace(re,
855 function(wholeMatch,m1,m2,m3){
857 var leading_space = m1;
858 var ends_with_double_newline = /\n\n$/.test(item);
859 var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/)>-1;
861 if (contains_double_newline || last_item_had_a_double_newline) {
862 item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */ true);
865 // Recursion for sub-lists:
866 item = _DoLists(_Outdent(item));
867 item = item.replace(/\n$/,""); // chomp(item)
868 item = _RunSpanGamut(item);
870 last_item_had_a_double_newline = ends_with_double_newline;
871 return "<li>" + item + "</li>\n";
875 // attacklab: strip sentinel
876 list_str = list_str.replace(/~0/g,"");
883 var _DoCodeBlocks = function(text) {
885 // Process Markdown `<pre><code>` blocks.
889 text = text.replace(text,
891 ( // $1 = the code block -- one or more lines, starting with a space/tab
893 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
897 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
901 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
904 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
905 function(wholeMatch,m1,m2) {
909 codeblock = _EncodeCode( _Outdent(codeblock));
910 codeblock = _Detab(codeblock);
911 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
912 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
914 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
916 return "\n\n" + codeblock + "\n\n" + nextChar;
920 // attacklab: strip sentinel
921 text = text.replace(/~0/,"");
926 var hashBlock = function(text) {
927 text = text.replace(/(^\n+|\n+$)/g,"");
928 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
932 var _DoCodeSpans = function(text) {
934 // * Backtick quotes are used for <code></code> spans.
936 // * You can use multiple backticks as the delimiters if you want to
937 // include literal backticks in the code span. So, this input:
939 // Just type ``foo `bar` baz`` at the prompt.
941 // Will translate to:
943 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
945 // There's no arbitrary limit to the number of backticks you
946 // can use as delimters. If you need three consecutive backticks
947 // in your code, use four for delimiters, etc.
949 // * You can use spaces to get literal backticks at the edges:
951 // ... type `` `bar` `` ...
955 // ... type <code>`bar`</code> ...
959 text = text.replace(/
960 (^|[^\\]) // Character before opening ` can't be a backslash
961 (`+) // $2 = Opening run of `
962 ( // $3 = The code block
964 [^`] // attacklab: work around lack of lookbehind
966 \2 // Matching closer
968 /gm, function(){...});
971 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
972 function(wholeMatch,m1,m2,m3,m4) {
974 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
975 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
977 return m1+"<code>"+c+"</code>";
984 var _EncodeCode = function(text) {
986 // Encode/escape certain characters inside Markdown code runs.
987 // The point is that in code, these characters are literals,
988 // and lose their special Markdown meanings.
990 // Encode all ampersands; HTML entities are not
991 // entities within a Markdown code span.
992 text = text.replace(/&/g,"&");
994 // Do the angle bracket song and dance:
995 text = text.replace(/</g,"<");
996 text = text.replace(/>/g,">");
998 // Now, escape characters that are magic in Markdown:
999 text = escapeCharacters(text,"\*_{}[]\\",false);
1001 // jj the line above breaks this:
1015 var _DoItalicsAndBold = function(text) {
1017 // <strong> must go first:
1018 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g,
1019 "<strong>$2</strong>");
1021 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1028 var _DoBlockQuotes = function(text) {
1031 text = text.replace(/
1032 ( // Wrap whole match in $1
1034 ^[ \t]*>[ \t]? // '>' at the start of a line
1035 .+\n // rest of the first line
1036 (.+\n)* // subsequent consecutive lines
1040 /gm, function(){...});
1043 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1044 function(wholeMatch,m1) {
1047 // attacklab: hack around Konqueror 3.5.4 bug:
1048 // "----------bug".replace(/^-/g,"") == "bug"
1050 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1052 // attacklab: clean up hack
1053 bq = bq.replace(/~0/g,"");
1055 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1056 bq = _RunBlockGamut(bq); // recurse
1058 bq = bq.replace(/(^|\n)/g,"$1 ");
1059 // These leading spaces screw with <pre> content, so we need to fix that:
1061 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1062 function(wholeMatch,m1) {
1064 // attacklab: hack around Konqueror 3.5.4 bug:
1065 pre = pre.replace(/^ /mg,"~0");
1066 pre = pre.replace(/~0/g,"");
1070 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1076 var _FormParagraphs = function(text, doNotUnhash) {
1079 // $text - string to process with html <p> tags
1082 // Strip leading and trailing lines:
1083 text = text.replace(/^\n+/g,"");
1084 text = text.replace(/\n+$/g,"");
1086 var grafs = text.split(/\n{2,}/g);
1087 var grafsOut = new Array();
1092 var end = grafs.length;
1093 for (var i=0; i<end; i++) {
1096 // if this is an HTML marker, copy it
1097 if (str.search(/~K(\d+)K/g) >= 0) {
1100 else if (str.search(/\S/) >= 0) {
1101 str = _RunSpanGamut(str);
1102 str = str.replace(/^([ \t]*)/g,"<p>");
1109 // Unhashify HTML blocks
1112 end = grafsOut.length;
1113 for (var i=0; i<end; i++) {
1114 // if this is a marker for an html block...
1115 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1116 var blockText = g_html_blocks[RegExp.$1];
1117 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1118 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1122 return grafsOut.join("\n\n");
1126 var _EncodeAmpsAndAngles = function(text) {
1127 // Smart processing for ampersands and angle brackets that need to be encoded.
1129 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1130 // http://bumppo.net/projects/amputator/
1131 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1134 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1140 var _EncodeBackslashEscapes = function(text) {
1142 // Parameter: String.
1143 // Returns: The string, with after processing the following backslash
1144 // escape sequences.
1147 // attacklab: The polite way to do this is with the new
1148 // escapeCharacters() function:
1150 // text = escapeCharacters(text,"\\",true);
1151 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1153 // ...but we're sidestepping its use of the (slow) RegExp constructor
1154 // as an optimization for Firefox. This function gets called a LOT.
1156 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1157 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1162 var _DoAutoLinks = function(text) {
1164 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1166 // Email addresses: <address@domain.foo>
1169 text = text.replace(/
1175 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1178 /gi, _DoAutoLinks_callback());
1180 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1181 function(wholeMatch,m1) {
1182 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1190 var _EncodeEmailAddress = function(addr) {
1192 // Input: an email address, e.g. "foo@example.com"
1194 // Output: the email address as a mailto link, with each character
1195 // of the address encoded as either a decimal or hex entity, in
1196 // the hopes of foiling most address harvesting spam bots. E.g.:
1198 // <a href="mailto:foo@e
1199 // xample.com">foo
1200 // @example.com</a>
1202 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1203 // mailing list: <http://tinyurl.com/yu7ue>
1206 // attacklab: why can't javascript speak hex?
1207 function char2hex(ch) {
1208 var hexDigits = '0123456789ABCDEF';
1209 var dec = ch.charCodeAt(0);
1210 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1214 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1215 function(ch){return "&#x"+char2hex(ch)+";";},
1216 function(ch){return ch;}
1219 addr = "mailto:" + addr;
1221 addr = addr.replace(/./g, function(ch) {
1223 // this *must* be encoded. I insist.
1224 ch = encode[Math.floor(Math.random()*2)](ch);
1225 } else if (ch !=":") {
1226 // leave ':' alone (to spot mailto: later)
1227 var r = Math.random();
1228 // roughly 10% raw, 45% hex, 45% dec
1230 r > .9 ? encode[2](ch) :
1231 r > .45 ? encode[1](ch) :
1238 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1239 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1245 var _UnescapeSpecialChars = function(text) {
1247 // Swap back in all the special characters we've hidden.
1249 text = text.replace(/~E(\d+)E/g,
1250 function(wholeMatch,m1) {
1251 var charCodeToReplace = parseInt(m1);
1252 return String.fromCharCode(charCodeToReplace);
1259 var _Outdent = function(text) {
1261 // Remove one level of line-leading tabs or spaces
1264 // attacklab: hack around Konqueror 3.5.4 bug:
1265 // "----------bug".replace(/^-/g,"") == "bug"
1267 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1269 // attacklab: clean up hack
1270 text = text.replace(/~0/g,"")
1275 var _Detab = function (text) {
1276 if (!/\t/.test(text))
1279 var spaces = [" ", " ", " ", " "],
1283 return text.replace(/[\n\t]/g, function (match, offset) {
1284 if (match === "\n") {
1288 v = (offset - skew) % 4;
1295 // attacklab: Utility functions
1299 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1300 // First we have to escape the escape characters so that
1301 // we can build a character class out of them
1302 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1304 if (afterBackslash) {
1305 regexString = "\\\\" + regexString;
1308 var regex = new RegExp(regexString,"g");
1309 text = text.replace(regex,escapeCharacters_callback);
1315 var escapeCharacters_callback = function(wholeMatch,m1) {
1316 var charCodeToEscape = m1.charCodeAt(0);
1317 return "~E"+charCodeToEscape+"E";
1320 } // end of Attacklab.showdown.converter
1323 // Version 0.9 used the Showdown namespace instead of Attacklab.showdown
1324 // The old namespace is deprecated, but we'll support it for now:
1325 var Showdown = Attacklab.showdown;
1327 // If anyone's interested, tell the world that this file's been loaded
1328 if (Attacklab.fileLoaded) {
1329 Attacklab.fileLoaded("showdown.js");