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 // Redistributable under a BSD-style open source license.
10 // See license.txt for more information.
12 // The full source distribution is at:
18 // <http://www.attacklab.net/>
22 // Wherever possible, Showdown is a straight, line-by-line port
23 // of the Perl version of Markdown.
25 // This is not a normal parser design; it's basically just a
26 // series of string substitutions. It's hard to read and
27 // maintain this way, but keeping Showdown close to the original
28 // design makes it easier to port new features.
30 // More importantly, Showdown behaves like markdown.pl in most
31 // edge cases. So web applications can do client-side preview
32 // in Javascript, and then build identical HTML on the server.
34 // This port needs the new RegExp functionality of ECMA 262,
35 // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
36 // should do fine. Even with the new regular expression features,
37 // We do a lot of work to emulate Perl's regex functionality.
38 // The tricky changes in this file mostly have the "attacklab:"
39 // label. Major or self-explanatory changes don't.
41 // Smart diff tools like Araxis Merge will be able to match up
42 // this file with markdown.pl in a useful way. A little tweaking
43 // helps: in a copy of markdown.pl, replace "#" with "//" and
44 // replace "$text" with "text". Be sure to ignore whitespace
52 // var text = "Markdown *rocks*.";
54 // var markdown = require("markdown");
55 // var html = markdown.encode(text);
59 // Note: move the sample code to the bottom of this
60 // file before uncommenting it.
68 // Global hashes, used by various utility routines
73 // Used to track when we're inside an ordered or unordered list
74 // (see _ProcessListItems() for details):
78 exports.makeHtml = function(text) {
80 // Main function. The order in which other subs are called here is
81 // essential. Link and image substitutions need to happen before
82 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
83 // and <img> tags get encoded.
86 // Clear the global hashes. If we don't clear these, you get conflicts
87 // from other articles when generating a page which contains more than
88 // one article (e.g. an index page that shows the N most recent
91 g_titles = new Array();
92 g_html_blocks = new Array();
94 // attacklab: Replace ~ with ~T
95 // This lets us use tilde as an escape char to avoid md5 hashes
96 // The choice of character is arbitray; anything that isn't
97 // magic in Markdown will work.
98 text = text.replace(/~/g,"~T");
100 // attacklab: Replace $ with ~D
101 // RegExp interprets $ as a special character
102 // when it's in a replacement string
103 text = text.replace(/\$/g,"~D");
105 // Standardize line endings
106 text = text.replace(/\r\n/g,"\n"); // DOS to Unix
107 text = text.replace(/\r/g,"\n"); // Mac to Unix
109 // Make sure text begins and ends with a couple of newlines:
110 text = "\n\n" + text + "\n\n";
112 // Convert all tabs to spaces.
115 // Strip any lines consisting only of spaces and tabs.
116 // This makes subsequent regexen easier to write, because we can
117 // match consecutive blank lines with /\n+/ instead of something
118 // contorted like /[ \t]*\n+/ .
119 text = text.replace(/^[ \t]+$/mg,"");
121 // Turn block-level HTML blocks into hash entries
122 text = _HashHTMLBlocks(text);
124 // Strip link definitions, store in hashes.
125 text = _StripLinkDefinitions(text);
127 text = _RunBlockGamut(text);
129 text = _UnescapeSpecialChars(text);
131 // attacklab: Restore dollar signs
132 text = text.replace(/~D/g,"$$");
134 // attacklab: Restore tildes
135 text = text.replace(/~T/g,"~");
140 var _StripLinkDefinitions = function(text) {
142 // Strips link definitions from text, stores the URLs and titles in
146 // Link defs are in the form: ^[id]: url "optional title"
149 var text = text.replace(/
150 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
152 \n? // maybe *one* newline
154 <?(\S+?)>? // url = $2
156 \n? // maybe one newline
159 (\n*) // any lines skipped = $3 attacklab: lookbehind removed
164 )? // title is optional
169 var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
170 function (wholeMatch,m1,m2,m3,m4) {
171 m1 = m1.toLowerCase();
172 g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
174 // Oops, found blank lines, so it's not a title.
175 // Put back the parenthetical statement we stole.
178 g_titles[m1] = m4.replace(/"/g,""");
181 // Completely remove the definition from the text
190 var _HashHTMLBlocks = function(text) {
191 // attacklab: Double up blank lines to reduce lookaround
192 text = text.replace(/\n/g,"\n\n");
194 // Hashify HTML blocks:
195 // We only want to do this for block-level HTML tags, such as headers,
196 // lists, and tables. That's because we still want to wrap <p>s around
197 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
198 // phrase emphasis, and spans. The list of tags we're looking for is
200 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
201 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
203 // First, look for nested blocks, e.g.:
206 // tags for inner block must be indented.
210 // The outermost tags must start at the left margin for this to match, and
211 // the inner nested divs must be indented.
212 // We need to do this before the next, more liberal match, because the next
213 // match will start at the first `<div>` and stop at the first `</div>`.
215 // attacklab: This regex can be expensive when it fails.
217 var text = text.replace(/
219 ^ // start of line (with /m)
220 <($block_tags_a) // start tag = $2
222 // attacklab: hack around khtml/pcre bug...
223 [^\r]*?\n // any number of lines, minimally matching
224 </\2> // the matching end tag
225 [ \t]* // trailing spaces/tabs
226 (?=\n+) // followed by a newline
227 ) // attacklab: there are sentinel newlines at end of document
228 /gm,function(){...}};
230 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);
233 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
237 var text = text.replace(/
239 ^ // start of line (with /m)
240 <($block_tags_b) // start tag = $2
242 // attacklab: hack around khtml/pcre bug...
243 [^\r]*? // any number of lines, minimally matching
244 .*</\2> // the matching end tag
245 [ \t]* // trailing spaces/tabs
246 (?=\n+) // followed by a newline
247 ) // attacklab: there are sentinel newlines at end of document
248 /gm,function(){...}};
250 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);
252 // Special case just for <hr />. It was easier to make a special case than
253 // to make the other regex more complicated.
256 text = text.replace(/
258 \n\n // Starting after a blank line
260 (<(hr) // start tag = $2
263 \/?>) // the matching end tag
265 (?=\n{2,}) // followed by a blank line
269 text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
271 // Special case for standalone HTML comments:
274 text = text.replace(/
276 \n\n // Starting after a blank line
277 [ ]{0,3} // attacklab: g_tab_width - 1
282 (?=\n{2,}) // followed by a blank line
286 text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
288 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
291 text = text.replace(/
293 \n\n // Starting after a blank line
296 [ ]{0,3} // attacklab: g_tab_width - 1
303 (?=\n{2,}) // followed by a blank line
307 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
309 // attacklab: Undo double lines (see comment at top of this function)
310 text = text.replace(/\n\n/g,"\n");
314 var hashElement = function(wholeMatch,m1) {
318 blockText = blockText.replace(/\n\n/g,"\n");
319 blockText = blockText.replace(/^\n/,"");
321 // strip trailing blank lines
322 blockText = blockText.replace(/\n+$/g,"");
324 // Replace the element text with a marker ("~KxK" where x is its key)
325 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
330 var _RunBlockGamut = function(text) {
332 // These are all the transformations that form block-level
333 // tags like paragraphs, headers, and list items.
335 text = _DoHeaders(text);
337 // Do Horizontal Rules:
338 var key = hashBlock("<hr />");
339 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
340 text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
341 text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
343 text = _DoLists(text);
344 text = _DoCodeBlocks(text);
345 text = _DoBlockQuotes(text);
347 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
348 // was to escape raw HTML in the original Markdown source. This time,
349 // we're escaping the markup we've just created, so that we don't wrap
350 // <p> tags around block-level tags.
351 text = _HashHTMLBlocks(text);
352 text = _FormParagraphs(text);
358 var _RunSpanGamut = function(text) {
360 // These are all the transformations that occur *within* block-level
361 // tags like paragraphs, headers, and list items.
364 text = _DoCodeSpans(text);
365 text = _EscapeSpecialCharsWithinTagAttributes(text);
366 text = _EncodeBackslashEscapes(text);
368 // Process anchor and image tags. Images must come first,
369 // because ![foo][f] looks like an anchor.
370 text = _DoImages(text);
371 text = _DoAnchors(text);
373 // Make links out of things like `<http://example.com/>`
374 // Must come after _DoAnchors(), because you can use < and >
375 // delimiters in inline links like [this](<url>).
376 text = _DoAutoLinks(text);
377 text = _EncodeAmpsAndAngles(text);
378 text = _DoItalicsAndBold(text);
381 text = text.replace(/ +\n/g," <br />\n");
386 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
388 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
389 // don't conflict with their use in Markdown for code, italics and strong.
392 // Build a regex to find HTML tags and comments. See Friedl's
393 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
394 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
396 text = text.replace(regex, function(wholeMatch) {
397 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
398 tag = escapeCharacters(tag,"\\`*_");
405 var _DoAnchors = function(text) {
407 // Turn Markdown link shortcuts into XHTML <a> tags.
410 // First, handle reference-style links: [link text] [id]
414 text = text.replace(/
415 ( // wrap whole match in $1
419 \[[^\]]*\] // allow brackets nested one level
421 [^\[] // or anything else
426 [ ]? // one optional space
427 (?:\n[ ]*)? // one optional newline followed by spaces
432 )()()()() // pad remaining backreferences
433 /g,_DoAnchors_callback);
435 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
438 // Next, inline-style links: [link text](url "optional title")
442 text = text.replace(/
443 ( // wrap whole match in $1
447 \[[^\]]*\] // allow brackets nested one level
449 [^\[\]] // or anything else
455 () // no id, so leave $3 empty
456 <?(.*?)>? // href = $4
459 (['"]) // quote char = $6
462 [ \t]* // ignore any spaces/tabs between closing quote and )
463 )? // title is optional
468 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
471 // Last, handle reference-style shortcuts: [link text]
472 // These must come last in case you've also got [link test][1]
473 // or [link test](/foo)
477 text = text.replace(/
478 ( // wrap whole match in $1
480 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
482 )()()()()() // pad rest of backreferences
485 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
490 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
491 if (m7 == undefined) m7 = "";
492 var whole_match = m1;
494 var link_id = m3.toLowerCase();
500 // lower-case and turn embedded newlines into spaces
501 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
505 if (g_urls[link_id] != undefined) {
506 url = g_urls[link_id];
507 if (g_titles[link_id] != undefined) {
508 title = g_titles[link_id];
512 if (whole_match.search(/\(\s*\)$/m)>-1) {
513 // Special case for explicit empty url
521 url = escapeCharacters(url,"*_");
522 var result = "<a href=\"" + url + "\"";
525 title = title.replace(/"/g,""");
526 title = escapeCharacters(title,"*_");
527 result += " title=\"" + title + "\"";
530 result += ">" + link_text + "</a>";
536 var _DoImages = function(text) {
538 // Turn Markdown image shortcuts into <img> tags.
542 // First, handle reference-style labeled images: ![alt text][id]
546 text = text.replace(/
547 ( // wrap whole match in $1
549 (.*?) // alt text = $2
552 [ ]? // one optional space
553 (?:\n[ ]*)? // one optional newline followed by spaces
558 )()()()() // pad rest of backreferences
561 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
564 // Next, handle inline images: ![alt text](url "optional title")
565 // Don't forget: encode * and _
568 text = text.replace(/
569 ( // wrap whole match in $1
571 (.*?) // alt text = $2
573 \s? // One optional whitespace character
576 () // no id, so leave $3 empty
577 <?(\S+?)>? // src url = $4
580 (['"]) // quote char = $6
584 )? // title is optional
589 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
594 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
595 var whole_match = m1;
597 var link_id = m3.toLowerCase();
601 if (!title) title = "";
605 // lower-case and turn embedded newlines into spaces
606 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
610 if (g_urls[link_id] != undefined) {
611 url = g_urls[link_id];
612 if (g_titles[link_id] != undefined) {
613 title = g_titles[link_id];
621 alt_text = alt_text.replace(/"/g,""");
622 url = escapeCharacters(url,"*_");
623 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
625 // attacklab: Markdown.pl adds empty title attributes to images.
626 // Replicate this bug.
629 title = title.replace(/"/g,""");
630 title = escapeCharacters(title,"*_");
631 result += " title=\"" + title + "\"";
640 var _DoHeaders = function(text) {
642 // Setext-style headers:
649 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
650 function(wholeMatch,m1){return hashBlock("<h1>" + _RunSpanGamut(m1) + "</h1>");});
652 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
653 function(matchFound,m1){return hashBlock("<h2>" + _RunSpanGamut(m1) + "</h2>");});
655 // atx-style headers:
658 // ## Header 2 with closing hashes ##
664 text = text.replace(/
665 ^(\#{1,6}) // $1 = string of #'s
667 (.+?) // $2 = Header text
669 \#* // optional closing #'s (not counted)
671 /gm, function() {...});
674 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
675 function(wholeMatch,m1,m2) {
676 var h_level = m1.length;
677 return hashBlock("<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">");
683 // This declaration keeps Dojo compressor from outputting garbage:
684 var _ProcessListItems;
686 var _DoLists = function(text) {
688 // Form HTML ordered (numbered) and unordered (bulleted) lists.
691 // attacklab: add sentinel to hack around khtml/safari bug:
692 // http://bugs.webkit.org/show_bug.cgi?id=11231
695 // Re-usable pattern to match any entirel ul or ol list:
701 [ ]{0,3} // attacklab: g_tab_width - 1
702 ([*+-]|\d+[.]) // $3 = first list item marker
707 ~0 // sentinel for workaround; should be $
711 (?! // Negative lookahead for another list item marker
713 (?:[*+-]|\d+[.])[ \t]+
718 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
721 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
723 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
725 // Turn double returns into triple returns, so that we can make a
726 // paragraph for the last item in a list, if necessary:
727 list = list.replace(/\n{2,}/g,"\n\n\n");;
728 var result = _ProcessListItems(list);
730 // Trim any trailing whitespace, to put the closing `</$list_type>`
731 // up on the preceding line, to get it past the current stupid
732 // HTML block parser. This is a hack to work around the terrible
733 // hack that is the HTML block parser.
734 result = result.replace(/\s+$/,"");
735 result = "<"+list_type+">" + result + "</"+list_type+">\n";
739 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
740 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
744 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
745 // Turn double returns into triple returns, so that we can make a
746 // paragraph for the last item in a list, if necessary:
747 var list = list.replace(/\n{2,}/g,"\n\n\n");;
748 var result = _ProcessListItems(list);
749 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
754 // attacklab: strip sentinel
755 text = text.replace(/~0/,"");
760 _ProcessListItems = function(list_str) {
762 // Process the contents of a single ordered or unordered list, splitting it
763 // into individual list items.
765 // The $g_list_level global keeps track of when we're inside a list.
766 // Each time we enter a list, we increment it; when we leave a list,
767 // we decrement. If it's zero, we're not in a list anymore.
769 // We do this because when we're not inside a list, we want to treat
770 // something like this:
772 // I recommend upgrading to version
773 // 8. Oops, now this line is treated
776 // As a single paragraph, despite the fact that the second line starts
777 // with a digit-period-space sequence.
779 // Whereas when we're inside a list (or sub-list), that line will be
780 // treated as the start of a sub-list. What a kludge, huh? This is
781 // an aspect of Markdown's syntax that's hard to parse perfectly
782 // without resorting to mind-reading. Perhaps the solution is to
783 // change the syntax rules such that sub-lists must start with a
784 // starting cardinal number; e.g. "1." or "a.".
788 // trim trailing blank lines:
789 list_str = list_str.replace(/\n{2,}$/,"\n");
791 // attacklab: add sentinel to emulate \z
795 list_str = list_str.replace(/
796 (\n)? // leading line = $1
797 (^[ \t]*) // leading whitespace = $2
798 ([*+-]|\d+[.]) [ \t]+ // list marker = $3
799 ([^\r]+? // list item text = $4
801 (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
802 /gm, function(){...});
804 list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
805 function(wholeMatch,m1,m2,m3,m4){
807 var leading_line = m1;
808 var leading_space = m2;
810 if (leading_line || (item.search(/\n{2,}/)>-1)) {
811 item = _RunBlockGamut(_Outdent(item));
814 // Recursion for sub-lists:
815 item = _DoLists(_Outdent(item));
816 item = item.replace(/\n$/,""); // chomp(item)
817 item = _RunSpanGamut(item);
820 return "<li>" + item + "</li>\n";
824 // attacklab: strip sentinel
825 list_str = list_str.replace(/~0/g,"");
832 var _DoCodeBlocks = function(text) {
834 // Process Markdown `<pre><code>` blocks.
838 text = text.replace(text,
840 ( // $1 = the code block -- one or more lines, starting with a space/tab
842 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
846 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
850 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
853 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
854 function(wholeMatch,m1,m2) {
858 codeblock = _EncodeCode( _Outdent(codeblock));
859 codeblock = _Detab(codeblock);
860 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
861 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
863 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
865 return hashBlock(codeblock) + nextChar;
869 // attacklab: strip sentinel
870 text = text.replace(/~0/,"");
875 var hashBlock = function(text) {
876 text = text.replace(/(^\n+|\n+$)/g,"");
877 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
881 var _DoCodeSpans = function(text) {
883 // * Backtick quotes are used for <code></code> spans.
885 // * You can use multiple backticks as the delimiters if you want to
886 // include literal backticks in the code span. So, this input:
888 // Just type ``foo `bar` baz`` at the prompt.
890 // Will translate to:
892 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
894 // There's no arbitrary limit to the number of backticks you
895 // can use as delimters. If you need three consecutive backticks
896 // in your code, use four for delimiters, etc.
898 // * You can use spaces to get literal backticks at the edges:
900 // ... type `` `bar` `` ...
904 // ... type <code>`bar`</code> ...
908 text = text.replace(/
909 (^|[^\\]) // Character before opening ` can't be a backslash
910 (`+) // $2 = Opening run of `
911 ( // $3 = The code block
913 [^`] // attacklab: work around lack of lookbehind
915 \2 // Matching closer
917 /gm, function(){...});
920 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
921 function(wholeMatch,m1,m2,m3,m4) {
923 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
924 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
926 return m1+"<code>"+c+"</code>";
933 var _EncodeCode = function(text) {
935 // Encode/escape certain characters inside Markdown code runs.
936 // The point is that in code, these characters are literals,
937 // and lose their special Markdown meanings.
939 // Encode all ampersands; HTML entities are not
940 // entities within a Markdown code span.
941 text = text.replace(/&/g,"&");
943 // Do the angle bracket song and dance:
944 text = text.replace(/</g,"<");
945 text = text.replace(/>/g,">");
947 // Now, escape characters that are magic in Markdown:
948 text = escapeCharacters(text,"\*_{}[]\\",false);
950 // jj the line above breaks this:
964 var _DoItalicsAndBold = function(text) {
966 // <strong> must go first:
967 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
968 "<strong>$2</strong>");
970 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
977 var _DoBlockQuotes = function(text) {
980 text = text.replace(/
981 ( // Wrap whole match in $1
983 ^[ \t]*>[ \t]? // '>' at the start of a line
984 .+\n // rest of the first line
985 (.+\n)* // subsequent consecutive lines
989 /gm, function(){...});
992 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
993 function(wholeMatch,m1) {
996 // attacklab: hack around Konqueror 3.5.4 bug:
997 // "----------bug".replace(/^-/g,"") == "bug"
999 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1001 // attacklab: clean up hack
1002 bq = bq.replace(/~0/g,"");
1004 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1005 bq = _RunBlockGamut(bq); // recurse
1007 bq = bq.replace(/(^|\n)/g,"$1 ");
1008 // These leading spaces screw with <pre> content, so we need to fix that:
1010 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1011 function(wholeMatch,m1) {
1013 // attacklab: hack around Konqueror 3.5.4 bug:
1014 pre = pre.replace(/^ /mg,"~0");
1015 pre = pre.replace(/~0/g,"");
1019 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1025 var _FormParagraphs = function(text) {
1028 // $text - string to process with html <p> tags
1031 // Strip leading and trailing lines:
1032 text = text.replace(/^\n+/g,"");
1033 text = text.replace(/\n+$/g,"");
1035 var grafs = text.split(/\n{2,}/g);
1036 var grafsOut = new Array();
1041 var end = grafs.length;
1042 for (var i=0; i<end; i++) {
1045 // if this is an HTML marker, copy it
1046 if (str.search(/~K(\d+)K/g) >= 0) {
1049 else if (str.search(/\S/) >= 0) {
1050 str = _RunSpanGamut(str);
1051 str = str.replace(/^([ \t]*)/g,"<p>");
1059 // Unhashify HTML blocks
1061 end = grafsOut.length;
1062 for (var i=0; i<end; i++) {
1063 // if this is a marker for an html block...
1064 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1065 var blockText = g_html_blocks[RegExp.$1];
1066 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1067 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1071 return grafsOut.join("\n\n");
1075 var _EncodeAmpsAndAngles = function(text) {
1076 // Smart processing for ampersands and angle brackets that need to be encoded.
1078 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1079 // http://bumppo.net/projects/amputator/
1080 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1083 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1089 var _EncodeBackslashEscapes = function(text) {
1091 // Parameter: String.
1092 // Returns: The string, with after processing the following backslash
1093 // escape sequences.
1096 // attacklab: The polite way to do this is with the new
1097 // escapeCharacters() function:
1099 // text = escapeCharacters(text,"\\",true);
1100 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1102 // ...but we're sidestepping its use of the (slow) RegExp constructor
1103 // as an optimization for Firefox. This function gets called a LOT.
1105 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1106 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1111 var _DoAutoLinks = function(text) {
1113 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1115 // Email addresses: <address@domain.foo>
1118 text = text.replace(/
1124 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1127 /gi, _DoAutoLinks_callback());
1129 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1130 function(wholeMatch,m1) {
1131 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1139 var _EncodeEmailAddress = function(addr) {
1141 // Input: an email address, e.g. "foo@example.com"
1143 // Output: the email address as a mailto link, with each character
1144 // of the address encoded as either a decimal or hex entity, in
1145 // the hopes of foiling most address harvesting spam bots. E.g.:
1147 // <a href="mailto:foo@e
1148 // xample.com">foo
1149 // @example.com</a>
1151 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1152 // mailing list: <http://tinyurl.com/yu7ue>
1155 // attacklab: why can't javascript speak hex?
1156 function char2hex(ch) {
1157 var hexDigits = '0123456789ABCDEF';
1158 var dec = ch.charCodeAt(0);
1159 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1163 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1164 function(ch){return "&#x"+char2hex(ch)+";";},
1165 function(ch){return ch;}
1168 addr = "mailto:" + addr;
1170 addr = addr.replace(/./g, function(ch) {
1172 // this *must* be encoded. I insist.
1173 ch = encode[Math.floor(Math.random()*2)](ch);
1174 } else if (ch !=":") {
1175 // leave ':' alone (to spot mailto: later)
1176 var r = Math.random();
1177 // roughly 10% raw, 45% hex, 45% dec
1179 r > .9 ? encode[2](ch) :
1180 r > .45 ? encode[1](ch) :
1187 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1188 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1194 var _UnescapeSpecialChars = function(text) {
1196 // Swap back in all the special characters we've hidden.
1198 text = text.replace(/~E(\d+)E/g,
1199 function(wholeMatch,m1) {
1200 var charCodeToReplace = parseInt(m1);
1201 return String.fromCharCode(charCodeToReplace);
1208 var _Outdent = function(text) {
1210 // Remove one level of line-leading tabs or spaces
1213 // attacklab: hack around Konqueror 3.5.4 bug:
1214 // "----------bug".replace(/^-/g,"") == "bug"
1216 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1218 // attacklab: clean up hack
1219 text = text.replace(/~0/g,"")
1224 var _Detab = function(text) {
1225 // attacklab: Detab's completely rewritten for speed.
1226 // In perl we could fix it by anchoring the regexp with \G.
1227 // In javascript we're less fortunate.
1229 // expand first n-1 tabs
1230 text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
1232 // replace the nth with two sentinels
1233 text = text.replace(/\t/g,"~A~B");
1235 // use the sentinel to anchor our regex so it doesn't explode
1236 text = text.replace(/~B(.+?)~A/g,
1237 function(wholeMatch,m1,m2) {
1238 var leadingText = m1;
1239 var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
1241 // there *must* be a better way to do this:
1242 for (var i=0; i<numSpaces; i++) leadingText+=" ";
1248 // clean up sentinels
1249 text = text.replace(/~A/g," "); // attacklab: g_tab_width
1250 text = text.replace(/~B/g,"");
1257 // attacklab: Utility functions
1261 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1262 // First we have to escape the escape characters so that
1263 // we can build a character class out of them
1264 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1266 if (afterBackslash) {
1267 regexString = "\\\\" + regexString;
1270 var regex = new RegExp(regexString,"g");
1271 text = text.replace(regex,escapeCharacters_callback);
1277 var escapeCharacters_callback = function(wholeMatch,m1) {
1278 var charCodeToEscape = m1.charCodeAt(0);
1279 return "~E"+charCodeToEscape+"E";
1282 exports.encode = exports.markdown = function (src) {
1283 return exports.makeHtml(src);
1286 exports.main = function (system) {
1287 var command = system.args.shift();
1288 if (!system.args.length) {
1289 system.stdout.write(exports.markdown(system.stdin.read())).flush();
1292 while (arg = system.args.shift()) {
1293 var out = system.fs.basename(arg, '.md') + '.html';
1295 system.fs.write(out, exports.markdown(system.fs.read(arg)));