Welcome, guest | Sign In | My Account | Store | Cart
/**
 * @fileoverview  With an editor selection, pressing "[", "(" or "{" will place
 *                matching braces around the selected text.
 * @author        Todd Whiteman (toddw@activestate.com)
 * @version       0.1
 */

if (typeof(window.extensions) == 'undefined') {
    window.extensions = {};
}

if (extensions.smartbraces && extensions.smartbraces.onkeypress_handler) {
    // Remove the existing trigger handler, we'll re-instate it.
    var editor_pane = ko.views.manager.topView;
    editor_pane.removeEventListener('keypress', extensions.smartbraces.onkeypress_handler, true);
}
extensions.smartbraces = {};

(function() {

    var log = ko.logging.getLogger("SmartBraces");
    //log.setLevel(ko.logging.LOG_DEBUG);

    // The accepted keypress characters.
    var brace_charcodes =          ["{", "(", "["];
    var matching_brace_charcodes = ["}", ")", "]"];

    this.onkeypress_handler = function(e) {
        try {
            // Only trap brace keypresses that aren't used with a modifier.
            if (!e.charCode || e.ctrlKey || e.altKey) return;

            // Only trap the required brace keys.
            var key = String.fromCharCode(e.charCode);
            var idx = brace_charcodes.indexOf(key);
            if (idx < 0) return;
                
            log.debug("onkeypress_handler:: key: " + key);

            // Create shorthands for 'currentView'
            var view = ko.views.manager.currentView;
            /**
             * @type {Components.interfaces.ISciMoz}
             */
            var editor = view.scimoz;

            // Don't do anything if there isn't a selection within the document.
            var selection = editor.selText;
            if (!selection) {
                return;
            }

            var anchor = editor.anchor;
            var cursorPos = editor.currentPos;
            editor.replaceSel(key + selection + matching_brace_charcodes[idx]);

            // Restore the selection.
            if (anchor < cursorPos) {
                editor.anchor = anchor;
                editor.currentPos = cursorPos + 2;
            } else {
                editor.anchor = anchor + 2;
                editor.currentPos = cursorPos;
            }

            // Stop the event from going to the editor as a regular keypress.
            e.preventDefault();
            e.stopPropagation();
        } catch(ex) {
            log.exception(ex);
        }
    }

    // Hook up the keypress event listener.
    var editor_pane = ko.views.manager.topView;
    editor_pane.addEventListener('keypress', this.onkeypress_handler, true);

}).apply(extensions.smartbraces);

History