3 if (typeof exports === "object" && typeof require === "function") // we're in a CommonJS (e.g. Node.js) module
\r
8 // The following text is included for historical reasons, but should
\r
9 // be taken with a pinch of salt; it's not all true anymore.
\r
12 // Wherever possible, Showdown is a straight, line-by-line port
\r
13 // of the Perl version of Markdown.
\r
15 // This is not a normal parser design; it's basically just a
\r
16 // series of string substitutions. It's hard to read and
\r
17 // maintain this way, but keeping Showdown close to the original
\r
18 // design makes it easier to port new features.
\r
20 // More importantly, Showdown behaves like markdown.pl in most
\r
21 // edge cases. So web applications can do client-side preview
\r
22 // in Javascript, and then build identical HTML on the server.
\r
24 // This port needs the new RegExp functionality of ECMA 262,
\r
25 // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
\r
26 // should do fine. Even with the new regular expression features,
\r
27 // We do a lot of work to emulate Perl's regex functionality.
\r
28 // The tricky changes in this file mostly have the "attacklab:"
\r
29 // label. Major or self-explanatory changes don't.
\r
31 // Smart diff tools like Araxis Merge will be able to match up
\r
32 // this file with markdown.pl in a useful way. A little tweaking
\r
33 // helps: in a copy of markdown.pl, replace "#" with "//" and
\r
34 // replace "$text" with "text". Be sure to ignore whitespace
\r
35 // and line endings.
\r
42 // var text = "Markdown *rocks*.";
\r
44 // var converter = new Markdown.Converter();
\r
45 // var html = converter.makeHtml(text);
\r
49 // Note: move the sample code to the bottom of this
\r
50 // file before uncommenting it.
\r
55 function identity(x) { return x; }
\r
56 function returnFalse(x) { return false; }
\r
58 function HookCollection() { }
\r
60 HookCollection.prototype = {
\r
62 chain: function (hookname, func) {
\r
63 var original = this[hookname];
\r
65 throw new Error("unknown hook " + hookname);
\r
67 if (original === identity)
\r
68 this[hookname] = func;
\r
70 this[hookname] = function (x) { return func(original(x)); }
\r
72 set: function (hookname, func) {
\r
73 if (!this[hookname])
\r
74 throw new Error("unknown hook " + hookname);
\r
75 this[hookname] = func;
\r
77 addNoop: function (hookname) {
\r
78 this[hookname] = identity;
\r
80 addFalse: function (hookname) {
\r
81 this[hookname] = returnFalse;
\r
85 Markdown.HookCollection = HookCollection;
\r
87 // g_urls and g_titles allow arbitrary user-entered strings as keys. This
\r
88 // caused an exception (and hence stopped the rendering) when the user entered
\r
89 // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this
\r
90 // (since no builtin property starts with "s_"). See
\r
91 // http://meta.stackoverflow.com/questions/64655/strange-wmd-bug
\r
92 // (granted, switching from Array() to Object() alone would have left only __proto__
\r
94 function SaveHash() { }
\r
95 SaveHash.prototype = {
\r
96 set: function (key, value) {
\r
97 this["s_" + key] = value;
\r
99 get: function (key) {
\r
100 return this["s_" + key];
\r
104 Markdown.Converter = function () {
\r
105 var pluginHooks = this.hooks = new HookCollection();
\r
106 pluginHooks.addNoop("plainLinkText"); // given a URL that was encountered by itself (without markup), should return the link text that's to be given to this link
\r
107 pluginHooks.addNoop("preConversion"); // called with the orignal text as given to makeHtml. The result of this plugin hook is the actual markdown source that will be cooked
\r
108 pluginHooks.addNoop("postConversion"); // called with the final cooked HTML code. The result of this plugin hook is the actual output of makeHtml
\r
111 // Private state of the converter instance:
\r
114 // Global hashes, used by various utility routines
\r
119 // Used to track when we're inside an ordered or unordered list
\r
120 // (see _ProcessListItems() for details):
\r
123 this.makeHtml = function (text) {
\r
126 // Main function. The order in which other subs are called here is
\r
127 // essential. Link and image substitutions need to happen before
\r
128 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
\r
129 // and <img> tags get encoded.
\r
132 // This will only happen if makeHtml on the same converter instance is called from a plugin hook.
\r
135 throw new Error("Recursive call to converter.makeHtml");
\r
137 // Create the private state objects.
\r
138 g_urls = new SaveHash();
\r
139 g_titles = new SaveHash();
\r
140 g_html_blocks = [];
\r
143 text = pluginHooks.preConversion(text);
\r
145 // attacklab: Replace ~ with ~T
\r
146 // This lets us use tilde as an escape char to avoid md5 hashes
\r
147 // The choice of character is arbitray; anything that isn't
\r
148 // magic in Markdown will work.
\r
149 text = text.replace(/~/g, "~T");
\r
151 // attacklab: Replace $ with ~D
\r
152 // RegExp interprets $ as a special character
\r
153 // when it's in a replacement string
\r
154 text = text.replace(/\$/g, "~D");
\r
156 // Standardize line endings
\r
157 text = text.replace(/\r\n/g, "\n"); // DOS to Unix
\r
158 text = text.replace(/\r/g, "\n"); // Mac to Unix
\r
160 // Make sure text begins and ends with a couple of newlines:
\r
161 text = "\n\n" + text + "\n\n";
\r
163 // Convert all tabs to spaces.
\r
164 text = _Detab(text);
\r
166 // Strip any lines consisting only of spaces and tabs.
\r
167 // This makes subsequent regexen easier to write, because we can
\r
168 // match consecutive blank lines with /\n+/ instead of something
\r
169 // contorted like /[ \t]*\n+/ .
\r
170 text = text.replace(/^[ \t]+$/mg, "");
\r
172 // Turn block-level HTML blocks into hash entries
\r
173 text = _HashHTMLBlocks(text);
\r
175 // Strip link definitions, store in hashes.
\r
176 text = _StripLinkDefinitions(text);
\r
178 text = _RunBlockGamut(text);
\r
180 text = _UnescapeSpecialChars(text);
\r
182 // attacklab: Restore dollar signs
\r
183 text = text.replace(/~D/g, "$$");
\r
185 // attacklab: Restore tildes
\r
186 text = text.replace(/~T/g, "~");
\r
188 text = pluginHooks.postConversion(text);
\r
190 g_html_blocks = g_titles = g_urls = null;
\r
195 function _StripLinkDefinitions(text) {
\r
197 // Strips link definitions from text, stores the URLs and titles in
\r
198 // hash references.
\r
201 // Link defs are in the form: ^[id]: url "optional title"
\r
204 text = text.replace(/
\r
205 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
\r
207 \n? // maybe *one* newline
\r
209 <?(\S+?)>? // url = $2
\r
210 (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
\r
212 \n? // maybe one newline
\r
214 ( // (potential) title = $3
\r
215 (\n*) // any lines skipped = $4 attacklab: lookbehind removed
\r
218 (.+?) // title = $5
\r
221 )? // title is optional
\r
223 /gm, function(){...});
\r
226 text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
\r
227 function (wholeMatch, m1, m2, m3, m4, m5) {
\r
228 m1 = m1.toLowerCase();
\r
229 g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
\r
231 // Oops, found blank lines, so it's not a title.
\r
232 // Put back the parenthetical statement we stole.
\r
235 g_titles.set(m1, m5.replace(/"/g, """));
\r
238 // Completely remove the definition from the text
\r
246 function _HashHTMLBlocks(text) {
\r
248 // Hashify HTML blocks:
\r
249 // We only want to do this for block-level HTML tags, such as headers,
\r
250 // lists, and tables. That's because we still want to wrap <p>s around
\r
251 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
\r
252 // phrase emphasis, and spans. The list of tags we're looking for is
\r
254 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
\r
255 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
\r
257 // First, look for nested blocks, e.g.:
\r
260 // tags for inner block must be indented.
\r
264 // The outermost tags must start at the left margin for this to match, and
\r
265 // the inner nested divs must be indented.
\r
266 // We need to do this before the next, more liberal match, because the next
\r
267 // match will start at the first `<div>` and stop at the first `</div>`.
\r
269 // attacklab: This regex can be expensive when it fails.
\r
272 text = text.replace(/
\r
274 ^ // start of line (with /m)
\r
275 <($block_tags_a) // start tag = $2
\r
277 // attacklab: hack around khtml/pcre bug...
\r
278 [^\r]*?\n // any number of lines, minimally matching
\r
279 </\2> // the matching end tag
\r
280 [ \t]* // trailing spaces/tabs
\r
281 (?=\n+) // followed by a newline
\r
282 ) // attacklab: there are sentinel newlines at end of document
\r
283 /gm,function(){...}};
\r
285 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);
\r
288 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
\r
292 text = text.replace(/
\r
294 ^ // start of line (with /m)
\r
295 <($block_tags_b) // start tag = $2
\r
297 // attacklab: hack around khtml/pcre bug...
\r
298 [^\r]*? // any number of lines, minimally matching
\r
299 .*</\2> // the matching end tag
\r
300 [ \t]* // trailing spaces/tabs
\r
301 (?=\n+) // followed by a newline
\r
302 ) // attacklab: there are sentinel newlines at end of document
\r
303 /gm,function(){...}};
\r
305 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);
\r
307 // Special case just for <hr />. It was easier to make a special case than
\r
308 // to make the other regex more complicated.
\r
311 text = text.replace(/
\r
312 \n // Starting after a blank line
\r
315 (<(hr) // start tag = $2
\r
318 \/?>) // the matching end tag
\r
320 (?=\n{2,}) // followed by a blank line
\r
324 text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashElement);
\r
326 // Special case for standalone HTML comments:
\r
329 text = text.replace(/
\r
330 \n\n // Starting after a blank line
\r
331 [ ]{0,3} // attacklab: g_tab_width - 1
\r
334 (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments and http://meta.stackoverflow.com/q/95256
\r
337 (?=\n{2,}) // followed by a blank line
\r
341 text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
\r
343 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
\r
346 text = text.replace(/
\r
348 \n\n // Starting after a blank line
\r
351 [ ]{0,3} // attacklab: g_tab_width - 1
\r
358 (?=\n{2,}) // followed by a blank line
\r
362 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashElement);
\r
367 function hashElement(wholeMatch, m1) {
\r
368 var blockText = m1;
\r
370 // Undo double lines
\r
371 blockText = blockText.replace(/^\n+/, "");
\r
373 // strip trailing blank lines
\r
374 blockText = blockText.replace(/\n+$/g, "");
\r
376 // Replace the element text with a marker ("~KxK" where x is its key)
\r
377 blockText = "\n\n~K" + (g_html_blocks.push(blockText) - 1) + "K\n\n";
\r
382 function _RunBlockGamut(text, doNotUnhash) {
\r
384 // These are all the transformations that form block-level
\r
385 // tags like paragraphs, headers, and list items.
\r
387 text = _DoHeaders(text);
\r
389 // Do Horizontal Rules:
\r
390 var replacement = "<hr />\n";
\r
391 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, replacement);
\r
392 text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, replacement);
\r
393 text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, replacement);
\r
395 text = _DoLists(text);
\r
396 text = _DoCodeBlocks(text);
\r
397 text = _DoBlockQuotes(text);
\r
399 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
\r
400 // was to escape raw HTML in the original Markdown source. This time,
\r
401 // we're escaping the markup we've just created, so that we don't wrap
\r
402 // <p> tags around block-level tags.
\r
403 text = _HashHTMLBlocks(text);
\r
404 text = _FormParagraphs(text, doNotUnhash);
\r
409 function _RunSpanGamut(text) {
\r
411 // These are all the transformations that occur *within* block-level
\r
412 // tags like paragraphs, headers, and list items.
\r
415 text = _DoCodeSpans(text);
\r
416 text = _EscapeSpecialCharsWithinTagAttributes(text);
\r
417 text = _EncodeBackslashEscapes(text);
\r
419 // Process anchor and image tags. Images must come first,
\r
420 // because ![foo][f] looks like an anchor.
\r
421 text = _DoImages(text);
\r
422 text = _DoAnchors(text);
\r
424 // Make links out of things like `<http://example.com/>`
\r
425 // Must come after _DoAnchors(), because you can use < and >
\r
426 // delimiters in inline links like [this](<url>).
\r
427 text = _DoAutoLinks(text);
\r
428 text = _EncodeAmpsAndAngles(text);
\r
429 text = _DoItalicsAndBold(text);
\r
432 text = text.replace(/ +\n/g, " <br>\n");
\r
437 function _EscapeSpecialCharsWithinTagAttributes(text) {
\r
439 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
\r
440 // don't conflict with their use in Markdown for code, italics and strong.
\r
443 // Build a regex to find HTML tags and comments. See Friedl's
\r
444 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
\r
446 // SE: changed the comment part of the regex
\r
448 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
\r
450 text = text.replace(regex, function (wholeMatch) {
\r
451 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`");
\r
452 tag = escapeCharacters(tag, wholeMatch.charAt(1) == "!" ? "\\`*_/" : "\\`*_"); // also escape slashes in comments to prevent autolinking there -- http://meta.stackoverflow.com/questions/95987
\r
459 function _DoAnchors(text) {
\r
461 // Turn Markdown link shortcuts into XHTML <a> tags.
\r
464 // First, handle reference-style links: [link text] [id]
\r
468 text = text.replace(/
\r
469 ( // wrap whole match in $1
\r
473 \[[^\]]*\] // allow brackets nested one level
\r
475 [^\[] // or anything else
\r
480 [ ]? // one optional space
\r
481 (?:\n[ ]*)? // one optional newline followed by spaces
\r
487 ()()()() // pad remaining backreferences
\r
488 /g, writeAnchorTag);
\r
490 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
\r
493 // Next, inline-style links: [link text](url "optional title")
\r
497 text = text.replace(/
\r
498 ( // wrap whole match in $1
\r
502 \[[^\]]*\] // allow brackets nested one level
\r
504 [^\[\]] // or anything else
\r
508 \( // literal paren
\r
510 () // no id, so leave $3 empty
\r
513 \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
\r
520 (['"]) // quote char = $6
\r
521 (.*?) // Title = $7
\r
522 \6 // matching quote
\r
523 [ \t]* // ignore any spaces/tabs between closing quote and )
\r
524 )? // title is optional
\r
527 /g, writeAnchorTag);
\r
530 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag);
\r
533 // Last, handle reference-style shortcuts: [link text]
\r
534 // These must come last in case you've also got [link test][1]
\r
535 // or [link test](/foo)
\r
539 text = text.replace(/
\r
540 ( // wrap whole match in $1
\r
542 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
\r
545 ()()()()() // pad rest of backreferences
\r
546 /g, writeAnchorTag);
\r
548 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
\r
553 function writeAnchorTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
\r
554 if (m7 == undefined) m7 = "";
\r
555 var whole_match = m1;
\r
556 var link_text = m2;
\r
557 var link_id = m3.toLowerCase();
\r
562 if (link_id == "") {
\r
563 // lower-case and turn embedded newlines into spaces
\r
564 link_id = link_text.toLowerCase().replace(/ ?\n/g, " ");
\r
566 url = "#" + link_id;
\r
568 if (g_urls.get(link_id) != undefined) {
\r
569 url = g_urls.get(link_id);
\r
570 if (g_titles.get(link_id) != undefined) {
\r
571 title = g_titles.get(link_id);
\r
575 if (whole_match.search(/\(\s*\)$/m) > -1) {
\r
576 // Special case for explicit empty url
\r
579 return whole_match;
\r
583 url = encodeProblemUrlChars(url);
\r
584 url = escapeCharacters(url, "*_");
\r
585 var result = "<a href=\"" + url + "\"";
\r
588 title = title.replace(/"/g, """);
\r
589 title = escapeCharacters(title, "*_");
\r
590 result += " title=\"" + title + "\"";
\r
593 result += ">" + link_text + "</a>";
\r
598 function _DoImages(text) {
\r
600 // Turn Markdown image shortcuts into <img> tags.
\r
604 // First, handle reference-style labeled images: ![alt text][id]
\r
608 text = text.replace(/
\r
609 ( // wrap whole match in $1
\r
611 (.*?) // alt text = $2
\r
614 [ ]? // one optional space
\r
615 (?:\n[ ]*)? // one optional newline followed by spaces
\r
621 ()()()() // pad rest of backreferences
\r
622 /g, writeImageTag);
\r
624 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
\r
627 // Next, handle inline images: ![alt text](url "optional title")
\r
628 // Don't forget: encode * and _
\r
631 text = text.replace(/
\r
632 ( // wrap whole match in $1
\r
634 (.*?) // alt text = $2
\r
636 \s? // One optional whitespace character
\r
637 \( // literal paren
\r
639 () // no id, so leave $3 empty
\r
640 <?(\S+?)>? // src url = $4
\r
643 (['"]) // quote char = $6
\r
644 (.*?) // title = $7
\r
645 \6 // matching quote
\r
647 )? // title is optional
\r
650 /g, writeImageTag);
\r
652 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag);
\r
657 function writeImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
\r
658 var whole_match = m1;
\r
660 var link_id = m3.toLowerCase();
\r
664 if (!title) title = "";
\r
667 if (link_id == "") {
\r
668 // lower-case and turn embedded newlines into spaces
\r
669 link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
\r
671 url = "#" + link_id;
\r
673 if (g_urls.get(link_id) != undefined) {
\r
674 url = g_urls.get(link_id);
\r
675 if (g_titles.get(link_id) != undefined) {
\r
676 title = g_titles.get(link_id);
\r
680 return whole_match;
\r
684 alt_text = alt_text.replace(/"/g, """);
\r
685 url = escapeCharacters(url, "*_");
\r
686 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
\r
688 // attacklab: Markdown.pl adds empty title attributes to images.
\r
689 // Replicate this bug.
\r
691 //if (title != "") {
\r
692 title = title.replace(/"/g, """);
\r
693 title = escapeCharacters(title, "*_");
\r
694 result += " title=\"" + title + "\"";
\r
702 function _DoHeaders(text) {
\r
704 // Setext-style headers:
\r
711 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
\r
712 function (wholeMatch, m1) { return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n"; }
\r
715 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
\r
716 function (matchFound, m1) { return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n"; }
\r
719 // atx-style headers:
\r
722 // ## Header 2 with closing hashes ##
\r
728 text = text.replace(/
\r
729 ^(\#{1,6}) // $1 = string of #'s
\r
731 (.+?) // $2 = Header text
\r
733 \#* // optional closing #'s (not counted)
\r
735 /gm, function() {...});
\r
738 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
\r
739 function (wholeMatch, m1, m2) {
\r
740 var h_level = m1.length;
\r
741 return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
\r
748 function _DoLists(text) {
\r
750 // Form HTML ordered (numbered) and unordered (bulleted) lists.
\r
753 // attacklab: add sentinel to hack around khtml/safari bug:
\r
754 // http://bugs.webkit.org/show_bug.cgi?id=11231
\r
757 // Re-usable pattern to match any entirel ul or ol list:
\r
761 ( // $1 = whole list
\r
763 [ ]{0,3} // attacklab: g_tab_width - 1
\r
764 ([*+-]|\d+[.]) // $3 = first list item marker
\r
769 ~0 // sentinel for workaround; should be $
\r
773 (?! // Negative lookahead for another list item marker
\r
775 (?:[*+-]|\d+[.])[ \t]+
\r
781 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
\r
783 if (g_list_level) {
\r
784 text = text.replace(whole_list, function (wholeMatch, m1, m2) {
\r
786 var list_type = (m2.search(/[*+-]/g) > -1) ? "ul" : "ol";
\r
788 var result = _ProcessListItems(list, list_type);
\r
790 // Trim any trailing whitespace, to put the closing `</$list_type>`
\r
791 // up on the preceding line, to get it past the current stupid
\r
792 // HTML block parser. This is a hack to work around the terrible
\r
793 // hack that is the HTML block parser.
\r
794 result = result.replace(/\s+$/, "");
\r
795 result = "<" + list_type + ">" + result + "</" + list_type + ">\n";
\r
799 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
\r
800 text = text.replace(whole_list, function (wholeMatch, m1, m2, m3) {
\r
804 var list_type = (m3.search(/[*+-]/g) > -1) ? "ul" : "ol";
\r
805 var result = _ProcessListItems(list, list_type);
\r
806 result = runup + "<" + list_type + ">\n" + result + "</" + list_type + ">\n";
\r
811 // attacklab: strip sentinel
\r
812 text = text.replace(/~0/, "");
\r
817 var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
\r
819 function _ProcessListItems(list_str, list_type) {
\r
821 // Process the contents of a single ordered or unordered list, splitting it
\r
822 // into individual list items.
\r
824 // list_type is either "ul" or "ol".
\r
826 // The $g_list_level global keeps track of when we're inside a list.
\r
827 // Each time we enter a list, we increment it; when we leave a list,
\r
828 // we decrement. If it's zero, we're not in a list anymore.
\r
830 // We do this because when we're not inside a list, we want to treat
\r
831 // something like this:
\r
833 // I recommend upgrading to version
\r
834 // 8. Oops, now this line is treated
\r
837 // As a single paragraph, despite the fact that the second line starts
\r
838 // with a digit-period-space sequence.
\r
840 // Whereas when we're inside a list (or sub-list), that line will be
\r
841 // treated as the start of a sub-list. What a kludge, huh? This is
\r
842 // an aspect of Markdown's syntax that's hard to parse perfectly
\r
843 // without resorting to mind-reading. Perhaps the solution is to
\r
844 // change the syntax rules such that sub-lists must start with a
\r
845 // starting cardinal number; e.g. "1." or "a.".
\r
849 // trim trailing blank lines:
\r
850 list_str = list_str.replace(/\n{2,}$/, "\n");
\r
852 // attacklab: add sentinel to emulate \z
\r
855 // In the original attacklab showdown, list_type was not given to this function, and anything
\r
856 // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
\r
858 // Markdown rendered by WMD rendered by MarkdownSharp
\r
859 // ------------------------------------------------------------------
\r
860 // 1. first 1. first 1. first
\r
861 // 2. second 2. second 2. second
\r
862 // - third 3. third * third
\r
864 // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
\r
865 // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
\r
868 list_str = list_str.replace(/
\r
869 (^[ \t]*) // leading whitespace = $1
\r
870 ({MARKER}) [ \t]+ // list marker = $2
\r
871 ([^\r]+? // list item text = $3
\r
875 (~0 | \2 ({MARKER}) [ \t]+)
\r
877 /gm, function(){...});
\r
880 var marker = _listItemMarkers[list_type];
\r
881 var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
\r
882 var last_item_had_a_double_newline = false;
\r
883 list_str = list_str.replace(re,
\r
884 function (wholeMatch, m1, m2, m3) {
\r
886 var leading_space = m1;
\r
887 var ends_with_double_newline = /\n\n$/.test(item);
\r
888 var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/) > -1;
\r
890 if (contains_double_newline || last_item_had_a_double_newline) {
\r
891 item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */true);
\r
894 // Recursion for sub-lists:
\r
895 item = _DoLists(_Outdent(item));
\r
896 item = item.replace(/\n$/, ""); // chomp(item)
\r
897 item = _RunSpanGamut(item);
\r
899 last_item_had_a_double_newline = ends_with_double_newline;
\r
900 return "<li>" + item + "</li>\n";
\r
904 // attacklab: strip sentinel
\r
905 list_str = list_str.replace(/~0/g, "");
\r
911 function _DoCodeBlocks(text) {
\r
913 // Process Markdown `<pre><code>` blocks.
\r
917 text = text.replace(/
\r
919 ( // $1 = the code block -- one or more lines, starting with a space/tab
\r
921 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
\r
925 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
\r
926 /g ,function(){...});
\r
929 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
\r
932 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
\r
933 function (wholeMatch, m1, m2) {
\r
934 var codeblock = m1;
\r
937 codeblock = _EncodeCode(_Outdent(codeblock));
\r
938 codeblock = _Detab(codeblock);
\r
939 codeblock = codeblock.replace(/^\n+/g, ""); // trim leading newlines
\r
940 codeblock = codeblock.replace(/\n+$/g, ""); // trim trailing whitespace
\r
942 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
\r
944 return "\n\n" + codeblock + "\n\n" + nextChar;
\r
948 // attacklab: strip sentinel
\r
949 text = text.replace(/~0/, "");
\r
954 function hashBlock(text) {
\r
955 text = text.replace(/(^\n+|\n+$)/g, "");
\r
956 return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n";
\r
959 function _DoCodeSpans(text) {
\r
961 // * Backtick quotes are used for <code></code> spans.
\r
963 // * You can use multiple backticks as the delimiters if you want to
\r
964 // include literal backticks in the code span. So, this input:
\r
966 // Just type ``foo `bar` baz`` at the prompt.
\r
968 // Will translate to:
\r
970 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
\r
972 // There's no arbitrary limit to the number of backticks you
\r
973 // can use as delimters. If you need three consecutive backticks
\r
974 // in your code, use four for delimiters, etc.
\r
976 // * You can use spaces to get literal backticks at the edges:
\r
978 // ... type `` `bar` `` ...
\r
982 // ... type <code>`bar`</code> ...
\r
986 text = text.replace(/
\r
987 (^|[^\\]) // Character before opening ` can't be a backslash
\r
988 (`+) // $2 = Opening run of `
\r
989 ( // $3 = The code block
\r
991 [^`] // attacklab: work around lack of lookbehind
\r
993 \2 // Matching closer
\r
995 /gm, function(){...});
\r
998 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
\r
999 function (wholeMatch, m1, m2, m3, m4) {
\r
1001 c = c.replace(/^([ \t]*)/g, ""); // leading whitespace
\r
1002 c = c.replace(/[ \t]*$/g, ""); // trailing whitespace
\r
1003 c = _EncodeCode(c);
\r
1004 return m1 + "<code>" + c + "</code>";
\r
1011 function _EncodeCode(text) {
\r
1013 // Encode/escape certain characters inside Markdown code runs.
\r
1014 // The point is that in code, these characters are literals,
\r
1015 // and lose their special Markdown meanings.
\r
1017 // Encode all ampersands; HTML entities are not
\r
1018 // entities within a Markdown code span.
\r
1019 text = text.replace(/&/g, "&");
\r
1021 // Do the angle bracket song and dance:
\r
1022 text = text.replace(/</g, "<");
\r
1023 text = text.replace(/>/g, ">");
\r
1025 // Now, escape characters that are magic in Markdown:
\r
1026 text = escapeCharacters(text, "\*_{}[]\\", false);
\r
1028 // jj the line above breaks this:
\r
1035 // special char: *
\r
1041 function _DoItalicsAndBold(text) {
\r
1043 // <strong> must go first:
\r
1044 text = text.replace(/([\W_]|^)(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\2([\W_]|$)/g,
\r
1045 "$1<strong>$3</strong>$4");
\r
1047 text = text.replace(/([\W_]|^)(\*|_)(?=\S)([^\r\*_]*?\S)\2([\W_]|$)/g,
\r
1048 "$1<em>$3</em>$4");
\r
1053 function _DoBlockQuotes(text) {
\r
1056 text = text.replace(/
\r
1057 ( // Wrap whole match in $1
\r
1059 ^[ \t]*>[ \t]? // '>' at the start of a line
\r
1060 .+\n // rest of the first line
\r
1061 (.+\n)* // subsequent consecutive lines
\r
1065 /gm, function(){...});
\r
1068 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
\r
1069 function (wholeMatch, m1) {
\r
1072 // attacklab: hack around Konqueror 3.5.4 bug:
\r
1073 // "----------bug".replace(/^-/g,"") == "bug"
\r
1075 bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting
\r
1077 // attacklab: clean up hack
\r
1078 bq = bq.replace(/~0/g, "");
\r
1080 bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines
\r
1081 bq = _RunBlockGamut(bq); // recurse
\r
1083 bq = bq.replace(/(^|\n)/g, "$1 ");
\r
1084 // These leading spaces screw with <pre> content, so we need to fix that:
\r
1086 /(\s*<pre>[^\r]+?<\/pre>)/gm,
\r
1087 function (wholeMatch, m1) {
\r
1089 // attacklab: hack around Konqueror 3.5.4 bug:
\r
1090 pre = pre.replace(/^ /mg, "~0");
\r
1091 pre = pre.replace(/~0/g, "");
\r
1095 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
\r
1101 function _FormParagraphs(text, doNotUnhash) {
\r
1104 // $text - string to process with html <p> tags
\r
1107 // Strip leading and trailing lines:
\r
1108 text = text.replace(/^\n+/g, "");
\r
1109 text = text.replace(/\n+$/g, "");
\r
1111 var grafs = text.split(/\n{2,}/g);
\r
1112 var grafsOut = [];
\r
1117 var end = grafs.length;
\r
1118 for (var i = 0; i < end; i++) {
\r
1119 var str = grafs[i];
\r
1121 // if this is an HTML marker, copy it
\r
1122 if (str.search(/~K(\d+)K/g) >= 0) {
\r
1123 grafsOut.push(str);
\r
1125 else if (str.search(/\S/) >= 0) {
\r
1126 str = _RunSpanGamut(str);
\r
1127 str = str.replace(/^([ \t]*)/g, "<p>");
\r
1129 grafsOut.push(str);
\r
1134 // Unhashify HTML blocks
\r
1136 if (!doNotUnhash) {
\r
1137 end = grafsOut.length;
\r
1138 for (var i = 0; i < end; i++) {
\r
1139 // if this is a marker for an html block...
\r
1140 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
\r
1141 var blockText = g_html_blocks[RegExp.$1];
\r
1142 blockText = blockText.replace(/\$/g, "$$$$"); // Escape any dollar signs
\r
1143 grafsOut[i] = grafsOut[i].replace(/~K\d+K/, blockText);
\r
1147 return grafsOut.join("\n\n");
\r
1150 function _EncodeAmpsAndAngles(text) {
\r
1151 // Smart processing for ampersands and angle brackets that need to be encoded.
\r
1153 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
\r
1154 // http://bumppo.net/projects/amputator/
\r
1155 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&");
\r
1157 // Encode naked <'s
\r
1158 text = text.replace(/<(?![a-z\/?\$!])/gi, "<");
\r
1163 function _EncodeBackslashEscapes(text) {
\r
1165 // Parameter: String.
\r
1166 // Returns: The string, with after processing the following backslash
\r
1167 // escape sequences.
\r
1170 // attacklab: The polite way to do this is with the new
\r
1171 // escapeCharacters() function:
\r
1173 // text = escapeCharacters(text,"\\",true);
\r
1174 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
\r
1176 // ...but we're sidestepping its use of the (slow) RegExp constructor
\r
1177 // as an optimization for Firefox. This function gets called a LOT.
\r
1179 text = text.replace(/\\(\\)/g, escapeCharacters_callback);
\r
1180 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, escapeCharacters_callback);
\r
1184 function _DoAutoLinks(text) {
\r
1186 // note that at this point, all other URL in the text are already hyperlinked as <a href=""></a>
\r
1187 // *except* for the <http://www.foo.com> case
\r
1189 // automatically add < and > around unadorned raw hyperlinks
\r
1190 // must be preceded by space/BOF and followed by non-word/EOF character
\r
1191 text = text.replace(/(^|\s)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)/gi, "$1<$2$3>$4");
\r
1193 // autolink anything like <http://example.com>
\r
1195 var replacer = function (wholematch, m1) { return "<a href=\"" + m1 + "\">" + pluginHooks.plainLinkText(m1) + "</a>"; }
\r
1196 text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, replacer);
\r
1198 // Email addresses: <address@domain.foo>
\r
1200 text = text.replace(/
\r
1206 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
\r
1209 /gi, _DoAutoLinks_callback());
\r
1212 /* disabling email autolinking, since we don't do that on the server, either
\r
1213 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
\r
1214 function(wholeMatch,m1) {
\r
1215 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
\r
1222 function _UnescapeSpecialChars(text) {
\r
1224 // Swap back in all the special characters we've hidden.
\r
1226 text = text.replace(/~E(\d+)E/g,
\r
1227 function (wholeMatch, m1) {
\r
1228 var charCodeToReplace = parseInt(m1);
\r
1229 return String.fromCharCode(charCodeToReplace);
\r
1235 function _Outdent(text) {
\r
1237 // Remove one level of line-leading tabs or spaces
\r
1240 // attacklab: hack around Konqueror 3.5.4 bug:
\r
1241 // "----------bug".replace(/^-/g,"") == "bug"
\r
1243 text = text.replace(/^(\t|[ ]{1,4})/gm, "~0"); // attacklab: g_tab_width
\r
1245 // attacklab: clean up hack
\r
1246 text = text.replace(/~0/g, "")
\r
1251 function _Detab(text) {
\r
1252 if (!/\t/.test(text))
\r
1255 var spaces = [" ", " ", " ", " "],
\r
1259 return text.replace(/[\n\t]/g, function (match, offset) {
\r
1260 if (match === "\n") {
\r
1261 skew = offset + 1;
\r
1264 v = (offset - skew) % 4;
\r
1265 skew = offset + 1;
\r
1271 // attacklab: Utility functions
\r
1274 var _problemUrlChars = /(?:["'*()[\]:]|~D)/g;
\r
1276 // hex-encodes some unusual "problem" chars in URLs to avoid URL detection problems
\r
1277 function encodeProblemUrlChars(url) {
\r
1281 var len = url.length;
\r
1283 return url.replace(_problemUrlChars, function (match, offset) {
\r
1284 if (match == "~D") // escape for dollar
\r
1286 if (match == ":") {
\r
1287 if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1)))
\r
1290 return "%" + match.charCodeAt(0).toString(16);
\r
1295 function escapeCharacters(text, charsToEscape, afterBackslash) {
\r
1296 // First we have to escape the escape characters so that
\r
1297 // we can build a character class out of them
\r
1298 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])";
\r
1300 if (afterBackslash) {
\r
1301 regexString = "\\\\" + regexString;
\r
1304 var regex = new RegExp(regexString, "g");
\r
1305 text = text.replace(regex, escapeCharacters_callback);
\r
1311 function escapeCharacters_callback(wholeMatch, m1) {
\r
1312 var charCodeToEscape = m1.charCodeAt(0);
\r
1313 return "~E" + charCodeToEscape + "E";
\r
1316 }; // end of the Markdown.Converter constructor
\r