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 html = Roo.ux.Showdown.makeHtml(text);
58 // Note: move the sample code to the bottom of this
59 // file before uncommenting it.
66 Roo.namespace('Roo.ux');
68 Roo.ux.Showdown.makeHTML = function(text) {
69 var c = new Roo.ux.Showdown.converter();
70 return c.makeHtml(text);
75 // Wraps all "globals" so that the only thing
76 // exposed is makeHtml().
78 Roo.ux.Showdown.converter = function() {
84 // Global hashes, used by various utility routines
89 // Used to track when we're inside an ordered or unordered list
90 // (see _ProcessListItems() for details):
94 this.makeHtml = function(text) {
96 // Main function. The order in which other subs are called here is
97 // essential. Link and image substitutions need to happen before
98 // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
99 // and <img> tags get encoded.
102 // Clear the global hashes. If we don't clear these, you get conflicts
103 // from other articles when generating a page which contains more than
104 // one article (e.g. an index page that shows the N most recent
106 g_urls = new Array();
107 g_titles = new Array();
108 g_html_blocks = new Array();
110 // attacklab: Replace ~ with ~T
111 // This lets us use tilde as an escape char to avoid md5 hashes
112 // The choice of character is arbitray; anything that isn't
113 // magic in Markdown will work.
114 text = text.replace(/~/g,"~T");
116 // attacklab: Replace $ with ~D
117 // RegExp interprets $ as a special character
118 // when it's in a replacement string
119 text = text.replace(/\$/g,"~D");
121 // Standardize line endings
122 text = text.replace(/\r\n/g,"\n"); // DOS to Unix
123 text = text.replace(/\r/g,"\n"); // Mac to Unix
125 // Make sure text begins and ends with a couple of newlines:
126 text = "\n\n" + text + "\n\n";
128 // Convert all tabs to spaces.
131 // Strip any lines consisting only of spaces and tabs.
132 // This makes subsequent regexen easier to write, because we can
133 // match consecutive blank lines with /\n+/ instead of something
134 // contorted like /[ \t]*\n+/ .
135 text = text.replace(/^[ \t]+$/mg,"");
137 // Turn block-level HTML blocks into hash entries
138 text = _HashHTMLBlocks(text);
140 // Strip link definitions, store in hashes.
141 text = _StripLinkDefinitions(text);
143 text = _RunBlockGamut(text);
145 text = _UnescapeSpecialChars(text);
147 // attacklab: Restore dollar signs
148 text = text.replace(/~D/g,"$$");
150 // attacklab: Restore tildes
151 text = text.replace(/~T/g,"~");
157 var _StripLinkDefinitions = function(text) {
159 // Strips link definitions from text, stores the URLs and titles in
163 // Link defs are in the form: ^[id]: url "optional title"
166 var text = text.replace(/
167 ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
169 \n? // maybe *one* newline
171 <?(\S+?)>? // url = $2
173 \n? // maybe one newline
176 (\n*) // any lines skipped = $3 attacklab: lookbehind removed
181 )? // title is optional
186 text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
187 function (wholeMatch,m1,m2,m3,m4) {
188 m1 = m1.toLowerCase();
189 g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
191 // Oops, found blank lines, so it's not a title.
192 // Put back the parenthetical statement we stole.
195 g_titles[m1] = m4.replace(/"/g,""");
198 // Completely remove the definition from the text
207 var _HashHTMLBlocks = function(text) {
208 // attacklab: Double up blank lines to reduce lookaround
209 text = text.replace(/\n/g,"\n\n");
211 // Hashify HTML blocks:
212 // We only want to do this for block-level HTML tags, such as headers,
213 // lists, and tables. That's because we still want to wrap <p>s around
214 // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
215 // phrase emphasis, and spans. The list of tags we're looking for is
217 var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
218 var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
220 // First, look for nested blocks, e.g.:
223 // tags for inner block must be indented.
227 // The outermost tags must start at the left margin for this to match, and
228 // the inner nested divs must be indented.
229 // We need to do this before the next, more liberal match, because the next
230 // match will start at the first `<div>` and stop at the first `</div>`.
232 // attacklab: This regex can be expensive when it fails.
234 var text = text.replace(/
236 ^ // start of line (with /m)
237 <($block_tags_a) // start tag = $2
239 // attacklab: hack around khtml/pcre bug...
240 [^\r]*?\n // any number of lines, minimally matching
241 </\2> // the matching end tag
242 [ \t]* // trailing spaces/tabs
243 (?=\n+) // followed by a newline
244 ) // attacklab: there are sentinel newlines at end of document
245 /gm,function(){...}};
247 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);
250 // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
254 var text = text.replace(/
256 ^ // start of line (with /m)
257 <($block_tags_b) // start tag = $2
259 // attacklab: hack around khtml/pcre bug...
260 [^\r]*? // any number of lines, minimally matching
261 .*</\2> // the matching end tag
262 [ \t]* // trailing spaces/tabs
263 (?=\n+) // followed by a newline
264 ) // attacklab: there are sentinel newlines at end of document
265 /gm,function(){...}};
267 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);
269 // Special case just for <hr />. It was easier to make a special case than
270 // to make the other regex more complicated.
273 text = text.replace(/
275 \n\n // Starting after a blank line
277 (<(hr) // start tag = $2
280 \/?>) // the matching end tag
282 (?=\n{2,}) // followed by a blank line
286 text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
288 // Special case for standalone HTML comments:
291 text = text.replace(/
293 \n\n // Starting after a blank line
294 [ ]{0,3} // attacklab: g_tab_width - 1
299 (?=\n{2,}) // followed by a blank line
303 text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
305 // PHP and ASP-style processor instructions (<?...?> and <%...%>)
308 text = text.replace(/
310 \n\n // Starting after a blank line
313 [ ]{0,3} // attacklab: g_tab_width - 1
320 (?=\n{2,}) // followed by a blank line
324 text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
326 // attacklab: Undo double lines (see comment at top of this function)
327 text = text.replace(/\n\n/g,"\n");
331 var hashElement = function(wholeMatch,m1) {
335 blockText = blockText.replace(/\n\n/g,"\n");
336 blockText = blockText.replace(/^\n/,"");
338 // strip trailing blank lines
339 blockText = blockText.replace(/\n+$/g,"");
341 // Replace the element text with a marker ("~KxK" where x is its key)
342 blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
347 var _RunBlockGamut = function(text) {
349 // These are all the transformations that form block-level
350 // tags like paragraphs, headers, and list items.
352 text = _DoHeaders(text);
354 // Do Horizontal Rules:
355 var key = hashBlock("<hr />");
356 text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
357 text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
358 text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
360 text = _DoLists(text);
361 text = _DoCodeBlocks(text);
362 text = _DoBlockQuotes(text);
364 // We already ran _HashHTMLBlocks() before, in Markdown(), but that
365 // was to escape raw HTML in the original Markdown source. This time,
366 // we're escaping the markup we've just created, so that we don't wrap
367 // <p> tags around block-level tags.
368 text = _HashHTMLBlocks(text);
369 text = _FormParagraphs(text);
375 var _RunSpanGamut = function(text) {
377 // These are all the transformations that occur *within* block-level
378 // tags like paragraphs, headers, and list items.
381 text = _DoCodeSpans(text);
382 text = _EscapeSpecialCharsWithinTagAttributes(text);
383 text = _EncodeBackslashEscapes(text);
385 // Process anchor and image tags. Images must come first,
386 // because ![foo][f] looks like an anchor.
387 text = _DoImages(text);
388 text = _DoAnchors(text);
390 // Make links out of things like `<http://example.com/>`
391 // Must come after _DoAnchors(), because you can use < and >
392 // delimiters in inline links like [this](<url>).
393 text = _DoAutoLinks(text);
394 text = _EncodeAmpsAndAngles(text);
395 text = _DoItalicsAndBold(text);
398 text = text.replace(/ +\n/g," <br />\n");
403 var _EscapeSpecialCharsWithinTagAttributes = function(text) {
405 // Within tags -- meaning between < and > -- encode [\ ` * _] so they
406 // don't conflict with their use in Markdown for code, italics and strong.
409 // Build a regex to find HTML tags and comments. See Friedl's
410 // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
411 var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
413 text = text.replace(regex, function(wholeMatch) {
414 var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
415 tag = escapeCharacters(tag,"\\`*_");
422 var _DoAnchors = function(text) {
424 // Turn Markdown link shortcuts into XHTML <a> tags.
427 // First, handle reference-style links: [link text] [id]
431 text = text.replace(/
432 ( // wrap whole match in $1
436 \[[^\]]*\] // allow brackets nested one level
438 [^\[] // or anything else
443 [ ]? // one optional space
444 (?:\n[ ]*)? // one optional newline followed by spaces
449 )()()()() // pad remaining backreferences
450 /g,_DoAnchors_callback);
452 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
455 // Next, inline-style links: [link text](url "optional title")
459 text = text.replace(/
460 ( // wrap whole match in $1
464 \[[^\]]*\] // allow brackets nested one level
466 [^\[\]] // or anything else
472 () // no id, so leave $3 empty
473 <?(.*?)>? // href = $4
476 (['"]) // quote char = $6
479 [ \t]* // ignore any spaces/tabs between closing quote and )
480 )? // title is optional
485 text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
488 // Last, handle reference-style shortcuts: [link text]
489 // These must come last in case you've also got [link test][1]
490 // or [link test](/foo)
494 text = text.replace(/
495 ( // wrap whole match in $1
497 ([^\[\]]+) // link text = $2; can't contain '[' or ']'
499 )()()()()() // pad rest of backreferences
502 text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
507 var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
508 if (m7 == undefined) m7 = "";
509 var whole_match = m1;
511 var link_id = m3.toLowerCase();
517 // lower-case and turn embedded newlines into spaces
518 link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
522 if (g_urls[link_id] != undefined) {
523 url = g_urls[link_id];
524 if (g_titles[link_id] != undefined) {
525 title = g_titles[link_id];
529 if (whole_match.search(/\(\s*\)$/m)>-1) {
530 // Special case for explicit empty url
538 url = escapeCharacters(url,"*_");
539 var result = "<a href=\"" + url + "\"";
542 title = title.replace(/"/g,""");
543 title = escapeCharacters(title,"*_");
544 result += " title=\"" + title + "\"";
547 result += ">" + link_text + "</a>";
553 var _DoImages = function(text) {
555 // Turn Markdown image shortcuts into <img> tags.
559 // First, handle reference-style labeled images: ![alt text][id]
563 text = text.replace(/
564 ( // wrap whole match in $1
566 (.*?) // alt text = $2
569 [ ]? // one optional space
570 (?:\n[ ]*)? // one optional newline followed by spaces
575 )()()()() // pad rest of backreferences
578 text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
581 // Next, handle inline images: ![alt text](url "optional title")
582 // Don't forget: encode * and _
585 text = text.replace(/
586 ( // wrap whole match in $1
588 (.*?) // alt text = $2
590 \s? // One optional whitespace character
593 () // no id, so leave $3 empty
594 <?(\S+?)>? // src url = $4
597 (['"]) // quote char = $6
601 )? // title is optional
606 text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
611 var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
612 var whole_match = m1;
614 var link_id = m3.toLowerCase();
618 if (!title) title = "";
622 // lower-case and turn embedded newlines into spaces
623 link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
627 if (g_urls[link_id] != undefined) {
628 url = g_urls[link_id];
629 if (g_titles[link_id] != undefined) {
630 title = g_titles[link_id];
638 alt_text = alt_text.replace(/"/g,""");
639 url = escapeCharacters(url,"*_");
640 var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
642 // attacklab: Markdown.pl adds empty title attributes to images.
643 // Replicate this bug.
646 title = title.replace(/"/g,""");
647 title = escapeCharacters(title,"*_");
648 result += " title=\"" + title + "\"";
657 var _DoHeaders = function(text) {
659 // Setext-style headers:
666 text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
667 function(wholeMatch,m1){return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");});
669 text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
670 function(matchFound,m1){return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");});
672 // atx-style headers:
675 // ## Header 2 with closing hashes ##
681 text = text.replace(/
682 ^(\#{1,6}) // $1 = string of #'s
684 (.+?) // $2 = Header text
686 \#* // optional closing #'s (not counted)
688 /gm, function() {...});
691 text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
692 function(wholeMatch,m1,m2) {
693 var h_level = m1.length;
694 return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
697 function headerId(m) {
698 return m.replace(/[^\w]/g, '').toLowerCase();
703 // This declaration keeps Dojo compressor from outputting garbage:
704 var _ProcessListItems;
706 var _DoLists = function(text) {
708 // Form HTML ordered (numbered) and unordered (bulleted) lists.
711 // attacklab: add sentinel to hack around khtml/safari bug:
712 // http://bugs.webkit.org/show_bug.cgi?id=11231
715 // Re-usable pattern to match any entirel ul or ol list:
721 [ ]{0,3} // attacklab: g_tab_width - 1
722 ([*+-]|\d+[.]) // $3 = first list item marker
727 ~0 // sentinel for workaround; should be $
731 (?! // Negative lookahead for another list item marker
733 (?:[*+-]|\d+[.])[ \t]+
738 var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
741 text = text.replace(whole_list,function(wholeMatch,m1,m2) {
743 var list_type = (m2.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 list = list.replace(/\n{2,}/g,"\n\n\n");;
748 var result = _ProcessListItems(list);
750 // Trim any trailing whitespace, to put the closing `</$list_type>`
751 // up on the preceding line, to get it past the current stupid
752 // HTML block parser. This is a hack to work around the terrible
753 // hack that is the HTML block parser.
754 result = result.replace(/\s+$/,"");
755 result = "<"+list_type+">" + result + "</"+list_type+">\n";
759 whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
760 text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
764 var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
765 // Turn double returns into triple returns, so that we can make a
766 // paragraph for the last item in a list, if necessary:
767 var list = list.replace(/\n{2,}/g,"\n\n\n");;
768 var result = _ProcessListItems(list);
769 result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
774 // attacklab: strip sentinel
775 text = text.replace(/~0/,"");
780 _ProcessListItems = function(list_str) {
782 // Process the contents of a single ordered or unordered list, splitting it
783 // into individual list items.
785 // The $g_list_level global keeps track of when we're inside a list.
786 // Each time we enter a list, we increment it; when we leave a list,
787 // we decrement. If it's zero, we're not in a list anymore.
789 // We do this because when we're not inside a list, we want to treat
790 // something like this:
792 // I recommend upgrading to version
793 // 8. Oops, now this line is treated
796 // As a single paragraph, despite the fact that the second line starts
797 // with a digit-period-space sequence.
799 // Whereas when we're inside a list (or sub-list), that line will be
800 // treated as the start of a sub-list. What a kludge, huh? This is
801 // an aspect of Markdown's syntax that's hard to parse perfectly
802 // without resorting to mind-reading. Perhaps the solution is to
803 // change the syntax rules such that sub-lists must start with a
804 // starting cardinal number; e.g. "1." or "a.".
808 // trim trailing blank lines:
809 list_str = list_str.replace(/\n{2,}$/,"\n");
811 // attacklab: add sentinel to emulate \z
815 list_str = list_str.replace(/
816 (\n)? // leading line = $1
817 (^[ \t]*) // leading whitespace = $2
818 ([*+-]|\d+[.]) [ \t]+ // list marker = $3
819 ([^\r]+? // list item text = $4
821 (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
822 /gm, function(){...});
824 list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
825 function(wholeMatch,m1,m2,m3,m4){
827 var leading_line = m1;
828 var leading_space = m2;
830 if (leading_line || (item.search(/\n{2,}/)>-1)) {
831 item = _RunBlockGamut(_Outdent(item));
834 // Recursion for sub-lists:
835 item = _DoLists(_Outdent(item));
836 item = item.replace(/\n$/,""); // chomp(item)
837 item = _RunSpanGamut(item);
840 return "<li>" + item + "</li>\n";
844 // attacklab: strip sentinel
845 list_str = list_str.replace(/~0/g,"");
852 var _DoCodeBlocks = function(text) {
854 // Process Markdown `<pre><code>` blocks.
858 text = text.replace(text,
860 ( // $1 = the code block -- one or more lines, starting with a space/tab
862 (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
866 (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
870 // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
873 text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
874 function(wholeMatch,m1,m2) {
878 codeblock = _EncodeCode( _Outdent(codeblock));
879 codeblock = _Detab(codeblock);
880 codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
881 codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
883 codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
885 return hashBlock(codeblock) + nextChar;
889 // attacklab: strip sentinel
890 text = text.replace(/~0/,"");
895 var hashBlock = function(text) {
896 text = text.replace(/(^\n+|\n+$)/g,"");
897 return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
901 var _DoCodeSpans = function(text) {
903 // * Backtick quotes are used for <code></code> spans.
905 // * You can use multiple backticks as the delimiters if you want to
906 // include literal backticks in the code span. So, this input:
908 // Just type ``foo `bar` baz`` at the prompt.
910 // Will translate to:
912 // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
914 // There's no arbitrary limit to the number of backticks you
915 // can use as delimters. If you need three consecutive backticks
916 // in your code, use four for delimiters, etc.
918 // * You can use spaces to get literal backticks at the edges:
920 // ... type `` `bar` `` ...
924 // ... type <code>`bar`</code> ...
928 text = text.replace(/
929 (^|[^\\]) // Character before opening ` can't be a backslash
930 (`+) // $2 = Opening run of `
931 ( // $3 = The code block
933 [^`] // attacklab: work around lack of lookbehind
935 \2 // Matching closer
937 /gm, function(){...});
940 text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
941 function(wholeMatch,m1,m2,m3,m4) {
943 c = c.replace(/^([ \t]*)/g,""); // leading whitespace
944 c = c.replace(/[ \t]*$/g,""); // trailing whitespace
946 return m1+"<code>"+c+"</code>";
953 var _EncodeCode = function(text) {
955 // Encode/escape certain characters inside Markdown code runs.
956 // The point is that in code, these characters are literals,
957 // and lose their special Markdown meanings.
959 // Encode all ampersands; HTML entities are not
960 // entities within a Markdown code span.
961 text = text.replace(/&/g,"&");
963 // Do the angle bracket song and dance:
964 text = text.replace(/</g,"<");
965 text = text.replace(/>/g,">");
967 // Now, escape characters that are magic in Markdown:
968 text = escapeCharacters(text,"\*_{}[]\\",false);
970 // jj the line above breaks this:
984 var _DoItalicsAndBold = function(text) {
986 // <strong> must go first:
987 text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
988 "<strong>$2</strong>");
990 text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
997 var _DoBlockQuotes = function(text) {
1000 text = text.replace(/
1001 ( // Wrap whole match in $1
1003 ^[ \t]*>[ \t]? // '>' at the start of a line
1004 .+\n // rest of the first line
1005 (.+\n)* // subsequent consecutive lines
1009 /gm, function(){...});
1012 text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1013 function(wholeMatch,m1) {
1016 // attacklab: hack around Konqueror 3.5.4 bug:
1017 // "----------bug".replace(/^-/g,"") == "bug"
1019 bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1021 // attacklab: clean up hack
1022 bq = bq.replace(/~0/g,"");
1024 bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1025 bq = _RunBlockGamut(bq); // recurse
1027 bq = bq.replace(/(^|\n)/g,"$1 ");
1028 // These leading spaces screw with <pre> content, so we need to fix that:
1030 /(\s*<pre>[^\r]+?<\/pre>)/gm,
1031 function(wholeMatch,m1) {
1033 // attacklab: hack around Konqueror 3.5.4 bug:
1034 pre = pre.replace(/^ /mg,"~0");
1035 pre = pre.replace(/~0/g,"");
1039 return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1045 var _FormParagraphs = function(text) {
1048 // $text - string to process with html <p> tags
1051 // Strip leading and trailing lines:
1052 text = text.replace(/^\n+/g,"");
1053 text = text.replace(/\n+$/g,"");
1055 var grafs = text.split(/\n{2,}/g);
1056 var grafsOut = new Array();
1061 var end = grafs.length;
1062 for (var i=0; i<end; i++) {
1065 // if this is an HTML marker, copy it
1066 if (str.search(/~K(\d+)K/g) >= 0) {
1069 else if (str.search(/\S/) >= 0) {
1070 str = _RunSpanGamut(str);
1071 str = str.replace(/^([ \t]*)/g,"<p>");
1079 // Unhashify HTML blocks
1081 end = grafsOut.length;
1082 for (var i=0; i<end; i++) {
1083 // if this is a marker for an html block...
1084 while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1085 var blockText = g_html_blocks[RegExp.$1];
1086 blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1087 grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1091 return grafsOut.join("\n\n");
1095 var _EncodeAmpsAndAngles = function(text) {
1096 // Smart processing for ampersands and angle brackets that need to be encoded.
1098 // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1099 // http://bumppo.net/projects/amputator/
1100 text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&");
1103 text = text.replace(/<(?![a-z\/?\$!])/gi,"<");
1109 var _EncodeBackslashEscapes = function(text) {
1111 // Parameter: String.
1112 // Returns: The string, with after processing the following backslash
1113 // escape sequences.
1116 // attacklab: The polite way to do this is with the new
1117 // escapeCharacters() function:
1119 // text = escapeCharacters(text,"\\",true);
1120 // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1122 // ...but we're sidestepping its use of the (slow) RegExp constructor
1123 // as an optimization for Firefox. This function gets called a LOT.
1125 text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1126 text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1131 var _DoAutoLinks = function(text) {
1133 text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1135 // Email addresses: <address@domain.foo>
1138 text = text.replace(/
1144 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1147 /gi, _DoAutoLinks_callback());
1149 text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1150 function(wholeMatch,m1) {
1151 return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1159 var _EncodeEmailAddress = function(addr) {
1161 // Input: an email address, e.g. "foo@example.com"
1163 // Output: the email address as a mailto link, with each character
1164 // of the address encoded as either a decimal or hex entity, in
1165 // the hopes of foiling most address harvesting spam bots. E.g.:
1167 // <a href="mailto:foo@e
1168 // xample.com">foo
1169 // @example.com</a>
1171 // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1172 // mailing list: <http://tinyurl.com/yu7ue>
1175 // attacklab: why can't javascript speak hex?
1176 function char2hex(ch) {
1177 var hexDigits = '0123456789ABCDEF';
1178 var dec = ch.charCodeAt(0);
1179 return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1183 function(ch){return "&#"+ch.charCodeAt(0)+";";},
1184 function(ch){return "&#x"+char2hex(ch)+";";},
1185 function(ch){return ch;}
1188 addr = "mailto:" + addr;
1190 addr = addr.replace(/./g, function(ch) {
1192 // this *must* be encoded. I insist.
1193 ch = encode[Math.floor(Math.random()*2)](ch);
1194 } else if (ch !=":") {
1195 // leave ':' alone (to spot mailto: later)
1196 var r = Math.random();
1197 // roughly 10% raw, 45% hex, 45% dec
1199 r > .9 ? encode[2](ch) :
1200 r > .45 ? encode[1](ch) :
1207 addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1208 addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1214 var _UnescapeSpecialChars = function(text) {
1216 // Swap back in all the special characters we've hidden.
1218 text = text.replace(/~E(\d+)E/g,
1219 function(wholeMatch,m1) {
1220 var charCodeToReplace = parseInt(m1);
1221 return String.fromCharCode(charCodeToReplace);
1228 var _Outdent = function(text) {
1230 // Remove one level of line-leading tabs or spaces
1233 // attacklab: hack around Konqueror 3.5.4 bug:
1234 // "----------bug".replace(/^-/g,"") == "bug"
1236 text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1238 // attacklab: clean up hack
1239 text = text.replace(/~0/g,"")
1244 var _Detab = function(text) {
1245 // attacklab: Detab's completely rewritten for speed.
1246 // In perl we could fix it by anchoring the regexp with \G.
1247 // In javascript we're less fortunate.
1249 // expand first n-1 tabs
1250 text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
1252 // replace the nth with two sentinels
1253 text = text.replace(/\t/g,"~A~B");
1255 // use the sentinel to anchor our regex so it doesn't explode
1256 text = text.replace(/~B(.+?)~A/g,
1257 function(wholeMatch,m1,m2) {
1258 var leadingText = m1;
1259 var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
1261 // there *must* be a better way to do this:
1262 for (var i=0; i<numSpaces; i++) leadingText+=" ";
1268 // clean up sentinels
1269 text = text.replace(/~A/g," "); // attacklab: g_tab_width
1270 text = text.replace(/~B/g,"");
1277 // attacklab: Utility functions
1281 var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1282 // First we have to escape the escape characters so that
1283 // we can build a character class out of them
1284 var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1286 if (afterBackslash) {
1287 regexString = "\\\\" + regexString;
1290 var regex = new RegExp(regexString,"g");
1291 text = text.replace(regex,escapeCharacters_callback);
1297 var escapeCharacters_callback = function(wholeMatch,m1) {
1298 var charCodeToEscape = m1.charCodeAt(0);
1299 return "~E"+charCodeToEscape+"E";
1302 } // end of Showdown.converter
1305 //if (typeof exports != 'undefined') exports.Showdown = Showdown;