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() {
83 // Global hashes, used by various utility routines
88 // Used to track when we're inside an ordered or unordered list
89 // (see _ProcessListItems() for details):
93 this.makeHtml = function(text) {
95 // Main function. The order in which other subs are called here is
96 // essential. Link and image substitutions need to happen before
97 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
98 // and <img> tags get encoded.
101 // Clear the global hashes. If we don't clear these, you get conflicts
102 // from other articles when generating a page which contains more than
103 // one article (e.g. an index page that shows the N most recent
105 g_urls = new Array();
106 g_titles = new Array();
107 g_html_blocks = new Array();
109 // attacklab: Replace ~ with ~T
110 // This lets us use tilde as an escape char to avoid md5 hashes
111 // The choice of character is arbitray; anything that isn't
112 // magic in Markdown will work.
113 text = text.replace(/~/g,"~T");
115 // attacklab: Replace $ with ~D
116 // RegExp interprets $ as a special character
117 // when it's in a replacement string
118 text = text.replace(/\$/g,"~D");
120 // Standardize line endings
121 text = text.replace(/\r\n/g,"\n"); // DOS to Unix
122 text = text.replace(/\r/g,"\n"); // Mac to Unix
124 // Make sure text begins and ends with a couple of newlines:
125 text = "\n\n" + text + "\n\n";
127 // Convert all tabs to spaces.
130 // Strip any lines consisting only of spaces and tabs.
131 // This makes subsequent regexen easier to write, because we can
132 // match consecutive blank lines with /\n+/ instead of something
133 // contorted like /[ \t]*\n+/ .
134 text = text.replace(/^[ \t]+$/mg,"");
136 // Turn block-level HTML blocks into hash entries
137 text = _HashHTMLBlocks(text);
139 // Strip link definitions, store in hashes.
140 text = _StripLinkDefinitions(text);
142 text = _RunBlockGamut(text);
144 text = _UnescapeSpecialChars(text);
146 // attacklab: Restore dollar signs
147 text = text.replace(/~D/g,"$$");
149 // attacklab: Restore tildes
150 text = text.replace(/~T/g,"~");
155 var _StripLinkDefinitions = function(text) {
157 // Strips link definitions from text, stores the URLs and titles in
161 // Link defs are in the form: ^[id]: url "optional title"
164 var text = text.replace(/
165 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
167 \n? // maybe *one* newline
169 <?(\S+?)>? // url = $2
171 \n? // maybe one newline
174 (\n*) // any lines skipped = $3 attacklab: lookbehind removed
179 )? // title is optional
184 var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
185 function (wholeMatch,m1,m2,m3,m4) {
186 m1 = m1.toLowerCase();
187 g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
189 // Oops, found blank lines, so it's not a title.
190 // Put back the parenthetical statement we stole.
193 g_titles[m1] = m4.replace(/"/g,""");
196 // Completely remove the definition from the text
204 var _HashHTMLBlocks = function(text) {
205 // attacklab: Double up blank lines to reduce lookaround
206 text = text.replace(/\n/g,"\n\n");
208 // Hashify HTML blocks:
209 // We only want to do this for block-level HTML tags, such as headers,
210 // lists, and tables. That's because we still want to wrap <p>s around
211 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
212 // phrase emphasis, and spans. The list of tags we're looking for is
214 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
215 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
217 // First, look for nested blocks, e.g.:
220 // tags for inner block must be indented.
224 // The outermost tags must start at the left margin for this to match, and
225 // the inner nested divs must be indented.
226 // We need to do this before the next, more liberal match, because the next
227 // match will start at the first `<div>` and stop at the first `</div>`.
229 // attacklab: This regex can be expensive when it fails.
231 var text = text.replace(/
233 ^ // start of line (with /m)
234 <($block_tags_a) // start tag = $2
236 // attacklab: hack around khtml/pcre bug...
237 [^\r]*?\n // any number of lines, minimally matching
238 </\2> // the matching end tag
239 [ \t]* // trailing spaces/tabs
240 (?=\n+) // followed by a newline
241 ) // attacklab: there are sentinel newlines at end of document
242 /gm,function(){...}};
244 text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
247 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
251 var text = text.replace(/
253 ^ // start of line (with /m)
254 <($block_tags_b) // start tag = $2
256 // attacklab: hack around khtml/pcre bug...
257 [^\r]*? // any number of lines, minimally matching
258 .*</\2> // the matching end tag
259 [ \t]* // trailing spaces/tabs
260 (?=\n+) // followed by a newline
261 ) // attacklab: there are sentinel newlines at end of document
262 /gm,function(){...}};
264 text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
266 // Special case just for <hr />. It was easier to make a special case than
267 // to make the other regex more complicated.
270 text = text.replace(/
272 \n\n // Starting after a blank line
274 (<(hr) // start tag = $2
277 \/?>) // the matching end tag
279 (?=\n{2,}) // followed by a blank line
283 text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
285 // Special case for standalone HTML comments:
288 text = text.replace(/
290 \n\n // Starting after a blank line
291 [ ]{0,3} // attacklab: g_tab_width - 1
296 (?=\n{2,}) // followed by a blank line
300 text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
302 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
305 text = text.replace(/
307 \n\n // Starting after a blank line
310 [ ]{0,3} // attacklab: g_tab_width - 1
317 (?=\n{2,}) // followed by a blank line
321 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
323 // attacklab: Undo double lines (see comment at top of this function)
324 text = text.replace(/\n\n/g,"\n");
328 var hashElement = function(wholeMatch,m1) {
332 blockText = blockText.replace(/\n\n/g,"\n");
333 blockText = blockText.replace(/^\n/,"");
335 // strip trailing blank lines
336 blockText = blockText.replace(/\n+$/g,"");
338 // Replace the element text with a marker ("~KxK" where x is its key)
339 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
344 var _RunBlockGamut = function(text) {
346 // These are all the transformations that form block-level
347 // tags like paragraphs, headers, and list items.
349 text = _DoHeaders(text);
351 // Do Horizontal Rules:
352 var key = hashBlock("<hr />");
353 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
354 text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key);
355 text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key);
357 text = _DoLists(text);
358 text = _DoCodeBlocks(text);
359 text = _DoBlockQuotes(text);
361 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
362 // was to escape raw HTML in the original Markdown source. This time,
363 // we're escaping the markup we've just created, so that we don't wrap
364 // <p> tags around block-level tags.
365 text = _HashHTMLBlocks(text);
366 text = _FormParagraphs(text);
372 var _RunSpanGamut = function(text) {
374 // These are all the transformations that occur *within* block-level
375 // tags like paragraphs, headers, and list items.
378 text = _DoCodeSpans(text);
379 text = _EscapeSpecialCharsWithinTagAttributes(text);
380 text = _EncodeBackslashEscapes(text);
382 // Process anchor and image tags. Images must come first,
383 // because ![foo][f] looks like an anchor.
384 text = _DoImages(text);
385 text = _DoAnchors(text);
387 // Make links out of things like `<http://example.com/>`
388 // Must come after _DoAnchors(), because you can use < and >
389 // delimiters in inline links like [this](<url>).
390 text = _DoAutoLinks(text);
391 text = _EncodeAmpsAndAngles(text);
392 text = _DoItalicsAndBold(text);
395 text = text.replace(/ +\n/g," <br />\n");
400 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
402 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
403 // don't conflict with their use in Markdown for code, italics and strong.
406 // Build a regex to find HTML tags and comments. See Friedl's
407 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
408 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
410 text = text.replace(regex, function(wholeMatch) {
411 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
412 tag = escapeCharacters(tag,"\\`*_");
419 var _DoAnchors = function(text) {
421 // Turn Markdown link shortcuts into XHTML <a> tags.
424 // First, handle reference-style links: [link text] [id]
428 text = text.replace(/
429 ( // wrap whole match in $1
433 \[[^\]]*\] // allow brackets nested one level
435 [^\[] // or anything else
440 [ ]? // one optional space
441 (?:\n[ ]*)? // one optional newline followed by spaces
446 )()()()() // pad remaining backreferences
447 /g,_DoAnchors_callback);
449 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
452 // Next, inline-style links: [link text](url "optional title")
456 text = text.replace(/
457 ( // wrap whole match in $1
461 \[[^\]]*\] // allow brackets nested one level
463 [^\[\]] // or anything else
469 () // no id, so leave $3 empty
470 <?(.*?)>? // href = $4
473 (['"]) // quote char = $6
476 [ \t]* // ignore any spaces/tabs between closing quote and )
477 )? // title is optional
482 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
485 // Last, handle reference-style shortcuts: [link text]
486 // These must come last in case you've also got [link test][1]
487 // or [link test](/foo)
491 text = text.replace(/
492 ( // wrap whole match in $1
494 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
496 )()()()()() // pad rest of backreferences
499 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
504 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
505 if (m7 == undefined) m7 = "";
506 var whole_match = m1;
508 var link_id = m3.toLowerCase();
514 // lower-case and turn embedded newlines into spaces
515 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
519 if (g_urls[link_id] != undefined) {
520 url = g_urls[link_id];
521 if (g_titles[link_id] != undefined) {
522 title = g_titles[link_id];
526 if (whole_match.search(/\(\s*\)$/m)>-1) {
527 // Special case for explicit empty url
535 url = escapeCharacters(url,"*_");
536 var result = "<a href=\"" + url + "\"";
539 title = title.replace(/"/g,""");
540 title = escapeCharacters(title,"*_");
541 result += " title=\"" + title + "\"";
544 result += ">" + link_text + "</a>";
550 var _DoImages = function(text) {
552 // Turn Markdown image shortcuts into <img> tags.
556 // First, handle reference-style labeled images: ![alt text][id]
560 text = text.replace(/
561 ( // wrap whole match in $1
563 (.*?) // alt text = $2
566 [ ]? // one optional space
567 (?:\n[ ]*)? // one optional newline followed by spaces
572 )()()()() // pad rest of backreferences
575 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
578 // Next, handle inline images: ![alt text](url "optional title")
579 // Don't forget: encode * and _
582 text = text.replace(/
583 ( // wrap whole match in $1
585 (.*?) // alt text = $2
587 \s? // One optional whitespace character
590 () // no id, so leave $3 empty
591 <?(\S+?)>? // src url = $4
594 (['"]) // quote char = $6
598 )? // title is optional
603 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
608 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
609 var whole_match = m1;
611 var link_id = m3.toLowerCase();
615 if (!title) title = "";
619 // lower-case and turn embedded newlines into spaces
620 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
624 if (g_urls[link_id] != undefined) {
625 url = g_urls[link_id];
626 if (g_titles[link_id] != undefined) {
627 title = g_titles[link_id];
635 alt_text = alt_text.replace(/"/g,""");
636 url = escapeCharacters(url,"*_");
637 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
639 // attacklab: Markdown.pl adds empty title attributes to images.
640 // Replicate this bug.
643 title = title.replace(/"/g,""");
644 title = escapeCharacters(title,"*_");
645 result += " title=\"" + title + "\"";
654 var _DoHeaders = function(text) {
656 // Setext-style headers:
663 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
664 function(wholeMatch,m1){return hashBlock("<h1>" + _RunSpanGamut(m1) + "</h1>");});
666 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
667 function(matchFound,m1){return hashBlock("<h2>" + _RunSpanGamut(m1) + "</h2>");});
669 // atx-style headers:
672 // ## Header 2 with closing hashes ##
678 text = text.replace(/
679 ^(\#{1,6}) // $1 = string of #'s
681 (.+?) // $2 = Header text
683 \#* // optional closing #'s (not counted)
685 /gm, function() {...});
688 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
689 function(wholeMatch,m1,m2) {
690 var h_level = m1.length;
691 return hashBlock("<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">");
697 // This declaration keeps Dojo compressor from outputting garbage:
698 var _ProcessListItems;
700 var _DoLists = function(text) {
702 // Form HTML ordered (numbered) and unordered (bulleted) lists.
705 // attacklab: add sentinel to hack around khtml/safari bug:
706 // http://bugs.webkit.org/show_bug.cgi?id=11231
709 // Re-usable pattern to match any entirel ul or ol list:
715 [ ]{0,3} // attacklab: g_tab_width - 1
716 ([*+-]|\d+[.]) // $3 = first list item marker
721 ~0 // sentinel for workaround; should be $
725 (?! // Negative lookahead for another list item marker
727 (?:[*+-]|\d+[.])[ \t]+
732 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
735 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
737 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
739 // Turn double returns into triple returns, so that we can make a
740 // paragraph for the last item in a list, if necessary:
741 list = list.replace(/\n{2,}/g,"\n\n\n");;
742 var result = _ProcessListItems(list);
744 // Trim any trailing whitespace, to put the closing `</$list_type>`
745 // up on the preceding line, to get it past the current stupid
746 // HTML block parser. This is a hack to work around the terrible
747 // hack that is the HTML block parser.
748 result = result.replace(/\s+$/,"");
749 result = "<"+list_type+">" + result + "</"+list_type+">\n";
753 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
754 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
758 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
759 // Turn double returns into triple returns, so that we can make a
760 // paragraph for the last item in a list, if necessary:
761 var list = list.replace(/\n{2,}/g,"\n\n\n");;
762 var result = _ProcessListItems(list);
763 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
768 // attacklab: strip sentinel
769 text = text.replace(/~0/,"");
774 _ProcessListItems = function(list_str) {
776 // Process the contents of a single ordered or unordered list, splitting it
777 // into individual list items.
779 // The $g_list_level global keeps track of when we're inside a list.
780 // Each time we enter a list, we increment it; when we leave a list,
781 // we decrement. If it's zero, we're not in a list anymore.
783 // We do this because when we're not inside a list, we want to treat
784 // something like this:
786 // I recommend upgrading to version
787 // 8. Oops, now this line is treated
790 // As a single paragraph, despite the fact that the second line starts
791 // with a digit-period-space sequence.
793 // Whereas when we're inside a list (or sub-list), that line will be
794 // treated as the start of a sub-list. What a kludge, huh? This is
795 // an aspect of Markdown's syntax that's hard to parse perfectly
796 // without resorting to mind-reading. Perhaps the solution is to
797 // change the syntax rules such that sub-lists must start with a
798 // starting cardinal number; e.g. "1." or "a.".
802 // trim trailing blank lines:
803 list_str = list_str.replace(/\n{2,}$/,"\n");
805 // attacklab: add sentinel to emulate \z
809 list_str = list_str.replace(/
810 (\n)? // leading line = $1
811 (^[ \t]*) // leading whitespace = $2
812 ([*+-]|\d+[.]) [ \t]+ // list marker = $3
813 ([^\r]+? // list item text = $4
815 (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
816 /gm, function(){...});
818 list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
819 function(wholeMatch,m1,m2,m3,m4){
821 var leading_line = m1;
822 var leading_space = m2;
824 if (leading_line || (item.search(/\n{2,}/)>-1)) {
825 item = _RunBlockGamut(_Outdent(item));
828 // Recursion for sub-lists:
829 item = _DoLists(_Outdent(item));
830 item = item.replace(/\n$/,""); // chomp(item)
831 item = _RunSpanGamut(item);
834 return "<li>" + item + "</li>\n";
838 // attacklab: strip sentinel
839 list_str = list_str.replace(/~0/g,"");
846 var _DoCodeBlocks = function(text) {
848 // Process Markdown `<pre><code>` blocks.
852 text = text.replace(text,
854 ( // $1 = the code block -- one or more lines, starting with a space/tab
856 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
860 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
864 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
867 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
868 function(wholeMatch,m1,m2) {
872 codeblock = _EncodeCode( _Outdent(codeblock));
873 codeblock = _Detab(codeblock);
874 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
875 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
877 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
879 return hashBlock(codeblock) + nextChar;
883 // attacklab: strip sentinel
884 text = text.replace(/~0/,"");
889 var hashBlock = function(text) {
890 text = text.replace(/(^\n+|\n+$)/g,"");
891 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
895 var _DoCodeSpans = function(text) {
897 // * Backtick quotes are used for <code></code> spans.
899 // * You can use multiple backticks as the delimiters if you want to
900 // include literal backticks in the code span. So, this input:
902 // Just type ``foo `bar` baz`` at the prompt.
904 // Will translate to:
906 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
908 // There's no arbitrary limit to the number of backticks you
909 // can use as delimters. If you need three consecutive backticks
910 // in your code, use four for delimiters, etc.
912 // * You can use spaces to get literal backticks at the edges:
914 // ... type `` `bar` `` ...
918 // ... type <code>`bar`</code> ...
922 text = text.replace(/
923 (^|[^\\]) // Character before opening ` can't be a backslash
924 (`+) // $2 = Opening run of `
925 ( // $3 = The code block
927 [^`] // attacklab: work around lack of lookbehind
929 \2 // Matching closer
931 /gm, function(){...});
934 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
935 function(wholeMatch,m1,m2,m3,m4) {
937 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
938 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
940 return m1+"<code>"+c+"</code>";
947 var _EncodeCode = function(text) {
949 // Encode/escape certain characters inside Markdown code runs.
950 // The point is that in code, these characters are literals,
951 // and lose their special Markdown meanings.
953 // Encode all ampersands; HTML entities are not
954 // entities within a Markdown code span.
955 text = text.replace(/&/g,"&");
957 // Do the angle bracket song and dance:
958 text = text.replace(/</g,"<");
959 text = text.replace(/>/g,">");
961 // Now, escape characters that are magic in Markdown:
962 text = escapeCharacters(text,"\*_{}[]\\",false);
964 // jj the line above breaks this:
978 var _DoItalicsAndBold = function(text) {
980 // <strong> must go first:
981 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g,
982 "<strong>$2</strong>");
984 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
991 var _DoBlockQuotes = function(text) {
994 text = text.replace(/
995 ( // Wrap whole match in $1
997 ^[ \t]*>[ \t]? // '>' at the start of a line
998 .+\n // rest of the first line
999 (.+\n)* // subsequent consecutive lines
1003 /gm, function(){...});
1006 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1007 function(wholeMatch,m1) {
1010 // attacklab: hack around Konqueror 3.5.4 bug:
1011 // "----------bug".replace(/^-/g,"") == "bug"
1013 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1015 // attacklab: clean up hack
1016 bq = bq.replace(/~0/g,"");
1018 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1019 bq = _RunBlockGamut(bq); // recurse
1021 bq = bq.replace(/(^|\n)/g,"$1 ");
1022 // These leading spaces screw with <pre> content, so we need to fix that:
1024 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1025 function(wholeMatch,m1) {
1027 // attacklab: hack around Konqueror 3.5.4 bug:
1028 pre = pre.replace(/^ /mg,"~0");
1029 pre = pre.replace(/~0/g,"");
1033 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1039 var _FormParagraphs = function(text) {
1042 // $text - string to process with html <p> tags
1045 // Strip leading and trailing lines:
1046 text = text.replace(/^\n+/g,"");
1047 text = text.replace(/\n+$/g,"");
1049 var grafs = text.split(/\n{2,}/g);
1050 var grafsOut = new Array();
1055 var end = grafs.length;
1056 for (var i=0; i<end; i++) {
1059 // if this is an HTML marker, copy it
1060 if (str.search(/~K(\d+)K/g) >= 0) {
1063 else if (str.search(/\S/) >= 0) {
1064 str = _RunSpanGamut(str);
1065 str = str.replace(/^([ \t]*)/g,"<p>");
1073 // Unhashify HTML blocks
1075 end = grafsOut.length;
1076 for (var i=0; i<end; i++) {
1077 // if this is a marker for an html block...
1078 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1079 var blockText = g_html_blocks[RegExp.$1];
1080 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1081 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1085 return grafsOut.join("\n\n");
1089 var _EncodeAmpsAndAngles = function(text) {
1090 // Smart processing for ampersands and angle brackets that need to be encoded.
1092 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1093 // http://bumppo.net/projects/amputator/
1094 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1097 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1103 var _EncodeBackslashEscapes = function(text) {
1105 // Parameter: String.
1106 // Returns: The string, with after processing the following backslash
1107 // escape sequences.
1110 // attacklab: The polite way to do this is with the new
1111 // escapeCharacters() function:
1113 // text = escapeCharacters(text,"\\",true);
1114 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1116 // ...but we're sidestepping its use of the (slow) RegExp constructor
1117 // as an optimization for Firefox. This function gets called a LOT.
1119 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1120 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1125 var _DoAutoLinks = function(text) {
1127 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1129 // Email addresses: <address@domain.foo>
1132 text = text.replace(/
1138 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1141 /gi, _DoAutoLinks_callback());
1143 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1144 function(wholeMatch,m1) {
1145 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1153 var _EncodeEmailAddress = function(addr) {
1155 // Input: an email address, e.g. "foo@example.com"
1157 // Output: the email address as a mailto link, with each character
1158 // of the address encoded as either a decimal or hex entity, in
1159 // the hopes of foiling most address harvesting spam bots. E.g.:
1161 // <a href="mailto:foo@e
1162 // xample.com">foo
1163 // @example.com</a>
1165 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1166 // mailing list: <http://tinyurl.com/yu7ue>
1169 // attacklab: why can't javascript speak hex?
1170 function char2hex(ch) {
1171 var hexDigits = '0123456789ABCDEF';
1172 var dec = ch.charCodeAt(0);
1173 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1177 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1178 function(ch){return "&#x"+char2hex(ch)+";";},
1179 function(ch){return ch;}
1182 addr = "mailto:" + addr;
1184 addr = addr.replace(/./g, function(ch) {
1186 // this *must* be encoded. I insist.
1187 ch = encode[Math.floor(Math.random()*2)](ch);
1188 } else if (ch !=":") {
1189 // leave ':' alone (to spot mailto: later)
1190 var r = Math.random();
1191 // roughly 10% raw, 45% hex, 45% dec
1193 r > .9 ? encode[2](ch) :
1194 r > .45 ? encode[1](ch) :
1201 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1202 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1208 var _UnescapeSpecialChars = function(text) {
1210 // Swap back in all the special characters we've hidden.
1212 text = text.replace(/~E(\d+)E/g,
1213 function(wholeMatch,m1) {
1214 var charCodeToReplace = parseInt(m1);
1215 return String.fromCharCode(charCodeToReplace);
1222 var _Outdent = function(text) {
1224 // Remove one level of line-leading tabs or spaces
1227 // attacklab: hack around Konqueror 3.5.4 bug:
1228 // "----------bug".replace(/^-/g,"") == "bug"
1230 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1232 // attacklab: clean up hack
1233 text = text.replace(/~0/g,"")
1238 var _Detab = function(text) {
1239 // attacklab: Detab's completely rewritten for speed.
1240 // In perl we could fix it by anchoring the regexp with \G.
1241 // In javascript we're less fortunate.
1243 // expand first n-1 tabs
1244 text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
1246 // replace the nth with two sentinels
1247 text = text.replace(/\t/g,"~A~B");
1249 // use the sentinel to anchor our regex so it doesn't explode
1250 text = text.replace(/~B(.+?)~A/g,
1251 function(wholeMatch,m1,m2) {
1252 var leadingText = m1;
1253 var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
1255 // there *must* be a better way to do this:
1256 for (var i=0; i<numSpaces; i++) leadingText+=" ";
1262 // clean up sentinels
1263 text = text.replace(/~A/g," "); // attacklab: g_tab_width
1264 text = text.replace(/~B/g,"");
1271 // attacklab: Utility functions
1275 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1276 // First we have to escape the escape characters so that
1277 // we can build a character class out of them
1278 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1280 if (afterBackslash) {
1281 regexString = "\\\\" + regexString;
1284 var regex = new RegExp(regexString,"g");
1285 text = text.replace(regex,escapeCharacters_callback);
1291 var escapeCharacters_callback = function(wholeMatch,m1) {
1292 var charCodeToEscape = m1.charCodeAt(0);
1293 return "~E"+charCodeToEscape+"E";
1296 } // end of Attacklab.showdown.converter
1299 // Version 0.9 used the Showdown namespace instead of Attacklab.showdown
1300 // The old namespace is deprecated, but we'll support it for now:
1301 var Showdown = Attacklab.showdown;
1303 // If anyone's interested, tell the world that this file's been loaded
1304 if (Attacklab.fileLoaded) {
1305 Attacklab.fileLoaded("showdown.js");