Example #1
0
 .done(function () {
     // Restore original selection / scroll pos
     if (origSelection) {
         EditorManager.getCurrentFullEditor().setSelection(origSelection.start, origSelection.end);
         EditorManager.getCurrentFullEditor().setScrollPos(origScrollPos.x, origScrollPos.y);
     }
 });
Example #2
0
    QuickNavigateDialog.prototype._filterCallback = function (query) {
        // Re-evaluate which plugin is active each time query string changes
        currentPlugin = null;

        // "Go to line" mode is special-cased
        var cursorPos = extractCursorPos(query);
        if (cursorPos && cursorPos.local) {
            // Bare Go to Line (no filename search) - can validate & jump to it now, without waiting for Enter/commit
            var editor = EditorManager.getCurrentFullEditor();

            // Validate (could just use 0 and lineCount() here, but in future might want this to work for inline editors too)
            if (cursorPos && editor && cursorPos.line >= editor.getFirstVisibleLine() && cursorPos.line <= editor.getLastVisibleLine()) {
                var from = {line: cursorPos.line, ch: cursorPos.ch},
                    to   = {line: cursorPos.line};
                EditorManager.getCurrentFullEditor().setSelection(from, to, true);

                return { error: null };  // no error even though no results listed
            } else {
                return [];  // red error highlight: line number out of range, or no editor open
            }
        }
        if (query === ":") {  // treat blank ":" query as valid, but no-op
            return { error: null };
        }

        // Try to invoke a search plugin
        var curDoc = DocumentManager.getCurrentDocument(), languageId;
        if (curDoc) {
            languageId = curDoc.getLanguage().getId();
        }

        var i;
        for (i = 0; i < plugins.length; i++) {
            var plugin = plugins[i];
            var languageIdMatch = plugin.languageIds.length === 0 || plugin.languageIds.indexOf(languageId) !== -1;
            if (languageIdMatch && plugin.match(query)) {
                currentPlugin = plugin;

                // Look up the StringMatcher for this plugin.
                var matcher = this._matchers[currentPlugin.name];
                if (!matcher) {
                    matcher = new StringMatch.StringMatcher(plugin.matcherOptions);
                    this._matchers[currentPlugin.name] = matcher;
                }
                this._updateDialogLabel(plugin, query);
                return plugin.search(query, matcher);
            }
        }

        // Reflect current search mode in UI
        this._updateDialogLabel(null, query);

        // No matching plugin: use default file search mode
        return searchFileList(query, this._filenameMatcher);
    };
Example #3
0
    QuickNavigateDialog.prototype.showDialog = function (prefix, initialString) {
        if (this.isOpen) {
            return;
        }
        this.isOpen = true;

        // Record current document & cursor pos so we can restore it if search is canceled
        // We record scroll pos *before* modal bar is opened since we're going to restore it *after* it's closed
        var curDoc = DocumentManager.getCurrentDocument();
        this._origDocPath = curDoc ? curDoc.file.fullPath : null;
        if (curDoc) {
            this._origSelections = EditorManager.getCurrentFullEditor().getSelections();
            this._origScrollPos = EditorManager.getCurrentFullEditor().getScrollPos();
        } else {
            this._origSelections = null;
            this._origScrollPos = null;
        }

        // Show the search bar
        var searchBarHTML = "<div align='right'><input type='text' autocomplete='off' id='quickOpenSearch' placeholder='" + Strings.CMD_QUICK_OPEN + "\u2026' style='width: 30em'><span class='find-dialog-label'></span></div>";
        this.modalBar = new ModalBar(searchBarHTML, true);

        this.modalBar.on("close", this._handleCloseBar);

        this.$searchField = $("input#quickOpenSearch");

        this.searchField = new QuickSearchField(this.$searchField, {
            maxResults: 20,
            verticalAdjust: this.modalBar.getRoot().outerHeight(),
            resultProvider: this._filterCallback,
            formatter: this._resultsFormatterCallback,
            onCommit: this._handleItemSelect,
            onHighlight: this._handleItemHighlight
        });

        // Return files that are non-binary, or binary files that have a custom viewer
        function _filter(file) {
            return !LanguageManager.getLanguageForPath(file.fullPath).isBinary() ||
                MainViewFactory.findSuitableFactoryForPath(file.fullPath);
        }

        // Start prefetching the file list, which will be needed the first time the user enters an un-prefixed query. If file index
        // caches are out of date, this list might take some time to asynchronously build, forcing searchFileList() to wait. In the
        // meantime we show our old, stale fileList (unless the user has switched projects and we cleared it).
        fileListPromise = ProjectManager.getAllFiles(_filter, true)
            .done(function (files) {
                fileList = files;
                fileListPromise = null;
                this._filenameMatcher.reset();
            }.bind(this));

        // Prepopulated query
        this.$searchField.focus();
        this.setSearchFieldValue(prefix, initialString);
    };
 /**
  * @private
  * Sets the font size and restores the scroll position as best as possible.
  * TODO: Remove the viewportTop hack and direclty use scrollPos.y once #3115 is fixed.
  * @param {string} fontSizeStyle A string with the font size and the size unit
  * @param {string} lineHeightStyle A string with the line height and a the size unit
  */
 function _setSizeAndRestoreScroll(fontSizeStyle, lineHeightStyle) {
     var editor      = EditorManager.getCurrentFullEditor(),
         oldWidth    = editor._codeMirror.defaultCharWidth(),
         oldHeight   = editor.getTextHeight(),
         scrollPos   = editor.getScrollPos(),
         viewportTop = $(".CodeMirror-lines", editor.getRootElement()).parent().position().top,
         scrollTop   = scrollPos.y - viewportTop;
     
     // It's necessary to inject a new rule to address all editors.
     _removeDynamicFontSize();
     var style = $("<style type='text/css'></style>").attr("id", DYNAMIC_FONT_STYLE_ID);
     style.html(".CodeMirror {" +
                "font-size: "   + fontSizeStyle   + " !important;" +
                "line-height: " + lineHeightStyle + " !important;}");
     $("head").append(style);
     
     editor.refreshAll();
     
     // Calculate the new scroll based on the old font sizes and scroll position
     var newWidth    = editor._codeMirror.defaultCharWidth(),
         newHeight   = editor.getTextHeight(),
         deltaX      = scrollPos.x / oldWidth,
         deltaY      = scrollTop / oldHeight,
         scrollPosX  = scrollPos.x + Math.round(deltaX * (newWidth - oldWidth)),
         scrollPosY  = scrollPos.y + Math.round(deltaY * (newHeight - oldHeight));
     
     // Scroll the document back to its original position, but not on the first load since the position
     // was saved with the new height and already been restored.
     if (_fontSizePrefsLoaded) {
         editor.setScrollPos(scrollPosX, scrollPosY);
     }
 }
Example #5
0
    ModalBar.prototype.prepareClose = function (restoreScrollPos) {
        if (restoreScrollPos === undefined) {
            restoreScrollPos = true;
        }
        
        this._$root.addClass("popout");
        
        // Since the modal bar has now an absolute position relative to the editor holder,
        // when there are html menus we need to adjust the top position
        if (!brackets.nativeMenus) {
            var top = $("#titlebar").outerHeight();
            this._$root.css("top", top + "px");
        }

        // Preserve scroll position of the current full editor across the editor refresh, adjusting for the 
        // height of the modal bar so the code doesn't appear to shift if possible.
        var fullEditor = EditorManager.getCurrentFullEditor(),
            barHeight,
            scrollPos;
        if (restoreScrollPos && fullEditor) {
            barHeight = this.height();
            scrollPos = fullEditor.getScrollPos();
        }
        EditorManager.resizeEditor();
        if (restoreScrollPos && fullEditor) {
            fullEditor._codeMirror.scrollTo(scrollPos.x, scrollPos.y - barHeight);
        }
    };
Example #6
0
            .on("click", "tr", function (e) {
                if ($selectedRow) {
                    $selectedRow.removeClass("selected");
                }

                $selectedRow  = $(e.currentTarget);
                $selectedRow.addClass("selected");

                // This is a inspector title row, expand/collapse on click
                if ($selectedRow.hasClass("inspector-section")) {
                    // Clicking the inspector title section header collapses/expands result rows
                    $selectedRow.nextUntil(".inspector-section").toggle();

                    var $triangle = $(".disclosure-triangle", $selectedRow);
                    $triangle.toggleClass("expanded").toggleClass("collapsed");
                } else {
                    // This is a problem marker row, show the result on click
                    // Grab the required position data
                    var lineTd    = $selectedRow.find(".line-number");
                    var line      = parseInt(lineTd.text(), 10) - 1;  // convert friendlyLine back to pos.line
                    // if there is no line number available, don't do anything
                    if (!isNaN(line)) {
                        var character = lineTd.data("character");
    
                        var editor = EditorManager.getCurrentFullEditor();
                        editor.setCursorPos(line, character, true);
                        EditorManager.focusEditor();
                    }
                }
            });
Example #7
0
    /** Triggered by a document change from the DocumentManager */
    function _onDocumentChange() {
        var doc = _getCurrentDocument(),
            status = STATUS_ACTIVE;
        if (!doc) {
            return;
        }

        if (Inspector.connected()) {
            hideHighlight();
            if (agents.network && agents.network.wasURLRequested(doc.url)) {
                _closeDocument();
                var editor = EditorManager.getCurrentFullEditor();
                _openDocument(doc, editor);
            } else {
                if (exports.config.experimental || _isHtmlFileExt(doc.extension)) {
                    close();
                    window.setTimeout(open);
                }
            }
            
            if (doc.isDirty && _classForDocument(doc) !== CSSDocument) {
                status = STATUS_OUT_OF_SYNC;
            }
            _setStatus(status);
        }
    }
Example #8
0
    /** Triggered by a document change from the DocumentManager */
    function _onDocumentChange() {
        var doc = _getCurrentDocument(),
            status = STATUS_ACTIVE;
        if (!doc) {
            return;
        }

        if (Inspector.connected()) {
            if (agents.network && agents.network.wasURLRequested(doc.url)) {
                _closeDocument();
                var editor = EditorManager.getCurrentFullEditor();
                _openDocument(doc, editor);
            } else {
                /* FUTURE: support live connections for docments other than html */
                if (exports.config.experimental || (doc.extension && doc.extension.indexOf('htm') === 0)) {
                    close();
                    window.setTimeout(open);
                }
            }
            
            if (doc.isDirty && _classForDocument(doc) !== CSSDocument) {
                status = STATUS_OUT_OF_SYNC;
            }
            _setStatus(status);
        }
    }
Example #9
0
    /** Triggered by a document change from the DocumentManager */
    function _onDocumentChange() {
        var doc = _getCurrentDocument(),
            status = STATUS_ACTIVE,
            promise;
        
        if (!doc) {
            return;
        }

        if (Inspector.connected()) {
            hideHighlight();
            if (agents.network && agents.network.wasURLRequested(doc.url)) {
                _openDocument(doc, EditorManager.getCurrentFullEditor());
                
                promise = _getRelatedDocuments();
            } else {
                if (exports.config.experimental || _isHtmlFileExt(doc.extension)) {
                    promise = close().done(open);
                } else {
                    promise = $.Deferred().resolve();
                }
            }
            
            promise
                .fail(close)
                .done(function () {
                    if (doc.isDirty && _classForDocument(doc) !== CSSDocument) {
                        status = STATUS_OUT_OF_SYNC;
                    }
                    _setStatus(status);
                });
        }
    }
Example #10
0
    QuickNavigateDialog.prototype._handleCloseBar = function (event, reason, modalBarClosePromise) {
        console.assert(!this.closePromise);
        this.closePromise = modalBarClosePromise;
        this.isOpen = false;

        var i;
        for (i = 0; i < plugins.length; i++) {
            var plugin = plugins[i];
            if (plugin.done) {
                plugin.done();
            }
        }

        // Close popup & ensure we ignore any still-pending result promises
        this.searchField.destroy();

        // Restore original selection / scroll pos if closed via Escape
        if (reason === ModalBar.CLOSE_ESCAPE) {
            // We can reset the scroll position synchronously on ModalBar's "close" event (before close animation
            // completes) since ModalBar has already resized the editor and done its own scroll adjustment before
            // this event fired - so anything we set here will override the pos that was (re)set by ModalBar.
            var editor = EditorManager.getCurrentFullEditor();
            if (this._origSelections) {
                editor.setSelections(this._origSelections);
            }
            if (this._origScrollPos) {
                editor.setScrollPos(this._origScrollPos.x, this._origScrollPos.y);
            }
        }
    };
Example #11
0
 /**
  * @private
  * Updates the focused full editor and cleans listeners
  * TODO Add support for inline editors
  */
 function _onFocusedEditorChange(evt) {
     
     if (fullEditor) {
         $(fullEditor).off("cursorActivity", _updateCursorInfo);
     }
     
     fullEditor  = EditorManager.getCurrentFullEditor();
     
     if (fullEditor === null) {
         
        // Check if the statusbar is visible to hide it
         if ($statusBar.is(":visible")) {
             $statusBar.hide();
             EditorManager.resizeEditor();
         }
         
     } else {
         
         // Check if the statusbar is not visible to show it
         if (!$statusBar.is(":visible")) {
             $statusBar.show();
             EditorManager.resizeEditor();
         }
         
         $(fullEditor).on('cursorActivity', _updateCursorInfo);
         _updateCursorInfo();
         _updateModeInfo();
         _updateFileInfo();
         _updateTabCharInfo();
     }
 }
Example #12
0
 /** Run when all agents are loaded */
 function _onLoad() {
     var doc = _getCurrentDocument();
     if (doc) {
         var editor = EditorManager.getCurrentFullEditor();
         _openDocument(doc, editor);
     }
     _setStatus(STATUS_ACTIVE);
 }
Example #13
0
 /**
  * @private
  * Initialize the status bar and the focused editor status 
  */
 function _initStatusBar() {
     fullEditor = EditorManager.getCurrentFullEditor();
     $(fullEditor).on("cursorActivity", _updateCursorInfo);
     
     _updateCursorInfo();
     _updateModeInfo();
     _updateFileInfo();
     _updateTabCharInfo();
 }
Example #14
0
 /** Point the master editor to the given location
  * @param {integer} location in file
  */
 function openLocation(location) {
     var editor = EditorManager.getCurrentFullEditor();
     var codeMirror = editor._codeMirror;
     if (typeof location === "number") {
         location = codeMirror.posFromIndex(location);
     }
     codeMirror.setCursor(location);
     codeMirror.setLineClass(location.line, "flash");
     window.setTimeout(codeMirror.setLineClass.bind(codeMirror, location.line), 1000);
 }
Example #15
0
    /**
     * Scroll to the selected item in the current document (unless no query string entered yet,
     * in which case the topmost list item is irrelevant)
     * @param {?SearchResult} selectedItem
     * @param {string} query
     * @param {boolean} explicit False if this is only highlighted due to being at top of list after search()
     */
    function itemFocus(selectedItem, query, explicit) {
        if (!selectedItem || (query.length < 2 && !explicit)) {
            return;
        }
        var fileLocation = selectedItem.fileLocation;

        var from = {line: fileLocation.line, ch: fileLocation.chFrom};
        var to = {line: fileLocation.line, ch: fileLocation.chTo};
        EditorManager.getCurrentFullEditor().setSelection(from, to, true);
    }
Example #16
0
    /**
     * Creates a modal bar whose contents are the given template.
     * 
     * Dispatches one event:
     * - close - When the bar is closed, either via close() or via autoClose. After this event, the
     *     bar may remain visible and in the DOM while its closing animation is playing. However,
     *     by the time "close" is fired, the bar has been "popped out" of the layout and the
     *     editor scroll position has already been restored.
     * 
     * @constructor
     *
     * @param {string} template The HTML contents of the modal bar.
     * @param {boolean} autoClose If true, then close the dialog if the user hits Esc
     *      or if the bar loses focus.
     * @param {boolean} animate If true (the default), animate the dialog closed, otherwise
     *      close it immediately.
     */
    function ModalBar(template, autoClose, animate) {
        if (animate === undefined) {
            animate = true;
        }
        
        this._handleKeydown = this._handleKeydown.bind(this);
        this._handleFocusChange = this._handleFocusChange.bind(this);
        
        this._$root = $("<div class='modal-bar'/>")
            .html(template)
            .insertBefore("#editor-holder");

        if (animate) {
            this._$root.addClass("popout offscreen");
            // Forcing the renderer to do a layout, which will cause it to apply the transform for the "offscreen"
            // class, so it will animate when you remove the class.
            window.getComputedStyle(this._$root.get(0)).getPropertyValue("top");
            this._$root.removeClass("popout offscreen");
        }
        
        // If something *other* than an editor (like another modal bar) has focus, set the focus 
        // to the editor here, before opening up the new modal bar. This ensures that the old
        // focused item has time to react and close before the new modal bar is opened.
        // See bugs #4287 and #3424
        if (!EditorManager.getFocusedEditor()) {
            EditorManager.focusEditor();
        }
        
        if (autoClose) {
            this._autoClose = true;
            this._$root.on("keydown", this._handleKeydown);
            window.document.body.addEventListener("focusin", this._handleFocusChange, true);
                
            // Set focus to the first input field, or the first button if there is no input field.
            // TODO: remove this logic?
            var $firstInput = $("input[type='text']", this._$root).first();
            if ($firstInput.length > 0) {
                $firstInput.focus();
            } else {
                $("button", this._$root).first().focus();
            }
        }
        
        // Preserve scroll position of the current full editor across the editor refresh, adjusting for the 
        // height of the modal bar so the code doesn't appear to shift if possible.
        var fullEditor = EditorManager.getCurrentFullEditor(),
            scrollPos;
        if (fullEditor) {
            scrollPos = fullEditor.getScrollPos();
        }
        EditorManager.resizeEditor();
        if (fullEditor) {
            fullEditor._codeMirror.scrollTo(scrollPos.x, scrollPos.y + this.height());
        }
    }
Example #17
0
            $row.click(function () {
                if ($selectedRow) {
                    $selectedRow.removeClass("selected");
                }
                $row.addClass("selected");
                $selectedRow = $row;
 
                var editor = EditorManager.getCurrentFullEditor();
                editor.setCursorPos(message.line - 1, message.character - 1);
                EditorManager.focusEditor();
            });
Example #18
0
 var clickCallback = function () {
     if ($selectedRow) {
         $selectedRow.removeClass("selected");
     }
     $row.addClass("selected");
     $selectedRow = $row;
     
     var editor = EditorManager.getCurrentFullEditor();
     editor.setCursorPos(item.line - 1, item.character - 1, true);
     EditorManager.focusEditor();
 };
Example #19
0
 row.click(function () {
     if (selectedRow) {
         selectedRow.removeClass("selected");
     }
     row.addClass("selected");
     selectedRow = row;
     
     var editor = EditorManager.getCurrentFullEditor();
     editor.setCursorPos(item.line - 1, item.character - 1);
     EditorManager.focusEditor();
 });
Example #20
0
 QuickNavigateDialog.prototype._isValidLineNumberQuery = function (query) {
     // Empty query returns NaN from extractLineNumber, but we want to treat it as valid for UI purposes.
     if (query === ":") {
         return true;
     }
     
     var lineNum = extractLineNumber(query),
         editor = EditorManager.getCurrentFullEditor();
     
     // We could just use 0 and lineCount() here, but in future we might want this logic to work for inline editors as well.
     return (!isNaN(lineNum) && editor && lineNum >= editor.getFirstVisibleLine() && lineNum <= editor.getLastVisibleLine());
 };
Example #21
0
    QuickNavigateDialog.prototype._handleItemSelect = function (e, selectedDOMItem) {

        // This is a work-around to select first item when a selection event occurs
        // (usually from pressing the enter key) and no item is selected in the list.
        // This is a work-around since  Smart auto complete doesn't select the first item
        if (!selectedDOMItem) {
            selectedDOMItem = $(".smart_autocomplete_container > li:first-child").get(0);
        }
        
        var selectedItem = domItemToSearchResult(selectedDOMItem),
            doClose = true,
            self = this;

        // Delegate to current plugin
        if (currentPlugin) {
            currentPlugin.itemSelect(selectedItem);
        } else {

            // extract line number, if any
            var query = this.$searchField.val(),
                gotoLine = extractLineNumber(query);

            // Navigate to file and line number
            var fullPath = selectedItem && selectedItem.fullPath;
            if (fullPath) {
                // This case is tricky. We want to switch editors, so we need to deal with
                // resizing/rescrolling the current editor first. But we don't actually want
                // to start the animation of the ModalBar until afterward (otherwise it glitches
                // because it gets starved of cycles during the creation of the new editor). 
                // So we call `prepareClose()` first, and finish the close later.
                doClose = false;
                this.modalBar.prepareClose();
                CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, {fullPath: fullPath})
                    .done(function () {
                        if (!isNaN(gotoLine)) {
                            var editor = EditorManager.getCurrentFullEditor();
                            editor.setCursorPos(gotoLine, 0, true);
                        }
                    })
                    .always(function () {
                        self.close();
                    });
            } else if (!isNaN(gotoLine)) {
                EditorManager.getCurrentFullEditor().setCursorPos(gotoLine, 0, true);
            }
        }

        if (doClose) {
            this.close();
            EditorManager.focusEditor();
        }
    };
Example #22
0
 .always(function () {
     // If a line and column number were given, position the editor accordingly.
     if (fileInfo.line !== null) {
         if (fileInfo.column === null || (fileInfo.column <= 0)) {
             fileInfo.column = 1;
         }
         // setCursorPos expects line/column numbers as 0-origin, so we subtract 1
         EditorManager.getCurrentFullEditor().setCursorPos(fileInfo.line - 1, fileInfo.column - 1, true);
     }
     
     // Give the editor focus
     EditorManager.focusEditor();
 });
Example #23
0
    // helper function that actually does the launch once we are sure we have
    // a doc and the server for that doc is up and running.
    function _doLaunchAfterServerReady() {
        // update status
        _setStatus(STATUS_CONNECTING);
        
        // create live document
        _openDocument(_getCurrentDocument(), EditorManager.getCurrentFullEditor());

        // Install a one-time event handler when connected to the launcher page
        $(Inspector).one("connect", _onConnect);
        
        // open browser to the interstitial page to prepare for loading agents
        _openInterstitialPage();
    }
Example #24
0
    /** Run when all agents are loaded */
    function _onLoad() {
        var doc = _getCurrentDocument();
        if (doc) {
            var editor = EditorManager.getCurrentFullEditor(),
                status = STATUS_ACTIVE;

            _openDocument(doc, editor);
            if (doc.isDirty && _classForDocument(doc) !== CSSDocument) {
                status = STATUS_OUT_OF_SYNC;
            }
            _setStatus(status);
        }
    }
    /**
     * @private
     * Scroll the viewport one line up or down.
     * @param {number} direction -1 to scroll one line up; 1 to scroll one line down.
     */
    function _scrollLine(direction) {
        var editor        = EditorManager.getCurrentFullEditor(),
            textHeight    = editor.getTextHeight(),
            cursorPos     = editor.getCursorPos(),
            hasSelecction = editor.hasSelection(),
            inlineEditors = editor.getInlineWidgets(),
            scrollInfo    = editor._codeMirror.getScrollInfo(),
            paddingTop    = editor._getLineSpaceElement().offsetTop,
            editorHeight  = scrollInfo.clientHeight,
            scrollTop     = scrollInfo.top - paddingTop,
            removedScroll = paddingTop;

        // Go through all the editors and reduce the scroll top and editor height to properly calculate the lines in view
        var line, coords;
        inlineEditors.forEach(function (inlineEditor) {
            line   = editor._getInlineWidgetLineNumber(inlineEditor);
            coords = editor._codeMirror.charCoords({line: line, ch: 0}, "local");

            if (coords.top < scrollInfo.top) {
                scrollTop     -= inlineEditor.info.height;
                removedScroll += inlineEditor.info.height;

            } else if (coords.top + inlineEditor.info.height < scrollInfo.top + editorHeight) {
                editorHeight -= inlineEditor.info.height;
            }
        });

        // Calculate the lines in view
        var linesInView = _getLinesInView(textHeight, scrollTop, editorHeight);

        // If there is no selection move the cursor so that is always visible.
        if (!hasSelecction) {
            // Move the cursor to the first visible line.
            if (cursorPos.line < linesInView.first) {
                editor.setCursorPos({line: linesInView.first + direction, ch: cursorPos.ch});

            // Move the cursor to the last visible line.
            } else if (cursorPos.line > linesInView.last) {
                editor.setCursorPos({line: linesInView.last + direction, ch: cursorPos.ch});

            // Move the cursor up or down using moveV to keep the goal column intact, since setCursorPos deletes it.
            } else if ((direction > 0 && cursorPos.line === linesInView.first) ||
                    (direction < 0 && cursorPos.line === linesInView.last)) {
                editor._codeMirror.moveV(direction, "line");
            }
        }

        // Scroll and make it snap to lines
        var lines = linesInView.first + direction;
        editor.setScrollPos(scrollInfo.left, (textHeight * lines) + removedScroll);
    }
Example #26
0
            .on("click", "tr", function (e) {
                if ($selectedRow) {
                    $selectedRow.removeClass("selected");
                }

                $selectedRow  = $(e.currentTarget);
                $selectedRow.addClass("selected");
                var lineTd    = $selectedRow.find(".line-number");
                var line      = parseInt(lineTd.text(), 10) - 1;  // convert friendlyLine back to pos.line
                var character = lineTd.data("character");

                var editor = EditorManager.getCurrentFullEditor();
                editor.setCursorPos(line, character, true);
                EditorManager.focusEditor();
            });
Example #27
0
    QuickNavigateDialog.prototype._filterCallback = function (query) {
        // If previous filter calls ran slow, we may have accumulated several query change events in the meantime.
        // Only respond to the one that's current. Note that this only works because we're called on a timeout after
        // the key event; checking DURING the key event itself would never yield a future value for the input field.
        if (queryIsStale(query)) {
            return getLastFilterResult();
        }
        
        // "Go to line" mode is special-cased
        var gotoLine = extractLineNumber(query);
        if (!isNaN(gotoLine)) {
            var from = {line: gotoLine, ch: 0};
            var to = {line: gotoLine, ch: 99999};
            
            EditorManager.getCurrentFullEditor().setSelection(from, to, true);
        }
        
        // Try to invoke a search plugin
        var curDoc = DocumentManager.getCurrentDocument(), languageId;
        if (curDoc) {
            languageId = curDoc.getLanguage().getId();
        }

        var i;
        for (i = 0; i < plugins.length; i++) {
            var plugin = plugins[i];
            var languageIdMatch = plugin.languageIds.length === 0 || plugin.languageIds.indexOf(languageId) !== -1;
            if (languageIdMatch && plugin.match && plugin.match(query)) {
                currentPlugin = plugin;
                
                // Look up the StringMatcher for this plugin.
                var matcher = this._matchers[currentPlugin.name];
                if (!matcher) {
                    matcher = new StringMatch.StringMatcher(plugin.matcherOptions);
                    this._matchers[currentPlugin.name] = matcher;
                }
                this._updateDialogLabel(plugin, query);
                return plugin.search(query, matcher);
            }
        }
        
        // Reflect current search mode in UI
        this._updateDialogLabel(null, query);
        
        // No matching plugin: use default file search mode
        currentPlugin = null;
        return searchFileList(query, this._filenameMatcher);
    };
Example #28
0
        setTimeout(function () {
            self.modalBar.close(!scrollPos).done(function () {
                self._closeDeferred.resolve();
            });

            // Note that we deliberately reset the scroll position synchronously on return from
            // `ModalBar.close()` (before the animation completes).
            // See description of `restoreScrollPos` in `ModalBar.close()`.
            var editor = EditorManager.getCurrentFullEditor();
            if (selection) {
                editor.setSelection(selection.start, selection.end);
            }
            if (scrollPos) {
                editor.setScrollPos(scrollPos.x, scrollPos.y);
            }
        }, 0);
Example #29
0
    /** Point the master editor to the given location
     * @param {integer} location in file
     */
    function openLocation(location, noFlash) {
        var editor = EditorManager.getCurrentFullEditor();
        var codeMirror = editor._codeMirror;
        if (typeof location === "number") {
            location = codeMirror.posFromIndex(location);
        }
        codeMirror.setCursor(location);
        editor.focus();

        if (!noFlash) {
            codeMirror.addLineClass(location.line, "wrap", "flash");
            window.setTimeout(function () {
                codeMirror.removeLineClass(location.line, "wrap", "flash");
            }, 1000);
        }
    }
Example #30
0
    /**
     * @private
     * Increases or decreases the editor's font size.
     * @param {number} -1 to make the font smaller; 1 to make it bigger.
     */
    function _adjustFontSize(direction) {
        var styleId = "codemirror-dynamic-fonts";

        var fs = $(".CodeMirror-scroll").css("font-size");
        var lh = $(".CodeMirror-scroll").css("line-height");

        var validFont = /^[\d\.]+(px|em)$/;
        
        // Make sure the font size and line height are expressed in terms
        // we can handle (px or em). If not, simply bail.
        if (fs.search(validFont) === -1 || lh.search(validFont) === -1) {
            return;
        }
        
        // Guaranteed to work by the validation above.
        var fsUnits = fs.substring(fs.length - 2, fs.length);
        var lhUnits = lh.substring(lh.length - 2, lh.length);

        fs = fs.substring(0, fs.length - 2);
        lh = lh.substring(0, lh.length - 2);

        var fsDelta = (fsUnits === "px") ? 1 : 0.1;
        var lhDelta = (lhUnits === "px") ? 1 : 0.1;

        if (direction === -1) {
            fsDelta *= -1;
            lhDelta *= -1;
        }

        var fsStr = (parseFloat(fs) + fsDelta) + fsUnits;
        var lhStr = (parseFloat(lh) + lhDelta) + lhUnits;

        // Don't let the fonts get too small.
        if (direction === -1 && ((fsUnits === "px" && fs <= 1) || (fsUnits === "em" && fs <= 0.1))) {
            return;
        }

        // It's necessary to inject a new rule to address all editors.
        $("#" + styleId).remove();
        var style = $("<style type='text/css'></style>").attr("id", styleId);
        style.html(".CodeMirror-scroll {" +
                   "font-size: "   + fsStr + " !important;" +
                   "line-height: " + lhStr + " !important;}");
        $("head").append(style);

        EditorManager.getCurrentFullEditor().refreshAll();
    }