pagedown-bootstrap-rails 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/Readme.md ADDED
@@ -0,0 +1,67 @@
1
+ # PageDown Bootstrap Rails
2
+
3
+ A Ruby gem version of [https://github.com/tchapi/pagedown-bootstrap](https://github.com/tchapi/pagedown-bootstrap) for the Rails asset pipeline.
4
+
5
+ ## Installation
6
+
7
+ Add to your `Gemfile`:
8
+
9
+ gem 'pagedown-bootstrap-rails'
10
+
11
+ In Rails 3.1 or Rails 3.2 this goes in the `:asset` group, but in Rails 4 it goes with the top level gems.
12
+
13
+ ## Usage
14
+
15
+ Require the CSS with Sprockets:
16
+
17
+ /*= require pagedown_bootstrap */
18
+
19
+ Or with a SASS import:
20
+
21
+ @import "pagedown_bootstrap";
22
+
23
+ Sprockets require the JS too:
24
+
25
+ //= require pagedown_bootstrap
26
+
27
+ Or individually as you please:
28
+
29
+ //= require markdown.converter
30
+ //= require markdown.editor
31
+ //= require markdown.sanitizer
32
+
33
+ You will need to instantiate PageDown. I recommend a `lib/assets/javascripts/pagedown_init.js.coffee` that contains:
34
+
35
+ $ ->
36
+ $('textarea.wmd-input').each (i, input) ->
37
+ attr = $(input).attr('id').split('wmd-input')[1]
38
+ converter = new Markdown.Converter()
39
+ editor = new Markdown.Editor(converter, attr)
40
+ editor.run()
41
+
42
+ Require it with Sprockets:
43
+
44
+ //= require pagedown_bootstrap
45
+ //= require pagedown_init
46
+
47
+ Then combine it with a new [SimpleForm](https://github.com/plataformatec/simple_form) input:
48
+
49
+ class PagedownInput < SimpleForm::Inputs::TextInput
50
+ def input
51
+ out = "<div id=\"wmd-button-bar-#{attribute_name}\"></div>\n"
52
+ out << "#{@builder.text_area(attribute_name, input_html_options.merge(
53
+ { :class => 'wmd-input', :id => "wmd-input-#{attribute_name}"})) }"
54
+ if input_html_options[:preview]
55
+ out << "<div id=\"wmd-preview-#{attribute_name}\" class=\"wmd-preview\"></div>"
56
+ end
57
+ out.html_safe
58
+ end
59
+ end
60
+
61
+ Which you use in your form like so:
62
+
63
+ = f.input :description, :as => :pagedown, :input_html => { :preview => true }
64
+
65
+ This is how it looks:
66
+
67
+ ![Glorious](http://f.cl.ly/items/1f2H1x1F1D0o0n2r1p02/pagedown-bootstrap.png)
@@ -0,0 +1 @@
1
+ require 'pagedown_bootstrap/rails'
@@ -0,0 +1,2 @@
1
+ require 'pagedown_bootstrap/rails/engine'
2
+ require 'pagedown_bootstrap/rails/version'
@@ -0,0 +1,6 @@
1
+ module PageDownBootstrap
2
+ module Rails
3
+ class Engine < ::Rails::Engine
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,5 @@
1
+ module PageDownBootstrap
2
+ module Rails
3
+ VERSION = "1.0.0"
4
+ end
5
+ end
@@ -0,0 +1,1349 @@
1
+ var Markdown;
2
+
3
+ if (typeof exports === "object" && typeof require === "function") // we're in a CommonJS (e.g. Node.js) module
4
+ Markdown = exports;
5
+ else
6
+ Markdown = {};
7
+
8
+ // The following text is included for historical reasons, but should
9
+ // be taken with a pinch of salt; it's not all true anymore.
10
+
11
+ //
12
+ // Wherever possible, Showdown is a straight, line-by-line port
13
+ // of the Perl version of Markdown.
14
+ //
15
+ // This is not a normal parser design; it's basically just a
16
+ // series of string substitutions. It's hard to read and
17
+ // maintain this way, but keeping Showdown close to the original
18
+ // design makes it easier to port new features.
19
+ //
20
+ // More importantly, Showdown behaves like markdown.pl in most
21
+ // edge cases. So web applications can do client-side preview
22
+ // in Javascript, and then build identical HTML on the server.
23
+ //
24
+ // This port needs the new RegExp functionality of ECMA 262,
25
+ // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
26
+ // should do fine. Even with the new regular expression features,
27
+ // We do a lot of work to emulate Perl's regex functionality.
28
+ // The tricky changes in this file mostly have the "attacklab:"
29
+ // label. Major or self-explanatory changes don't.
30
+ //
31
+ // Smart diff tools like Araxis Merge will be able to match up
32
+ // this file with markdown.pl in a useful way. A little tweaking
33
+ // helps: in a copy of markdown.pl, replace "#" with "//" and
34
+ // replace "$text" with "text". Be sure to ignore whitespace
35
+ // and line endings.
36
+ //
37
+
38
+
39
+ //
40
+ // Usage:
41
+ //
42
+ // var text = "Markdown *rocks*.";
43
+ //
44
+ // var converter = new Markdown.Converter(autolink); // where autolink is true or false, defaults to false
45
+ // var html = converter.makeHtml(text);
46
+ //
47
+ // alert(html);
48
+ //
49
+ // Note: move the sample code to the bottom of this
50
+ // file before uncommenting it.
51
+ //
52
+
53
+ (function () {
54
+
55
+ function identity(x) { return x; }
56
+ function returnFalse(x) { return false; }
57
+
58
+ function HookCollection() { }
59
+
60
+ HookCollection.prototype = {
61
+
62
+ chain: function (hookname, func) {
63
+ var original = this[hookname];
64
+ if (!original)
65
+ throw new Error("unknown hook " + hookname);
66
+
67
+ if (original === identity)
68
+ this[hookname] = func;
69
+ else
70
+ this[hookname] = function (x) { return func(original(x)); }
71
+ },
72
+ set: function (hookname, func) {
73
+ if (!this[hookname])
74
+ throw new Error("unknown hook " + hookname);
75
+ this[hookname] = func;
76
+ },
77
+ addNoop: function (hookname) {
78
+ this[hookname] = identity;
79
+ },
80
+ addFalse: function (hookname) {
81
+ this[hookname] = returnFalse;
82
+ }
83
+ };
84
+
85
+ Markdown.HookCollection = HookCollection;
86
+
87
+ // g_urls and g_titles allow arbitrary user-entered strings as keys. This
88
+ // caused an exception (and hence stopped the rendering) when the user entered
89
+ // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this
90
+ // (since no builtin property starts with "s_"). See
91
+ // http://meta.stackoverflow.com/questions/64655/strange-wmd-bug
92
+ // (granted, switching from Array() to Object() alone would have left only __proto__
93
+ // to be a problem)
94
+ function SaveHash() { }
95
+ SaveHash.prototype = {
96
+ set: function (key, value) {
97
+ this["s_" + key] = value;
98
+ },
99
+ get: function (key) {
100
+ return this["s_" + key];
101
+ }
102
+ };
103
+
104
+ Markdown.Converter = function (autolink) {
105
+ var pluginHooks = this.hooks = new HookCollection();
106
+ pluginHooks.addNoop("plainLinkText"); // given a URL that was encountered by itself (without markup), should return the link text that's to be given to this link
107
+ pluginHooks.addNoop("preConversion"); // called with the orignal text as given to makeHtml. The result of this plugin hook is the actual markdown source that will be cooked
108
+ pluginHooks.addNoop("postConversion"); // called with the final cooked HTML code. The result of this plugin hook is the actual output of makeHtml
109
+
110
+ //
111
+ // Private state of the converter instance:
112
+ //
113
+
114
+ // Aloow for automatic linking
115
+ var g_autolink = (autolink === true);
116
+
117
+ // Global hashes, used by various utility routines
118
+ var g_urls;
119
+ var g_titles;
120
+ var g_html_blocks;
121
+
122
+ // Used to track when we're inside an ordered or unordered list
123
+ // (see _ProcessListItems() for details):
124
+ var g_list_level;
125
+
126
+ this.makeHtml = function (text) {
127
+
128
+ //
129
+ // Main function. The order in which other subs are called here is
130
+ // essential. Link and image substitutions need to happen before
131
+ // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
132
+ // and <img> tags get encoded.
133
+ //
134
+
135
+ // This will only happen if makeHtml on the same converter instance is called from a plugin hook.
136
+ // Don't do that.
137
+ if (g_urls)
138
+ throw new Error("Recursive call to converter.makeHtml");
139
+
140
+ // Create the private state objects.
141
+ g_urls = new SaveHash();
142
+ g_titles = new SaveHash();
143
+ g_html_blocks = [];
144
+ g_list_level = 0;
145
+
146
+ text = pluginHooks.preConversion(text);
147
+
148
+ // attacklab: Replace ~ with ~T
149
+ // This lets us use tilde as an escape char to avoid md5 hashes
150
+ // The choice of character is arbitray; anything that isn't
151
+ // magic in Markdown will work.
152
+ text = text.replace(/~/g, "~T");
153
+
154
+ // attacklab: Replace $ with ~D
155
+ // RegExp interprets $ as a special character
156
+ // when it's in a replacement string
157
+ text = text.replace(/\$/g, "~D");
158
+
159
+ // Standardize line endings
160
+ text = text.replace(/\r\n/g, "\n"); // DOS to Unix
161
+ text = text.replace(/\r/g, "\n"); // Mac to Unix
162
+
163
+ // Make sure text begins and ends with a couple of newlines:
164
+ text = "\n\n" + text + "\n\n";
165
+
166
+ // Convert all tabs to spaces.
167
+ text = _Detab(text);
168
+
169
+ // Strip any lines consisting only of spaces and tabs.
170
+ // This makes subsequent regexen easier to write, because we can
171
+ // match consecutive blank lines with /\n+/ instead of something
172
+ // contorted like /[ \t]*\n+/ .
173
+ text = text.replace(/^[ \t]+$/mg, "");
174
+
175
+ // Turn block-level HTML blocks into hash entries
176
+ text = _HashHTMLBlocks(text);
177
+
178
+ // Strip link definitions, store in hashes.
179
+ text = _StripLinkDefinitions(text);
180
+
181
+ text = _RunBlockGamut(text);
182
+
183
+ text = _UnescapeSpecialChars(text);
184
+
185
+ // attacklab: Restore dollar signs
186
+ text = text.replace(/~D/g, "$$");
187
+
188
+ // attacklab: Restore tildes
189
+ text = text.replace(/~T/g, "~");
190
+
191
+ text = pluginHooks.postConversion(text);
192
+
193
+ g_html_blocks = g_titles = g_urls = null;
194
+
195
+ return text;
196
+ };
197
+
198
+ function _StripLinkDefinitions(text) {
199
+ //
200
+ // Strips link definitions from text, stores the URLs and titles in
201
+ // hash references.
202
+ //
203
+
204
+ // Link defs are in the form: ^[id]: url "optional title"
205
+
206
+ /*
207
+ text = text.replace(/
208
+ ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
209
+ [ \t]*
210
+ \n? // maybe *one* newline
211
+ [ \t]*
212
+ <?(\S+?)>? // url = $2
213
+ (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
214
+ [ \t]*
215
+ \n? // maybe one newline
216
+ [ \t]*
217
+ ( // (potential) title = $3
218
+ (\n*) // any lines skipped = $4 attacklab: lookbehind removed
219
+ [ \t]+
220
+ ["(]
221
+ (.+?) // title = $5
222
+ [")]
223
+ [ \t]*
224
+ )? // title is optional
225
+ (?:\n+|$)
226
+ /gm, function(){...});
227
+ */
228
+
229
+ text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
230
+ function (wholeMatch, m1, m2, m3, m4, m5) {
231
+ m1 = m1.toLowerCase();
232
+ g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
233
+ if (m4) {
234
+ // Oops, found blank lines, so it's not a title.
235
+ // Put back the parenthetical statement we stole.
236
+ return m3;
237
+ } else if (m5) {
238
+ g_titles.set(m1, m5.replace(/"/g, "&quot;"));
239
+ }
240
+
241
+ // Completely remove the definition from the text
242
+ return "";
243
+ }
244
+ );
245
+
246
+ return text;
247
+ }
248
+
249
+ function _HashHTMLBlocks(text) {
250
+
251
+ // Hashify HTML blocks:
252
+ // We only want to do this for block-level HTML tags, such as headers,
253
+ // lists, and tables. That's because we still want to wrap <p>s around
254
+ // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
255
+ // phrase emphasis, and spans. The list of tags we're looking for is
256
+ // hard-coded:
257
+ var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
258
+ var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
259
+
260
+ // First, look for nested blocks, e.g.:
261
+ // <div>
262
+ // <div>
263
+ // tags for inner block must be indented.
264
+ // </div>
265
+ // </div>
266
+ //
267
+ // The outermost tags must start at the left margin for this to match, and
268
+ // the inner nested divs must be indented.
269
+ // We need to do this before the next, more liberal match, because the next
270
+ // match will start at the first `<div>` and stop at the first `</div>`.
271
+
272
+ // attacklab: This regex can be expensive when it fails.
273
+
274
+ /*
275
+ text = text.replace(/
276
+ ( // save in $1
277
+ ^ // start of line (with /m)
278
+ <($block_tags_a) // start tag = $2
279
+ \b // word break
280
+ // attacklab: hack around khtml/pcre bug...
281
+ [^\r]*?\n // any number of lines, minimally matching
282
+ </\2> // the matching end tag
283
+ [ \t]* // trailing spaces/tabs
284
+ (?=\n+) // followed by a newline
285
+ ) // attacklab: there are sentinel newlines at end of document
286
+ /gm,function(){...}};
287
+ */
288
+ 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);
289
+
290
+ //
291
+ // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
292
+ //
293
+
294
+ /*
295
+ text = text.replace(/
296
+ ( // save in $1
297
+ ^ // start of line (with /m)
298
+ <($block_tags_b) // start tag = $2
299
+ \b // word break
300
+ // attacklab: hack around khtml/pcre bug...
301
+ [^\r]*? // any number of lines, minimally matching
302
+ .*</\2> // the matching end tag
303
+ [ \t]* // trailing spaces/tabs
304
+ (?=\n+) // followed by a newline
305
+ ) // attacklab: there are sentinel newlines at end of document
306
+ /gm,function(){...}};
307
+ */
308
+ 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);
309
+
310
+ // Special case just for <hr />. It was easier to make a special case than
311
+ // to make the other regex more complicated.
312
+
313
+ /*
314
+ text = text.replace(/
315
+ \n // Starting after a blank line
316
+ [ ]{0,3}
317
+ ( // save in $1
318
+ (<(hr) // start tag = $2
319
+ \b // word break
320
+ ([^<>])*?
321
+ \/?>) // the matching end tag
322
+ [ \t]*
323
+ (?=\n{2,}) // followed by a blank line
324
+ )
325
+ /g,hashElement);
326
+ */
327
+ text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashElement);
328
+
329
+ // Special case for standalone HTML comments:
330
+
331
+ /*
332
+ text = text.replace(/
333
+ \n\n // Starting after a blank line
334
+ [ ]{0,3} // attacklab: g_tab_width - 1
335
+ ( // save in $1
336
+ <!
337
+ (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments and http://meta.stackoverflow.com/q/95256
338
+ >
339
+ [ \t]*
340
+ (?=\n{2,}) // followed by a blank line
341
+ )
342
+ /g,hashElement);
343
+ */
344
+ text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
345
+
346
+ // PHP and ASP-style processor instructions (<?...?> and <%...%>)
347
+
348
+ /*
349
+ text = text.replace(/
350
+ (?:
351
+ \n\n // Starting after a blank line
352
+ )
353
+ ( // save in $1
354
+ [ ]{0,3} // attacklab: g_tab_width - 1
355
+ (?:
356
+ <([?%]) // $2
357
+ [^\r]*?
358
+ \2>
359
+ )
360
+ [ \t]*
361
+ (?=\n{2,}) // followed by a blank line
362
+ )
363
+ /g,hashElement);
364
+ */
365
+ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashElement);
366
+
367
+ return text;
368
+ }
369
+
370
+ function hashElement(wholeMatch, m1) {
371
+ var blockText = m1;
372
+
373
+ // Undo double lines
374
+ blockText = blockText.replace(/^\n+/, "");
375
+
376
+ // strip trailing blank lines
377
+ blockText = blockText.replace(/\n+$/g, "");
378
+
379
+ // Replace the element text with a marker ("~KxK" where x is its key)
380
+ blockText = "\n\n~K" + (g_html_blocks.push(blockText) - 1) + "K\n\n";
381
+
382
+ return blockText;
383
+ }
384
+
385
+ function _RunBlockGamut(text, doNotUnhash) {
386
+ //
387
+ // These are all the transformations that form block-level
388
+ // tags like paragraphs, headers, and list items.
389
+ //
390
+ text = _DoHeaders(text);
391
+
392
+ // Do Horizontal Rules:
393
+ var replacement = "<hr />\n";
394
+ text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, replacement);
395
+ text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, replacement);
396
+ text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, replacement);
397
+
398
+ text = _DoLists(text);
399
+ text = _DoCodeBlocks(text);
400
+ text = _DoBlockQuotes(text);
401
+
402
+ // We already ran _HashHTMLBlocks() before, in Markdown(), but that
403
+ // was to escape raw HTML in the original Markdown source. This time,
404
+ // we're escaping the markup we've just created, so that we don't wrap
405
+ // <p> tags around block-level tags.
406
+ text = _HashHTMLBlocks(text);
407
+ text = _FormParagraphs(text, doNotUnhash);
408
+
409
+ return text;
410
+ }
411
+
412
+ function _RunSpanGamut(text) {
413
+ //
414
+ // These are all the transformations that occur *within* block-level
415
+ // tags like paragraphs, headers, and list items.
416
+ //
417
+
418
+ text = _DoCodeSpans(text);
419
+ text = _EscapeSpecialCharsWithinTagAttributes(text);
420
+ text = _EncodeBackslashEscapes(text);
421
+
422
+ // Process anchor and image tags. Images must come first,
423
+ // because ![foo][f] looks like an anchor.
424
+ text = _DoImages(text);
425
+ text = _DoAnchors(text);
426
+
427
+ // Make links out of things like `<http://example.com/>`
428
+ // Must come after _DoAnchors(), because you can use < and >
429
+ // delimiters in inline links like [this](<url>).
430
+ if (g_autolink) {
431
+ text = _DoAutoLinks(text);
432
+ }
433
+
434
+ text = text.replace(/~P/g, "://"); // put in place to prevent autolinking; reset now
435
+
436
+ text = _EncodeAmpsAndAngles(text);
437
+ text = _DoItalicsAndBold(text);
438
+
439
+ // Do hard breaks:
440
+ text = text.replace(/ +\n/g, " <br>\n");
441
+
442
+ return text;
443
+ }
444
+
445
+ function _EscapeSpecialCharsWithinTagAttributes(text) {
446
+ //
447
+ // Within tags -- meaning between < and > -- encode [\ ` * _] so they
448
+ // don't conflict with their use in Markdown for code, italics and strong.
449
+ //
450
+
451
+ // Build a regex to find HTML tags and comments. See Friedl's
452
+ // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
453
+
454
+ // SE: changed the comment part of the regex
455
+
456
+ var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
457
+
458
+ text = text.replace(regex, function (wholeMatch) {
459
+ var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`");
460
+ tag = escapeCharacters(tag, wholeMatch.charAt(1) == "!" ? "\\`*_/" : "\\`*_"); // also escape slashes in comments to prevent autolinking there -- http://meta.stackoverflow.com/questions/95987
461
+ return tag;
462
+ });
463
+
464
+ return text;
465
+ }
466
+
467
+ function _DoAnchors(text) {
468
+ //
469
+ // Turn Markdown link shortcuts into XHTML <a> tags.
470
+ //
471
+ //
472
+ // First, handle reference-style links: [link text] [id]
473
+ //
474
+
475
+ /*
476
+ text = text.replace(/
477
+ ( // wrap whole match in $1
478
+ \[
479
+ (
480
+ (?:
481
+ \[[^\]]*\] // allow brackets nested one level
482
+ |
483
+ [^\[] // or anything else
484
+ )*
485
+ )
486
+ \]
487
+
488
+ [ ]? // one optional space
489
+ (?:\n[ ]*)? // one optional newline followed by spaces
490
+
491
+ \[
492
+ (.*?) // id = $3
493
+ \]
494
+ )
495
+ ()()()() // pad remaining backreferences
496
+ /g, writeAnchorTag);
497
+ */
498
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
499
+
500
+ //
501
+ // Next, inline-style links: [link text](url "optional title")
502
+ //
503
+
504
+ /*
505
+ text = text.replace(/
506
+ ( // wrap whole match in $1
507
+ \[
508
+ (
509
+ (?:
510
+ \[[^\]]*\] // allow brackets nested one level
511
+ |
512
+ [^\[\]] // or anything else
513
+ )*
514
+ )
515
+ \]
516
+ \( // literal paren
517
+ [ \t]*
518
+ () // no id, so leave $3 empty
519
+ <?( // href = $4
520
+ (?:
521
+ \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
522
+ |
523
+ [^()]
524
+ )*?
525
+ )>?
526
+ [ \t]*
527
+ ( // $5
528
+ (['"]) // quote char = $6
529
+ (.*?) // Title = $7
530
+ \6 // matching quote
531
+ [ \t]* // ignore any spaces/tabs between closing quote and )
532
+ )? // title is optional
533
+ \)
534
+ )
535
+ /g, writeAnchorTag);
536
+ */
537
+
538
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag);
539
+
540
+ //
541
+ // Last, handle reference-style shortcuts: [link text]
542
+ // These must come last in case you've also got [link test][1]
543
+ // or [link test](/foo)
544
+ //
545
+
546
+ /*
547
+ text = text.replace(/
548
+ ( // wrap whole match in $1
549
+ \[
550
+ ([^\[\]]+) // link text = $2; can't contain '[' or ']'
551
+ \]
552
+ )
553
+ ()()()()() // pad rest of backreferences
554
+ /g, writeAnchorTag);
555
+ */
556
+ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
557
+
558
+ return text;
559
+ }
560
+
561
+ function writeAnchorTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
562
+ if (m7 == undefined) m7 = "";
563
+ var whole_match = m1;
564
+ var link_text = m2.replace(/:\/\//g, "~P"); // to prevent auto-linking withing the link. will be converted back after the auto-linker runs
565
+ var link_id = m3.toLowerCase();
566
+ var url = m4;
567
+ var title = m7;
568
+
569
+ if (url == "") {
570
+ if (link_id == "") {
571
+ // lower-case and turn embedded newlines into spaces
572
+ link_id = link_text.toLowerCase().replace(/ ?\n/g, " ");
573
+ }
574
+ url = "#" + link_id;
575
+
576
+ if (g_urls.get(link_id) != undefined) {
577
+ url = g_urls.get(link_id);
578
+ if (g_titles.get(link_id) != undefined) {
579
+ title = g_titles.get(link_id);
580
+ }
581
+ }
582
+ else {
583
+ if (whole_match.search(/\(\s*\)$/m) > -1) {
584
+ // Special case for explicit empty url
585
+ url = "";
586
+ } else {
587
+ return whole_match;
588
+ }
589
+ }
590
+ }
591
+ url = encodeProblemUrlChars(url);
592
+ url = escapeCharacters(url, "*_");
593
+ var result = "<a href=\"" + url + "\"";
594
+
595
+ if (title != "") {
596
+ title = attributeEncode(title);
597
+ title = escapeCharacters(title, "*_");
598
+ result += " title=\"" + title + "\"";
599
+ }
600
+
601
+ result += ">" + link_text + "</a>";
602
+
603
+ return result;
604
+ }
605
+
606
+ function _DoImages(text) {
607
+ //
608
+ // Turn Markdown image shortcuts into <img> tags.
609
+ //
610
+
611
+ //
612
+ // First, handle reference-style labeled images: ![alt text][id]
613
+ //
614
+
615
+ /*
616
+ text = text.replace(/
617
+ ( // wrap whole match in $1
618
+ !\[
619
+ (.*?) // alt text = $2
620
+ \]
621
+
622
+ [ ]? // one optional space
623
+ (?:\n[ ]*)? // one optional newline followed by spaces
624
+
625
+ \[
626
+ (.*?) // id = $3
627
+ \]
628
+ )
629
+ ()()()() // pad rest of backreferences
630
+ /g, writeImageTag);
631
+ */
632
+ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
633
+
634
+ //
635
+ // Next, handle inline images: ![alt text](url "optional title")
636
+ // Don't forget: encode * and _
637
+
638
+ /*
639
+ text = text.replace(/
640
+ ( // wrap whole match in $1
641
+ !\[
642
+ (.*?) // alt text = $2
643
+ \]
644
+ \s? // One optional whitespace character
645
+ \( // literal paren
646
+ [ \t]*
647
+ () // no id, so leave $3 empty
648
+ <?(\S+?)>? // src url = $4
649
+ [ \t]*
650
+ ( // $5
651
+ (['"]) // quote char = $6
652
+ (.*?) // title = $7
653
+ \6 // matching quote
654
+ [ \t]*
655
+ )? // title is optional
656
+ \)
657
+ )
658
+ /g, writeImageTag);
659
+ */
660
+ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag);
661
+
662
+ return text;
663
+ }
664
+
665
+ function attributeEncode(text) {
666
+ // unconditionally replace angle brackets here -- what ends up in an attribute (e.g. alt or title)
667
+ // never makes sense to have verbatim HTML in it (and the sanitizer would totally break it)
668
+ return text.replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
669
+ }
670
+
671
+ function writeImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
672
+ var whole_match = m1;
673
+ var alt_text = m2;
674
+ var link_id = m3.toLowerCase();
675
+ var url = m4;
676
+ var title = m7;
677
+
678
+ if (!title) title = "";
679
+
680
+ if (url == "") {
681
+ if (link_id == "") {
682
+ // lower-case and turn embedded newlines into spaces
683
+ link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
684
+ }
685
+ url = "#" + link_id;
686
+
687
+ if (g_urls.get(link_id) != undefined) {
688
+ url = g_urls.get(link_id);
689
+ if (g_titles.get(link_id) != undefined) {
690
+ title = g_titles.get(link_id);
691
+ }
692
+ }
693
+ else {
694
+ return whole_match;
695
+ }
696
+ }
697
+
698
+ alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()");
699
+ url = escapeCharacters(url, "*_");
700
+ var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
701
+
702
+ // attacklab: Markdown.pl adds empty title attributes to images.
703
+ // Replicate this bug.
704
+
705
+ //if (title != "") {
706
+ title = attributeEncode(title);
707
+ title = escapeCharacters(title, "*_");
708
+ result += " title=\"" + title + "\"";
709
+ //}
710
+
711
+ result += " />";
712
+
713
+ return result;
714
+ }
715
+
716
+ function _DoHeaders(text) {
717
+
718
+ // Setext-style headers:
719
+ // Header 1
720
+ // ========
721
+ //
722
+ // Header 2
723
+ // --------
724
+ //
725
+ text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
726
+ function (wholeMatch, m1) { return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n"; }
727
+ );
728
+
729
+ text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
730
+ function (matchFound, m1) { return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n"; }
731
+ );
732
+
733
+ // atx-style headers:
734
+ // # Header 1
735
+ // ## Header 2
736
+ // ## Header 2 with closing hashes ##
737
+ // ...
738
+ // ###### Header 6
739
+ //
740
+
741
+ /*
742
+ text = text.replace(/
743
+ ^(\#{1,6}) // $1 = string of #'s
744
+ [ \t]*
745
+ (.+?) // $2 = Header text
746
+ [ \t]*
747
+ \#* // optional closing #'s (not counted)
748
+ \n+
749
+ /gm, function() {...});
750
+ */
751
+
752
+ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
753
+ function (wholeMatch, m1, m2) {
754
+ var h_level = m1.length;
755
+ return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
756
+ }
757
+ );
758
+
759
+ return text;
760
+ }
761
+
762
+ function _DoLists(text) {
763
+ //
764
+ // Form HTML ordered (numbered) and unordered (bulleted) lists.
765
+ //
766
+
767
+ // attacklab: add sentinel to hack around khtml/safari bug:
768
+ // http://bugs.webkit.org/show_bug.cgi?id=11231
769
+ text += "~0";
770
+
771
+ // Re-usable pattern to match any entirel ul or ol list:
772
+
773
+ /*
774
+ var whole_list = /
775
+ ( // $1 = whole list
776
+ ( // $2
777
+ [ ]{0,3} // attacklab: g_tab_width - 1
778
+ ([*+-]|\d+[.]) // $3 = first list item marker
779
+ [ \t]+
780
+ )
781
+ [^\r]+?
782
+ ( // $4
783
+ ~0 // sentinel for workaround; should be $
784
+ |
785
+ \n{2,}
786
+ (?=\S)
787
+ (?! // Negative lookahead for another list item marker
788
+ [ \t]*
789
+ (?:[*+-]|\d+[.])[ \t]+
790
+ )
791
+ )
792
+ )
793
+ /g
794
+ */
795
+ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
796
+
797
+ if (g_list_level) {
798
+ text = text.replace(whole_list, function (wholeMatch, m1, m2) {
799
+ var list = m1;
800
+ var list_type = (m2.search(/[*+-]/g) > -1) ? "ul" : "ol";
801
+
802
+ var result = _ProcessListItems(list, list_type);
803
+
804
+ // Trim any trailing whitespace, to put the closing `</$list_type>`
805
+ // up on the preceding line, to get it past the current stupid
806
+ // HTML block parser. This is a hack to work around the terrible
807
+ // hack that is the HTML block parser.
808
+ result = result.replace(/\s+$/, "");
809
+ result = "<" + list_type + ">" + result + "</" + list_type + ">\n";
810
+ return result;
811
+ });
812
+ } else {
813
+ whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
814
+ text = text.replace(whole_list, function (wholeMatch, m1, m2, m3) {
815
+ var runup = m1;
816
+ var list = m2;
817
+
818
+ var list_type = (m3.search(/[*+-]/g) > -1) ? "ul" : "ol";
819
+ var result = _ProcessListItems(list, list_type);
820
+ result = runup + "<" + list_type + ">\n" + result + "</" + list_type + ">\n";
821
+ return result;
822
+ });
823
+ }
824
+
825
+ // attacklab: strip sentinel
826
+ text = text.replace(/~0/, "");
827
+
828
+ return text;
829
+ }
830
+
831
+ var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
832
+
833
+ function _ProcessListItems(list_str, list_type) {
834
+ //
835
+ // Process the contents of a single ordered or unordered list, splitting it
836
+ // into individual list items.
837
+ //
838
+ // list_type is either "ul" or "ol".
839
+
840
+ // The $g_list_level global keeps track of when we're inside a list.
841
+ // Each time we enter a list, we increment it; when we leave a list,
842
+ // we decrement. If it's zero, we're not in a list anymore.
843
+ //
844
+ // We do this because when we're not inside a list, we want to treat
845
+ // something like this:
846
+ //
847
+ // I recommend upgrading to version
848
+ // 8. Oops, now this line is treated
849
+ // as a sub-list.
850
+ //
851
+ // As a single paragraph, despite the fact that the second line starts
852
+ // with a digit-period-space sequence.
853
+ //
854
+ // Whereas when we're inside a list (or sub-list), that line will be
855
+ // treated as the start of a sub-list. What a kludge, huh? This is
856
+ // an aspect of Markdown's syntax that's hard to parse perfectly
857
+ // without resorting to mind-reading. Perhaps the solution is to
858
+ // change the syntax rules such that sub-lists must start with a
859
+ // starting cardinal number; e.g. "1." or "a.".
860
+
861
+ g_list_level++;
862
+
863
+ // trim trailing blank lines:
864
+ list_str = list_str.replace(/\n{2,}$/, "\n");
865
+
866
+ // attacklab: add sentinel to emulate \z
867
+ list_str += "~0";
868
+
869
+ // In the original attacklab showdown, list_type was not given to this function, and anything
870
+ // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
871
+ //
872
+ // Markdown rendered by WMD rendered by MarkdownSharp
873
+ // ------------------------------------------------------------------
874
+ // 1. first 1. first 1. first
875
+ // 2. second 2. second 2. second
876
+ // - third 3. third * third
877
+ //
878
+ // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
879
+ // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
880
+
881
+ /*
882
+ list_str = list_str.replace(/
883
+ (^[ \t]*) // leading whitespace = $1
884
+ ({MARKER}) [ \t]+ // list marker = $2
885
+ ([^\r]+? // list item text = $3
886
+ (\n+)
887
+ )
888
+ (?=
889
+ (~0 | \2 ({MARKER}) [ \t]+)
890
+ )
891
+ /gm, function(){...});
892
+ */
893
+
894
+ var marker = _listItemMarkers[list_type];
895
+ var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
896
+ var last_item_had_a_double_newline = false;
897
+ list_str = list_str.replace(re,
898
+ function (wholeMatch, m1, m2, m3) {
899
+ var item = m3;
900
+ var leading_space = m1;
901
+ var ends_with_double_newline = /\n\n$/.test(item);
902
+ var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/) > -1;
903
+
904
+ if (contains_double_newline || last_item_had_a_double_newline) {
905
+ item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */true);
906
+ }
907
+ else {
908
+ // Recursion for sub-lists:
909
+ item = _DoLists(_Outdent(item));
910
+ item = item.replace(/\n$/, ""); // chomp(item)
911
+ item = _RunSpanGamut(item);
912
+ }
913
+ last_item_had_a_double_newline = ends_with_double_newline;
914
+ return "<li>" + item + "</li>\n";
915
+ }
916
+ );
917
+
918
+ // attacklab: strip sentinel
919
+ list_str = list_str.replace(/~0/g, "");
920
+
921
+ g_list_level--;
922
+ return list_str;
923
+ }
924
+
925
+ function _DoCodeBlocks(text) {
926
+ //
927
+ // Process Markdown `<pre><code>` blocks.
928
+ //
929
+
930
+ /*
931
+ text = text.replace(/
932
+ (?:\n\n|^)
933
+ ( // $1 = the code block -- one or more lines, starting with a space/tab
934
+ (?:
935
+ (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
936
+ .*\n+
937
+ )+
938
+ )
939
+ (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
940
+ /g ,function(){...});
941
+ */
942
+
943
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
944
+ text += "~0";
945
+
946
+ text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
947
+ function (wholeMatch, m1, m2) {
948
+ var codeblock = m1;
949
+ var nextChar = m2;
950
+
951
+ codeblock = _EncodeCode(_Outdent(codeblock));
952
+ codeblock = _Detab(codeblock);
953
+ codeblock = codeblock.replace(/^\n+/g, ""); // trim leading newlines
954
+ codeblock = codeblock.replace(/\n+$/g, ""); // trim trailing whitespace
955
+
956
+ codeblock = '<pre class="prettyprint linenums"><code>' + codeblock + '\n</code></pre>';
957
+
958
+ return "\n\n" + codeblock + "\n\n" + nextChar;
959
+ }
960
+ );
961
+
962
+ // attacklab: strip sentinel
963
+ text = text.replace(/~0/, "");
964
+
965
+ return text;
966
+ }
967
+
968
+ function hashBlock(text) {
969
+ text = text.replace(/(^\n+|\n+$)/g, "");
970
+ return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n";
971
+ }
972
+
973
+ function _DoCodeSpans(text) {
974
+ //
975
+ // * Backtick quotes are used for <code></code> spans.
976
+ //
977
+ // * You can use multiple backticks as the delimiters if you want to
978
+ // include literal backticks in the code span. So, this input:
979
+ //
980
+ // Just type ``foo `bar` baz`` at the prompt.
981
+ //
982
+ // Will translate to:
983
+ //
984
+ // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
985
+ //
986
+ // There's no arbitrary limit to the number of backticks you
987
+ // can use as delimters. If you need three consecutive backticks
988
+ // in your code, use four for delimiters, etc.
989
+ //
990
+ // * You can use spaces to get literal backticks at the edges:
991
+ //
992
+ // ... type `` `bar` `` ...
993
+ //
994
+ // Turns to:
995
+ //
996
+ // ... type <code>`bar`</code> ...
997
+ //
998
+
999
+ /*
1000
+ text = text.replace(/
1001
+ (^|[^\\]) // Character before opening ` can't be a backslash
1002
+ (`+) // $2 = Opening run of `
1003
+ ( // $3 = The code block
1004
+ [^\r]*?
1005
+ [^`] // attacklab: work around lack of lookbehind
1006
+ )
1007
+ \2 // Matching closer
1008
+ (?!`)
1009
+ /gm, function(){...});
1010
+ */
1011
+
1012
+ text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
1013
+ function (wholeMatch, m1, m2, m3, m4) {
1014
+ var c = m3;
1015
+ c = c.replace(/^([ \t]*)/g, ""); // leading whitespace
1016
+ c = c.replace(/[ \t]*$/g, ""); // trailing whitespace
1017
+ c = _EncodeCode(c);
1018
+ c = c.replace(/:\/\//g, "~P"); // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. Will be converted back after the auto-linker runs.
1019
+ return m1 + "<code>" + c + "</code>";
1020
+ }
1021
+ );
1022
+
1023
+ return text;
1024
+ }
1025
+
1026
+ function _EncodeCode(text) {
1027
+ //
1028
+ // Encode/escape certain characters inside Markdown code runs.
1029
+ // The point is that in code, these characters are literals,
1030
+ // and lose their special Markdown meanings.
1031
+ //
1032
+ // Encode all ampersands; HTML entities are not
1033
+ // entities within a Markdown code span.
1034
+ text = text.replace(/&/g, "&amp;");
1035
+
1036
+ // Do the angle bracket song and dance:
1037
+ text = text.replace(/</g, "&lt;");
1038
+ text = text.replace(/>/g, "&gt;");
1039
+
1040
+ // Now, escape characters that are magic in Markdown:
1041
+ text = escapeCharacters(text, "\*_{}[]\\", false);
1042
+
1043
+ // jj the line above breaks this:
1044
+ //---
1045
+
1046
+ //* Item
1047
+
1048
+ // 1. Subitem
1049
+
1050
+ // special char: *
1051
+ //---
1052
+
1053
+ return text;
1054
+ }
1055
+
1056
+ function _DoItalicsAndBold(text) {
1057
+
1058
+ // <strong> must go first:
1059
+ text = text.replace(/([\W_]|^)(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\2([\W_]|$)/g,
1060
+ "$1<strong>$3</strong>$4");
1061
+
1062
+ text = text.replace(/([\W_]|^)(\*|_)(?=\S)([^\r\*_]*?\S)\2([\W_]|$)/g,
1063
+ "$1<em>$3</em>$4");
1064
+
1065
+ return text;
1066
+ }
1067
+
1068
+ function _DoBlockQuotes(text) {
1069
+
1070
+ /*
1071
+ text = text.replace(/
1072
+ ( // Wrap whole match in $1
1073
+ (
1074
+ ^[ \t]*>[ \t]? // '>' at the start of a line
1075
+ .+\n // rest of the first line
1076
+ (.+\n)* // subsequent consecutive lines
1077
+ \n* // blanks
1078
+ )+
1079
+ )
1080
+ /gm, function(){...});
1081
+ */
1082
+
1083
+ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1084
+ function (wholeMatch, m1) {
1085
+ var bq = m1;
1086
+
1087
+ // attacklab: hack around Konqueror 3.5.4 bug:
1088
+ // "----------bug".replace(/^-/g,"") == "bug"
1089
+
1090
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting
1091
+
1092
+ // attacklab: clean up hack
1093
+ bq = bq.replace(/~0/g, "");
1094
+
1095
+ bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines
1096
+ bq = _RunBlockGamut(bq); // recurse
1097
+
1098
+ bq = bq.replace(/(^|\n)/g, "$1 ");
1099
+ // These leading spaces screw with <pre> content, so we need to fix that:
1100
+ bq = bq.replace(
1101
+ /(\s*<pre>[^\r]+?<\/pre>)/gm,
1102
+ function (wholeMatch, m1) {
1103
+ var pre = m1;
1104
+ // attacklab: hack around Konqueror 3.5.4 bug:
1105
+ pre = pre.replace(/^ /mg, "~0");
1106
+ pre = pre.replace(/~0/g, "");
1107
+ return pre;
1108
+ });
1109
+
1110
+ return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1111
+ }
1112
+ );
1113
+ return text;
1114
+ }
1115
+
1116
+ function _FormParagraphs(text, doNotUnhash) {
1117
+ //
1118
+ // Params:
1119
+ // $text - string to process with html <p> tags
1120
+ //
1121
+
1122
+ // Strip leading and trailing lines:
1123
+ text = text.replace(/^\n+/g, "");
1124
+ text = text.replace(/\n+$/g, "");
1125
+
1126
+ var grafs = text.split(/\n{2,}/g);
1127
+ var grafsOut = [];
1128
+
1129
+ var markerRe = /~K(\d+)K/;
1130
+
1131
+ //
1132
+ // Wrap <p> tags.
1133
+ //
1134
+ var end = grafs.length;
1135
+ for (var i = 0; i < end; i++) {
1136
+ var str = grafs[i];
1137
+
1138
+ // if this is an HTML marker, copy it
1139
+ if (markerRe.test(str)) {
1140
+ grafsOut.push(str);
1141
+ }
1142
+ else if (/\S/.test(str)) {
1143
+ str = _RunSpanGamut(str);
1144
+ str = str.replace(/^([ \t]*)/g, "<p>");
1145
+ str += "</p>"
1146
+ grafsOut.push(str);
1147
+ }
1148
+
1149
+ }
1150
+ //
1151
+ // Unhashify HTML blocks
1152
+ //
1153
+ if (!doNotUnhash) {
1154
+ end = grafsOut.length;
1155
+ for (var i = 0; i < end; i++) {
1156
+ var foundAny = true;
1157
+ while (foundAny) { // we may need several runs, since the data may be nested
1158
+ foundAny = false;
1159
+ grafsOut[i] = grafsOut[i].replace(/~K(\d+)K/g, function (wholeMatch, id) {
1160
+ foundAny = true;
1161
+ return g_html_blocks[id];
1162
+ });
1163
+ }
1164
+ }
1165
+ }
1166
+ return grafsOut.join("\n\n");
1167
+ }
1168
+
1169
+ function _EncodeAmpsAndAngles(text) {
1170
+ // Smart processing for ampersands and angle brackets that need to be encoded.
1171
+
1172
+ // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1173
+ // http://bumppo.net/projects/amputator/
1174
+ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&amp;");
1175
+
1176
+ // Encode naked <'s
1177
+ text = text.replace(/<(?![a-z\/?\$!])/gi, "&lt;");
1178
+
1179
+ return text;
1180
+ }
1181
+
1182
+ function _EncodeBackslashEscapes(text) {
1183
+ //
1184
+ // Parameter: String.
1185
+ // Returns: The string, with after processing the following backslash
1186
+ // escape sequences.
1187
+ //
1188
+
1189
+ // attacklab: The polite way to do this is with the new
1190
+ // escapeCharacters() function:
1191
+ //
1192
+ // text = escapeCharacters(text,"\\",true);
1193
+ // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1194
+ //
1195
+ // ...but we're sidestepping its use of the (slow) RegExp constructor
1196
+ // as an optimization for Firefox. This function gets called a LOT.
1197
+
1198
+ text = text.replace(/\\(\\)/g, escapeCharacters_callback);
1199
+ text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, escapeCharacters_callback);
1200
+ return text;
1201
+ }
1202
+
1203
+ function _DoAutoLinks(text) {
1204
+
1205
+ // note that at this point, all other URL in the text are already hyperlinked as <a href=""></a>
1206
+ // *except* for the <http://www.foo.com> case
1207
+
1208
+ // automatically add < and > around unadorned raw hyperlinks
1209
+ // must be preceded by space/BOF and followed by non-word/EOF character
1210
+ text = text.replace(/(^|\s)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)/gi, "$1<$2$3>$4");
1211
+
1212
+ // autolink anything like <http://example.com>
1213
+
1214
+ var replacer = function (wholematch, m1) { return "<a href=\"" + m1 + "\">" + pluginHooks.plainLinkText(m1) + "</a>"; }
1215
+ text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, replacer);
1216
+
1217
+ // Email addresses: <address@domain.foo>
1218
+ /*
1219
+ text = text.replace(/
1220
+ <
1221
+ (?:mailto:)?
1222
+ (
1223
+ [-.\w]+
1224
+ \@
1225
+ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1226
+ )
1227
+ >
1228
+ /gi, _DoAutoLinks_callback());
1229
+ */
1230
+
1231
+ var email_replacer = function(wholematch, m1) {
1232
+ var mailto = 'mailto:'
1233
+ var link
1234
+ var email
1235
+ if (m1.substring(0, mailto.length) != mailto){
1236
+ link = mailto + m1;
1237
+ email = m1;
1238
+ } else {
1239
+ link = m1;
1240
+ email = m1.substring(mailto.length, m1.length);
1241
+ }
1242
+ return "<a href=\"" + link + "\">" + pluginHooks.plainLinkText(email) + "</a>";
1243
+ }
1244
+ text = text.replace(/<((?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+))>/gi, email_replacer);
1245
+
1246
+ return text;
1247
+ }
1248
+
1249
+ function _UnescapeSpecialChars(text) {
1250
+ //
1251
+ // Swap back in all the special characters we've hidden.
1252
+ //
1253
+ text = text.replace(/~E(\d+)E/g,
1254
+ function (wholeMatch, m1) {
1255
+ var charCodeToReplace = parseInt(m1);
1256
+ return String.fromCharCode(charCodeToReplace);
1257
+ }
1258
+ );
1259
+ return text;
1260
+ }
1261
+
1262
+ function _Outdent(text) {
1263
+ //
1264
+ // Remove one level of line-leading tabs or spaces
1265
+ //
1266
+
1267
+ // attacklab: hack around Konqueror 3.5.4 bug:
1268
+ // "----------bug".replace(/^-/g,"") == "bug"
1269
+
1270
+ text = text.replace(/^(\t|[ ]{1,4})/gm, "~0"); // attacklab: g_tab_width
1271
+
1272
+ // attacklab: clean up hack
1273
+ text = text.replace(/~0/g, "")
1274
+
1275
+ return text;
1276
+ }
1277
+
1278
+ function _Detab(text) {
1279
+ if (!/\t/.test(text))
1280
+ return text;
1281
+
1282
+ var spaces = [" ", " ", " ", " "],
1283
+ skew = 0,
1284
+ v;
1285
+
1286
+ return text.replace(/[\n\t]/g, function (match, offset) {
1287
+ if (match === "\n") {
1288
+ skew = offset + 1;
1289
+ return match;
1290
+ }
1291
+ v = (offset - skew) % 4;
1292
+ skew = offset + 1;
1293
+ return spaces[v];
1294
+ });
1295
+ }
1296
+
1297
+ //
1298
+ // attacklab: Utility functions
1299
+ //
1300
+
1301
+ var _problemUrlChars = /(?:["'*()[\]:]|~D)/g;
1302
+
1303
+ // hex-encodes some unusual "problem" chars in URLs to avoid URL detection problems
1304
+ function encodeProblemUrlChars(url) {
1305
+ if (!url)
1306
+ return "";
1307
+
1308
+ var len = url.length;
1309
+
1310
+ return url.replace(_problemUrlChars, function (match, offset) {
1311
+ if (match == "~D") // escape for dollar
1312
+ return "%24";
1313
+ if (match == ":") {
1314
+ if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1)))
1315
+ return ":";
1316
+ if (url.substring(0, 'mailto:'.length) === 'mailto:')
1317
+ return ":";
1318
+ if (url.substring(0, 'magnet:'.length) === 'magnet:')
1319
+ return ":";
1320
+ }
1321
+ return "%" + match.charCodeAt(0).toString(16);
1322
+ });
1323
+ }
1324
+
1325
+
1326
+ function escapeCharacters(text, charsToEscape, afterBackslash) {
1327
+ // First we have to escape the escape characters so that
1328
+ // we can build a character class out of them
1329
+ var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])";
1330
+
1331
+ if (afterBackslash) {
1332
+ regexString = "\\\\" + regexString;
1333
+ }
1334
+
1335
+ var regex = new RegExp(regexString, "g");
1336
+ text = text.replace(regex, escapeCharacters_callback);
1337
+
1338
+ return text;
1339
+ }
1340
+
1341
+
1342
+ function escapeCharacters_callback(wholeMatch, m1) {
1343
+ var charCodeToEscape = m1.charCodeAt(0);
1344
+ return "~E" + charCodeToEscape + "E";
1345
+ }
1346
+
1347
+ }; // end of the Markdown.Converter constructor
1348
+
1349
+ })();