Markdown.Editor.js 86.1 KB
Newer Older
1
// needs Markdown.Converter.js at the moment
Rocky Duan committed
2

3
(function() {
Rocky Duan committed
4 5 6 7 8 9
    var util = {},
        position = {},
        ui = {},
        doc = window.document,
        re = window.RegExp,
        nav = window.navigator,
10
        SETTINGS = {lineLength: 72},
Rocky Duan committed
11 12 13 14 15 16 17 18 19 20 21 22

    // Used to work around some browser bugs where we can't use feature testing.
        uaSniffed = {
            isIE: /msie/.test(nav.userAgent.toLowerCase()),
            isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()),
            isOpera: /opera/.test(nav.userAgent.toLowerCase())
        };


    // -------------------------------------------------------------------
    //  YOUR CHANGES GO HERE
    //
23
    // I've tried to localize the things you are likely to change to
Rocky Duan committed
24 25 26
    // this area.
    // -------------------------------------------------------------------

27
    // The text that appears on the dialog box when entering links.
28
    var linkDialogText = gettext('Insert Hyperlink'),
29
        linkUrlHelpText = gettext("e.g. 'http://google.com'"),
30
        linkDestinationLabel = gettext('Link Description'),
31
        linkDestinationHelpText = gettext("e.g. 'google'"),
32 33
        linkDestinationError = gettext('Please provide a description of the link destination.'),
        linkDefaultText = 'http://'; // The default text that appears in input
34 35

    // The text that appears on the dialog box when entering Images.
36
    var imageDialogText = gettext('Insert Image (upload file or type URL)'),
37
        imageUrlHelpText = gettext("Type in a URL or use the \"Choose File\" button to upload a file from your machine. (e.g. 'http://example.com/img/clouds.jpg')"),  // eslint-disable-line max-len
38 39
        imageDescriptionLabel = gettext('Image Description'),
        imageDefaultText = 'http://', // The default text that appears in input
40 41
        imageDescError = gettext('Please describe this image or agree that it has no contextual value by checking the checkbox.'),  // eslint-disable-line max-len
        imageDescriptionHelpText = gettext("e.g. 'Sky with clouds'. The description is helpful for users who cannot see the image."),  // eslint-disable-line max-len
42 43
        imageDescriptionHelpLink = {
            href: 'http://www.w3.org/TR/html5/embedded-content-0.html#alt',
44
            text: gettext('How to create useful text alternatives.')
45
        },
46
        imageIsDecorativeLabel = gettext('This image is for decorative purposes only and does not require a description.');  // eslint-disable-line max-len
47 48

    // Text that is shared between both link and image dialog boxes.
49 50 51
    var defaultHelpHoverTitle = gettext('Markdown Editing Help'),
        urlLabel = gettext('URL'),
        urlError = gettext('Please provide a valid URL.');
Rocky Duan committed
52 53 54 55 56 57 58 59 60 61 62 63 64

    // -------------------------------------------------------------------
    //  END OF YOUR CHANGES
    // -------------------------------------------------------------------

    // help, if given, should have a property "handler", the click handler for the help button,
    // and can have an optional property "title" for the button's tooltip (defaults to "Markdown Editing Help").
    // If help isn't given, not help button is created.
    //
    // The constructed editor object has the methods:
    // - getConverter() returns the markdown converter object that was passed to the constructor
    // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
    // - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
65 66
    Markdown.Editor = function(markdownConverter, idPostfix, help, imageUploadHandler) {
        idPostfix = idPostfix || '';
Rocky Duan committed
67 68

        var hooks = this.hooks = new Markdown.HookCollection();
69 70 71
        hooks.addNoop('onPreviewPush');       // called with no arguments after the preview has been refreshed
        hooks.addNoop('postBlockquoteCreation'); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
        hooks.addFalse('insertImageDialog');     /* called with one parameter: a callback to be called with the URL of the image. If the application creates
Rocky Duan committed
72 73 74
                                                  * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
                                                  * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
                                                  */
75
        this.util = util;
Rocky Duan committed
76

77
        this.getConverter = function() { return markdownConverter; };
Rocky Duan committed
78 79 80 81

        var that = this,
            panels;

82
        this.run = function() {
Rocky Duan committed
83 84 85 86 87
            if (panels)
                return; // already initialized

            panels = new PanelCollection(idPostfix);
            var commandManager = new CommandManager(hooks);
88
            var previewManager = new PreviewManager(markdownConverter, panels, function(text, previewSet) { hooks.onPreviewPush(text, previewSet); });
Rocky Duan committed
89 90 91
            var undoManager, uiManager;

            if (!/\?noundo/.test(doc.location.href)) {
92
                undoManager = new UndoManager(function() {
Rocky Duan committed
93 94 95 96
                    previewManager.refresh();
                    if (uiManager) // not available on the first call
                        uiManager.setUndoRedoButtonStates();
                }, panels);
97
                this.textOperation = function(f) {
Rocky Duan committed
98 99 100
                    undoManager.setCommandMode();
                    f();
                    that.refreshPreview();
101
                };
Rocky Duan committed
102 103
            }

104
            uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help, imageUploadHandler);
Rocky Duan committed
105 106
            uiManager.setUndoRedoButtonStates();

107
            var forceRefresh = that.refreshPreview = function() { previewManager.refresh(true); };
Rocky Duan committed
108 109

            forceRefresh();
110 111
        };
    };
Rocky Duan committed
112 113 114 115 116 117 118

    // before: contains all the text in the input box BEFORE the selection.
    // after: contains all the text in the input box AFTER the selection.
    function Chunks() { }

    // startRegex: a regular expression to find the start tag
    // endRegex: a regular expresssion to find the end tag
119
    Chunks.prototype.findTags = function(startRegex, endRegex) {
Rocky Duan committed
120 121 122
        var chunkObj = this;
        var regex;

123 124
        if (startRegex) {
            regex = util.extendRegExp(startRegex, '', '$');
Rocky Duan committed
125 126

            this.before = this.before.replace(regex,
127
                function(match) {
Rocky Duan committed
128
                    chunkObj.startTag = chunkObj.startTag + match;
129
                    return '';
Rocky Duan committed
130 131
                });

132
            regex = util.extendRegExp(startRegex, '^', '');
Rocky Duan committed
133 134

            this.selection = this.selection.replace(regex,
135
                function(match) {
Rocky Duan committed
136
                    chunkObj.startTag = chunkObj.startTag + match;
137
                    return '';
Rocky Duan committed
138 139 140
                });
        }

141 142
        if (endRegex) {
            regex = util.extendRegExp(endRegex, '', '$');
Rocky Duan committed
143 144

            this.selection = this.selection.replace(regex,
145
                function(match) {
Rocky Duan committed
146
                    chunkObj.endTag = match + chunkObj.endTag;
147
                    return '';
Rocky Duan committed
148 149
                });

150
            regex = util.extendRegExp(endRegex, '^', '');
Rocky Duan committed
151 152

            this.after = this.after.replace(regex,
153
                function(match) {
Rocky Duan committed
154
                    chunkObj.endTag = match + chunkObj.endTag;
155
                    return '';
Rocky Duan committed
156 157 158 159 160 161 162 163
                });
        }
    };

    // If remove is false, the whitespace is transferred
    // to the before/after regions.
    //
    // If remove is true, the whitespace disappears.
164
    Chunks.prototype.trimWhitespace = function(remove) {
Rocky Duan committed
165 166
        var beforeReplacer, afterReplacer, that = this;
        if (remove) {
167
            beforeReplacer = afterReplacer = '';
Rocky Duan committed
168
        } else {
169 170
            beforeReplacer = function(s) { that.before += s; return ''; };
            afterReplacer = function(s) { that.after = s + that.after; return ''; };
Rocky Duan committed
171
        }
172

Rocky Duan committed
173 174 175 176
        this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
    };


177
    Chunks.prototype.skipLines = function(nLinesBefore, nLinesAfter, findExtraNewlines) {
Rocky Duan committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
        if (nLinesBefore === undefined) {
            nLinesBefore = 1;
        }

        if (nLinesAfter === undefined) {
            nLinesAfter = 1;
        }

        nLinesBefore++;
        nLinesAfter++;

        var regexText;
        var replacementText;

        // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985
        if (navigator.userAgent.match(/Chrome/)) {
194
            'X'.match(/()./);
Rocky Duan committed
195 196
        }

197
        this.selection = this.selection.replace(/(^\n*)/, '');
Rocky Duan committed
198 199 200

        this.startTag = this.startTag + re.$1;

201
        this.selection = this.selection.replace(/(\n*$)/, '');
Rocky Duan committed
202
        this.endTag = this.endTag + re.$1;
203
        this.startTag = this.startTag.replace(/(^\n*)/, '');
Rocky Duan committed
204
        this.before = this.before + re.$1;
205
        this.endTag = this.endTag.replace(/(\n*$)/, '');
Rocky Duan committed
206 207
        this.after = this.after + re.$1;

208 209
        if (this.before) {
            regexText = replacementText = '';
Rocky Duan committed
210 211

            while (nLinesBefore--) {
212 213
                regexText += '\\n?';
                replacementText += '\n';
Rocky Duan committed
214 215 216
            }

            if (findExtraNewlines) {
217
                regexText = '\\n*';
Rocky Duan committed
218
            }
219
            this.before = this.before.replace(new re(regexText + '$', ''), replacementText);
Rocky Duan committed
220 221
        }

222 223
        if (this.after) {
            regexText = replacementText = '';
Rocky Duan committed
224 225

            while (nLinesAfter--) {
226 227
                regexText += '\\n?';
                replacementText += '\n';
Rocky Duan committed
228 229
            }
            if (findExtraNewlines) {
230
                regexText = '\\n*';
Rocky Duan committed
231 232
            }

233
            this.after = this.after.replace(new re(regexText, ''), replacementText);
Rocky Duan committed
234 235 236
        }
    };

237
    // end of Chunks
Rocky Duan committed
238 239 240 241 242 243

    // A collection of the important regions on the page.
    // Cached so we don't have to keep traversing the DOM.
    // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around
    // this issue:
    // Internet explorer has problems with CSS sprite buttons that use HTML
244
    // lists.  When you click on the background image "button", IE will
Rocky Duan committed
245 246 247 248 249 250 251 252 253 254 255
    // select the non-existent link text and discard the selection in the
    // textarea.  The solution to this is to cache the textarea selection
    // on the button's mousedown event and set a flag.  In the part of the
    // code where we need to grab the selection, we check for the flag
    // and, if it's set, use the cached area instead of querying the
    // textarea.
    //
    // This ONLY affects Internet Explorer (tested on versions 6, 7
    // and 8) and ONLY on button clicks.  Keyboard shortcuts work
    // normally since the focus never leaves the textarea.
    function PanelCollection(postfix) {
256 257 258 259
        this.buttonBar = doc.getElementById('wmd-button-bar' + postfix);
        this.preview = doc.getElementById('wmd-preview' + postfix);
        this.input = doc.getElementById('wmd-input' + postfix);
    }
Rocky Duan committed
260

261 262 263 264
    util.isValidUrl = function(url) {
        return /^((?:http|https|ftp):\/{2}|\/)[^]+$/.test(url);
    };

Rocky Duan committed
265 266
    // Returns true if the DOM element is visible, false if it's hidden.
    // Checks if display is anything other than none.
267
    util.isVisible = function(elem) {
Rocky Duan committed
268 269
        if (window.getComputedStyle) {
            // Most browsers
270
            return window.getComputedStyle(elem, null).getPropertyValue('display') !== 'none';
Rocky Duan committed
271 272 273
        }
        else if (elem.currentStyle) {
            // IE
274
            return elem.currentStyle['display'] !== 'none';
Rocky Duan committed
275 276 277 278 279 280
        }
    };


    // Adds a listener callback to a DOM element which is fired on a specified
    // event.
281
    util.addEvent = function(elem, event, listener) {
Rocky Duan committed
282 283
        if (elem.attachEvent) {
            // IE only.  The "on" is mandatory.
284
            elem.attachEvent('on' + event, listener);
Rocky Duan committed
285 286 287 288 289 290 291 292 293 294
        }
        else {
            // Other browsers.
            elem.addEventListener(event, listener, false);
        }
    };


    // Removes a listener callback from a DOM element which is fired on a specified
    // event.
295
    util.removeEvent = function(elem, event, listener) {
Rocky Duan committed
296 297
        if (elem.detachEvent) {
            // IE only.  The "on" is mandatory.
298
            elem.detachEvent('on' + event, listener);
Rocky Duan committed
299 300 301 302 303 304 305 306
        }
        else {
            // Other browsers.
            elem.removeEventListener(event, listener, false);
        }
    };

    // Converts \r\n and \r to \n.
307 308 309
    util.fixEolChars = function(text) {
        text = text.replace(/\r\n/g, '\n');
        text = text.replace(/\r/g, '\n');
Rocky Duan committed
310 311 312 313 314 315 316 317 318 319 320
        return text;
    };

    // Extends a regular expression.  Returns a new RegExp
    // using pre + regex + post as the expression.
    // Used in a few functions where we have a base
    // expression and we want to pre- or append some
    // conditions to it (e.g. adding "$" to the end).
    // The flags are unchanged.
    //
    // regex is a RegExp, pre and post are strings.
321
    util.extendRegExp = function(regex, pre, post) {
Rocky Duan committed
322
        if (pre === null || pre === undefined) {
323
            pre = '';
Rocky Duan committed
324 325
        }
        if (post === null || post === undefined) {
326
            post = '';
Rocky Duan committed
327 328 329 330 331 332
        }

        var pattern = regex.toString();
        var flags;

        // Replace the flags with empty space and store them.
333
        pattern = pattern.replace(/\/([gim]*)$/, function(wholeMatch, flagsPart) {
Rocky Duan committed
334
            flags = flagsPart;
335
            return '';
Rocky Duan committed
336 337 338
        });

        // Remove the slash delimiters on the regular expression.
339
        pattern = pattern.replace(/(^\/|\/$)/g, '');
Rocky Duan committed
340 341 342
        pattern = pre + pattern + post;

        return new re(pattern, flags);
343
    };
Rocky Duan committed
344 345 346 347

    // UNFINISHED
    // The assignment in the while loop makes jslint cranky.
    // I'll change it to a better loop later.
348
    position.getTop = function(elem, isInner) {
Rocky Duan committed
349 350 351 352 353 354 355 356 357
        var result = elem.offsetTop;
        if (!isInner) {
            while (elem = elem.offsetParent) {
                result += elem.offsetTop;
            }
        }
        return result;
    };

358
    position.getHeight = function(elem) {
Rocky Duan committed
359 360 361
        return elem.offsetHeight || elem.scrollHeight;
    };

362
    position.getWidth = function(elem) {
Rocky Duan committed
363 364 365
        return elem.offsetWidth || elem.scrollWidth;
    };

366
    position.getPageSize = function() {
Rocky Duan committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        var scrollWidth, scrollHeight;
        var innerWidth, innerHeight;

        // It's not very clear which blocks work with which browsers.
        if (self.innerHeight && self.scrollMaxY) {
            scrollWidth = doc.body.scrollWidth;
            scrollHeight = self.innerHeight + self.scrollMaxY;
        }
        else if (doc.body.scrollHeight > doc.body.offsetHeight) {
            scrollWidth = doc.body.scrollWidth;
            scrollHeight = doc.body.scrollHeight;
        }
        else {
            scrollWidth = doc.body.offsetWidth;
            scrollHeight = doc.body.offsetHeight;
        }

        if (self.innerHeight) {
            // Non-IE browser
            innerWidth = self.innerWidth;
            innerHeight = self.innerHeight;
        }
        else if (doc.documentElement && doc.documentElement.clientHeight) {
            // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
            innerWidth = doc.documentElement.clientWidth;
            innerHeight = doc.documentElement.clientHeight;
        }
        else if (doc.body) {
            // Other versions of IE
            innerWidth = doc.body.clientWidth;
            innerHeight = doc.body.clientHeight;
        }

        var maxWidth = Math.max(scrollWidth, innerWidth);
        var maxHeight = Math.max(scrollHeight, innerHeight);
        return [maxWidth, maxHeight, innerWidth, innerHeight];
    };

    // Handles pushing and popping TextareaStates for undo/redo commands.
    // I should rename the stack variables to list.
407
    function UndoManager(callback, panels) {
Rocky Duan committed
408 409 410
        var undoObj = this;
        var undoStack = []; // A stack of undo states
        var stackPtr = 0; // The index of the current state
411
        var mode = 'none';
Rocky Duan committed
412 413 414 415 416
        var lastState; // The last state
        var timer; // The setTimeout handle for cancelling the timer
        var inputStateObj;

        // Set the mode for later logic steps.
417
        var setMode = function(newMode, noSave) {
Rocky Duan committed
418 419 420 421 422 423 424
            if (mode != newMode) {
                mode = newMode;
                if (!noSave) {
                    saveState();
                }
            }

425
            if (!uaSniffed.isIE || mode != 'moving') {
Rocky Duan committed
426 427 428 429 430 431 432
                timer = setTimeout(refreshState, 1);
            }
            else {
                inputStateObj = null;
            }
        };

433
        var refreshState = function(isInitialState) {
Rocky Duan committed
434 435 436 437
            inputStateObj = new TextareaState(panels, isInitialState);
            timer = undefined;
        };

438 439
        this.setCommandMode = function() {
            mode = 'command';
Rocky Duan committed
440 441 442 443
            saveState();
            timer = setTimeout(refreshState, 0);
        };

444
        this.canUndo = function() {
Rocky Duan committed
445 446 447
            return stackPtr > 1;
        };

448
        this.canRedo = function() {
Rocky Duan committed
449 450 451 452 453 454 455
            if (undoStack[stackPtr + 1]) {
                return true;
            }
            return false;
        };

        // Removes the last state and restores it.
456
        this.undo = function() {
Rocky Duan committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            if (undoObj.canUndo()) {
                if (lastState) {
                    // What about setting state -1 to null or checking for undefined?
                    lastState.restore();
                    lastState = null;
                }
                else {
                    undoStack[stackPtr] = new TextareaState(panels);
                    undoStack[--stackPtr].restore();

                    if (callback) {
                        callback();
                    }
                }
            }

473
            mode = 'none';
Rocky Duan committed
474 475 476 477 478
            panels.input.focus();
            refreshState();
        };

        // Redo an action.
479 480
        this.redo = function() {
            if (undoObj.canRedo()) {
Rocky Duan committed
481 482 483 484 485 486 487
                undoStack[++stackPtr].restore();

                if (callback) {
                    callback();
                }
            }

488
            mode = 'none';
Rocky Duan committed
489 490 491 492 493
            panels.input.focus();
            refreshState();
        };

        // Push the input area state to the stack.
494
        var saveState = function() {
Rocky Duan committed
495 496 497 498 499
            var currState = inputStateObj || new TextareaState(panels);

            if (!currState) {
                return false;
            }
500
            if (mode == 'moving') {
Rocky Duan committed
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
                if (!lastState) {
                    lastState = currState;
                }
                return;
            }
            if (lastState) {
                if (undoStack[stackPtr - 1].text != lastState.text) {
                    undoStack[stackPtr++] = lastState;
                }
                lastState = null;
            }
            undoStack[stackPtr++] = currState;
            undoStack[stackPtr + 1] = null;
            if (callback) {
                callback();
            }
        };

519
        var handleCtrlYZ = function(event) {
Rocky Duan committed
520 521
            var handled = false;

522
            if (event.ctrlKey || event.metaKey) {
Rocky Duan committed
523 524 525 526 527 528
                // IE and Opera do not support charCode.
                var keyCode = event.charCode || event.keyCode;
                var keyCodeChar = String.fromCharCode(keyCode);

                switch (keyCodeChar) {

529 530 531 532
                case 'y':
                    undoObj.redo();
                    handled = true;
                    break;
Rocky Duan committed
533

534 535 536 537 538 539 540 541 542
                case 'z':
                    if (!event.shiftKey) {
                        undoObj.undo();
                    }
                    else {
                        undoObj.redo();
                    }
                    handled = true;
                    break;
Rocky Duan committed
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
                }
            }

            if (handled) {
                if (event.preventDefault) {
                    event.preventDefault();
                }
                if (window.event) {
                    window.event.returnValue = false;
                }
                return;
            }
        };

        // Set the mode depending on what is going on in the input area.
558 559
        var handleModeChange = function(event) {
            if (!event.ctrlKey && !event.metaKey) {
Rocky Duan committed
560 561 562 563 564
                var keyCode = event.keyCode;

                if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
                    // 33 - 40: page up/dn and arrow keys
                    // 63232 - 63235: page up/dn and arrow keys on safari
565
                    setMode('moving');
Rocky Duan committed
566 567 568 569 570
                }
                else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
                    // 8: backspace
                    // 46: delete
                    // 127: delete
571
                    setMode('deleting');
Rocky Duan committed
572 573 574
                }
                else if (keyCode == 13) {
                    // 13: Enter
575
                    setMode('newlines');
Rocky Duan committed
576 577 578
                }
                else if (keyCode == 27) {
                    // 27: escape
579
                    setMode('escape');
Rocky Duan committed
580 581
                }
                else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
582
                    // 16-20 are shift, etc.
Rocky Duan committed
583 584 585
                    // 91: left window key
                    // I think this might be a little messed up since there are
                    // a lot of nonprinting keys above 20.
586
                    setMode('typing');
Rocky Duan committed
587 588 589 590
                }
            }
        };

591 592
        var setEventHandlers = function() {
            util.addEvent(panels.input, 'keypress', function(event) {
Rocky Duan committed
593 594 595 596 597 598 599
                // keyCode 89: y
                // keyCode 90: z
                if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
                    event.preventDefault();
                }
            });

600
            var handlePaste = function() {
Rocky Duan committed
601 602
                if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
                    if (timer == undefined) {
603
                        mode = 'paste';
Rocky Duan committed
604 605 606 607 608 609
                        saveState();
                        refreshState();
                    }
                }
            };

610 611 612 613
            util.addEvent(panels.input, 'keydown', handleCtrlYZ);
            util.addEvent(panels.input, 'keydown', handleModeChange);
            util.addEvent(panels.input, 'mousedown', function() {
                setMode('moving');
Rocky Duan committed
614 615 616 617 618 619
            });

            panels.input.onpaste = handlePaste;
            panels.input.ondrop = handlePaste;
        };

620
        var init = function() {
Rocky Duan committed
621 622 623 624 625 626 627 628 629 630 631 632
            setEventHandlers();
            refreshState(true);
            saveState();
        };

        init();
    }

    // end of UndoManager

    // The input textarea state/contents.
    // This is used to implement undo/redo by the undo manager.
633
    function TextareaState(panels, isInitialState) {
Rocky Duan committed
634 635 636
        // Aliases
        var stateObj = this;
        var inputArea = panels.input;
637
        this.init = function() {
Rocky Duan committed
638 639 640 641 642 643 644 645 646 647 648
            if (!util.isVisible(inputArea)) {
                return;
            }
            if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box
                return;
            }

            this.setInputAreaSelectionStartEnd();
            this.scrollTop = inputArea.scrollTop;
            if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
                this.text = inputArea.value;
649 650
            }
        };
Rocky Duan committed
651 652 653

        // Sets the selected text in the input box after we've performed an
        // operation.
654
        this.setInputAreaSelection = function() {
Rocky Duan committed
655 656 657 658
            if (!util.isVisible(inputArea)) {
                return;
            }

659
            if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
Rocky Duan committed
660 661 662 663 664
                inputArea.focus();
                inputArea.selectionStart = stateObj.start;
                inputArea.selectionEnd = stateObj.end;
                inputArea.scrollTop = stateObj.scrollTop;
            }
665
            else if (doc.selection) {
Rocky Duan committed
666 667 668 669 670 671
                if (doc.activeElement && doc.activeElement !== inputArea) {
                    return;
                }

                inputArea.focus();
                var range = inputArea.createTextRange();
672 673 674 675
                range.moveStart('character', -inputArea.value.length);
                range.moveEnd('character', -inputArea.value.length);
                range.moveEnd('character', stateObj.end);
                range.moveStart('character', stateObj.start);
Rocky Duan committed
676 677 678 679
                range.select();
            }
        };

680 681
        this.setInputAreaSelectionStartEnd = function() {
            if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
Rocky Duan committed
682 683 684
                stateObj.start = inputArea.selectionStart;
                stateObj.end = inputArea.selectionEnd;
            }
685
            else if (doc.selection) {
Rocky Duan committed
686 687 688 689 690 691 692 693
                stateObj.text = util.fixEolChars(inputArea.value);

                // IE loses the selection in the textarea when buttons are
                // clicked.  On IE we cache the selection. Here, if something is cached,
                // we take it.
                var range = panels.ieCachedRange || doc.selection.createRange();

                var fixedRange = util.fixEolChars(range.text);
694
                var marker = '\x07';
Rocky Duan committed
695 696 697 698
                var markedRange = marker + fixedRange + marker;
                range.text = markedRange;
                var inputText = util.fixEolChars(inputArea.value);

699
                range.moveStart('character', -markedRange.length);
Rocky Duan committed
700 701 702 703 704 705 706 707
                range.text = fixedRange;

                stateObj.start = inputText.indexOf(marker);
                stateObj.end = inputText.lastIndexOf(marker) - marker.length;

                var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;

                if (len) {
708
                    range.moveStart('character', -fixedRange.length);
Rocky Duan committed
709
                    while (len--) {
710
                        fixedRange += '\n';
Rocky Duan committed
711 712 713 714 715 716 717
                        stateObj.end += 1;
                    }
                    range.text = fixedRange;
                }

                if (panels.ieCachedRange)
                    stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange
718

Rocky Duan committed
719 720 721 722 723 724 725
                panels.ieCachedRange = null;

                this.setInputAreaSelection();
            }
        };

        // Restore this state into the input area.
726
        this.restore = function() {
Rocky Duan committed
727 728 729 730 731 732 733 734
            if (stateObj.text != undefined && stateObj.text != inputArea.value) {
                inputArea.value = stateObj.text;
            }
            this.setInputAreaSelection();
            inputArea.scrollTop = stateObj.scrollTop;
        };

        // Gets a collection of HTML chunks from the inptut textarea.
735
        this.getChunks = function() {
Rocky Duan committed
736 737
            var chunk = new Chunks();
            chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
738
            chunk.startTag = '';
Rocky Duan committed
739
            chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
740
            chunk.endTag = '';
Rocky Duan committed
741 742 743 744 745 746 747
            chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
            chunk.scrollTop = stateObj.scrollTop;

            return chunk;
        };

        // Sets the TextareaState properties given a chunk of markdown.
748
        this.setChunks = function(chunk) {
Rocky Duan committed
749 750 751 752 753 754 755 756 757
            chunk.before = chunk.before + chunk.startTag;
            chunk.after = chunk.endTag + chunk.after;

            this.start = chunk.before.length;
            this.end = chunk.before.length + chunk.selection.length;
            this.text = chunk.before + chunk.selection + chunk.after;
            this.scrollTop = chunk.scrollTop;
        };
        this.init();
758
    }
Rocky Duan committed
759

760
    function PreviewManager(converter, panels, previewPushCallback) {
Rocky Duan committed
761 762 763 764 765
        var managerObj = this;
        var timeout;
        var elapsedTime;
        var oldInputText;
        var maxDelay = 3000;
766
        var startType = 'delayed'; // The other legal value is "manual"
Rocky Duan committed
767 768

        // Adds event listeners to elements
769 770
        var setupEvents = function(inputElem, listener) {
            util.addEvent(inputElem, 'input', listener);
Rocky Duan committed
771 772 773
            inputElem.onpaste = listener;
            inputElem.ondrop = listener;

774 775
            util.addEvent(inputElem, 'keypress', listener);
            util.addEvent(inputElem, 'keydown', listener);
Rocky Duan committed
776 777
        };

778
        var getDocScrollTop = function() {
Rocky Duan committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
            var result = 0;

            if (window.innerHeight) {
                result = window.pageYOffset;
            }
            else
                if (doc.documentElement && doc.documentElement.scrollTop) {
                    result = doc.documentElement.scrollTop;
                }
                else
                    if (doc.body) {
                        result = doc.body.scrollTop;
                    }

            return result;
        };

796
        var makePreviewHtml = function() {
Rocky Duan committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
            // If there is no registered preview panel
            // there is nothing to do.
            if (!panels.preview)
                return;


            var text = panels.input.value;
            if (text && text == oldInputText) {
                return; // Input text hasn't changed.
            }
            else {
                oldInputText = text;
            }

            var prevTime = new Date().getTime();

            text = converter.makeHtml(text);

            // Calculate the processing time of the HTML creation.
            // It's used as the delay time in the event listener.
            var currTime = new Date().getTime();
            elapsedTime = currTime - prevTime;

            pushPreviewHtml(text);
        };

        // setTimeout is already used.  Used as an event listener.
824
        var applyTimeout = function() {
Rocky Duan committed
825 826 827 828 829
            if (timeout) {
                clearTimeout(timeout);
                timeout = undefined;
            }

830
            if (startType !== 'manual') {
Rocky Duan committed
831 832
                var delay = 0;

833
                if (startType === 'delayed') {
Rocky Duan committed
834 835 836 837 838 839 840 841 842 843
                    delay = elapsedTime;
                }

                if (delay > maxDelay) {
                    delay = maxDelay;
                }
                timeout = setTimeout(makePreviewHtml, delay);
            }
        };

844
        var getScaleFactor = function(panel) {
Rocky Duan committed
845 846 847 848 849 850
            if (panel.scrollHeight <= panel.clientHeight) {
                return 1;
            }
            return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
        };

851
        var setPanelScrollTops = function() {
Rocky Duan committed
852 853 854 855 856
            if (panels.preview) {
                panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
            }
        };

857
        this.refresh = function(requiresRefresh) {
Rocky Duan committed
858
            if (requiresRefresh) {
859
                oldInputText = '';
Rocky Duan committed
860 861 862 863 864 865 866
                makePreviewHtml();
            }
            else {
                applyTimeout();
            }
        };

867
        this.processingTime = function() {
Rocky Duan committed
868 869 870 871 872 873 874 875
            return elapsedTime;
        };

        var isFirstTimeFilled = true;

        // IE doesn't let you use innerHTML if the element is contained somewhere in a table
        // (which is the case for inline editing) -- in that case, detach the element, set the
        // value, and reattach. Yes, that *is* ridiculous.
876
        var ieSafePreviewSet = function(text) {
Rocky Duan committed
877 878 879 880 881 882 883 884 885
            var preview = panels.preview;
            var parent = preview.parentNode;
            var sibling = preview.nextSibling;
            parent.removeChild(preview);
            preview.innerHTML = text;
            if (!sibling)
                parent.appendChild(preview);
            else
                parent.insertBefore(preview, sibling);
886
        };
Rocky Duan committed
887

888
        var nonSuckyBrowserPreviewSet = function(text) {
Rocky Duan committed
889
            panels.preview.innerHTML = text;
890
        };
Rocky Duan committed
891 892 893

        var previewSetter;

894
        var previewSet = function(text) {
Rocky Duan committed
895 896 897 898 899 900 901 902 903 904 905 906
            if (previewSetter)
                return previewSetter(text);

            try {
                nonSuckyBrowserPreviewSet(text);
                previewSetter = nonSuckyBrowserPreviewSet;
            } catch (e) {
                previewSetter = ieSafePreviewSet;
                previewSetter(text);
            }
        };

907
        var pushPreviewHtml = function(text) {
Rocky Duan committed
908 909 910
            var emptyTop = position.getTop(panels.input) - getDocScrollTop();

            if (panels.preview) {
911
                previewPushCallback(text, previewSet);
Rocky Duan committed
912 913 914 915 916 917 918 919 920 921 922 923
            }

            setPanelScrollTops();

            if (isFirstTimeFilled) {
                isFirstTimeFilled = false;
                return;
            }

            var fullTop = position.getTop(panels.input) - getDocScrollTop();

            if (uaSniffed.isIE) {
924
                setTimeout(function() {
Rocky Duan committed
925 926 927 928 929 930 931 932
                    window.scrollBy(0, fullTop - emptyTop);
                }, 0);
            }
            else {
                window.scrollBy(0, fullTop - emptyTop);
            }
        };

933
        var init = function() {
Rocky Duan committed
934 935 936 937 938 939 940 941 942
            setupEvents(panels.input, applyTimeout);
            makePreviewHtml();

            if (panels.preview) {
                panels.preview.scrollTop = 0;
            }
        };

        init();
943
    }
Rocky Duan committed
944 945 946 947 948

    // Creates the background behind the hyperlink text entry box.
    // And download dialog
    // Most of this has been moved to CSS but the div creation and
    // browser-specific hacks remain here.
949 950
    ui.createBackground = function() {
        var background = doc.createElement('div'),
Rocky Duan committed
951
            style = background.style;
952

953
        background.className = 'wmd-prompt-background';
954

955 956
        style.position = 'absolute';
        style.top = '0';
Rocky Duan committed
957

958
        style.zIndex = '1000';
Rocky Duan committed
959 960

        if (uaSniffed.isIE) {
961
            style.filter = 'alpha(opacity=50)';
Rocky Duan committed
962 963
        }
        else {
964
            style.opacity = '0.5';
Rocky Duan committed
965 966 967
        }

        var pageSize = position.getPageSize();
968
        style.height = pageSize[1] + 'px';
Rocky Duan committed
969 970 971 972 973 974

        if (uaSniffed.isIE) {
            style.left = doc.documentElement.scrollLeft;
            style.width = doc.documentElement.clientWidth;
        }
        else {
975 976
            style.left = '0';
            style.width = '100%';
Rocky Duan committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990
        }

        doc.body.appendChild(background);
        return background;
    };

    // This simulates a modal dialog box and asks for the URL when you
    // click the hyperlink or image buttons.
    //
    // text: The html for the input box.
    // defaultInputText: The default value that appears in the input box.
    // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
    //      It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
    //      was chosen).
991
    ui.prompt = function(title,
992 993 994 995 996 997 998 999 1000 1001
                          urlLabel,
                          urlHelp,
                          urlError,
                          urlDescLabel,
                          urlDescHelp,
                          urlDescHelpLink,
                          urlDescError,
                          defaultInputText,
                          callback,
                          imageIsDecorativeLabel,
1002
                          imageUploadHandler) {
Rocky Duan committed
1003 1004
        // These variables need to be declared at this level since they are used
        // in multiple functions.
1005 1006 1007 1008 1009 1010 1011
        var dialog,         // The dialog box.
            urlInput,       // The text box where you enter the hyperlink.
            urlErrorMsg,
            descInput,      // The text box where you enter the description.
            descErrorMsg,
            okButton,
            cancelButton;
Rocky Duan committed
1012 1013 1014

        // Used as a keydown event handler. Esc dismisses the prompt.
        // Key code 27 is ESC.
1015
        var checkEscape = function(key) {
Rocky Duan committed
1016 1017 1018 1019 1020 1021
            var code = (key.charCode || key.keyCode);
            if (code === 27) {
                close(true);
            }
        };

1022
        var clearFormErrorMessages = function() {
1023 1024 1025 1026 1027 1028
            urlInput.classList.remove('has-error');
            urlErrorMsg.style.display = 'none';
            descInput.classList.remove('has-error');
            descErrorMsg.style.display = 'none';
        };

Rocky Duan committed
1029 1030 1031
        // Dismisses the hyperlink input box.
        // isCancel is true if we don't care about the input text.
        // isCancel is false if we are going to keep the text.
1032 1033
        var close = function(isCancel) {
            util.removeEvent(doc.body, 'keydown', checkEscape);
1034 1035 1036 1037
            var url = urlInput.value.trim();
            var description = descInput.value.trim();

            clearFormErrorMessages();
Rocky Duan committed
1038 1039

            if (isCancel) {
1040
                url = null;
Rocky Duan committed
1041 1042 1043
            }
            else {
                // Fixes common pasting errors.
1044
                url = url.replace(/^http:\/\/(https?|ftp):\/\//, '$1://');
1045
                // doesn't change url if started with '/' (local)
1046 1047
                if (!/^(?:https?|ftp):\/\//.test(url) && url.charAt(0) !== '/') {
                    url = 'http://' + url;
1048
                }
Rocky Duan committed
1049 1050
            }

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
            var isValidUrl = util.isValidUrl(url),
                isValidDesc = (
                    descInput.checkValidity() &&
                    (descInput.required ? description.length : true)
                );

            if ((isValidUrl && isValidDesc) || isCancel) {
                dialog.parentNode.removeChild(dialog);
                callback(url, description);
            } else {
                var errorCount = 0;
                if (!isValidUrl) {
                    urlInput.classList.add('has-error');
                    urlErrorMsg.style.display = 'inline-block';
                    errorCount += 1;
                } if (!isValidDesc) {
                    descInput.classList.add('has-error');
                    descErrorMsg.style.display = 'inline-block';
                    errorCount += 1;
                }
Rocky Duan committed
1071

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
                document.getElementById('wmd-editor-dialog-form-errors').textContent = [
                    interpolate(
                        ngettext(
                            // Translators: 'errorCount' is the number of errors found in the form.
                            '%(errorCount)s error found in form.', '%(errorCount)s errors found in form.',
                            errorCount
                        ), {'errorCount': errorCount}, true
                    ),
                    !isValidUrl ? urlErrorMsg.textContent : '',
                    !isValidDesc ? descErrorMsg.textContent : ''
                ].join(' ');
Rocky Duan committed
1083

1084 1085
                document.getElementById('wmd-editor-dialog-form-errors').focus();
            }
Rocky Duan committed
1086

1087 1088
            return false;
        };
Rocky Duan committed
1089 1090

        // Create the text input box form/window.
1091
        var createDialog = function() {
Rocky Duan committed
1092
            // The main dialog box.
1093
            dialog = doc.createElement('div');
1094
            dialog.innerHTML = _.template(
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                document.getElementById('customwmd-prompt-template').innerHTML)({
                    title: title,
                    uploadFieldClass: (imageUploadHandler ? 'file-upload' : ''),
                    urlLabel: urlLabel,
                    urlError: urlError,
                    urlHelp: urlHelp,
                    urlDescLabel: urlDescLabel,
                    descError: urlDescError,
                    urlDescHelp: urlDescHelp,
                    urlDescHelpLink: urlDescHelpLink,
                    okText: gettext('OK'),
                    cancelText: gettext('Cancel'),
                    chooseFileText: gettext('Choose File'),
                    imageIsDecorativeLabel: imageIsDecorativeLabel,
                    imageUploadHandler: imageUploadHandler
                });
1111
            dialog.setAttribute('dir', doc.head.getAttribute('dir'));
1112 1113 1114 1115 1116 1117 1118 1119
            dialog.setAttribute('role', 'dialog');
            dialog.setAttribute('tabindex', '-1');
            dialog.setAttribute('aria-labelledby', 'editorDialogTitle');
            dialog.className = 'wmd-prompt-dialog';
            dialog.style.padding = '10px;';
            dialog.style.position = 'fixed';
            dialog.style.width = '500px';
            dialog.style.zIndex = '1001';
Rocky Duan committed
1120

1121
            doc.body.appendChild(dialog);
Rocky Duan committed
1122

1123 1124
            // This has to be done AFTER adding the dialog to the form if you
            // want it to be centered.
1125 1126 1127 1128
            util.addEvent(doc.body, 'keydown', checkEscape);
            dialog.style.top = '50%';
            dialog.style.left = '50%';
            dialog.style.display = 'block';
Rocky Duan committed
1129
            if (uaSniffed.isIE_5or6) {
1130 1131 1132
                dialog.style.position = 'absolute';
                dialog.style.top = doc.documentElement.scrollTop + 200 + 'px';
                dialog.style.left = '50%';
Rocky Duan committed
1133
            }
1134 1135
            dialog.style.marginTop = -(position.getHeight(dialog) / 2) + 'px';
            dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + 'px';
Rocky Duan committed
1136

1137 1138 1139 1140
            urlInput = document.getElementById('new-url-input');
            urlErrorMsg = document.getElementById('new-url-input-field-message');
            descInput = document.getElementById('new-url-desc-input');
            descErrorMsg = document.getElementById('new-url-desc-input-field-message');
1141 1142
            urlInput.value = defaultInputText;

1143 1144
            okButton = document.getElementById('new-link-image-ok');
            cancelButton = document.getElementById('new-link-image-cancel');
1145

1146 1147
            okButton.onclick = function() { return close(false); };
            cancelButton.onclick = function() { return close(true); };
1148

1149 1150 1151
            if (imageUploadHandler) {
                var startUploadHandler = function() {
                    document.getElementById('file-upload').onchange = function() {
1152 1153 1154 1155 1156 1157 1158 1159
                        imageUploadHandler(this, urlInput);
                        urlInput.focus();

                        // Ensures that a user can update their file choice.
                        startUploadHandler();
                    };
                };
                startUploadHandler();
1160 1161
                document.getElementById('file-upload-proxy').onclick = function() {
                    document.getElementById('file-upload').click();
1162 1163
                    return false;
                };
1164
                document.getElementById('img-is-decorative').onchange = function() {
1165 1166 1167 1168 1169
                    descInput.required = !descInput.required;
                };
            }

            // trap focus in the dialog box
1170
            $(dialog).on('keydown', function(event) {
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
                // On tab backward from the first tabbable item in the prompt
                if (event.which === 9 && event.shiftKey && event.target === urlInput) {
                    event.preventDefault();
                    cancelButton.focus();
                }
                // On tab forward from the last tabbable item in the prompt
                else if (event.which === 9 && !event.shiftKey && event.target === cancelButton) {
                    event.preventDefault();
                    urlInput.focus();
                }
            });
Rocky Duan committed
1182 1183
        };

1184

Rocky Duan committed
1185 1186
        // Why is this in a zero-length timeout?
        // Is it working around a browser bug?
1187
        setTimeout(function() {
Rocky Duan committed
1188 1189 1190
            createDialog();

            var defTextLen = defaultInputText.length;
1191 1192 1193
            if (urlInput.selectionStart !== undefined) {
                urlInput.selectionStart = 0;
                urlInput.selectionEnd = defTextLen;
Rocky Duan committed
1194
            }
1195 1196
            else if (urlInput.createTextRange) {
                var range = urlInput.createTextRange();
Rocky Duan committed
1197
                range.collapse(false);
1198 1199
                range.moveStart('character', -defTextLen);
                range.moveEnd('character', defTextLen);
Rocky Duan committed
1200 1201 1202
                range.select();
            }

1203
            dialog.focus();
Rocky Duan committed
1204 1205 1206
        }, 0);
    };

1207
    function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, imageUploadHandler) {
Rocky Duan committed
1208 1209 1210 1211 1212
        var inputBox = panels.input,
            buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.

        makeSpritedButtonRow();

1213
        var keyEvent = 'keydown';
Rocky Duan committed
1214
        if (uaSniffed.isOpera) {
1215
            keyEvent = 'keypress';
Rocky Duan committed
1216 1217
        }

1218
        util.addEvent(inputBox, keyEvent, function(key) {
Rocky Duan committed
1219
            // Check to see if we have a button key and, if so execute the callback.
1220
            if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
Rocky Duan committed
1221 1222 1223 1224
                var keyCode = key.charCode || key.keyCode;
                var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();

                switch (keyCodeStr) {
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
                case 'b':
                    doClick(buttons.bold);
                    break;
                case 'i':
                    doClick(buttons.italic);
                    break;
                case 'l':
                    doClick(buttons.link);
                    break;
                case 'q':
                    doClick(buttons.quote);
                    break;
                case 'k':
                    doClick(buttons.code);
                    break;
                case 'g':
                    doClick(buttons.image);
                    break;
                case 'o':
                    doClick(buttons.olist);
                    break;
                case 'u':
                    doClick(buttons.ulist);
                    break;
                case 'h':
                    doClick(buttons.heading);
                    break;
                case 'r':
                    doClick(buttons.hr);
                    break;
                case 'y':
                    doClick(buttons.redo);
                    break;
                case 'z':
                    if (key.shiftKey) {
Rocky Duan committed
1260
                        doClick(buttons.redo);
1261 1262 1263 1264 1265 1266 1267
                    }
                    else {
                        doClick(buttons.undo);
                    }
                    break;
                default:
                    return;
Rocky Duan committed
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                }


                if (key.preventDefault) {
                    key.preventDefault();
                }

                if (window.event) {
                    window.event.returnValue = false;
                }
            }
        });

        // Auto-indent on shift-enter
1282
        util.addEvent(inputBox, 'keyup', function(key) {
Rocky Duan committed
1283 1284 1285 1286 1287
            if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
                var keyCode = key.charCode || key.keyCode;
                // Character 13 is Enter
                if (keyCode === 13) {
                    var fakeButton = {};
1288
                    fakeButton.textOp = bindCommand('doAutoindent');
Rocky Duan committed
1289 1290 1291 1292 1293 1294 1295
                    doClick(fakeButton);
                }
            }
        });

        // special handler because IE clears the context of the textbox on ESC
        if (uaSniffed.isIE) {
1296
            util.addEvent(inputBox, 'keydown', function(key) {
Rocky Duan committed
1297 1298 1299 1300 1301 1302 1303 1304 1305
                var code = key.keyCode;
                if (code === 27) {
                    return false;
                }
            });
        }


        // Perform the button's action.
1306
        function doClick(button) {
Rocky Duan committed
1307 1308
            inputBox.focus();

1309
            if (button.textOp) {
Rocky Duan committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
                if (undoManager) {
                    undoManager.setCommandMode();
                }

                var state = new TextareaState(panels);

                if (!state) {
                    return;
                }

                var chunks = state.getChunks();

                // Some commands launch a "modal" prompt dialog.  Javascript
                // can't really make a modal dialog box and the WMD code
                // will continue to execute while the dialog is displayed.
                // This prevents the dialog pattern I'm used to and means
                // I can't do something like this:
                //
                // var link = CreateLinkDialog();
                // makeMarkdownLink(link);
1330
                //
Rocky Duan committed
1331 1332 1333 1334 1335 1336 1337 1338
                // Instead of this straightforward method of handling a
                // dialog I have to pass any code which would execute
                // after the dialog is dismissed (e.g. link creation)
                // in a function parameter.
                //
                // Yes this is awkward and I think it sucks, but there's
                // no real workaround.  Only the image and link code
                // create dialogs and require the function pointers.
1339
                var fixupInputArea = function() {
Rocky Duan committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
                    inputBox.focus();

                    if (chunks) {
                        state.setChunks(chunks);
                    }

                    state.restore();
                    previewManager.refresh();
                };

                var noCleanup = button.textOp(chunks, fixupInputArea);

                if (!noCleanup) {
                    fixupInputArea();
1354
                }
Rocky Duan committed
1355 1356 1357 1358 1359
            }

            if (button.execute) {
                button.execute(undoManager);
            }
1360
        }
Rocky Duan committed
1361

1362 1363 1364 1365 1366
        function setupButton(button, isEnabled) {
            var normalYShift = '0px';
            var disabledYShift = '-20px';
            var highlightYShift = '-40px';
            var image = button.getElementsByTagName('span')[0];
Rocky Duan committed
1367
            if (isEnabled) {
1368 1369 1370
                image.style.backgroundPosition = button.XShift + ' ' + normalYShift;
                button.onmouseover = function() {
                    image.style.backgroundPosition = this.XShift + ' ' + highlightYShift;
Rocky Duan committed
1371 1372
                };

1373 1374
                button.onmouseout = function() {
                    image.style.backgroundPosition = this.XShift + ' ' + normalYShift;
Rocky Duan committed
1375 1376 1377 1378 1379 1380
                };

                // IE tries to select the background image "button" text (it's
                // implemented in a list item) so we have to cache the selection
                // on mousedown.
                if (uaSniffed.isIE) {
1381
                    button.onmousedown = function() {
Rocky Duan committed
1382 1383 1384 1385 1386 1387 1388 1389 1390
                        if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
                            return;
                        }
                        panels.ieCachedRange = document.selection.createRange();
                        panels.ieCachedScrollTop = panels.input.scrollTop;
                    };
                }

                if (!button.isHelp) {
1391
                    button.onclick = function() {
Rocky Duan committed
1392 1393 1394 1395 1396
                        if (this.onmouseout) {
                            this.onmouseout();
                        }
                        doClick(this);
                        return false;
1397 1398
                    };
                    util.addEvent(button, 'keydown', function(event) {
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
                        var keyCode = event.charCode || event.keyCode;
                        if (keyCode == 32 || keyCode == 13) {
                            if (event.preventDefault) {
                                event.preventDefault();
                            }
                            if (window.event) {
                                window.event.returnValue = false;
                            }
                            doClick(button);
                        }
1409
                    });
Rocky Duan committed
1410
                }
1411 1412 1413 1414
                // This line does not appear in vanilla WMD. It was added by edX to improve accessibility.
                // It should become a separate commit applied to WMD's official HEAD if we remove this edited version
                // of WMD from Git and install it from NPM / a maintained public fork.
                button.removeAttribute('aria-disabled');
Rocky Duan committed
1415 1416
            }
            else {
1417 1418
                image.style.backgroundPosition = button.XShift + ' ' + disabledYShift;
                button.onmouseover = button.onmouseout = button.onclick = function() { };
1419 1420 1421 1422
                // This line does not appear in vanilla WMD. It was added by edX to improve accessibility.
                // It should become a separate commit applied to WMD's official HEAD if we remove this edited version
                // of WMD from Git and install it from NPM / a maintained public fork.
                button.setAttribute('aria-disabled', true);
Rocky Duan committed
1423 1424 1425 1426
            }
        }

        function bindCommand(method) {
1427
            if (typeof method === 'string')
Rocky Duan committed
1428
                method = commandManager[method];
1429
            return function() { method.apply(commandManager, arguments); };
Rocky Duan committed
1430 1431
        }

1432
        function makeSpritedButtonRow() {
Rocky Duan committed
1433 1434
            var buttonBar = panels.buttonBar;

1435 1436 1437
            var normalYShift = '0px';
            var disabledYShift = '-20px';
            var highlightYShift = '-40px';
Rocky Duan committed
1438

1439 1440 1441
            var buttonRow = document.createElement('div');
            buttonRow.setAttribute('role', 'toolbar');
            buttonRow.id = 'wmd-button-row' + postfix;
Rocky Duan committed
1442 1443 1444
            buttonRow.className = 'wmd-button-row';
            buttonRow = buttonBar.appendChild(buttonRow);
            var xPosition = 0;
1445
            var makeButton = function(id, title, XShift, textOp) {
1446
                var button = document.createElement('button');
1447
                button.tabIndex = 0;
1448 1449
                button.className = 'wmd-button';
                button.style.left = xPosition + 'px';
Rocky Duan committed
1450
                xPosition += 25;
1451
                var buttonImage = document.createElement('span');
Rocky Duan committed
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
                button.id = id + postfix;
                button.appendChild(buttonImage);
                button.title = title;
                button.XShift = XShift;
                if (textOp)
                    button.textOp = textOp;
                setupButton(button, true);
                buttonRow.appendChild(button);
                return button;
            };
1462 1463 1464 1465 1466
            var makeSpacer = function(num) {
                var spacer = document.createElement('span');
                spacer.setAttribute('role', 'separator');
                spacer.className = 'wmd-spacer wmd-spacer' + num;
                spacer.id = 'wmd-spacer' + num + postfix;
Rocky Duan committed
1467 1468
                buttonRow.appendChild(spacer);
                xPosition += 25;
1469
            };
Rocky Duan committed
1470

1471 1472
            buttons.bold = makeButton('wmd-bold-button', gettext('Bold (Ctrl+B)'), '0px', bindCommand('doBold'));
            buttons.italic = makeButton('wmd-italic-button', gettext('Italic (Ctrl+I)'), '-20px', bindCommand('doItalic'));
Rocky Duan committed
1473
            makeSpacer(1);
1474
            buttons.link = makeButton('wmd-link-button', gettext('Hyperlink (Ctrl+L)'), '-40px', bindCommand(function(chunk, postProcessing) {
Rocky Duan committed
1475 1476
                return this.doLinkOrImage(chunk, postProcessing, false);
            }));
1477 1478 1479
            buttons.quote = makeButton('wmd-quote-button', gettext('Blockquote (Ctrl+Q)'), '-60px', bindCommand('doBlockquote'));
            buttons.code = makeButton('wmd-code-button', gettext('Code Sample (Ctrl+K)'), '-80px', bindCommand('doCode'));
            buttons.image = makeButton('wmd-image-button', gettext('Image (Ctrl+G)'), '-100px', bindCommand(function(chunk, postProcessing) {
1480
                return this.doLinkOrImage(chunk, postProcessing, true, imageUploadHandler);
Rocky Duan committed
1481 1482
            }));
            makeSpacer(2);
1483
            buttons.olist = makeButton('wmd-olist-button', gettext('Numbered List (Ctrl+O)'), '-120px', bindCommand(function(chunk, postProcessing) {
Rocky Duan committed
1484 1485
                this.doList(chunk, postProcessing, true);
            }));
1486
            buttons.ulist = makeButton('wmd-ulist-button', gettext('Bulleted List (Ctrl+U)'), '-140px', bindCommand(function(chunk, postProcessing) {
Rocky Duan committed
1487 1488
                this.doList(chunk, postProcessing, false);
            }));
1489 1490
            buttons.heading = makeButton('wmd-heading-button', gettext('Heading (Ctrl+H)'), '-160px', bindCommand('doHeading'));
            buttons.hr = makeButton('wmd-hr-button', gettext('Horizontal Rule (Ctrl+R)'), '-180px', bindCommand('doHorizontalRule'));
Rocky Duan committed
1491
            makeSpacer(3);
1492 1493
            buttons.undo = makeButton('wmd-undo-button', gettext('Undo (Ctrl+Z)'), '-200px', null);
            buttons.undo.execute = function(manager) { if (manager) manager.undo(); };
Rocky Duan committed
1494 1495

            var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
1496 1497
                gettext('Redo (Ctrl+Y)') :
                gettext('Redo (Ctrl+Shift+Z)'); // mac and other non-Windows platforms
Rocky Duan committed
1498

1499 1500
            buttons.redo = makeButton('wmd-redo-button', redoTitle, '-220px', null);
            buttons.redo.execute = function(manager) { if (manager) manager.redo(); };
Rocky Duan committed
1501 1502

            if (helpOptions) {
1503 1504
                var helpButton = document.createElement('span');
                var helpButtonImage = document.createElement('span');
Rocky Duan committed
1505
                helpButton.appendChild(helpButtonImage);
1506 1507 1508
                helpButton.className = 'wmd-button wmd-help-button';
                helpButton.id = 'wmd-help-button' + postfix;
                helpButton.XShift = '-240px';
Rocky Duan committed
1509
                helpButton.isHelp = true;
1510
                helpButton.style.right = '0px';
Rocky Duan committed
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
                helpButton.title = helpOptions.title || defaultHelpHoverTitle;
                helpButton.onclick = helpOptions.handler;

                setupButton(helpButton, true);
                buttonRow.appendChild(helpButton);
                buttons.help = helpButton;
            }

            setUndoRedoButtonStates();
        }

        function setUndoRedoButtonStates() {
            if (undoManager) {
                setupButton(buttons.undo, undoManager.canUndo());
                setupButton(buttons.redo, undoManager.canRedo());
            }
1527
        }
Rocky Duan committed
1528

1529
        this.setUndoRedoButtonStates = setUndoRedoButtonStates;
Rocky Duan committed
1530 1531 1532 1533 1534 1535 1536 1537 1538
    }

    function CommandManager(pluginHooks) {
        this.hooks = pluginHooks;
    }

    var commandProto = CommandManager.prototype;

    // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1539
    commandProto.prefixes = '(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)';
Rocky Duan committed
1540 1541

    // Remove markdown symbols from the chunk selection.
1542 1543 1544
    commandProto.unwrap = function(chunk) {
        var txt = new re('([^\\n])\\n(?!(\\n|' + this.prefixes + '))', 'g');
        chunk.selection = chunk.selection.replace(txt, '$1 $2');
Rocky Duan committed
1545 1546
    };

1547
    commandProto.wrap = function(chunk, len) {
Rocky Duan committed
1548
        this.unwrap(chunk);
1549
        var regex = new re('(.{1,' + len + '})( +|$\\n?)', 'gm'),
Rocky Duan committed
1550 1551
            that = this;

1552 1553
        chunk.selection = chunk.selection.replace(regex, function(line, marked) {
            if (new re('^' + that.prefixes, '').test(line)) {
Rocky Duan committed
1554 1555
                return line;
            }
1556
            return marked + '\n';
Rocky Duan committed
1557 1558
        });

1559
        chunk.selection = chunk.selection.replace(/\s+$/, '');
Rocky Duan committed
1560 1561
    };

1562 1563
    commandProto.doBold = function(chunk, postProcessing) {
        return this.doBorI(chunk, postProcessing, 2, gettext('strong text'));
Rocky Duan committed
1564 1565
    };

1566 1567
    commandProto.doItalic = function(chunk, postProcessing) {
        return this.doBorI(chunk, postProcessing, 1, gettext('emphasized text'));
Rocky Duan committed
1568 1569 1570 1571 1572
    };

    // chunk: The selected region that will be enclosed with */**
    // nStars: 1 for italics, 2 for bold
    // insertText: If you just click the button without highlighting text, this gets inserted
1573
    commandProto.doBorI = function(chunk, postProcessing, nStars, insertText) {
Rocky Duan committed
1574 1575
        // Get rid of whitespace and fixup newlines.
        chunk.trimWhitespace();
1576
        chunk.selection = chunk.selection.replace(/\n{2,}/g, '\n');
Rocky Duan committed
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586

        // Look for stars before and after.  Is the chunk already marked up?
        // note that these regex matches cannot fail
        var starsBefore = /(\**$)/.exec(chunk.before)[0];
        var starsAfter = /(^\**)/.exec(chunk.after)[0];

        var prevStars = Math.min(starsBefore.length, starsAfter.length);

        // Remove stars if we have to since the button acts as a toggle.
        if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1587 1588
            chunk.before = chunk.before.replace(re('[*]{' + nStars + '}$', ''), '');
            chunk.after = chunk.after.replace(re('^[*]{' + nStars + '}', ''), '');
Rocky Duan committed
1589 1590 1591 1592
        }
        else if (!chunk.selection && starsAfter) {
            // It's not really clear why this code is necessary.  It just moves
            // some arbitrary stuff around.
1593 1594
            chunk.after = chunk.after.replace(/^([*_]*)/, '');
            chunk.before = chunk.before.replace(/(\s?)$/, '');
Rocky Duan committed
1595 1596 1597
            var whitespace = re.$1;
            chunk.before = chunk.before + starsAfter + whitespace;
        }
1598
        else {
Rocky Duan committed
1599 1600 1601 1602 1603 1604 1605
            // In most cases, if you don't have any selected text and click the button
            // you'll get a selected, marked up region with the default text inserted.
            if (!chunk.selection && !starsAfter) {
                chunk.selection = insertText;
            }

            // Add the true markup.
1606
            var markup = nStars <= 1 ? '*' : '**'; // shouldn't the test be = ?
Rocky Duan committed
1607 1608 1609 1610 1611 1612 1613
            chunk.before = chunk.before + markup;
            chunk.after = markup + chunk.after;
        }

        return;
    };

1614
    commandProto.stripLinkDefs = function(text, defsToAdd) {
Rocky Duan committed
1615
        text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1616 1617
            function(totalMatch, id, link, newlines, title) {
                defsToAdd[id] = totalMatch.replace(/\s*$/, '');
Rocky Duan committed
1618 1619
                if (newlines) {
                    // Strip the title and return that separately.
1620
                    defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, '');
Rocky Duan committed
1621 1622
                    return newlines + title;
                }
1623
                return '';
Rocky Duan committed
1624 1625 1626 1627 1628
            });

        return text;
    };

1629
    commandProto.addLinkDef = function(chunk, linkDef) {
Rocky Duan committed
1630 1631 1632 1633 1634 1635 1636
        var refNumber = 0; // The current reference number
        var defsToAdd = {}; //
        // Start with a clean slate by removing all previous link definitions.
        chunk.before = this.stripLinkDefs(chunk.before, defsToAdd);
        chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
        chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);

1637
        var defs = '';
Rocky Duan committed
1638 1639
        var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;

1640
        var addDefNumber = function(def) {
Rocky Duan committed
1641
            refNumber++;
1642 1643
            def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, '  [' + refNumber + ']:');
            defs += '\n' + def;
Rocky Duan committed
1644 1645 1646 1647 1648 1649 1650
        };

        // note that
        // a) the recursive call to getLink cannot go infinite, because by definition
        //    of regex, inner is always a proper substring of wholeMatch, and
        // b) more than one level of nesting is neither supported by the regex
        //    nor making a lot of sense (the only use case for nesting is a linked image)
1651
        var getLink = function(wholeMatch, before, inner, afterInner, id, end) {
Rocky Duan committed
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
            inner = inner.replace(regex, getLink);
            if (defsToAdd[id]) {
                addDefNumber(defsToAdd[id]);
                return before + inner + afterInner + refNumber + end;
            }
            return wholeMatch;
        };

        chunk.before = chunk.before.replace(regex, getLink);

        if (linkDef) {
            addDefNumber(linkDef);
        }
        else {
            chunk.selection = chunk.selection.replace(regex, getLink);
        }

        var refOut = refNumber;

        chunk.after = chunk.after.replace(regex, getLink);

        if (chunk.after) {
1674
            chunk.after = chunk.after.replace(/\n*$/, '');
Rocky Duan committed
1675 1676
        }
        if (!chunk.after) {
1677
            chunk.selection = chunk.selection.replace(/\n*$/, '');
Rocky Duan committed
1678 1679
        }

1680
        chunk.after += '\n\n' + defs;
Rocky Duan committed
1681 1682 1683 1684 1685 1686 1687

        return refOut;
    };

    // takes the line as entered into the add link/as image dialog and makes
    // sure the URL and the optinal title are "nice".
    function properlyEncoded(linkdef) {
1688 1689 1690
        return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function(wholematch, link, title) {
            link = link.replace(/\?.*$/, function(querypart) {
                return querypart.replace(/\+/g, ' '); // in the query string, a plus and a space are identical
Rocky Duan committed
1691 1692 1693
            });
            link = decodeURIComponent(link); // unencode first, to prevent double encoding
            link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
1694 1695
            link = link.replace(/\?.*$/, function(querypart) {
                return querypart.replace(/\+/g, '%2b'); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
Rocky Duan committed
1696 1697
            });
            if (title) {
1698 1699
                title = title.trim ? title.trim() : title.replace(/^\s*/, '').replace(/\s*$/, '');
                title = $.trim(title).replace(/"/g, 'quot;').replace(/\(/g, '&#40;').replace(/\)/g, '&#41;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
Rocky Duan committed
1700 1701 1702 1703 1704
            }
            return title ? link + ' "' + title + '"' : link;
        });
    }

1705
    commandProto.doLinkOrImage = function(chunk, postProcessing, isImage, imageUploadHandler) {
Rocky Duan committed
1706 1707 1708 1709
        chunk.trimWhitespace();
        chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
        var background;

1710 1711 1712 1713
        if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
            chunk.startTag = chunk.startTag.replace(/!?\[/, '');
            chunk.endTag = '';
            this.addLinkDef(chunk, null);
Rocky Duan committed
1714
        }
1715
        else {
Rocky Duan committed
1716 1717 1718 1719
            // We're moving start and end tag back into the selection, since (as we're in the else block) we're not
            // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
            // link text. linkEnteredCallback takes care of escaping any brackets.
            chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
1720
            chunk.startTag = chunk.endTag = '';
Rocky Duan committed
1721 1722 1723 1724 1725 1726 1727 1728

            if (/\n\n/.test(chunk.selection)) {
                this.addLinkDef(chunk, null);
                return;
            }
            var that = this;
            // The function to be executed when you enter a link and press OK or Cancel.
            // Marks up the link and adds the ref.
1729
            var linkEnteredCallback = function(link, description) {
Rocky Duan committed
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
                background.parentNode.removeChild(background);

                if (link !== null) {
                    // (                          $1
                    //     [^\\]                  anything that's not a backslash
                    //     (?:\\\\)*              an even number (this includes zero) of backslashes
                    // )
                    // (?=                        followed by
                    //     [[\]]                  an opening or closing bracket
                    // )
                    //
                    // In other words, a non-escaped bracket. These have to be escaped now to make sure they
                    // don't count as the end of the link or similar.
                    // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets),
                    // the bracket in one match may be the "not a backslash" character in the next match, so it
                    // should not be consumed by the first match.
                    // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the
                    // start of the string, so this also works if the selection begins with a bracket. We cannot solve
                    // this by anchoring with ^, because in the case that the selection starts with two brackets, this
                    // would mean a zero-width match at the start. Since zero-width matches advance the string position,
                    // the first bracket could then not act as the "not a backslash" for the second.
1751
                    chunk.selection = (' ' + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, '$1\\').substr(1);
1752

1753
                    var linkDef = ' [999]: ' + properlyEncoded(link);
Rocky Duan committed
1754 1755

                    var num = that.addLinkDef(chunk, linkDef);
1756 1757
                    chunk.startTag = isImage ? '![' : '[';
                    chunk.endTag = '][' + num + ']';
Rocky Duan committed
1758 1759 1760

                    if (!chunk.selection) {
                        if (isImage) {
1761
                            chunk.selection = description ? description : '';
Rocky Duan committed
1762 1763
                        }
                        else {
1764
                            chunk.selection = description ? description : gettext('enter link description here');
Rocky Duan committed
1765 1766 1767 1768 1769 1770 1771 1772 1773
                        }
                    }
                }
                postProcessing();
            };

            background = ui.createBackground();

            if (isImage) {
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
                if (!this.hooks.insertImageDialog(linkEnteredCallback)) {
                    ui.prompt(
                        imageDialogText,
                        urlLabel,
                        imageUrlHelpText,
                        urlError,
                        imageDescriptionLabel,
                        imageDescriptionHelpText,
                        imageDescriptionHelpLink,
                        imageDescError,
                        imageDefaultText,
                        linkEnteredCallback,
                        imageIsDecorativeLabel,
                        imageUploadHandler
                    );
                }
Rocky Duan committed
1790 1791
            }
            else {
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
                ui.prompt(
                    linkDialogText,
                    urlLabel,
                    linkUrlHelpText,
                    urlError,
                    linkDestinationLabel,
                    linkDestinationHelpText,
                    '',
                    linkDestinationError,
                    linkDefaultText,
                    linkEnteredCallback
                );
Rocky Duan committed
1804 1805 1806 1807 1808 1809 1810
            }
            return true;
        }
    };

    // When making a list, hitting shift-enter will put your cursor on the next line
    // at the current indent level.
1811
    commandProto.doAutoindent = function(chunk, postProcessing) {
Rocky Duan committed
1812 1813 1814
        var commandMgr = this,
            fakeSelection = false;

1815 1816 1817
        chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, '\n\n');
        chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, '\n\n');
        chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, '\n\n');
1818

Rocky Duan committed
1819 1820 1821 1822 1823
        // There's no selection, end the cursor wasn't at the end of the line:
        // The user wants to split the current list item / code line / blockquote line
        // (for the latter it doesn't really matter) in two. Temporarily select the
        // (rest of the) line to achieve this.
        if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
1824
            chunk.after = chunk.after.replace(/^[^\n]*/, function(wholeMatch) {
Rocky Duan committed
1825
                chunk.selection = wholeMatch;
1826
                return '';
Rocky Duan committed
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
            });
            fakeSelection = true;
        }

        if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
            if (commandMgr.doList) {
                commandMgr.doList(chunk);
            }
        }
        if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
            if (commandMgr.doBlockquote) {
                commandMgr.doBlockquote(chunk);
            }
        }
        if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
            if (commandMgr.doCode) {
                commandMgr.doCode(chunk);
            }
        }
1846

Rocky Duan committed
1847 1848
        if (fakeSelection) {
            chunk.after = chunk.selection + chunk.after;
1849
            chunk.selection = '';
Rocky Duan committed
1850 1851 1852
        }
    };

1853
    commandProto.doBlockquote = function(chunk, postProcessing) {
Rocky Duan committed
1854
        chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
1855
            function(totalMatch, newlinesBefore, text, newlinesAfter) {
Rocky Duan committed
1856 1857 1858 1859 1860 1861
                chunk.before += newlinesBefore;
                chunk.after = newlinesAfter + chunk.after;
                return text;
            });

        chunk.before = chunk.before.replace(/(>[ \t]*)$/,
1862
            function(totalMatch, blankLine) {
Rocky Duan committed
1863
                chunk.selection = blankLine + chunk.selection;
1864
                return '';
Rocky Duan committed
1865 1866
            });

1867 1868
        chunk.selection = chunk.selection.replace(/^(\s|>)+$/, '');
        chunk.selection = chunk.selection || gettext('Blockquote');
Rocky Duan committed
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899

        // The original code uses a regular expression to find out how much of the
        // text *directly before* the selection already was a blockquote:

        /*
        if (chunk.before) {
        chunk.before = chunk.before.replace(/\n?$/, "\n");
        }
        chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
        function (totalMatch) {
        chunk.startTag = totalMatch;
        return "";
        });
        */

        // This comes down to:
        // Go backwards as many lines a possible, such that each line
        //  a) starts with ">", or
        //  b) is almost empty, except for whitespace, or
        //  c) is preceeded by an unbroken chain of non-empty lines
        //     leading up to a line that starts with ">" and at least one more character
        // and in addition
        //  d) at least one line fulfills a)
        //
        // Since this is essentially a backwards-moving regex, it's susceptible to
        // catstrophic backtracking and can cause the browser to hang;
        // see e.g. http://meta.stackoverflow.com/questions/9807.
        //
        // Hence we replaced this by a simple state machine that just goes through the
        // lines and checks for a), b), and c).

1900 1901
        var match = '',
            leftOver = '',
Rocky Duan committed
1902 1903
            line;
        if (chunk.before) {
1904
            var lines = chunk.before.replace(/\n$/, '').split('\n');
Rocky Duan committed
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
            var inChain = false;
            for (var i = 0; i < lines.length; i++) {
                var good = false;
                line = lines[i];
                inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
                if (/^>/.test(line)) {                // a)
                    good = true;
                    if (!inChain && line.length > 1)  // c) any line that starts with ">" and has at least one more character starts the chain
                        inChain = true;
                } else if (/^[ \t]*$/.test(line)) {   // b)
                    good = true;
                } else {
                    good = inChain;                   // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
                }
                if (good) {
1920
                    match += line + '\n';
Rocky Duan committed
1921 1922
                } else {
                    leftOver += match + line;
1923
                    match = '\n';
Rocky Duan committed
1924 1925 1926 1927
                }
            }
            if (!/(^|\n)>/.test(match)) {             // d)
                leftOver += match;
1928
                match = '';
Rocky Duan committed
1929 1930 1931 1932 1933 1934 1935 1936 1937
            }
        }

        chunk.startTag = match;
        chunk.before = leftOver;

        // end of change

        if (chunk.after) {
1938
            chunk.after = chunk.after.replace(/^\n?/, '\n');
Rocky Duan committed
1939 1940 1941
        }

        chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
1942
            function(totalMatch) {
Rocky Duan committed
1943
                chunk.endTag = totalMatch;
1944
                return '';
Rocky Duan committed
1945 1946 1947
            }
        );

1948 1949
        var replaceBlanksInTags = function(useBracket) {
            var replacement = useBracket ? '> ' : '';
Rocky Duan committed
1950 1951 1952

            if (chunk.startTag) {
                chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
1953 1954
                    function(totalMatch, markdown) {
                        return '\n' + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + '\n';
Rocky Duan committed
1955 1956 1957 1958
                    });
            }
            if (chunk.endTag) {
                chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
1959 1960
                    function(totalMatch, markdown) {
                        return '\n' + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + '\n';
Rocky Duan committed
1961 1962 1963 1964 1965 1966
                    });
            }
        };

        if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
            this.wrap(chunk, SETTINGS.lineLength - 2);
1967
            chunk.selection = chunk.selection.replace(/^/gm, '> ');
Rocky Duan committed
1968 1969 1970
            replaceBlanksInTags(true);
            chunk.skipLines();
        } else {
1971
            chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, '');
Rocky Duan committed
1972 1973 1974 1975
            this.unwrap(chunk);
            replaceBlanksInTags(false);

            if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
1976
                chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, '\n\n');
Rocky Duan committed
1977 1978 1979
            }

            if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
1980
                chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, '\n\n');
Rocky Duan committed
1981 1982 1983 1984 1985 1986 1987
            }
        }

        chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection);

        if (!/\n/.test(chunk.selection)) {
            chunk.selection = chunk.selection.replace(/^(> *)/,
1988
            function(wholeMatch, blanks) {
Rocky Duan committed
1989
                chunk.startTag += blanks;
1990
                return '';
Rocky Duan committed
1991 1992 1993 1994
            });
        }
    };

1995
    commandProto.doCode = function(chunk, postProcessing) {
Rocky Duan committed
1996 1997 1998 1999 2000
        var hasTextBefore = /\S[ ]*$/.test(chunk.before);
        var hasTextAfter = /^[ ]*\S/.test(chunk.after);

        // Use 'four space' markdown if the selection is on its own
        // line or is multiline.
2001
        if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
Rocky Duan committed
2002
            chunk.before = chunk.before.replace(/[ ]{4}$/,
2003
                function(totalMatch) {
Rocky Duan committed
2004
                    chunk.selection = totalMatch + chunk.selection;
2005
                    return '';
Rocky Duan committed
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
                });

            var nLinesBack = 1;
            var nLinesForward = 1;

            if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
                nLinesBack = 0;
            }
            if (/^\n(\t|[ ]{4,})/.test(chunk.after)) {
                nLinesForward = 0;
            }

            chunk.skipLines(nLinesBack, nLinesForward);

            if (!chunk.selection) {
2021 2022
                chunk.startTag = '    ';
                chunk.selection = gettext('enter code here');
Rocky Duan committed
2023 2024 2025 2026
            }
            else {
                if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
                    if (/\n/.test(chunk.selection))
2027
                        chunk.selection = chunk.selection.replace(/^/gm, '    ');
Rocky Duan committed
2028
                    else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
2029
                        chunk.before += '    ';
Rocky Duan committed
2030 2031
                }
                else {
2032
                    chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, '');
Rocky Duan committed
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
                }
            }
        }
        else {
            // Use backticks (`) to delimit the code block.

            chunk.trimWhitespace();
            chunk.findTags(/`/, /`/);

            if (!chunk.startTag && !chunk.endTag) {
2043
                chunk.startTag = chunk.endTag = '`';
Rocky Duan committed
2044
                if (!chunk.selection) {
2045
                    chunk.selection = gettext('enter code here');
Rocky Duan committed
2046 2047 2048 2049
                }
            }
            else if (chunk.endTag && !chunk.startTag) {
                chunk.before += chunk.endTag;
2050
                chunk.endTag = '';
Rocky Duan committed
2051 2052
            }
            else {
2053
                chunk.startTag = chunk.endTag = '';
Rocky Duan committed
2054 2055 2056 2057
            }
        }
    };

2058
    commandProto.doList = function(chunk, postProcessing, isNumberedList) {
Rocky Duan committed
2059 2060 2061 2062 2063 2064 2065 2066
        // These are identical except at the very beginning and end.
        // Should probably use the regex extension function to make this clearer.
        var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
        var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;

        // The default bullet is a dash but others are possible.
        // This has nothing to do with the particular HTML bullet,
        // it's just a markdown bullet.
2067
        var bullet = '-';
Rocky Duan committed
2068 2069 2070 2071 2072

        // The number in a numbered list.
        var num = 1;

        // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2073
        var getItemPrefix = function() {
Rocky Duan committed
2074 2075
            var prefix;
            if (isNumberedList) {
2076
                prefix = ' ' + num + '. ';
Rocky Duan committed
2077 2078 2079
                num++;
            }
            else {
2080
                prefix = ' ' + bullet + ' ';
Rocky Duan committed
2081 2082 2083 2084 2085
            }
            return prefix;
        };

        // Fixes the prefixes of the other list items.
2086
        var getPrefixedItem = function(itemText) {
Rocky Duan committed
2087 2088 2089 2090 2091 2092 2093
            // The numbering flag is unset when called by autoindent.
            if (isNumberedList === undefined) {
                isNumberedList = /^\s*\d/.test(itemText);
            }

            // Renumber/bullet the list element.
            itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2094
                function(_) {
Rocky Duan committed
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
                    return getItemPrefix();
                });

            return itemText;
        };

        chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);

        if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
            chunk.before += chunk.startTag;
2105
            chunk.startTag = '';
Rocky Duan committed
2106 2107
        }

2108
        if (chunk.startTag) {
Rocky Duan committed
2109
            var hasDigits = /\d+[.]/.test(chunk.startTag);
2110 2111
            chunk.startTag = '';
            chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, '\n');
Rocky Duan committed
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
            this.unwrap(chunk);
            chunk.skipLines();

            if (hasDigits) {
                // Have to renumber the bullet points if this is a numbered list.
                chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
            }
            if (isNumberedList == hasDigits) {
                return;
            }
        }

        var nLinesUp = 1;

        chunk.before = chunk.before.replace(previousItemsRegex,
2127
            function(itemText) {
Rocky Duan committed
2128 2129 2130 2131 2132 2133 2134 2135
                if (/^\s*([*+-])/.test(itemText)) {
                    bullet = re.$1;
                }
                nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
                return getPrefixedItem(itemText);
            });

        if (!chunk.selection) {
2136
            chunk.selection = gettext('List item');
Rocky Duan committed
2137 2138 2139 2140 2141 2142 2143
        }

        var prefix = getItemPrefix();

        var nLinesDown = 1;

        chunk.after = chunk.after.replace(nextItemsRegex,
2144
            function(itemText) {
Rocky Duan committed
2145 2146 2147 2148 2149 2150 2151
                nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
                return getPrefixedItem(itemText);
            });

        chunk.trimWhitespace(true);
        chunk.skipLines(nLinesUp, nLinesDown, true);
        chunk.startTag = prefix;
2152
        var spaces = prefix.replace(/./g, ' ');
Rocky Duan committed
2153
        this.wrap(chunk, SETTINGS.lineLength - spaces.length);
2154
        chunk.selection = chunk.selection.replace(/\n/g, '\n' + spaces);
Rocky Duan committed
2155 2156
    };

2157
    commandProto.doHeading = function(chunk, postProcessing) {
Rocky Duan committed
2158
        // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2159 2160
        chunk.selection = chunk.selection.replace(/\s+/g, ' ');
        chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, '');
Rocky Duan committed
2161 2162 2163 2164

        // If we clicked the button with no selected text, we just
        // make a level 2 hash header around some default text.
        if (!chunk.selection) {
2165 2166 2167
            chunk.startTag = '## ';
            chunk.selection = gettext('Heading');
            chunk.endTag = ' ##';
Rocky Duan committed
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
            return;
        }

        var headerLevel = 0;     // The existing header level of the selected text.

        // Remove any existing hash heading markdown and save the header level.
        chunk.findTags(/#+[ ]*/, /[ ]*#+/);
        if (/#+/.test(chunk.startTag)) {
            headerLevel = re.lastMatch.length;
        }
2178
        chunk.startTag = chunk.endTag = '';
Rocky Duan committed
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190

        // Try to get the current header level by looking for - and = in the line
        // below the selection.
        chunk.findTags(null, /\s?(-+|=+)/);
        if (/=+/.test(chunk.endTag)) {
            headerLevel = 1;
        }
        if (/-+/.test(chunk.endTag)) {
            headerLevel = 2;
        }

        // Skip to the next line so we can create the header markdown.
2191
        chunk.startTag = chunk.endTag = '';
Rocky Duan committed
2192 2193 2194 2195 2196 2197 2198
        chunk.skipLines(1, 1);

        // We make a level 2 header if there is no current header.
        // If there is a header level, we substract one from the header level.
        // If it's already a level 1 header, it's removed.
        var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;

2199
        if (headerLevelToCreate > 0) {
Rocky Duan committed
2200 2201
            // The button only creates level 1 and 2 underline headers.
            // Why not have it iterate over hash header levels?  Wouldn't that be easier and cleaner?
2202
            var headerChar = headerLevelToCreate >= 2 ? '-' : '=';
Rocky Duan committed
2203 2204 2205 2206
            var len = chunk.selection.length;
            if (len > SETTINGS.lineLength) {
                len = SETTINGS.lineLength;
            }
2207
            chunk.endTag = '\n';
Rocky Duan committed
2208 2209 2210 2211 2212 2213
            while (len--) {
                chunk.endTag += headerChar;
            }
        }
    };

2214 2215 2216
    commandProto.doHorizontalRule = function(chunk, postProcessing) {
        chunk.startTag = '----------\n';
        chunk.selection = '';
Rocky Duan committed
2217
        chunk.skipLines(2, 1, true);
2218
    };
2219
})();