browser/devtools/sourceeditor/editor.js

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* vim:set ts=2 sw=2 sts=2 et tw=80:
michael@0 2 * This Source Code Form is subject to the terms of the Mozilla Public
michael@0 3 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 5
michael@0 6 "use strict";
michael@0 7
michael@0 8 const { Cu, Cc, Ci, components } = require("chrome");
michael@0 9
michael@0 10 const TAB_SIZE = "devtools.editor.tabsize";
michael@0 11 const EXPAND_TAB = "devtools.editor.expandtab";
michael@0 12 const KEYMAP = "devtools.editor.keymap";
michael@0 13 const AUTO_CLOSE = "devtools.editor.autoclosebrackets";
michael@0 14 const DETECT_INDENT = "devtools.editor.detectindentation";
michael@0 15 const DETECT_INDENT_MAX_LINES = 500;
michael@0 16 const L10N_BUNDLE = "chrome://browser/locale/devtools/sourceeditor.properties";
michael@0 17 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
michael@0 18
michael@0 19 // Maximum allowed margin (in number of lines) from top or bottom of the editor
michael@0 20 // while shifting to a line which was initially out of view.
michael@0 21 const MAX_VERTICAL_OFFSET = 3;
michael@0 22
michael@0 23 const {Promise: promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
michael@0 24 const events = require("devtools/toolkit/event-emitter");
michael@0 25
michael@0 26 Cu.import("resource://gre/modules/Services.jsm");
michael@0 27 const L10N = Services.strings.createBundle(L10N_BUNDLE);
michael@0 28
michael@0 29 // CM_STYLES, CM_SCRIPTS and CM_IFRAME represent the HTML,
michael@0 30 // JavaScript and CSS that is injected into an iframe in
michael@0 31 // order to initialize a CodeMirror instance.
michael@0 32
michael@0 33 const CM_STYLES = [
michael@0 34 "chrome://browser/skin/devtools/common.css",
michael@0 35 "chrome://browser/content/devtools/codemirror/codemirror.css",
michael@0 36 "chrome://browser/content/devtools/codemirror/dialog.css",
michael@0 37 "chrome://browser/content/devtools/codemirror/mozilla.css"
michael@0 38 ];
michael@0 39
michael@0 40 const CM_SCRIPTS = [
michael@0 41 "chrome://browser/content/devtools/theme-switching.js",
michael@0 42 "chrome://browser/content/devtools/codemirror/codemirror.js",
michael@0 43 "chrome://browser/content/devtools/codemirror/dialog.js",
michael@0 44 "chrome://browser/content/devtools/codemirror/searchcursor.js",
michael@0 45 "chrome://browser/content/devtools/codemirror/search.js",
michael@0 46 "chrome://browser/content/devtools/codemirror/matchbrackets.js",
michael@0 47 "chrome://browser/content/devtools/codemirror/closebrackets.js",
michael@0 48 "chrome://browser/content/devtools/codemirror/comment.js",
michael@0 49 "chrome://browser/content/devtools/codemirror/javascript.js",
michael@0 50 "chrome://browser/content/devtools/codemirror/xml.js",
michael@0 51 "chrome://browser/content/devtools/codemirror/css.js",
michael@0 52 "chrome://browser/content/devtools/codemirror/htmlmixed.js",
michael@0 53 "chrome://browser/content/devtools/codemirror/clike.js",
michael@0 54 "chrome://browser/content/devtools/codemirror/activeline.js",
michael@0 55 "chrome://browser/content/devtools/codemirror/trailingspace.js",
michael@0 56 "chrome://browser/content/devtools/codemirror/emacs.js",
michael@0 57 "chrome://browser/content/devtools/codemirror/vim.js",
michael@0 58 "chrome://browser/content/devtools/codemirror/sublime.js",
michael@0 59 "chrome://browser/content/devtools/codemirror/foldcode.js",
michael@0 60 "chrome://browser/content/devtools/codemirror/brace-fold.js",
michael@0 61 "chrome://browser/content/devtools/codemirror/comment-fold.js",
michael@0 62 "chrome://browser/content/devtools/codemirror/xml-fold.js",
michael@0 63 "chrome://browser/content/devtools/codemirror/foldgutter.js"
michael@0 64 ];
michael@0 65
michael@0 66 const CM_IFRAME =
michael@0 67 "data:text/html;charset=utf8,<!DOCTYPE html>" +
michael@0 68 "<html dir='ltr'>" +
michael@0 69 " <head>" +
michael@0 70 " <style>" +
michael@0 71 " html, body { height: 100%; }" +
michael@0 72 " body { margin: 0; overflow: hidden; }" +
michael@0 73 " .CodeMirror { width: 100%; height: 100% !important; line-height: 1.25 !important;}" +
michael@0 74 " </style>" +
michael@0 75 [ " <link rel='stylesheet' href='" + style + "'>" for (style of CM_STYLES) ].join("\n") +
michael@0 76 " </head>" +
michael@0 77 " <body class='theme-body devtools-monospace'></body>" +
michael@0 78 "</html>";
michael@0 79
michael@0 80 const CM_MAPPING = [
michael@0 81 "focus",
michael@0 82 "hasFocus",
michael@0 83 "lineCount",
michael@0 84 "somethingSelected",
michael@0 85 "getCursor",
michael@0 86 "setSelection",
michael@0 87 "getSelection",
michael@0 88 "replaceSelection",
michael@0 89 "extendSelection",
michael@0 90 "undo",
michael@0 91 "redo",
michael@0 92 "clearHistory",
michael@0 93 "openDialog",
michael@0 94 "refresh",
michael@0 95 "getScrollInfo",
michael@0 96 "getOption",
michael@0 97 "setOption"
michael@0 98 ];
michael@0 99
michael@0 100 const { cssProperties, cssValues, cssColors } = getCSSKeywords();
michael@0 101
michael@0 102 const editors = new WeakMap();
michael@0 103
michael@0 104 Editor.modes = {
michael@0 105 text: { name: "text" },
michael@0 106 html: { name: "htmlmixed" },
michael@0 107 css: { name: "css" },
michael@0 108 js: { name: "javascript" },
michael@0 109 vs: { name: "x-shader/x-vertex" },
michael@0 110 fs: { name: "x-shader/x-fragment" }
michael@0 111 };
michael@0 112
michael@0 113 /**
michael@0 114 * A very thin wrapper around CodeMirror. Provides a number
michael@0 115 * of helper methods to make our use of CodeMirror easier and
michael@0 116 * another method, appendTo, to actually create and append
michael@0 117 * the CodeMirror instance.
michael@0 118 *
michael@0 119 * Note that Editor doesn't expose CodeMirror instance to the
michael@0 120 * outside world.
michael@0 121 *
michael@0 122 * Constructor accepts one argument, config. It is very
michael@0 123 * similar to the CodeMirror configuration object so for most
michael@0 124 * properties go to CodeMirror's documentation (see below).
michael@0 125 *
michael@0 126 * Other than that, it accepts one additional and optional
michael@0 127 * property contextMenu. This property should be an ID of
michael@0 128 * an element we can use as a context menu.
michael@0 129 *
michael@0 130 * This object is also an event emitter.
michael@0 131 *
michael@0 132 * CodeMirror docs: http://codemirror.net/doc/manual.html
michael@0 133 */
michael@0 134 function Editor(config) {
michael@0 135 const tabSize = Services.prefs.getIntPref(TAB_SIZE);
michael@0 136 const useTabs = !Services.prefs.getBoolPref(EXPAND_TAB);
michael@0 137 const keyMap = Services.prefs.getCharPref(KEYMAP);
michael@0 138 const useAutoClose = Services.prefs.getBoolPref(AUTO_CLOSE);
michael@0 139
michael@0 140 this.version = null;
michael@0 141 this.config = {
michael@0 142 value: "",
michael@0 143 mode: Editor.modes.text,
michael@0 144 indentUnit: tabSize,
michael@0 145 tabSize: tabSize,
michael@0 146 contextMenu: null,
michael@0 147 matchBrackets: true,
michael@0 148 extraKeys: {},
michael@0 149 indentWithTabs: useTabs,
michael@0 150 styleActiveLine: true,
michael@0 151 autoCloseBrackets: "()[]{}''\"\"",
michael@0 152 autoCloseEnabled: useAutoClose,
michael@0 153 theme: "mozilla"
michael@0 154 };
michael@0 155
michael@0 156 // Additional shortcuts.
michael@0 157 this.config.extraKeys[Editor.keyFor("jumpToLine")] = () => this.jumpToLine();
michael@0 158 this.config.extraKeys[Editor.keyFor("moveLineUp", { noaccel: true })] = () => this.moveLineUp();
michael@0 159 this.config.extraKeys[Editor.keyFor("moveLineDown", { noaccel: true })] = () => this.moveLineDown();
michael@0 160 this.config.extraKeys[Editor.keyFor("toggleComment")] = "toggleComment";
michael@0 161
michael@0 162 // Disable ctrl-[ and ctrl-] because toolbox uses those shortcuts.
michael@0 163 this.config.extraKeys[Editor.keyFor("indentLess")] = false;
michael@0 164 this.config.extraKeys[Editor.keyFor("indentMore")] = false;
michael@0 165
michael@0 166 // If alternative keymap is provided, use it.
michael@0 167 if (keyMap === "emacs" || keyMap === "vim" || keyMap === "sublime")
michael@0 168 this.config.keyMap = keyMap;
michael@0 169
michael@0 170 // Overwrite default config with user-provided, if needed.
michael@0 171 Object.keys(config).forEach((k) => {
michael@0 172 if (k != "extraKeys") {
michael@0 173 this.config[k] = config[k];
michael@0 174 return;
michael@0 175 }
michael@0 176
michael@0 177 if (!config.extraKeys)
michael@0 178 return;
michael@0 179
michael@0 180 Object.keys(config.extraKeys).forEach((key) => {
michael@0 181 this.config.extraKeys[key] = config.extraKeys[key];
michael@0 182 });
michael@0 183 });
michael@0 184
michael@0 185 // Set the code folding gutter, if needed.
michael@0 186 if (this.config.enableCodeFolding) {
michael@0 187 this.config.foldGutter = true;
michael@0 188
michael@0 189 if (!this.config.gutters) {
michael@0 190 this.config.gutters = this.config.lineNumbers ? ["CodeMirror-linenumbers"] : [];
michael@0 191 this.config.gutters.push("CodeMirror-foldgutter");
michael@0 192 }
michael@0 193 }
michael@0 194
michael@0 195 // Configure automatic bracket closing.
michael@0 196 if (!this.config.autoCloseEnabled)
michael@0 197 this.config.autoCloseBrackets = false;
michael@0 198
michael@0 199 // Overwrite default tab behavior. If something is selected,
michael@0 200 // indent those lines. If nothing is selected and we're
michael@0 201 // indenting with tabs, insert one tab. Otherwise insert N
michael@0 202 // whitespaces where N == indentUnit option.
michael@0 203 this.config.extraKeys.Tab = (cm) => {
michael@0 204 if (cm.somethingSelected()) {
michael@0 205 cm.indentSelection("add");
michael@0 206 return;
michael@0 207 }
michael@0 208
michael@0 209 if (this.config.indentWithTabs) {
michael@0 210 cm.replaceSelection("\t", "end", "+input");
michael@0 211 return;
michael@0 212 }
michael@0 213
michael@0 214 var num = cm.getOption("indentUnit");
michael@0 215 if (cm.getCursor().ch !== 0) num -= 1;
michael@0 216 cm.replaceSelection(" ".repeat(num), "end", "+input");
michael@0 217 };
michael@0 218
michael@0 219 events.decorate(this);
michael@0 220 }
michael@0 221
michael@0 222 Editor.prototype = {
michael@0 223 container: null,
michael@0 224 version: null,
michael@0 225 config: null,
michael@0 226
michael@0 227 /**
michael@0 228 * Appends the current Editor instance to the element specified by
michael@0 229 * 'el'. You can also provide your won iframe to host the editor as
michael@0 230 * an optional second parameter. This method actually creates and
michael@0 231 * loads CodeMirror and all its dependencies.
michael@0 232 *
michael@0 233 * This method is asynchronous and returns a promise.
michael@0 234 */
michael@0 235 appendTo: function (el, env) {
michael@0 236 let def = promise.defer();
michael@0 237 let cm = editors.get(this);
michael@0 238
michael@0 239 if (!env)
michael@0 240 env = el.ownerDocument.createElementNS(XUL_NS, "iframe");
michael@0 241
michael@0 242 env.flex = 1;
michael@0 243
michael@0 244 if (cm)
michael@0 245 throw new Error("You can append an editor only once.");
michael@0 246
michael@0 247 let onLoad = () => {
michael@0 248 // Once the iframe is loaded, we can inject CodeMirror
michael@0 249 // and its dependencies into its DOM.
michael@0 250
michael@0 251 env.removeEventListener("load", onLoad, true);
michael@0 252 let win = env.contentWindow.wrappedJSObject;
michael@0 253
michael@0 254 CM_SCRIPTS.forEach((url) =>
michael@0 255 Services.scriptloader.loadSubScript(url, win, "utf8"));
michael@0 256
michael@0 257 // Replace the propertyKeywords, colorKeywords and valueKeywords
michael@0 258 // properties of the CSS MIME type with the values provided by Gecko.
michael@0 259 let cssSpec = win.CodeMirror.resolveMode("text/css");
michael@0 260 cssSpec.propertyKeywords = cssProperties;
michael@0 261 cssSpec.colorKeywords = cssColors;
michael@0 262 cssSpec.valueKeywords = cssValues;
michael@0 263 win.CodeMirror.defineMIME("text/css", cssSpec);
michael@0 264
michael@0 265 let scssSpec = win.CodeMirror.resolveMode("text/x-scss");
michael@0 266 scssSpec.propertyKeywords = cssProperties;
michael@0 267 scssSpec.colorKeywords = cssColors;
michael@0 268 scssSpec.valueKeywords = cssValues;
michael@0 269 win.CodeMirror.defineMIME("text/x-scss", scssSpec);
michael@0 270
michael@0 271 win.CodeMirror.commands.save = () => this.emit("save");
michael@0 272
michael@0 273 // Create a CodeMirror instance add support for context menus,
michael@0 274 // overwrite the default controller (otherwise items in the top and
michael@0 275 // context menus won't work).
michael@0 276
michael@0 277 cm = win.CodeMirror(win.document.body, this.config);
michael@0 278 cm.getWrapperElement().addEventListener("contextmenu", (ev) => {
michael@0 279 ev.preventDefault();
michael@0 280 if (!this.config.contextMenu) return;
michael@0 281 let popup = el.ownerDocument.getElementById(this.config.contextMenu);
michael@0 282 popup.openPopupAtScreen(ev.screenX, ev.screenY, true);
michael@0 283 }, false);
michael@0 284
michael@0 285 cm.on("focus", () => this.emit("focus"));
michael@0 286 cm.on("scroll", () => this.emit("scroll"));
michael@0 287 cm.on("change", () => {
michael@0 288 this.emit("change");
michael@0 289 if (!this._lastDirty) {
michael@0 290 this._lastDirty = true;
michael@0 291 this.emit("dirty-change");
michael@0 292 }
michael@0 293 });
michael@0 294 cm.on("cursorActivity", (cm) => this.emit("cursorActivity"));
michael@0 295
michael@0 296 cm.on("gutterClick", (cm, line, gutter, ev) => {
michael@0 297 let head = { line: line, ch: 0 };
michael@0 298 let tail = { line: line, ch: this.getText(line).length };
michael@0 299
michael@0 300 // Shift-click on a gutter selects the whole line.
michael@0 301 if (ev.shiftKey) {
michael@0 302 cm.setSelection(head, tail);
michael@0 303 return;
michael@0 304 }
michael@0 305
michael@0 306 this.emit("gutterClick", line);
michael@0 307 });
michael@0 308
michael@0 309 win.CodeMirror.defineExtension("l10n", (name) => {
michael@0 310 return L10N.GetStringFromName(name);
michael@0 311 });
michael@0 312
michael@0 313 cm.getInputField().controllers.insertControllerAt(0, controller(this));
michael@0 314
michael@0 315 this.container = env;
michael@0 316 editors.set(this, cm);
michael@0 317
michael@0 318 this.resetIndentUnit();
michael@0 319
michael@0 320 def.resolve();
michael@0 321 };
michael@0 322
michael@0 323 env.addEventListener("load", onLoad, true);
michael@0 324 env.setAttribute("src", CM_IFRAME);
michael@0 325 el.appendChild(env);
michael@0 326
michael@0 327 this.once("destroy", () => el.removeChild(env));
michael@0 328 return def.promise;
michael@0 329 },
michael@0 330
michael@0 331 /**
michael@0 332 * Returns the currently active highlighting mode.
michael@0 333 * See Editor.modes for the list of all suppoert modes.
michael@0 334 */
michael@0 335 getMode: function () {
michael@0 336 return this.getOption("mode");
michael@0 337 },
michael@0 338
michael@0 339 /**
michael@0 340 * Changes the value of a currently used highlighting mode.
michael@0 341 * See Editor.modes for the list of all suppoert modes.
michael@0 342 */
michael@0 343 setMode: function (value) {
michael@0 344 this.setOption("mode", value);
michael@0 345 },
michael@0 346
michael@0 347 /**
michael@0 348 * Returns text from the text area. If line argument is provided
michael@0 349 * the method returns only that line.
michael@0 350 */
michael@0 351 getText: function (line) {
michael@0 352 let cm = editors.get(this);
michael@0 353
michael@0 354 if (line == null)
michael@0 355 return cm.getValue();
michael@0 356
michael@0 357 let info = cm.lineInfo(line);
michael@0 358 return info ? cm.lineInfo(line).text : "";
michael@0 359 },
michael@0 360
michael@0 361 /**
michael@0 362 * Replaces whatever is in the text area with the contents of
michael@0 363 * the 'value' argument.
michael@0 364 */
michael@0 365 setText: function (value) {
michael@0 366 let cm = editors.get(this);
michael@0 367 cm.setValue(value);
michael@0 368
michael@0 369 this.resetIndentUnit();
michael@0 370 },
michael@0 371
michael@0 372 /**
michael@0 373 * Set the editor's indentation based on the current prefs and
michael@0 374 * re-detect indentation if we should.
michael@0 375 */
michael@0 376 resetIndentUnit: function() {
michael@0 377 let cm = editors.get(this);
michael@0 378
michael@0 379 let indentWithTabs = !Services.prefs.getBoolPref(EXPAND_TAB);
michael@0 380 let indentUnit = Services.prefs.getIntPref(TAB_SIZE);
michael@0 381 let shouldDetect = Services.prefs.getBoolPref(DETECT_INDENT);
michael@0 382
michael@0 383 cm.setOption("tabSize", indentUnit);
michael@0 384
michael@0 385 if (shouldDetect) {
michael@0 386 let indent = detectIndentation(this);
michael@0 387 if (indent != null) {
michael@0 388 indentWithTabs = indent.tabs;
michael@0 389 indentUnit = indent.spaces ? indent.spaces : indentUnit;
michael@0 390 }
michael@0 391 }
michael@0 392
michael@0 393 cm.setOption("indentUnit", indentUnit);
michael@0 394 cm.setOption("indentWithTabs", indentWithTabs);
michael@0 395 },
michael@0 396
michael@0 397 /**
michael@0 398 * Replaces contents of a text area within the from/to {line, ch}
michael@0 399 * range. If neither from nor to arguments are provided works
michael@0 400 * exactly like setText. If only from object is provided, inserts
michael@0 401 * text at that point, *overwriting* as many characters as needed.
michael@0 402 */
michael@0 403 replaceText: function (value, from, to) {
michael@0 404 let cm = editors.get(this);
michael@0 405
michael@0 406 if (!from) {
michael@0 407 this.setText(value);
michael@0 408 return;
michael@0 409 }
michael@0 410
michael@0 411 if (!to) {
michael@0 412 let text = cm.getRange({ line: 0, ch: 0 }, from);
michael@0 413 this.setText(text + value);
michael@0 414 return;
michael@0 415 }
michael@0 416
michael@0 417 cm.replaceRange(value, from, to);
michael@0 418 },
michael@0 419
michael@0 420 /**
michael@0 421 * Inserts text at the specified {line, ch} position, shifting existing
michael@0 422 * contents as necessary.
michael@0 423 */
michael@0 424 insertText: function (value, at) {
michael@0 425 let cm = editors.get(this);
michael@0 426 cm.replaceRange(value, at, at);
michael@0 427 },
michael@0 428
michael@0 429 /**
michael@0 430 * Deselects contents of the text area.
michael@0 431 */
michael@0 432 dropSelection: function () {
michael@0 433 if (!this.somethingSelected())
michael@0 434 return;
michael@0 435
michael@0 436 this.setCursor(this.getCursor());
michael@0 437 },
michael@0 438
michael@0 439 /**
michael@0 440 * Returns true if there is more than one selection in the editor.
michael@0 441 */
michael@0 442 hasMultipleSelections: function () {
michael@0 443 let cm = editors.get(this);
michael@0 444 return cm.listSelections().length > 1;
michael@0 445 },
michael@0 446
michael@0 447 /**
michael@0 448 * Gets the first visible line number in the editor.
michael@0 449 */
michael@0 450 getFirstVisibleLine: function () {
michael@0 451 let cm = editors.get(this);
michael@0 452 return cm.lineAtHeight(0, "local");
michael@0 453 },
michael@0 454
michael@0 455 /**
michael@0 456 * Scrolls the view such that the given line number is the first visible line.
michael@0 457 */
michael@0 458 setFirstVisibleLine: function (line) {
michael@0 459 let cm = editors.get(this);
michael@0 460 let { top } = cm.charCoords({line: line, ch: 0}, "local");
michael@0 461 cm.scrollTo(0, top);
michael@0 462 },
michael@0 463
michael@0 464 /**
michael@0 465 * Sets the cursor to the specified {line, ch} position with an additional
michael@0 466 * option to align the line at the "top", "center" or "bottom" of the editor
michael@0 467 * with "top" being default value.
michael@0 468 */
michael@0 469 setCursor: function ({line, ch}, align) {
michael@0 470 let cm = editors.get(this);
michael@0 471 this.alignLine(line, align);
michael@0 472 cm.setCursor({line: line, ch: ch});
michael@0 473 },
michael@0 474
michael@0 475 /**
michael@0 476 * Aligns the provided line to either "top", "center" or "bottom" of the
michael@0 477 * editor view with a maximum margin of MAX_VERTICAL_OFFSET lines from top or
michael@0 478 * bottom.
michael@0 479 */
michael@0 480 alignLine: function(line, align) {
michael@0 481 let cm = editors.get(this);
michael@0 482 let from = cm.lineAtHeight(0, "page");
michael@0 483 let to = cm.lineAtHeight(cm.getWrapperElement().clientHeight, "page");
michael@0 484 let linesVisible = to - from;
michael@0 485 let halfVisible = Math.round(linesVisible/2);
michael@0 486
michael@0 487 // If the target line is in view, skip the vertical alignment part.
michael@0 488 if (line <= to && line >= from) {
michael@0 489 return;
michael@0 490 }
michael@0 491
michael@0 492 // Setting the offset so that the line always falls in the upper half
michael@0 493 // of visible lines (lower half for bottom aligned).
michael@0 494 // MAX_VERTICAL_OFFSET is the maximum allowed value.
michael@0 495 let offset = Math.min(halfVisible, MAX_VERTICAL_OFFSET);
michael@0 496
michael@0 497 let topLine = {
michael@0 498 "center": Math.max(line - halfVisible, 0),
michael@0 499 "bottom": Math.max(line - linesVisible + offset, 0),
michael@0 500 "top": Math.max(line - offset, 0)
michael@0 501 }[align || "top"] || offset;
michael@0 502
michael@0 503 // Bringing down the topLine to total lines in the editor if exceeding.
michael@0 504 topLine = Math.min(topLine, this.lineCount());
michael@0 505 this.setFirstVisibleLine(topLine);
michael@0 506 },
michael@0 507
michael@0 508 /**
michael@0 509 * Returns whether a marker of a specified class exists in a line's gutter.
michael@0 510 */
michael@0 511 hasMarker: function (line, gutterName, markerClass) {
michael@0 512 let cm = editors.get(this);
michael@0 513 let info = cm.lineInfo(line);
michael@0 514 if (!info)
michael@0 515 return false;
michael@0 516
michael@0 517 let gutterMarkers = info.gutterMarkers;
michael@0 518 if (!gutterMarkers)
michael@0 519 return false;
michael@0 520
michael@0 521 let marker = gutterMarkers[gutterName];
michael@0 522 if (!marker)
michael@0 523 return false;
michael@0 524
michael@0 525 return marker.classList.contains(markerClass);
michael@0 526 },
michael@0 527
michael@0 528 /**
michael@0 529 * Adds a marker with a specified class to a line's gutter. If another marker
michael@0 530 * exists on that line, the new marker class is added to its class list.
michael@0 531 */
michael@0 532 addMarker: function (line, gutterName, markerClass) {
michael@0 533 let cm = editors.get(this);
michael@0 534 let info = cm.lineInfo(line);
michael@0 535 if (!info)
michael@0 536 return;
michael@0 537
michael@0 538 let gutterMarkers = info.gutterMarkers;
michael@0 539 if (gutterMarkers) {
michael@0 540 let marker = gutterMarkers[gutterName];
michael@0 541 if (marker) {
michael@0 542 marker.classList.add(markerClass);
michael@0 543 return;
michael@0 544 }
michael@0 545 }
michael@0 546
michael@0 547 let marker = cm.getWrapperElement().ownerDocument.createElement("div");
michael@0 548 marker.className = markerClass;
michael@0 549 cm.setGutterMarker(info.line, gutterName, marker);
michael@0 550 },
michael@0 551
michael@0 552 /**
michael@0 553 * The reverse of addMarker. Removes a marker of a specified class from a
michael@0 554 * line's gutter.
michael@0 555 */
michael@0 556 removeMarker: function (line, gutterName, markerClass) {
michael@0 557 if (!this.hasMarker(line, gutterName, markerClass))
michael@0 558 return;
michael@0 559
michael@0 560 let cm = editors.get(this);
michael@0 561 cm.lineInfo(line).gutterMarkers[gutterName].classList.remove(markerClass);
michael@0 562 },
michael@0 563
michael@0 564 /**
michael@0 565 * Remove all gutter markers in the gutter with the given name.
michael@0 566 */
michael@0 567 removeAllMarkers: function (gutterName) {
michael@0 568 let cm = editors.get(this);
michael@0 569 cm.clearGutter(gutterName);
michael@0 570 },
michael@0 571
michael@0 572 /**
michael@0 573 * Handles attaching a set of events listeners on a marker. They should
michael@0 574 * be passed as an object literal with keys as event names and values as
michael@0 575 * function listeners. The line number, marker node and optional data
michael@0 576 * will be passed as arguments to the function listener.
michael@0 577 *
michael@0 578 * You don't need to worry about removing these event listeners.
michael@0 579 * They're automatically orphaned when clearing markers.
michael@0 580 */
michael@0 581 setMarkerListeners: function(line, gutterName, markerClass, events, data) {
michael@0 582 if (!this.hasMarker(line, gutterName, markerClass))
michael@0 583 return;
michael@0 584
michael@0 585 let cm = editors.get(this);
michael@0 586 let marker = cm.lineInfo(line).gutterMarkers[gutterName];
michael@0 587
michael@0 588 for (let name in events) {
michael@0 589 let listener = events[name].bind(this, line, marker, data);
michael@0 590 marker.addEventListener(name, listener);
michael@0 591 }
michael@0 592 },
michael@0 593
michael@0 594 /**
michael@0 595 * Returns whether a line is decorated using the specified class name.
michael@0 596 */
michael@0 597 hasLineClass: function (line, className) {
michael@0 598 let cm = editors.get(this);
michael@0 599 let info = cm.lineInfo(line);
michael@0 600
michael@0 601 if (!info || !info.wrapClass)
michael@0 602 return false;
michael@0 603
michael@0 604 return info.wrapClass.split(" ").indexOf(className) != -1;
michael@0 605 },
michael@0 606
michael@0 607 /**
michael@0 608 * Set a CSS class name for the given line, including the text and gutter.
michael@0 609 */
michael@0 610 addLineClass: function (line, className) {
michael@0 611 let cm = editors.get(this);
michael@0 612 cm.addLineClass(line, "wrap", className);
michael@0 613 },
michael@0 614
michael@0 615 /**
michael@0 616 * The reverse of addLineClass.
michael@0 617 */
michael@0 618 removeLineClass: function (line, className) {
michael@0 619 let cm = editors.get(this);
michael@0 620 cm.removeLineClass(line, "wrap", className);
michael@0 621 },
michael@0 622
michael@0 623 /**
michael@0 624 * Mark a range of text inside the two {line, ch} bounds. Since the range may
michael@0 625 * be modified, for example, when typing text, this method returns a function
michael@0 626 * that can be used to remove the mark.
michael@0 627 */
michael@0 628 markText: function(from, to, className = "marked-text") {
michael@0 629 let cm = editors.get(this);
michael@0 630 let text = cm.getRange(from, to);
michael@0 631 let span = cm.getWrapperElement().ownerDocument.createElement("span");
michael@0 632 span.className = className;
michael@0 633 span.textContent = text;
michael@0 634
michael@0 635 let mark = cm.markText(from, to, { replacedWith: span });
michael@0 636 return {
michael@0 637 anchor: span,
michael@0 638 clear: () => mark.clear()
michael@0 639 };
michael@0 640 },
michael@0 641
michael@0 642 /**
michael@0 643 * Calculates and returns one or more {line, ch} objects for
michael@0 644 * a zero-based index who's value is relative to the start of
michael@0 645 * the editor's text.
michael@0 646 *
michael@0 647 * If only one argument is given, this method returns a single
michael@0 648 * {line,ch} object. Otherwise it returns an array.
michael@0 649 */
michael@0 650 getPosition: function (...args) {
michael@0 651 let cm = editors.get(this);
michael@0 652 let res = args.map((ind) => cm.posFromIndex(ind));
michael@0 653 return args.length === 1 ? res[0] : res;
michael@0 654 },
michael@0 655
michael@0 656 /**
michael@0 657 * The reverse of getPosition. Similarly to getPosition this
michael@0 658 * method returns a single value if only one argument was given
michael@0 659 * and an array otherwise.
michael@0 660 */
michael@0 661 getOffset: function (...args) {
michael@0 662 let cm = editors.get(this);
michael@0 663 let res = args.map((pos) => cm.indexFromPos(pos));
michael@0 664 return args.length > 1 ? res : res[0];
michael@0 665 },
michael@0 666
michael@0 667 /**
michael@0 668 * Returns a {line, ch} object that corresponds to the
michael@0 669 * left, top coordinates.
michael@0 670 */
michael@0 671 getPositionFromCoords: function ({left, top}) {
michael@0 672 let cm = editors.get(this);
michael@0 673 return cm.coordsChar({ left: left, top: top });
michael@0 674 },
michael@0 675
michael@0 676 /**
michael@0 677 * The reverse of getPositionFromCoords. Similarly, returns a {left, top}
michael@0 678 * object that corresponds to the specified line and character number.
michael@0 679 */
michael@0 680 getCoordsFromPosition: function ({line, ch}) {
michael@0 681 let cm = editors.get(this);
michael@0 682 return cm.charCoords({ line: ~~line, ch: ~~ch });
michael@0 683 },
michael@0 684
michael@0 685 /**
michael@0 686 * Returns true if there's something to undo and false otherwise.
michael@0 687 */
michael@0 688 canUndo: function () {
michael@0 689 let cm = editors.get(this);
michael@0 690 return cm.historySize().undo > 0;
michael@0 691 },
michael@0 692
michael@0 693 /**
michael@0 694 * Returns true if there's something to redo and false otherwise.
michael@0 695 */
michael@0 696 canRedo: function () {
michael@0 697 let cm = editors.get(this);
michael@0 698 return cm.historySize().redo > 0;
michael@0 699 },
michael@0 700
michael@0 701 /**
michael@0 702 * Marks the contents as clean and returns the current
michael@0 703 * version number.
michael@0 704 */
michael@0 705 setClean: function () {
michael@0 706 let cm = editors.get(this);
michael@0 707 this.version = cm.changeGeneration();
michael@0 708 this._lastDirty = false;
michael@0 709 this.emit("dirty-change");
michael@0 710 return this.version;
michael@0 711 },
michael@0 712
michael@0 713 /**
michael@0 714 * Returns true if contents of the text area are
michael@0 715 * clean i.e. no changes were made since the last version.
michael@0 716 */
michael@0 717 isClean: function () {
michael@0 718 let cm = editors.get(this);
michael@0 719 return cm.isClean(this.version);
michael@0 720 },
michael@0 721
michael@0 722 /**
michael@0 723 * This method opens an in-editor dialog asking for a line to
michael@0 724 * jump to. Once given, it changes cursor to that line.
michael@0 725 */
michael@0 726 jumpToLine: function () {
michael@0 727 let doc = editors.get(this).getWrapperElement().ownerDocument;
michael@0 728 let div = doc.createElement("div");
michael@0 729 let inp = doc.createElement("input");
michael@0 730 let txt = doc.createTextNode(L10N.GetStringFromName("gotoLineCmd.promptTitle"));
michael@0 731
michael@0 732 inp.type = "text";
michael@0 733 inp.style.width = "10em";
michael@0 734 inp.style.MozMarginStart = "1em";
michael@0 735
michael@0 736 div.appendChild(txt);
michael@0 737 div.appendChild(inp);
michael@0 738
michael@0 739 this.openDialog(div, (line) => this.setCursor({ line: line - 1, ch: 0 }));
michael@0 740 },
michael@0 741
michael@0 742 /**
michael@0 743 * Moves the content of the current line or the lines selected up a line.
michael@0 744 */
michael@0 745 moveLineUp: function () {
michael@0 746 let cm = editors.get(this);
michael@0 747 let start = cm.getCursor("start");
michael@0 748 let end = cm.getCursor("end");
michael@0 749
michael@0 750 if (start.line === 0)
michael@0 751 return;
michael@0 752
michael@0 753 // Get the text in the lines selected or the current line of the cursor
michael@0 754 // and append the text of the previous line.
michael@0 755 let value;
michael@0 756 if (start.line !== end.line) {
michael@0 757 value = cm.getRange({ line: start.line, ch: 0 },
michael@0 758 { line: end.line, ch: cm.getLine(end.line).length }) + "\n";
michael@0 759 } else {
michael@0 760 value = cm.getLine(start.line) + "\n";
michael@0 761 }
michael@0 762 value += cm.getLine(start.line - 1);
michael@0 763
michael@0 764 // Replace the previous line and the currently selected lines with the new
michael@0 765 // value and maintain the selection of the text.
michael@0 766 cm.replaceRange(value, { line: start.line - 1, ch: 0 },
michael@0 767 { line: end.line, ch: cm.getLine(end.line).length });
michael@0 768 cm.setSelection({ line: start.line - 1, ch: start.ch },
michael@0 769 { line: end.line - 1, ch: end.ch });
michael@0 770 },
michael@0 771
michael@0 772 /**
michael@0 773 * Moves the content of the current line or the lines selected down a line.
michael@0 774 */
michael@0 775 moveLineDown: function () {
michael@0 776 let cm = editors.get(this);
michael@0 777 let start = cm.getCursor("start");
michael@0 778 let end = cm.getCursor("end");
michael@0 779
michael@0 780 if (end.line + 1 === cm.lineCount())
michael@0 781 return;
michael@0 782
michael@0 783 // Get the text of next line and append the text in the lines selected
michael@0 784 // or the current line of the cursor.
michael@0 785 let value = cm.getLine(end.line + 1) + "\n";
michael@0 786 if (start.line !== end.line) {
michael@0 787 value += cm.getRange({ line: start.line, ch: 0 },
michael@0 788 { line: end.line, ch: cm.getLine(end.line).length });
michael@0 789 } else {
michael@0 790 value += cm.getLine(start.line);
michael@0 791 }
michael@0 792
michael@0 793 // Replace the currently selected lines and the next line with the new
michael@0 794 // value and maintain the selection of the text.
michael@0 795 cm.replaceRange(value, { line: start.line, ch: 0 },
michael@0 796 { line: end.line + 1, ch: cm.getLine(end.line + 1).length});
michael@0 797 cm.setSelection({ line: start.line + 1, ch: start.ch },
michael@0 798 { line: end.line + 1, ch: end.ch });
michael@0 799 },
michael@0 800
michael@0 801 /**
michael@0 802 * Returns current font size for the editor area, in pixels.
michael@0 803 */
michael@0 804 getFontSize: function () {
michael@0 805 let cm = editors.get(this);
michael@0 806 let el = cm.getWrapperElement();
michael@0 807 let win = el.ownerDocument.defaultView;
michael@0 808
michael@0 809 return parseInt(win.getComputedStyle(el).getPropertyValue("font-size"), 10);
michael@0 810 },
michael@0 811
michael@0 812 /**
michael@0 813 * Sets font size for the editor area.
michael@0 814 */
michael@0 815 setFontSize: function (size) {
michael@0 816 let cm = editors.get(this);
michael@0 817 cm.getWrapperElement().style.fontSize = parseInt(size, 10) + "px";
michael@0 818 cm.refresh();
michael@0 819 },
michael@0 820
michael@0 821 /**
michael@0 822 * Extends an instance of the Editor object with additional
michael@0 823 * functions. Each function will be called with context as
michael@0 824 * the first argument. Context is a {ed, cm} object where
michael@0 825 * 'ed' is an instance of the Editor object and 'cm' is an
michael@0 826 * instance of the CodeMirror object. Example:
michael@0 827 *
michael@0 828 * function hello(ctx, name) {
michael@0 829 * let { cm, ed } = ctx;
michael@0 830 * cm; // CodeMirror instance
michael@0 831 * ed; // Editor instance
michael@0 832 * name; // 'Mozilla'
michael@0 833 * }
michael@0 834 *
michael@0 835 * editor.extend({ hello: hello });
michael@0 836 * editor.hello('Mozilla');
michael@0 837 */
michael@0 838 extend: function (funcs) {
michael@0 839 Object.keys(funcs).forEach((name) => {
michael@0 840 let cm = editors.get(this);
michael@0 841 let ctx = { ed: this, cm: cm, Editor: Editor};
michael@0 842
michael@0 843 if (name === "initialize") {
michael@0 844 funcs[name](ctx);
michael@0 845 return;
michael@0 846 }
michael@0 847
michael@0 848 this[name] = funcs[name].bind(null, ctx);
michael@0 849 });
michael@0 850 },
michael@0 851
michael@0 852 destroy: function () {
michael@0 853 this.container = null;
michael@0 854 this.config = null;
michael@0 855 this.version = null;
michael@0 856 this.emit("destroy");
michael@0 857 }
michael@0 858 };
michael@0 859
michael@0 860 // Since Editor is a thin layer over CodeMirror some methods
michael@0 861 // are mapped directly—without any changes.
michael@0 862
michael@0 863 CM_MAPPING.forEach(function (name) {
michael@0 864 Editor.prototype[name] = function (...args) {
michael@0 865 let cm = editors.get(this);
michael@0 866 return cm[name].apply(cm, args);
michael@0 867 };
michael@0 868 });
michael@0 869
michael@0 870 // Static methods on the Editor object itself.
michael@0 871
michael@0 872 /**
michael@0 873 * Returns a string representation of a shortcut 'key' with
michael@0 874 * a OS specific modifier. Cmd- for Macs, Ctrl- for other
michael@0 875 * platforms. Useful with extraKeys configuration option.
michael@0 876 *
michael@0 877 * CodeMirror defines all keys with modifiers in the following
michael@0 878 * order: Shift - Ctrl/Cmd - Alt - Key
michael@0 879 */
michael@0 880 Editor.accel = function (key, modifiers={}) {
michael@0 881 return (modifiers.shift ? "Shift-" : "") +
michael@0 882 (Services.appinfo.OS == "Darwin" ? "Cmd-" : "Ctrl-") +
michael@0 883 (modifiers.alt ? "Alt-" : "") + key;
michael@0 884 };
michael@0 885
michael@0 886 /**
michael@0 887 * Returns a string representation of a shortcut for a
michael@0 888 * specified command 'cmd'. Append Cmd- for macs, Ctrl- for other
michael@0 889 * platforms unless noaccel is specified in the options. Useful when overwriting
michael@0 890 * or disabling default shortcuts.
michael@0 891 */
michael@0 892 Editor.keyFor = function (cmd, opts={ noaccel: false }) {
michael@0 893 let key = L10N.GetStringFromName(cmd + ".commandkey");
michael@0 894 return opts.noaccel ? key : Editor.accel(key);
michael@0 895 };
michael@0 896
michael@0 897 // Since Gecko already provide complete and up to date list of CSS property
michael@0 898 // names, values and color names, we compute them so that they can replace
michael@0 899 // the ones used in CodeMirror while initiating an editor object. This is done
michael@0 900 // here instead of the file codemirror/css.js so as to leave that file untouched
michael@0 901 // and easily upgradable.
michael@0 902 function getCSSKeywords() {
michael@0 903 function keySet(array) {
michael@0 904 var keys = {};
michael@0 905 for (var i = 0; i < array.length; ++i) {
michael@0 906 keys[array[i]] = true;
michael@0 907 }
michael@0 908 return keys;
michael@0 909 }
michael@0 910
michael@0 911 let domUtils = Cc["@mozilla.org/inspector/dom-utils;1"]
michael@0 912 .getService(Ci.inIDOMUtils);
michael@0 913 let cssProperties = domUtils.getCSSPropertyNames(domUtils.INCLUDE_ALIASES);
michael@0 914 let cssColors = {};
michael@0 915 let cssValues = {};
michael@0 916 cssProperties.forEach(property => {
michael@0 917 if (property.contains("color")) {
michael@0 918 domUtils.getCSSValuesForProperty(property).forEach(value => {
michael@0 919 cssColors[value] = true;
michael@0 920 });
michael@0 921 }
michael@0 922 else {
michael@0 923 domUtils.getCSSValuesForProperty(property).forEach(value => {
michael@0 924 cssValues[value] = true;
michael@0 925 });
michael@0 926 }
michael@0 927 });
michael@0 928 return {
michael@0 929 cssProperties: keySet(cssProperties),
michael@0 930 cssValues: cssValues,
michael@0 931 cssColors: cssColors
michael@0 932 };
michael@0 933 }
michael@0 934
michael@0 935 /**
michael@0 936 * Returns a controller object that can be used for
michael@0 937 * editor-specific commands such as find, jump to line,
michael@0 938 * copy/paste, etc.
michael@0 939 */
michael@0 940 function controller(ed) {
michael@0 941 return {
michael@0 942 supportsCommand: function (cmd) {
michael@0 943 switch (cmd) {
michael@0 944 case "cmd_find":
michael@0 945 case "cmd_findAgain":
michael@0 946 case "cmd_findPrevious":
michael@0 947 case "cmd_gotoLine":
michael@0 948 case "cmd_undo":
michael@0 949 case "cmd_redo":
michael@0 950 case "cmd_delete":
michael@0 951 case "cmd_selectAll":
michael@0 952 return true;
michael@0 953 }
michael@0 954
michael@0 955 return false;
michael@0 956 },
michael@0 957
michael@0 958 isCommandEnabled: function (cmd) {
michael@0 959 let cm = editors.get(ed);
michael@0 960
michael@0 961 switch (cmd) {
michael@0 962 case "cmd_find":
michael@0 963 case "cmd_gotoLine":
michael@0 964 case "cmd_selectAll":
michael@0 965 return true;
michael@0 966 case "cmd_findAgain":
michael@0 967 return cm.state.search != null && cm.state.search.query != null;
michael@0 968 case "cmd_undo":
michael@0 969 return ed.canUndo();
michael@0 970 case "cmd_redo":
michael@0 971 return ed.canRedo();
michael@0 972 case "cmd_delete":
michael@0 973 return ed.somethingSelected();
michael@0 974 }
michael@0 975
michael@0 976 return false;
michael@0 977 },
michael@0 978
michael@0 979 doCommand: function (cmd) {
michael@0 980 let cm = editors.get(ed);
michael@0 981 let map = {
michael@0 982 "cmd_selectAll": "selectAll",
michael@0 983 "cmd_find": "find",
michael@0 984 "cmd_undo": "undo",
michael@0 985 "cmd_redo": "redo",
michael@0 986 "cmd_delete": "delCharAfter",
michael@0 987 "cmd_findAgain": "findNext"
michael@0 988 };
michael@0 989
michael@0 990 if (map[cmd]) {
michael@0 991 cm.execCommand(map[cmd]);
michael@0 992 return;
michael@0 993 }
michael@0 994
michael@0 995 if (cmd == "cmd_gotoLine")
michael@0 996 ed.jumpToLine();
michael@0 997 },
michael@0 998
michael@0 999 onEvent: function () {}
michael@0 1000 };
michael@0 1001 }
michael@0 1002
michael@0 1003 /**
michael@0 1004 * Detect the indentation used in an editor. Returns an object
michael@0 1005 * with 'tabs' - whether this is tab-indented and 'spaces' - the
michael@0 1006 * width of one indent in spaces. Or `null` if it's inconclusive.
michael@0 1007 */
michael@0 1008 function detectIndentation(ed) {
michael@0 1009 let cm = editors.get(ed);
michael@0 1010
michael@0 1011 let spaces = {}; // # spaces indent -> # lines with that indent
michael@0 1012 let last = 0; // indentation width of the last line we saw
michael@0 1013 let tabs = 0; // # of lines that start with a tab
michael@0 1014 let total = 0; // # of indented lines (non-zero indent)
michael@0 1015
michael@0 1016 cm.eachLine(0, DETECT_INDENT_MAX_LINES, (line) => {
michael@0 1017 let text = line.text;
michael@0 1018
michael@0 1019 if (text.startsWith("\t")) {
michael@0 1020 tabs++;
michael@0 1021 total++;
michael@0 1022 return;
michael@0 1023 }
michael@0 1024 let width = 0;
michael@0 1025 while (text[width] === " ") {
michael@0 1026 width++;
michael@0 1027 }
michael@0 1028 // don't count lines that are all spaces
michael@0 1029 if (width == text.length) {
michael@0 1030 last = 0;
michael@0 1031 return;
michael@0 1032 }
michael@0 1033 if (width > 1) {
michael@0 1034 total++;
michael@0 1035 }
michael@0 1036
michael@0 1037 // see how much this line is offset from the line above it
michael@0 1038 let indent = Math.abs(width - last);
michael@0 1039 if (indent > 1 && indent <= 8) {
michael@0 1040 spaces[indent] = (spaces[indent] || 0) + 1;
michael@0 1041 }
michael@0 1042 last = width;
michael@0 1043 });
michael@0 1044
michael@0 1045 // this file is not indented at all
michael@0 1046 if (total == 0) {
michael@0 1047 return null;
michael@0 1048 }
michael@0 1049
michael@0 1050 // mark as tabs if they start more than half the lines
michael@0 1051 if (tabs >= total / 2) {
michael@0 1052 return { tabs: true };
michael@0 1053 }
michael@0 1054
michael@0 1055 // find most frequent non-zero width difference between adjacent lines
michael@0 1056 let freqIndent = null, max = 1;
michael@0 1057 for (let width in spaces) {
michael@0 1058 width = parseInt(width, 10);
michael@0 1059 let tally = spaces[width];
michael@0 1060 if (tally > max) {
michael@0 1061 max = tally;
michael@0 1062 freqIndent = width;
michael@0 1063 }
michael@0 1064 }
michael@0 1065 if (!freqIndent) {
michael@0 1066 return null;
michael@0 1067 }
michael@0 1068
michael@0 1069 return { tabs: false, spaces: freqIndent };
michael@0 1070 }
michael@0 1071
michael@0 1072 module.exports = Editor;

mercurial