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 // alert( Roo.ux.Showdown.toHtml("Markdown *rocks*.") );
54 // Note: move the sample code to the bottom of this
55 // file before uncommenting it.
62 Roo.namespace('Roo.ux');
64 Roo.ux.Showdown.toHtml = function(text) {
65 var c = new Roo.ux.Showdown.converter();
66 return c.makeHtml(text);
71 // Wraps all "globals" so that the only thing
72 // exposed is makeHtml().
74 Roo.ux.Showdown.converter = function() {
80 // Global hashes, used by various utility routines
85 // Used to track when we're inside an ordered or unordered list
86 // (see _ProcessListItems() for details):
90 this.makeHtml = function(_text) {
92 // Main function. The order in which other subs are called here is
93 // essential. Link and image substitutions need to happen before
94 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
95 // and <img> tags get encoded.
97 var text = '' + _text;
98 // Clear the global hashes. If we don't clear these, you get conflicts
99 // from other articles when generating a page which contains more than
100 // one article (e.g. an index page that shows the N most recent
102 g_urls = new Array();
103 g_titles = new Array();
104 g_html_blocks = new Array();
106 // attacklab: Replace ~ with ~T
107 // This lets us use tilde as an escape char to avoid md5 hashes
108 // The choice of character is arbitray; anything that isn't
109 // magic in Markdown will work.
110 text = text.replace(/~/g,"~T");
112 // attacklab: Replace $ with ~D
113 // RegExp interprets $ as a special character
114 // when it's in a replacement string
115 text = text.replace(/\$/g,"~D");
117 // Standardize line endings
118 text = text.replace(/\r\n/g,"\n"); // DOS to Unix
119 text = text.replace(/\r/g,"\n"); // Mac to Unix
121 // Make sure text begins and ends with a couple of newlines:
122 text = "\n\n" + text + "\n\n";
124 // Convert all tabs to spaces.
127 // Strip any lines consisting only of spaces and tabs.
128 // This makes subsequent regexen easier to write, because we can
129 // match consecutive blank lines with /\n+/ instead of something
130 // contorted like /[ \t]*\n+/ .
131 text = text.replace(/^[ \t]+$/mg,"");
133 text = _DoCodeBlcoks(text);
135 // Turn block-level HTML blocks into hash entries
136 text = _HashHTMLBlocks(text);
138 // Strip link definitions, store in hashes.
139 text = _StripLinkDefinitions(text);
141 text = _RunBlockGamut(text);
143 text = _UnescapeSpecialChars(text);
145 // attacklab: Restore dollar signs
146 text = text.replace(/~D/g,"$$");
148 // attacklab: Restore tildes
149 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 text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/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
205 var _HashHTMLBlocks = function(text) {
206 // attacklab: Double up blank lines to reduce lookaround
207 text = text.replace(/\n/g,"\n\n");
209 // Hashify HTML blocks:
210 // We only want to do this for block-level HTML tags, such as headers,
211 // lists, and tables. That's because we still want to wrap <p>s around
212 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
213 // phrase emphasis, and spans. The list of tags we're looking for is
215 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
216 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
218 // First, look for nested blocks, e.g.:
221 // tags for inner block must be indented.
225 // The outermost tags must start at the left margin for this to match, and
226 // the inner nested divs must be indented.
227 // We need to do this before the next, more liberal match, because the next
228 // match will start at the first `<div>` and stop at the first `</div>`.
230 // attacklab: This regex can be expensive when it fails.
232 var text = text.replace(/
234 ^ // start of line (with /m)
235 <($block_tags_a) // start tag = $2
237 // attacklab: hack around khtml/pcre bug...
238 [^\r]*?\n // any number of lines, minimally matching
239 </\2> // the matching end tag
240 [ \t]* // trailing spaces/tabs
241 (?=\n+) // followed by a newline
242 ) // attacklab: there are sentinel newlines at end of document
243 /gm,function(){...}};
245 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);
248 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
252 var text = text.replace(/
254 ^ // start of line (with /m)
255 <($block_tags_b) // start tag = $2
257 // attacklab: hack around khtml/pcre bug...
258 [^\r]*? // any number of lines, minimally matching
259 .*</\2> // the matching end tag
260 [ \t]* // trailing spaces/tabs
261 (?=\n+) // followed by a newline
262 ) // attacklab: there are sentinel newlines at end of document
263 /gm,function(){...}};
265 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);
267 // Special case just for <hr />. It was easier to make a special case than
268 // to make the other regex more complicated.
271 text = text.replace(/
273 \n\n // Starting after a blank line
275 (<(hr) // start tag = $2
278 \/?>) // the matching end tag
280 (?=\n{2,}) // followed by a blank line
284 text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
286 // Special case for standalone HTML comments:
289 text = text.replace(/
291 \n\n // Starting after a blank line
292 [ ]{0,3} // attacklab: g_tab_width - 1
297 (?=\n{2,}) // followed by a blank line
301 text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
303 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
306 text = text.replace(/
308 \n\n // Starting after a blank line
311 [ ]{0,3} // attacklab: g_tab_width - 1
318 (?=\n{2,}) // followed by a blank line
322 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
324 // attacklab: Undo double lines (see comment at top of this function)
325 text = text.replace(/\n\n/g,"\n");
329 var hashElement = function(wholeMatch,m1) {
333 blockText = blockText.replace(/\n\n/g,"\n");
334 blockText = blockText.replace(/^\n/,"");
336 // strip trailing blank lines
337 blockText = blockText.replace(/\n+$/g,"");
339 // Replace the element text with a marker ("~KxK" where x is its key)
340 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
345 var _RunBlockGamut = function(text) {
347 // These are all the transformations that form block-level
348 // tags like paragraphs, headers, and list items.
350 // code blocks first... so content does not get translated..
351 text = _DoCodeBlocks(text);
353 text = _DoHeaders(text);
355 // Do Horizontal Rules:
356 var key = hashBlock("<hr />");
357 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
358 text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
359 text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
361 text = _DoLists(text);
363 text = _DoBlockQuotes(text);
365 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
366 // was to escape raw HTML in the original Markdown source. This time,
367 // we're escaping the markup we've just created, so that we don't wrap
368 // <p> tags around block-level tags.
370 text = _FormParagraphs(text);
371 text = _HashHTMLBlocks(text);
376 var _RunSpanGamut = function(text) {
378 // These are all the transformations that occur *within* block-level
379 // tags like paragraphs, headers, and list items.
382 text = _DoCodeSpans(text);
383 text = _EscapeSpecialCharsWithinTagAttributes(text);
384 text = _EncodeBackslashEscapes(text);
386 // Process anchor and image tags. Images must come first,
387 // because ![foo][f] looks like an anchor.
388 text = _DoImages(text);
389 text = _DoAnchors(text);
391 // Make links out of things like `<http://example.com/>`
392 // Must come after _DoAnchors(), because you can use < and >
393 // delimiters in inline links like [this](<url>).
394 text = _DoAutoLinks(text);
395 text = _EncodeAmpsAndAngles(text);
396 text = _DoItalicsAndBold(text);
399 text = text.replace(/ +\n/g," <br />\n");
404 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
406 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
407 // don't conflict with their use in Markdown for code, italics and strong.
410 // Build a regex to find HTML tags and comments. See Friedl's
411 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
412 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
414 text = text.replace(regex, function(wholeMatch) {
415 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
416 tag = escapeCharacters(tag,"\\`*_");
423 var _DoAnchors = function(text) {
425 // Turn Markdown link shortcuts into XHTML <a> tags.
428 // First, handle reference-style links: [link text] [id]
432 text = text.replace(/
433 ( // wrap whole match in $1
437 \[[^\]]*\] // allow brackets nested one level
439 [^\[] // or anything else
444 [ ]? // one optional space
445 (?:\n[ ]*)? // one optional newline followed by spaces
450 )()()()() // pad remaining backreferences
451 /g,_DoAnchors_callback);
453 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
456 // Next, inline-style links: [link text](url "optional title")
460 text = text.replace(/
461 ( // wrap whole match in $1
465 \[[^\]]*\] // allow brackets nested one level
467 [^\[\]] // or anything else
473 () // no id, so leave $3 empty
474 <?(.*?)>? // href = $4
477 (['"]) // quote char = $6
480 [ \t]* // ignore any spaces/tabs between closing quote and )
481 )? // title is optional
486 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
489 // Last, handle reference-style shortcuts: [link text]
490 // These must come last in case you've also got [link test][1]
491 // or [link test](/foo)
495 text = text.replace(/
496 ( // wrap whole match in $1
498 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
500 )()()()()() // pad rest of backreferences
503 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
508 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
509 if (m7 == undefined) m7 = "";
510 var whole_match = m1;
512 var link_id = m3.toLowerCase();
518 // lower-case and turn embedded newlines into spaces
519 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
523 if (g_urls[link_id] != undefined) {
524 url = g_urls[link_id];
525 if (g_titles[link_id] != undefined) {
526 title = g_titles[link_id];
530 if (whole_match.search(/\(\s*\)$/m)>-1) {
531 // Special case for explicit empty url
539 url = escapeCharacters(url,"*_");
540 var result = "<a href=\"" + url + "\"";
543 title = title.replace(/"/g,""");
544 title = escapeCharacters(title,"*_");
545 result += " title=\"" + title + "\"";
548 result += ">" + link_text + "</a>";
554 var _DoImages = function(text) {
556 // Turn Markdown image shortcuts into <img> tags.
560 // First, handle reference-style labeled images: ![alt text][id]
564 text = text.replace(/
565 ( // wrap whole match in $1
567 (.*?) // alt text = $2
570 [ ]? // one optional space
571 (?:\n[ ]*)? // one optional newline followed by spaces
576 )()()()() // pad rest of backreferences
579 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
582 // Next, handle inline images: ![alt text](url "optional title")
583 // Don't forget: encode * and _
586 text = text.replace(/
587 ( // wrap whole match in $1
589 (.*?) // alt text = $2
591 \s? // One optional whitespace character
594 () // no id, so leave $3 empty
595 <?(\S+?)>? // src url = $4
598 (['"]) // quote char = $6
602 )? // title is optional
607 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
612 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
613 var whole_match = m1;
615 var link_id = m3.toLowerCase();
619 if (!title) title = "";
623 // lower-case and turn embedded newlines into spaces
624 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
628 if (g_urls[link_id] != undefined) {
629 url = g_urls[link_id];
630 if (g_titles[link_id] != undefined) {
631 title = g_titles[link_id];
639 alt_text = alt_text.replace(/"/g,""");
640 url = escapeCharacters(url,"*_");
641 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
643 // attacklab: Markdown.pl adds empty title attributes to images.
644 // Replicate this bug.
647 title = title.replace(/"/g,""");
648 title = escapeCharacters(title,"*_");
649 result += " title=\"" + title + "\"";
658 var _DoHeaders = function(text) {
660 // Setext-style headers:
667 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
668 function(wholeMatch,m1){return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");});
670 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
671 function(matchFound,m1){return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");});
673 // atx-style headers:
676 // ## Header 2 with closing hashes ##
682 text = text.replace(/
683 ^(\#{1,6}) // $1 = string of #'s
685 (.+?) // $2 = Header text
687 \#* // optional closing #'s (not counted)
689 /gm, function() {...});
692 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
693 function(wholeMatch,m1,m2) {
694 var h_level = m1.length;
695 return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
698 function headerId(m) {
699 return m.replace(/[^\w]/g, '').toLowerCase();
704 // This declaration keeps Dojo compressor from outputting garbage:
705 var _ProcessListItems;
707 var _DoLists = function(text) {
709 // Form HTML ordered (numbered) and unordered (bulleted) lists.
712 // attacklab: add sentinel to hack around khtml/safari bug:
713 // http://bugs.webkit.org/show_bug.cgi?id=11231
716 // Re-usable pattern to match any entirel ul or ol list:
722 [ ]{0,3} // attacklab: g_tab_width - 1
723 ([*+-]|\d+[.]) // $3 = first list item marker
728 ~0 // sentinel for workaround; should be $
732 (?! // Negative lookahead for another list item marker
734 (?:[*+-]|\d+[.])[ \t]+
739 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
742 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
744 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
746 // Turn double returns into triple returns, so that we can make a
747 // paragraph for the last item in a list, if necessary:
748 list = list.replace(/\n{2,}/g,"\n\n\n");;
749 var result = _ProcessListItems(list);
751 // Trim any trailing whitespace, to put the closing `</$list_type>`
752 // up on the preceding line, to get it past the current stupid
753 // HTML block parser. This is a hack to work around the terrible
754 // hack that is the HTML block parser.
755 result = result.replace(/\s+$/,"");
756 result = "<"+list_type+">" + result + "</"+list_type+">\n";
760 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
761 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
765 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
766 // Turn double returns into triple returns, so that we can make a
767 // paragraph for the last item in a list, if necessary:
768 var list = list.replace(/\n{2,}/g,"\n\n\n");;
769 var result = _ProcessListItems(list);
770 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
775 // attacklab: strip sentinel
776 text = text.replace(/~0/,"");
781 _ProcessListItems = function(list_str) {
783 // Process the contents of a single ordered or unordered list, splitting it
784 // into individual list items.
786 // The $g_list_level global keeps track of when we're inside a list.
787 // Each time we enter a list, we increment it; when we leave a list,
788 // we decrement. If it's zero, we're not in a list anymore.
790 // We do this because when we're not inside a list, we want to treat
791 // something like this:
793 // I recommend upgrading to version
794 // 8. Oops, now this line is treated
797 // As a single paragraph, despite the fact that the second line starts
798 // with a digit-period-space sequence.
800 // Whereas when we're inside a list (or sub-list), that line will be
801 // treated as the start of a sub-list. What a kludge, huh? This is
802 // an aspect of Markdown's syntax that's hard to parse perfectly
803 // without resorting to mind-reading. Perhaps the solution is to
804 // change the syntax rules such that sub-lists must start with a
805 // starting cardinal number; e.g. "1." or "a.".
809 // trim trailing blank lines:
810 list_str = list_str.replace(/\n{2,}$/,"\n");
812 // attacklab: add sentinel to emulate \z
816 list_str = list_str.replace(/
817 (\n)? // leading line = $1
818 (^[ \t]*) // leading whitespace = $2
819 ([*+-]|\d+[.]) [ \t]+ // list marker = $3
820 ([^\r]+? // list item text = $4
822 (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
823 /gm, function(){...});
825 list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
826 function(wholeMatch,m1,m2,m3,m4){
828 var leading_line = m1;
829 var leading_space = m2;
831 if (leading_line || (item.search(/\n{2,}/)>-1)) {
832 item = _RunBlockGamut(_Outdent(item));
835 // Recursion for sub-lists:
836 item = _DoLists(_Outdent(item));
837 item = item.replace(/\n$/,""); // chomp(item)
838 item = _RunSpanGamut(item);
841 return "<li>" + item + "</li>\n";
845 // attacklab: strip sentinel
846 list_str = list_str.replace(/~0/g,"");
853 var _DoCodeBlocks = function(text) {
855 // Process Markdown `<pre><code>` blocks.
859 text = text.replace(text,
861 ( // $1 = the code block -- one or more lines, starting with a space/tab
863 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
867 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
871 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
872 text = text.replace(/~0/,"");
875 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
876 function(wholeMatch,m1,m2) {
880 codeblock = _EncodeCode( _Outdent(codeblock));
881 codeblock = _Detab(codeblock);
882 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
883 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
885 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
887 return hashBlock(codeblock) + nextChar;
891 // attacklab: strip sentinel
892 text = text.replace(/~0/,"");
898 text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
901 // First parse the github code block
902 codeblock = _EncodeCode( codeblock);
903 codeblock = _Detab(codeblock);
904 codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
905 codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
907 codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
909 return hashBlock(codeblock) ;
912 // attacklab: strip sentinel
913 text = text.replace(/~0/, '');
919 var hashBlock = function(text) {
920 text = text.replace(/(^\n+|\n+$)/g,"");
921 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
925 var _DoCodeSpans = function(text) {
927 // * Backtick quotes are used for <code></code> spans.
929 // * You can use multiple backticks as the delimiters if you want to
930 // include literal backticks in the code span. So, this input:
932 // Just type ``foo `bar` baz`` at the prompt.
934 // Will translate to:
936 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
938 // There's no arbitrary limit to the number of backticks you
939 // can use as delimters. If you need three consecutive backticks
940 // in your code, use four for delimiters, etc.
942 // * You can use spaces to get literal backticks at the edges:
944 // ... type `` `bar` `` ...
948 // ... type <code>`bar`</code> ...
952 text = text.replace(/
953 (^|[^\\]) // Character before opening ` can't be a backslash
954 (`+) // $2 = Opening run of `
955 ( // $3 = The code block
957 [^`] // attacklab: work around lack of lookbehind
959 \2 // Matching closer
961 /gm, function(){...});
964 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
965 function(wholeMatch,m1,m2,m3,m4) {
967 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
968 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
970 return m1+"<code>"+c+"</code>";
977 var _EncodeCode = function(text) {
979 // Encode/escape certain characters inside Markdown code runs.
980 // The point is that in code, these characters are literals,
981 // and lose their special Markdown meanings.
983 // REMOVED - Data going into markdown should be encoded before it enters..
986 // Encode all ampersands; HTML entities are not
987 // entities within a Markdown code span.
990 //text = text.replace(/&/g,"&");
992 // Do the angle bracket song and dance:
993 //text = text.replace(/</g,"<");
994 //text = text.replace(/>/g,">");
996 // Now, escape characters that are magic in Markdown:
997 text = escapeCharacters(text,"\*_{}[]\\",false);
999 // jj the line above breaks this:
1013 var _DoItalicsAndBold = function(text) {
1015 // <strong> must go first:
1016 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
1017 "<strong>$2</strong>");
1019 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1026 var _DoBlockQuotes = function(text) {
1029 text = text.replace(/
1030 ( // Wrap whole match in $1
1032 ^[ \t]*>[ \t]? // '>' at the start of a line
1033 .+\n // rest of the first line
1034 (.+\n)* // subsequent consecutive lines
1038 /gm, function(){...});
1041 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1042 function(wholeMatch,m1) {
1045 // attacklab: hack around Konqueror 3.5.4 bug:
1046 // "----------bug".replace(/^-/g,"") == "bug"
1048 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1050 // attacklab: clean up hack
1051 bq = bq.replace(/~0/g,"");
1053 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1054 bq = _RunBlockGamut(bq); // recurse
1056 bq = bq.replace(/(^|\n)/g,"$1 ");
1057 // These leading spaces screw with <pre> content, so we need to fix that:
1059 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1060 function(wholeMatch,m1) {
1062 // attacklab: hack around Konqueror 3.5.4 bug:
1063 pre = pre.replace(/^ /mg,"~0");
1064 pre = pre.replace(/~0/g,"");
1068 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1074 var _FormParagraphs = function(text) {
1077 // $text - string to process with html <p> tags
1080 // Strip leading and trailing lines:
1081 text = text.replace(/^\n+/g,"");
1082 text = text.replace(/\n+$/g,"");
1084 var grafs = text.split(/\n{2,}/g);
1085 var grafsOut = new Array();
1090 var end = grafs.length;
1091 for (var i=0; i<end; i++) {
1094 // if this is an HTML marker, copy it
1095 if (str.search(/~K(\d+)K/g) >= 0) {
1098 else if (str.search(/\S/) >= 0) {
1099 str = _RunSpanGamut(str);
1100 str = str.replace(/^([ \t]*)/g,"<p>");
1108 // Unhashify HTML blocks
1110 end = grafsOut.length;
1111 for (var i=0; i<end; i++) {
1112 // if this is a marker for an html block...
1113 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1114 var blockText = g_html_blocks[RegExp.$1];
1115 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1116 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1120 return grafsOut.join("\n\n");
1124 var _EncodeAmpsAndAngles = function(text) {
1125 // Smart processing for ampersands and angle brackets that need to be encoded.
1127 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1128 // http://bumppo.net/projects/amputator/
1129 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1132 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1138 var _EncodeBackslashEscapes = function(text) {
1140 // Parameter: String.
1141 // Returns: The string, with after processing the following backslash
1142 // escape sequences.
1145 // attacklab: The polite way to do this is with the new
1146 // escapeCharacters() function:
1148 // text = escapeCharacters(text,"\\",true);
1149 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1151 // ...but we're sidestepping its use of the (slow) RegExp constructor
1152 // as an optimization for Firefox. This function gets called a LOT.
1154 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1155 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1160 var _DoAutoLinks = function(text) {
1162 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1164 // Email addresses: <address@domain.foo>
1167 text = text.replace(/
1173 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1176 /gi, _DoAutoLinks_callback());
1178 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1179 function(wholeMatch,m1) {
1180 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1188 var _EncodeEmailAddress = function(addr) {
1190 // Input: an email address, e.g. "foo@example.com"
1192 // Output: the email address as a mailto link, with each character
1193 // of the address encoded as either a decimal or hex entity, in
1194 // the hopes of foiling most address harvesting spam bots. E.g.:
1196 // <a href="mailto:foo@e
1197 // xample.com">foo
1198 // @example.com</a>
1200 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1201 // mailing list: <http://tinyurl.com/yu7ue>
1204 // attacklab: why can't javascript speak hex?
1205 function char2hex(ch) {
1206 var hexDigits = '0123456789ABCDEF';
1207 var dec = ch.charCodeAt(0);
1208 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1212 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1213 function(ch){return "&#x"+char2hex(ch)+";";},
1214 function(ch){return ch;}
1217 addr = "mailto:" + addr;
1219 addr = addr.replace(/./g, function(ch) {
1221 // this *must* be encoded. I insist.
1222 ch = encode[Math.floor(Math.random()*2)](ch);
1223 } else if (ch !=":") {
1224 // leave ':' alone (to spot mailto: later)
1225 var r = Math.random();
1226 // roughly 10% raw, 45% hex, 45% dec
1228 r > .9 ? encode[2](ch) :
1229 r > .45 ? encode[1](ch) :
1236 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1237 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1243 var _UnescapeSpecialChars = function(text) {
1245 // Swap back in all the special characters we've hidden.
1247 text = text.replace(/~E(\d+)E/g,
1248 function(wholeMatch,m1) {
1249 var charCodeToReplace = parseInt(m1);
1250 return String.fromCharCode(charCodeToReplace);
1257 var _Outdent = function(text) {
1259 // Remove one level of line-leading tabs or spaces
1262 // attacklab: hack around Konqueror 3.5.4 bug:
1263 // "----------bug".replace(/^-/g,"") == "bug"
1265 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1267 // attacklab: clean up hack
1268 text = text.replace(/~0/g,"");
1273 var _Detab = function(text) {
1274 // attacklab: Detab's completely rewritten for speed.
1275 // In perl we could fix it by anchoring the regexp with \G.
1276 // In javascript we're less fortunate.
1278 // expand first n-1 tabs
1279 text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
1281 // replace the nth with two sentinels
1282 text = text.replace(/\t/g,"~A~B");
1284 // use the sentinel to anchor our regex so it doesn't explode
1285 text = text.replace(/~B(.+?)~A/g,
1286 function(wholeMatch,m1,m2) {
1287 var leadingText = m1;
1288 var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
1290 // there *must* be a better way to do this:
1291 for (var i=0; i<numSpaces; i++) leadingText+=" ";
1297 // clean up sentinels
1298 text = text.replace(/~A/g," "); // attacklab: g_tab_width
1299 text = text.replace(/~B/g,"");
1306 // attacklab: Utility functions
1310 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1311 // First we have to escape the escape characters so that
1312 // we can build a character class out of them
1313 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1315 if (afterBackslash) {
1316 regexString = "\\\\" + regexString;
1319 var regex = new RegExp(regexString,"g");
1320 text = text.replace(regex,escapeCharacters_callback);
1326 var escapeCharacters_callback = function(wholeMatch,m1) {
1327 var charCodeToEscape = m1.charCodeAt(0);
1328 return "~E"+charCodeToEscape+"E";
1331 } // end of Showdown.converter
1334 //if (typeof exports != 'undefined') exports.Showdown = Showdown;