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 // Turn block-level HTML blocks into hash entries
134 text = _HashHTMLBlocks(text);
136 // Strip link definitions, store in hashes.
137 text = _StripLinkDefinitions(text);
139 text = _RunBlockGamut(text);
141 text = _UnescapeSpecialChars(text);
143 // attacklab: Restore dollar signs
144 text = text.replace(/~D/g,"$$");
146 // attacklab: Restore tildes
147 text = text.replace(/~T/g,"~");
153 var _StripLinkDefinitions = function(text) {
155 // Strips link definitions from text, stores the URLs and titles in
159 // Link defs are in the form: ^[id]: url "optional title"
162 var text = text.replace(/
163 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
165 \n? // maybe *one* newline
167 <?(\S+?)>? // url = $2
169 \n? // maybe one newline
172 (\n*) // any lines skipped = $3 attacklab: lookbehind removed
177 )? // title is optional
182 text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
183 function (wholeMatch,m1,m2,m3,m4) {
184 m1 = m1.toLowerCase();
185 g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
187 // Oops, found blank lines, so it's not a title.
188 // Put back the parenthetical statement we stole.
191 g_titles[m1] = m4.replace(/"/g,""");
194 // Completely remove the definition from the text
203 var _HashHTMLBlocks = function(text) {
204 // attacklab: Double up blank lines to reduce lookaround
205 text = text.replace(/\n/g,"\n\n");
207 // Hashify HTML blocks:
208 // We only want to do this for block-level HTML tags, such as headers,
209 // lists, and tables. That's because we still want to wrap <p>s around
210 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
211 // phrase emphasis, and spans. The list of tags we're looking for is
213 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
214 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
216 // First, look for nested blocks, e.g.:
219 // tags for inner block must be indented.
223 // The outermost tags must start at the left margin for this to match, and
224 // the inner nested divs must be indented.
225 // We need to do this before the next, more liberal match, because the next
226 // match will start at the first `<div>` and stop at the first `</div>`.
228 // attacklab: This regex can be expensive when it fails.
230 var text = text.replace(/
232 ^ // start of line (with /m)
233 <($block_tags_a) // start tag = $2
235 // attacklab: hack around khtml/pcre bug...
236 [^\r]*?\n // any number of lines, minimally matching
237 </\2> // the matching end tag
238 [ \t]* // trailing spaces/tabs
239 (?=\n+) // followed by a newline
240 ) // attacklab: there are sentinel newlines at end of document
241 /gm,function(){...}};
243 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);
246 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
250 var text = text.replace(/
252 ^ // start of line (with /m)
253 <($block_tags_b) // start tag = $2
255 // attacklab: hack around khtml/pcre bug...
256 [^\r]*? // any number of lines, minimally matching
257 .*</\2> // the matching end tag
258 [ \t]* // trailing spaces/tabs
259 (?=\n+) // followed by a newline
260 ) // attacklab: there are sentinel newlines at end of document
261 /gm,function(){...}};
263 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);
265 // Special case just for <hr />. It was easier to make a special case than
266 // to make the other regex more complicated.
269 text = text.replace(/
271 \n\n // Starting after a blank line
273 (<(hr) // start tag = $2
276 \/?>) // the matching end tag
278 (?=\n{2,}) // followed by a blank line
282 text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
284 // Special case for standalone HTML comments:
287 text = text.replace(/
289 \n\n // Starting after a blank line
290 [ ]{0,3} // attacklab: g_tab_width - 1
295 (?=\n{2,}) // followed by a blank line
299 text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
301 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
304 text = text.replace(/
306 \n\n // Starting after a blank line
309 [ ]{0,3} // attacklab: g_tab_width - 1
316 (?=\n{2,}) // followed by a blank line
320 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
322 // attacklab: Undo double lines (see comment at top of this function)
323 text = text.replace(/\n\n/g,"\n");
327 var hashElement = function(wholeMatch,m1) {
331 blockText = blockText.replace(/\n\n/g,"\n");
332 blockText = blockText.replace(/^\n/,"");
334 // strip trailing blank lines
335 blockText = blockText.replace(/\n+$/g,"");
337 // Replace the element text with a marker ("~KxK" where x is its key)
338 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
343 var _RunBlockGamut = function(text) {
345 // These are all the transformations that form block-level
346 // tags like paragraphs, headers, and list items.
348 // code blocks first... so content does not get translated..
349 text = _DoCodeBlocks(text);
351 text = _DoHeaders(text);
353 // Do Horizontal Rules:
354 var key = hashBlock("<hr />");
355 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
356 text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
357 text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
359 text = _DoLists(text);
361 text = _DoBlockQuotes(text);
363 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
364 // was to escape raw HTML in the original Markdown source. This time,
365 // we're escaping the markup we've just created, so that we don't wrap
366 // <p> tags around block-level tags.
367 text = _HashHTMLBlocks(text);
368 text = _FormParagraphs(text);
374 var _RunSpanGamut = function(text) {
376 // These are all the transformations that occur *within* block-level
377 // tags like paragraphs, headers, and list items.
380 text = _DoCodeSpans(text);
381 text = _EscapeSpecialCharsWithinTagAttributes(text);
382 text = _EncodeBackslashEscapes(text);
384 // Process anchor and image tags. Images must come first,
385 // because ![foo][f] looks like an anchor.
386 text = _DoImages(text);
387 text = _DoAnchors(text);
389 // Make links out of things like `<http://example.com/>`
390 // Must come after _DoAnchors(), because you can use < and >
391 // delimiters in inline links like [this](<url>).
392 text = _DoAutoLinks(text);
393 text = _EncodeAmpsAndAngles(text);
394 text = _DoItalicsAndBold(text);
397 text = text.replace(/ +\n/g," <br />\n");
402 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
404 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
405 // don't conflict with their use in Markdown for code, italics and strong.
408 // Build a regex to find HTML tags and comments. See Friedl's
409 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
410 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
412 text = text.replace(regex, function(wholeMatch) {
413 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
414 tag = escapeCharacters(tag,"\\`*_");
421 var _DoAnchors = function(text) {
423 // Turn Markdown link shortcuts into XHTML <a> tags.
426 // First, handle reference-style links: [link text] [id]
430 text = text.replace(/
431 ( // wrap whole match in $1
435 \[[^\]]*\] // allow brackets nested one level
437 [^\[] // or anything else
442 [ ]? // one optional space
443 (?:\n[ ]*)? // one optional newline followed by spaces
448 )()()()() // pad remaining backreferences
449 /g,_DoAnchors_callback);
451 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
454 // Next, inline-style links: [link text](url "optional title")
458 text = text.replace(/
459 ( // wrap whole match in $1
463 \[[^\]]*\] // allow brackets nested one level
465 [^\[\]] // or anything else
471 () // no id, so leave $3 empty
472 <?(.*?)>? // href = $4
475 (['"]) // quote char = $6
478 [ \t]* // ignore any spaces/tabs between closing quote and )
479 )? // title is optional
484 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
487 // Last, handle reference-style shortcuts: [link text]
488 // These must come last in case you've also got [link test][1]
489 // or [link test](/foo)
493 text = text.replace(/
494 ( // wrap whole match in $1
496 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
498 )()()()()() // pad rest of backreferences
501 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
506 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
507 if (m7 == undefined) m7 = "";
508 var whole_match = m1;
510 var link_id = m3.toLowerCase();
516 // lower-case and turn embedded newlines into spaces
517 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
521 if (g_urls[link_id] != undefined) {
522 url = g_urls[link_id];
523 if (g_titles[link_id] != undefined) {
524 title = g_titles[link_id];
528 if (whole_match.search(/\(\s*\)$/m)>-1) {
529 // Special case for explicit empty url
537 url = escapeCharacters(url,"*_");
538 var result = "<a href=\"" + url + "\"";
541 title = title.replace(/"/g,""");
542 title = escapeCharacters(title,"*_");
543 result += " title=\"" + title + "\"";
546 result += ">" + link_text + "</a>";
552 var _DoImages = function(text) {
554 // Turn Markdown image shortcuts into <img> tags.
558 // First, handle reference-style labeled images: ![alt text][id]
562 text = text.replace(/
563 ( // wrap whole match in $1
565 (.*?) // alt text = $2
568 [ ]? // one optional space
569 (?:\n[ ]*)? // one optional newline followed by spaces
574 )()()()() // pad rest of backreferences
577 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
580 // Next, handle inline images: ![alt text](url "optional title")
581 // Don't forget: encode * and _
584 text = text.replace(/
585 ( // wrap whole match in $1
587 (.*?) // alt text = $2
589 \s? // One optional whitespace character
592 () // no id, so leave $3 empty
593 <?(\S+?)>? // src url = $4
596 (['"]) // quote char = $6
600 )? // title is optional
605 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
610 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
611 var whole_match = m1;
613 var link_id = m3.toLowerCase();
617 if (!title) title = "";
621 // lower-case and turn embedded newlines into spaces
622 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
626 if (g_urls[link_id] != undefined) {
627 url = g_urls[link_id];
628 if (g_titles[link_id] != undefined) {
629 title = g_titles[link_id];
637 alt_text = alt_text.replace(/"/g,""");
638 url = escapeCharacters(url,"*_");
639 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
641 // attacklab: Markdown.pl adds empty title attributes to images.
642 // Replicate this bug.
645 title = title.replace(/"/g,""");
646 title = escapeCharacters(title,"*_");
647 result += " title=\"" + title + "\"";
656 var _DoHeaders = function(text) {
658 // Setext-style headers:
665 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
666 function(wholeMatch,m1){return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");});
668 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
669 function(matchFound,m1){return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");});
671 // atx-style headers:
674 // ## Header 2 with closing hashes ##
680 text = text.replace(/
681 ^(\#{1,6}) // $1 = string of #'s
683 (.+?) // $2 = Header text
685 \#* // optional closing #'s (not counted)
687 /gm, function() {...});
690 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
691 function(wholeMatch,m1,m2) {
692 var h_level = m1.length;
693 return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
696 function headerId(m) {
697 return m.replace(/[^\w]/g, '').toLowerCase();
702 // This declaration keeps Dojo compressor from outputting garbage:
703 var _ProcessListItems;
705 var _DoLists = function(text) {
707 // Form HTML ordered (numbered) and unordered (bulleted) lists.
710 // attacklab: add sentinel to hack around khtml/safari bug:
711 // http://bugs.webkit.org/show_bug.cgi?id=11231
714 // Re-usable pattern to match any entirel ul or ol list:
720 [ ]{0,3} // attacklab: g_tab_width - 1
721 ([*+-]|\d+[.]) // $3 = first list item marker
726 ~0 // sentinel for workaround; should be $
730 (?! // Negative lookahead for another list item marker
732 (?:[*+-]|\d+[.])[ \t]+
737 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
740 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
742 var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
744 // Turn double returns into triple returns, so that we can make a
745 // paragraph for the last item in a list, if necessary:
746 list = list.replace(/\n{2,}/g,"\n\n\n");;
747 var result = _ProcessListItems(list);
749 // Trim any trailing whitespace, to put the closing `</$list_type>`
750 // up on the preceding line, to get it past the current stupid
751 // HTML block parser. This is a hack to work around the terrible
752 // hack that is the HTML block parser.
753 result = result.replace(/\s+$/,"");
754 result = "<"+list_type+">" + result + "</"+list_type+">\n";
758 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
759 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
763 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
764 // Turn double returns into triple returns, so that we can make a
765 // paragraph for the last item in a list, if necessary:
766 var list = list.replace(/\n{2,}/g,"\n\n\n");;
767 var result = _ProcessListItems(list);
768 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
773 // attacklab: strip sentinel
774 text = text.replace(/~0/,"");
779 _ProcessListItems = function(list_str) {
781 // Process the contents of a single ordered or unordered list, splitting it
782 // into individual list items.
784 // The $g_list_level global keeps track of when we're inside a list.
785 // Each time we enter a list, we increment it; when we leave a list,
786 // we decrement. If it's zero, we're not in a list anymore.
788 // We do this because when we're not inside a list, we want to treat
789 // something like this:
791 // I recommend upgrading to version
792 // 8. Oops, now this line is treated
795 // As a single paragraph, despite the fact that the second line starts
796 // with a digit-period-space sequence.
798 // Whereas when we're inside a list (or sub-list), that line will be
799 // treated as the start of a sub-list. What a kludge, huh? This is
800 // an aspect of Markdown's syntax that's hard to parse perfectly
801 // without resorting to mind-reading. Perhaps the solution is to
802 // change the syntax rules such that sub-lists must start with a
803 // starting cardinal number; e.g. "1." or "a.".
807 // trim trailing blank lines:
808 list_str = list_str.replace(/\n{2,}$/,"\n");
810 // attacklab: add sentinel to emulate \z
814 list_str = list_str.replace(/
815 (\n)? // leading line = $1
816 (^[ \t]*) // leading whitespace = $2
817 ([*+-]|\d+[.]) [ \t]+ // list marker = $3
818 ([^\r]+? // list item text = $4
820 (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
821 /gm, function(){...});
823 list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
824 function(wholeMatch,m1,m2,m3,m4){
826 var leading_line = m1;
827 var leading_space = m2;
829 if (leading_line || (item.search(/\n{2,}/)>-1)) {
830 item = _RunBlockGamut(_Outdent(item));
833 // Recursion for sub-lists:
834 item = _DoLists(_Outdent(item));
835 item = item.replace(/\n$/,""); // chomp(item)
836 item = _RunSpanGamut(item);
839 return "<li>" + item + "</li>\n";
843 // attacklab: strip sentinel
844 list_str = list_str.replace(/~0/g,"");
851 var _DoCodeBlocks = function(text) {
853 // Process Markdown `<pre><code>` blocks.
857 text = text.replace(text,
859 ( // $1 = the code block -- one or more lines, starting with a space/tab
861 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
865 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
869 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
872 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
873 function(wholeMatch,m1,m2) {
877 codeblock = _EncodeCode( _Outdent(codeblock));
878 codeblock = _Detab(codeblock);
879 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
880 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
882 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
884 return hashBlock(codeblock) + nextChar;
888 // attacklab: strip sentinel
889 text = text.replace(/~0/,"");
895 text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
898 // First parse the github code block
899 codeblock = _EncodeCode( codeblock);
900 codeblock = _Detab(codeblock);
901 codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
902 codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
904 codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
906 return hashBlock(codeblock) ;
909 // attacklab: strip sentinel
910 text = text.replace(/~0/, '');
916 var hashBlock = function(text) {
917 text = text.replace(/(^\n+|\n+$)/g,"");
918 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
922 var _DoCodeSpans = function(text) {
924 // * Backtick quotes are used for <code></code> spans.
926 // * You can use multiple backticks as the delimiters if you want to
927 // include literal backticks in the code span. So, this input:
929 // Just type ``foo `bar` baz`` at the prompt.
931 // Will translate to:
933 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
935 // There's no arbitrary limit to the number of backticks you
936 // can use as delimters. If you need three consecutive backticks
937 // in your code, use four for delimiters, etc.
939 // * You can use spaces to get literal backticks at the edges:
941 // ... type `` `bar` `` ...
945 // ... type <code>`bar`</code> ...
949 text = text.replace(/
950 (^|[^\\]) // Character before opening ` can't be a backslash
951 (`+) // $2 = Opening run of `
952 ( // $3 = The code block
954 [^`] // attacklab: work around lack of lookbehind
956 \2 // Matching closer
958 /gm, function(){...});
961 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
962 function(wholeMatch,m1,m2,m3,m4) {
964 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
965 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
967 return m1+"<code>"+c+"</code>";
974 var _EncodeCode = function(text) {
976 // Encode/escape certain characters inside Markdown code runs.
977 // The point is that in code, these characters are literals,
978 // and lose their special Markdown meanings.
980 // REMOVED - Data going into markdown should be encoded before it enters..
983 // Encode all ampersands; HTML entities are not
984 // entities within a Markdown code span.
987 //text = text.replace(/&/g,"&");
989 // Do the angle bracket song and dance:
990 //text = text.replace(/</g,"<");
991 //text = text.replace(/>/g,">");
993 // Now, escape characters that are magic in Markdown:
994 text = escapeCharacters(text,"\*_{}[]\\",false);
996 // jj the line above breaks this:
1010 var _DoItalicsAndBold = function(text) {
1012 // <strong> must go first:
1013 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
1014 "<strong>$2</strong>");
1016 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1023 var _DoBlockQuotes = function(text) {
1026 text = text.replace(/
1027 ( // Wrap whole match in $1
1029 ^[ \t]*>[ \t]? // '>' at the start of a line
1030 .+\n // rest of the first line
1031 (.+\n)* // subsequent consecutive lines
1035 /gm, function(){...});
1038 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1039 function(wholeMatch,m1) {
1042 // attacklab: hack around Konqueror 3.5.4 bug:
1043 // "----------bug".replace(/^-/g,"") == "bug"
1045 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1047 // attacklab: clean up hack
1048 bq = bq.replace(/~0/g,"");
1050 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1051 bq = _RunBlockGamut(bq); // recurse
1053 bq = bq.replace(/(^|\n)/g,"$1 ");
1054 // These leading spaces screw with <pre> content, so we need to fix that:
1056 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1057 function(wholeMatch,m1) {
1059 // attacklab: hack around Konqueror 3.5.4 bug:
1060 pre = pre.replace(/^ /mg,"~0");
1061 pre = pre.replace(/~0/g,"");
1065 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1071 var _FormParagraphs = function(text) {
1074 // $text - string to process with html <p> tags
1077 // Strip leading and trailing lines:
1078 text = text.replace(/^\n+/g,"");
1079 text = text.replace(/\n+$/g,"");
1081 var grafs = text.split(/\n{2,}/g);
1082 var grafsOut = new Array();
1087 var end = grafs.length;
1088 for (var i=0; i<end; i++) {
1091 // if this is an HTML marker, copy it
1092 if (str.search(/~K(\d+)K/g) >= 0) {
1095 else if (str.search(/\S/) >= 0) {
1096 str = _RunSpanGamut(str);
1097 str = str.replace(/^([ \t]*)/g,"<p>");
1105 // Unhashify HTML blocks
1107 end = grafsOut.length;
1108 for (var i=0; i<end; i++) {
1109 // if this is a marker for an html block...
1110 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1111 var blockText = g_html_blocks[RegExp.$1];
1112 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1113 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1117 return grafsOut.join("\n\n");
1121 var _EncodeAmpsAndAngles = function(text) {
1122 // Smart processing for ampersands and angle brackets that need to be encoded.
1124 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1125 // http://bumppo.net/projects/amputator/
1126 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1129 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1135 var _EncodeBackslashEscapes = function(text) {
1137 // Parameter: String.
1138 // Returns: The string, with after processing the following backslash
1139 // escape sequences.
1142 // attacklab: The polite way to do this is with the new
1143 // escapeCharacters() function:
1145 // text = escapeCharacters(text,"\\",true);
1146 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1148 // ...but we're sidestepping its use of the (slow) RegExp constructor
1149 // as an optimization for Firefox. This function gets called a LOT.
1151 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1152 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1157 var _DoAutoLinks = function(text) {
1159 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1161 // Email addresses: <address@domain.foo>
1164 text = text.replace(/
1170 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1173 /gi, _DoAutoLinks_callback());
1175 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1176 function(wholeMatch,m1) {
1177 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1185 var _EncodeEmailAddress = function(addr) {
1187 // Input: an email address, e.g. "foo@example.com"
1189 // Output: the email address as a mailto link, with each character
1190 // of the address encoded as either a decimal or hex entity, in
1191 // the hopes of foiling most address harvesting spam bots. E.g.:
1193 // <a href="mailto:foo@e
1194 // xample.com">foo
1195 // @example.com</a>
1197 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1198 // mailing list: <http://tinyurl.com/yu7ue>
1201 // attacklab: why can't javascript speak hex?
1202 function char2hex(ch) {
1203 var hexDigits = '0123456789ABCDEF';
1204 var dec = ch.charCodeAt(0);
1205 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1209 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1210 function(ch){return "&#x"+char2hex(ch)+";";},
1211 function(ch){return ch;}
1214 addr = "mailto:" + addr;
1216 addr = addr.replace(/./g, function(ch) {
1218 // this *must* be encoded. I insist.
1219 ch = encode[Math.floor(Math.random()*2)](ch);
1220 } else if (ch !=":") {
1221 // leave ':' alone (to spot mailto: later)
1222 var r = Math.random();
1223 // roughly 10% raw, 45% hex, 45% dec
1225 r > .9 ? encode[2](ch) :
1226 r > .45 ? encode[1](ch) :
1233 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1234 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1240 var _UnescapeSpecialChars = function(text) {
1242 // Swap back in all the special characters we've hidden.
1244 text = text.replace(/~E(\d+)E/g,
1245 function(wholeMatch,m1) {
1246 var charCodeToReplace = parseInt(m1);
1247 return String.fromCharCode(charCodeToReplace);
1254 var _Outdent = function(text) {
1256 // Remove one level of line-leading tabs or spaces
1259 // attacklab: hack around Konqueror 3.5.4 bug:
1260 // "----------bug".replace(/^-/g,"") == "bug"
1262 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1264 // attacklab: clean up hack
1265 text = text.replace(/~0/g,"");
1270 var _Detab = function(text) {
1271 // attacklab: Detab's completely rewritten for speed.
1272 // In perl we could fix it by anchoring the regexp with \G.
1273 // In javascript we're less fortunate.
1275 // expand first n-1 tabs
1276 text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
1278 // replace the nth with two sentinels
1279 text = text.replace(/\t/g,"~A~B");
1281 // use the sentinel to anchor our regex so it doesn't explode
1282 text = text.replace(/~B(.+?)~A/g,
1283 function(wholeMatch,m1,m2) {
1284 var leadingText = m1;
1285 var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
1287 // there *must* be a better way to do this:
1288 for (var i=0; i<numSpaces; i++) leadingText+=" ";
1294 // clean up sentinels
1295 text = text.replace(/~A/g," "); // attacklab: g_tab_width
1296 text = text.replace(/~B/g,"");
1303 // attacklab: Utility functions
1307 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1308 // First we have to escape the escape characters so that
1309 // we can build a character class out of them
1310 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1312 if (afterBackslash) {
1313 regexString = "\\\\" + regexString;
1316 var regex = new RegExp(regexString,"g");
1317 text = text.replace(regex,escapeCharacters_callback);
1323 var escapeCharacters_callback = function(wholeMatch,m1) {
1324 var charCodeToEscape = m1.charCodeAt(0);
1325 return "~E"+charCodeToEscape+"E";
1328 } // end of Showdown.converter
1331 //if (typeof exports != 'undefined') exports.Showdown = Showdown;