): Editor;
export function createEditSession(text: import("ace-code/src/document").Document | string, mode?: import("ace-code").Ace.SyntaxMode): EditSession;
import { Editor } from "ace-code/src/editor";
import { EditSession } from "ace-code/src/edit_session";
import { Range } from "ace-code/src/range";
import { UndoManager } from "ace-code/src/undomanager";
import { VirtualRenderer as Renderer } from "ace-code/src/virtual_renderer";
export var version: "1.43.6";
export { Range, Editor, EditSession, UndoManager, Renderer as VirtualRenderer };
}
================================================
FILE: amplify.yml
================================================
version: 0.1
frontend:
phases:
preBuild:
commands:
- npm install
# IMPORTANT - Please verify your build commands
build:
commands:
- make build
artifacts:
# IMPORTANT - Please verify your build output directory
baseDirectory: /
files:
- '**/*'
cache:
paths:
- node_modules/**/*
================================================
FILE: build_support/editor.html
================================================
Editor
function foo(items) {
var i;
for (i = 0; i < items.length; i++) {
alert("Ace Rocks " + items[i]);
}
}
================================================
FILE: build_support/mini_require.js
================================================
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload
* @param module a name for the payload
* @param payload a function to call with (require, exports, module) params
*/
(function() {
var ACE_NAMESPACE = "";
var global = (function() { return this; })();
if (!global && typeof window != "undefined") global = window; // strict mode
if (!ACE_NAMESPACE && typeof requirejs !== "undefined")
return;
var define = function(module, deps, payload) {
if (typeof module !== "string") {
if (define.original)
define.original.apply(this, arguments);
else {
console.error("dropping module because define wasn\'t a string.");
console.trace();
}
return;
}
if (arguments.length == 2)
payload = deps;
if (!define.modules[module]) {
define.payloads[module] = payload;
define.modules[module] = null;
}
};
define.modules = {};
define.payloads = {};
/**
* Get at functionality define()ed using the function above
*/
var _require = function(parentId, module, callback) {
if (typeof module === "string") {
var payload = lookup(parentId, module);
if (payload != undefined) {
callback && callback();
return payload;
}
} else if (Object.prototype.toString.call(module) === "[object Array]") {
var params = [];
for (var i = 0, l = module.length; i < l; ++i) {
var dep = lookup(parentId, module[i]);
if (dep == undefined && require.original)
return;
params.push(dep);
}
return callback && callback.apply(null, params) || true;
}
};
var require = function(module, callback) {
var packagedModule = _require("", module, callback);
if (packagedModule == undefined && require.original)
return require.original.apply(this, arguments);
return packagedModule;
};
var normalizeModule = function(parentId, moduleName) {
// normalize plugin requires
if (moduleName.indexOf("!") !== -1) {
var chunks = moduleName.split("!");
return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
}
// normalize relative requires
if (moduleName.charAt(0) == ".") {
var base = parentId.split("/").slice(0, -1).join("/");
moduleName = base + "/" + moduleName;
while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
var previous = moduleName;
moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
}
}
return moduleName;
};
/**
* Internal function to lookup moduleNames and resolve them by calling the
* definition function if needed.
*/
var lookup = function(parentId, moduleName) {
moduleName = normalizeModule(parentId, moduleName);
var module = define.modules[moduleName];
if (!module) {
module = define.payloads[moduleName];
if (typeof module === 'function') {
var exports = {};
var mod = {
id: moduleName,
uri: '',
exports: exports,
packaged: true
};
var req = function(module, callback) {
return _require(moduleName, module, callback);
};
var returnValue = module(req, exports, mod);
exports = returnValue || mod.exports;
define.modules[moduleName] = exports;
delete define.payloads[moduleName];
}
module = define.modules[moduleName] = exports || module;
}
return module;
};
function exportAce(ns) {
var root = global;
if (ns) {
if (!global[ns])
global[ns] = {};
root = global[ns];
}
if (!root.define || !root.define.packaged) {
define.original = root.define;
root.define = define;
root.define.packaged = true;
}
if (!root.require || !root.require.packaged) {
require.original = root.require;
root.require = require;
root.require.packaged = true;
}
}
exportAce(ACE_NAMESPACE);
})();
================================================
FILE: demo/autocompletion.html
================================================
ACE Autocompletion demo
================================================
FILE: demo/autoresize.html
================================================
Editor
autoresizing editor
minHeight = 2 lines
================================================
FILE: demo/code_lens.html
================================================
ACE Code Lens demo
================================================
FILE: demo/csp.html
================================================
Editor
================================================
FILE: demo/diff/examples/editor.16.js
================================================
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var lang = require("./lib/lang");
var useragent = require("./lib/useragent");
var TextInput = require("./keyboard/textinput").TextInput;
var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
var FoldHandler = require("./mouse/fold_handler").FoldHandler;
var KeyBinding = require("./keyboard/keybinding").KeyBinding;
var EditSession = require("./edit_session").EditSession;
var Search = require("./search").Search;
var Range = require("./range").Range;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var CommandManager = require("./commands/command_manager").CommandManager;
var defaultCommands = require("./commands/default_commands").commands;
var config = require("./config");
var TokenIterator = require("./token_iterator").TokenIterator;
var LineWidgets = require("./line_widgets").LineWidgets;
var clipboard = require("./clipboard");
/**
* The main entry point into the Ace functionality.
*
* The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen.
*
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
* @class Editor
**/
/**
* Creates a new `Editor` object.
*
* @param {VirtualRenderer} renderer Associated `VirtualRenderer` that draws everything
* @param {EditSession} session The `EditSession` to refer to
*
*
* @constructor
**/
var Editor = function(renderer, session, options) {
this.$toDestroy = [];
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.id = "editor" + (++Editor.$uid);
this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
if (typeof document == "object") {
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.renderer.textarea = this.textInput.getElement();
// TODO detect touch event support
this.$mouseHandler = new MouseHandler(this);
new FoldHandler(this);
}
this.keyBinding = new KeyBinding(this);
this.$search = new Search().set({
wrap: true
});
this.$historyTracker = this.$historyTracker.bind(this);
this.commands.on("exec", this.$historyTracker);
this.$initOperationListeners();
this._$emitInputEvent = lang.delayedCall(function() {
this._signal("input", {});
if (this.session && !this.session.destroyed)
this.session.bgTokenizer.scheduleStart();
}.bind(this));
this.on("change", function(_, _self) {
_self._$emitInputEvent.schedule(31);
});
this.setSession(session || options && options.session || new EditSession(""));
config.resetOptions(this);
if (options)
this.setOptions(options);
config._signal("editor", this);
};
Editor.$uid = 0;
(function(){
oop.implement(this, EventEmitter);
this.$initOperationListeners = function() {
this.commands.on("exec", this.startOperation.bind(this), true);
this.commands.on("afterExec", this.endOperation.bind(this), true);
this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this, true));
// todo: add before change events?
this.on("change", function() {
if (!this.curOp) {
this.startOperation();
this.curOp.selectionBefore = this.$lastSel;
}
this.curOp.docChanged = true;
}.bind(this), true);
this.on("changeSelection", function() {
if (!this.curOp) {
this.startOperation();
this.curOp.selectionBefore = this.$lastSel;
}
this.curOp.selectionChanged = true;
}.bind(this), true);
};
this.curOp = null;
this.prevOp = {};
this.startOperation = function(commandEvent) {
if (this.curOp) {
if (!commandEvent || this.curOp.command)
return;
this.prevOp = this.curOp;
}
if (!commandEvent) {
this.previousCommand = null;
commandEvent = {};
}
this.$opResetTimer.schedule();
this.curOp = this.session.curOp = {
command: commandEvent.command || {},
args: commandEvent.args,
scrollTop: this.renderer.scrollTop
};
this.curOp.selectionBefore = this.selection.toJSON();
};
this.endOperation = function(e) {
if (this.curOp && this.session) {
if (e && e.returnValue === false || !this.session)
return (this.curOp = null);
if (e == true && this.curOp.command && this.curOp.command.name == "mouse")
return;
this._signal("beforeEndOperation");
if (!this.curOp) return;
var command = this.curOp.command;
var scrollIntoView = command && command.scrollIntoView;
if (scrollIntoView) {
switch (scrollIntoView) {
case "center-animate":
scrollIntoView = "animate";
/* fall through */
case "center":
this.renderer.scrollCursorIntoView(null, 0.5);
break;
case "animate":
case "cursor":
this.renderer.scrollCursorIntoView();
break;
case "selectionPart":
var range = this.selection.getRange();
var config = this.renderer.layerConfig;
if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
}
break;
default:
break;
}
if (scrollIntoView == "animate")
this.renderer.animateScrolling(this.curOp.scrollTop);
}
var sel = this.selection.toJSON();
this.curOp.selectionAfter = sel;
this.$lastSel = this.selection.toJSON();
// console.log(this.$lastSel+" endOP")
this.session.getUndoManager().addSelection(sel);
this.prevOp = this.curOp;
this.curOp = null;
}
};
// TODO use property on commands instead of this
this.$mergeableCommands = ["backspace", "del", "insertstring"];
this.$historyTracker = function(e) {
if (!this.$mergeUndoDeltas)
return;
var prev = this.prevOp;
var mergeableCommands = this.$mergeableCommands;
// previous command was the same
var shouldMerge = prev.command && (e.command.name == prev.command.name);
if (e.command.name == "insertstring") {
var text = e.args;
if (this.mergeNextCommand === undefined)
this.mergeNextCommand = true;
shouldMerge = shouldMerge
&& this.mergeNextCommand // previous command allows to coalesce with
&& (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
this.mergeNextCommand = true;
} else {
shouldMerge = shouldMerge
&& mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
}
if (
this.$mergeUndoDeltas != "always"
&& Date.now() - this.sequenceStartTime > 2000
) {
shouldMerge = false; // the sequence is too long
}
if (shouldMerge)
this.session.mergeUndoDeltas = true;
else if (mergeableCommands.indexOf(e.command.name) !== -1)
this.sequenceStartTime = Date.now();
};
/**
* Sets a new key handler, such as "vim" or "windows".
* @param {String} keyboardHandler The new key handler
*
**/
this.setKeyboardHandler = function(keyboardHandler, cb) {
if (keyboardHandler && typeof keyboardHandler === "string" && keyboardHandler != "ace") {
this.$keybindingId = keyboardHandler;
var _self = this;
config.loadModule(["keybinding", keyboardHandler], function(module) {
if (_self.$keybindingId == keyboardHandler)
_self.keyBinding.setKeyboardHandler(module && module.handler);
cb && cb();
});
} else {
this.$keybindingId = null;
this.keyBinding.setKeyboardHandler(keyboardHandler);
cb && cb();
}
};
/**
* Returns the keyboard handler, such as "vim" or "windows".
*
* @returns {String}
*
**/
this.getKeyboardHandler = function() {
return this.keyBinding.getKeyboardHandler();
};
/**
* Emitted whenever the [[EditSession]] changes.
* @event changeSession
* @param {Object} e An object with two properties, `oldSession` and `session`, that represent the old and new [[EditSession]]s.
*
**/
/**
* Sets a new editsession to use. This method also emits the `'changeSession'` event.
* @param {EditSession} session The new session to use
*
**/
this.setSession = function(session) {
if (this.session == session)
return;
// make sure operationEnd events are not emitted to wrong session
if (this.curOp) this.endOperation();
this.curOp = {};
var oldSession = this.session;
if (oldSession) {
this.session.off("change", this.$onDocumentChange);
this.session.off("changeMode", this.$onChangeMode);
this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.off("changeTabSize", this.$onChangeTabSize);
this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
this.session.off("changeWrapMode", this.$onChangeWrapMode);
this.session.off("changeFold", this.$onChangeFold);
this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
this.session.off("changeBackMarker", this.$onChangeBackMarker);
this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
this.session.off("changeAnnotation", this.$onChangeAnnotation);
this.session.off("changeOverwrite", this.$onCursorChange);
this.session.off("changeScrollTop", this.$onScrollTopChange);
this.session.off("changeScrollLeft", this.$onScrollLeftChange);
var selection = this.session.getSelection();
selection.off("changeCursor", this.$onCursorChange);
selection.off("changeSelection", this.$onSelectionChange);
}
this.session = session;
if (session) {
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.on("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.on("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.on("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
session.on("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.on("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.on("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.on("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.on("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.on("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.on("changeOverwrite", this.$onCursorChange);
this.$onScrollTopChange = this.onScrollTopChange.bind(this);
this.session.on("changeScrollTop", this.$onScrollTopChange);
this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
this.session.on("changeScrollLeft", this.$onScrollLeftChange);
this.selection = session.getSelection();
this.selection.on("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.on("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.onCursorChange();
this.onScrollTopChange();
this.onScrollLeftChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.updateFull();
} else {
this.selection = null;
this.renderer.setSession(session);
}
this._signal("changeSession", {
session: session,
oldSession: oldSession
});
this.curOp = null;
oldSession && oldSession._signal("changeEditor", {oldEditor: this});
session && session._signal("changeEditor", {editor: this});
if (session && !session.destroyed)
session.bgTokenizer.scheduleStart();
};
/**
* Returns the current session being used.
* @returns {EditSession}
**/
this.getSession = function() {
return this.session;
};
/**
* Sets the current document to `val`.
* @param {String} val The new value to set for the document
* @param {Number} cursorPos Where to set the new value. `undefined` or 0 is selectAll, -1 is at the document start, and 1 is at the end
*
* @returns {String} The current document value
* @related Document.setValue
**/
this.setValue = function(val, cursorPos) {
this.session.doc.setValue(val);
if (!cursorPos)
this.selectAll();
else if (cursorPos == 1)
this.navigateFileEnd();
else if (cursorPos == -1)
this.navigateFileStart();
return val;
};
/**
* Returns the current session's content.
*
* @returns {String}
* @related EditSession.getValue
**/
this.getValue = function() {
return this.session.getValue();
};
/**
*
* Returns the currently highlighted selection.
* @returns {Selection} The selection object
**/
this.getSelection = function() {
return this.selection;
};
/**
* {:VirtualRenderer.onResize}
* @param {Boolean} force If `true`, recomputes the size, even if the height and width haven't changed
*
*
* @related VirtualRenderer.onResize
**/
this.resize = function(force) {
this.renderer.onResize(force);
};
/**
* {:VirtualRenderer.setTheme}
* @param {String} theme The path to a theme
* @param {Function} cb optional callback called when theme is loaded
**/
this.setTheme = function(theme, cb) {
this.renderer.setTheme(theme, cb);
};
/**
* {:VirtualRenderer.getTheme}
*
* @returns {String} The set theme
* @related VirtualRenderer.getTheme
**/
this.getTheme = function() {
return this.renderer.getTheme();
};
/**
* {:VirtualRenderer.setStyle}
* @param {String} style A class name
*
*
* @related VirtualRenderer.setStyle
**/
this.setStyle = function(style) {
this.renderer.setStyle(style);
};
/**
* {:VirtualRenderer.unsetStyle}
* @related VirtualRenderer.unsetStyle
**/
this.unsetStyle = function(style) {
this.renderer.unsetStyle(style);
};
/**
* Gets the current font size of the editor text.
*/
this.getFontSize = function () {
return this.getOption("fontSize") ||
dom.computedStyle(this.container).fontSize;
};
/**
* Set a new font size (in pixels) for the editor text.
* @param {String} size A font size ( _e.g._ "12px")
*
*
**/
this.setFontSize = function(size) {
this.setOption("fontSize", size);
};
this.$highlightBrackets = function() {
if (this.$highlightPending) {
return;
}
// perform highlight async to not block the browser during navigation
var self = this;
this.$highlightPending = true;
setTimeout(function () {
self.$highlightPending = false;
var session = self.session;
if (!session || session.destroyed) return;
if (session.$bracketHighlight) {
session.$bracketHighlight.markerIds.forEach(function(id) {
session.removeMarker(id);
});
session.$bracketHighlight = null;
}
var pos = self.getCursorPosition();
var handler = self.getKeyboardHandler();
var isBackwards = handler && handler.$getDirectionForHighlight && handler.$getDirectionForHighlight(self);
var ranges = session.getMatchingBracketRanges(pos, isBackwards);
if (!ranges) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
if (token && /\b(?:tag-open|tag-name)/.test(token.type)) {
var tagNamesRanges = session.getMatchingTags(pos);
if (tagNamesRanges) ranges = [tagNamesRanges.openTagName, tagNamesRanges.closeTagName];
}
}
if (!ranges && session.$mode.getMatching)
ranges = session.$mode.getMatching(self.session);
if (!ranges) {
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
return;
}
var markerType = "ace_bracket";
if (!Array.isArray(ranges)) {
ranges = [ranges];
} else if (ranges.length == 1) {
markerType = "ace_error_bracket";
}
// show adjacent ranges as one
if (ranges.length == 2) {
if (Range.comparePoints(ranges[0].end, ranges[1].start) == 0)
ranges = [Range.fromPoints(ranges[0].start, ranges[1].end)];
else if (Range.comparePoints(ranges[0].start, ranges[1].end) == 0)
ranges = [Range.fromPoints(ranges[1].start, ranges[0].end)];
}
session.$bracketHighlight = {
ranges: ranges,
markerIds: ranges.map(function(range) {
return session.addMarker(range, markerType, "text");
})
};
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
}, 50);
};
/**
*
* Brings the current `textInput` into focus.
**/
this.focus = function() {
this.textInput.focus();
};
/**
* Returns `true` if the current `textInput` is in focus.
* @return {Boolean}
**/
this.isFocused = function() {
return this.textInput.isFocused();
};
/**
*
* Blurs the current `textInput`.
**/
this.blur = function() {
this.textInput.blur();
};
/**
* Emitted once the editor comes into focus.
* @event focus
*
*
**/
this.onFocus = function(e) {
if (this.$isFocused)
return;
this.$isFocused = true;
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._emit("focus", e);
};
/**
* Emitted once the editor has been blurred.
* @event blur
*
*
**/
this.onBlur = function(e) {
if (!this.$isFocused)
return;
this.$isFocused = false;
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._emit("blur", e);
};
this.$cursorChange = function() {
this.renderer.updateCursor();
this.$highlightBrackets();
this.$updateHighlightActiveLine();
};
/**
* Emitted whenever the document is changed.
* @event change
* @param {Object} e Contains a single property, `data`, which has the delta of changes
*
*
*
**/
this.onDocumentChange = function(delta) {
// Rerender and emit "change" event.
var wrap = this.session.$useWrapMode;
var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
this.renderer.updateLines(delta.start.row, lastRow, wrap);
this._signal("change", delta);
// Update cursor because tab characters can influence the cursor position.
this.$cursorChange();
};
this.onTokenizerUpdate = function(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
};
this.onScrollTopChange = function() {
this.renderer.scrollToY(this.session.getScrollTop());
};
this.onScrollLeftChange = function() {
this.renderer.scrollToX(this.session.getScrollLeft());
};
/**
* Emitted when the selection changes.
*
**/
this.onCursorChange = function() {
this.$cursorChange();
this._signal("changeSelection");
};
this.$updateHighlightActiveLine = function() {
var session = this.getSession();
var highlight;
if (this.$highlightActiveLine) {
if (this.$selectionStyle != "line" || !this.selection.isMultiLine())
highlight = this.getCursorPosition();
if (this.renderer.theme && this.renderer.theme.$selectionColorConflict && !this.selection.isEmpty())
highlight = false;
if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
highlight = false;
}
if (session.$highlightLineMarker && !highlight) {
session.removeMarker(session.$highlightLineMarker.id);
session.$highlightLineMarker = null;
} else if (!session.$highlightLineMarker && highlight) {
var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
range.id = session.addMarker(range, "ace_active-line", "screenLine");
session.$highlightLineMarker = range;
} else if (highlight) {
session.$highlightLineMarker.start.row = highlight.row;
session.$highlightLineMarker.end.row = highlight.row;
session.$highlightLineMarker.start.column = highlight.column;
session._signal("changeBackMarker");
}
};
this.onSelectionChange = function(e) {
var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
this.session.highlight(re);
this._signal("changeSelection");
};
this.$getSelectionHighLightRegexp = function() {
var session = this.session;
var selection = this.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startColumn = selection.start.column;
var endColumn = selection.end.column;
var line = session.getLine(selection.start.row);
var needle = line.substring(startColumn, endColumn);
// maximum allowed size for regular expressions in 32000,
// but getting close to it has significant impact on the performance
if (needle.length > 5000 || !/[\w\d]/.test(needle))
return;
var re = this.$search.$assembleRegExp({
wholeWord: true,
caseSensitive: true,
needle: needle
});
var wordWithBoundary = line.substring(startColumn - 1, endColumn + 1);
if (!re.test(wordWithBoundary))
return;
return re;
};
this.onChangeFrontMarker = function() {
this.renderer.updateFrontMarkers();
};
this.onChangeBackMarker = function() {
this.renderer.updateBackMarkers();
};
this.onChangeBreakpoint = function() {
this.renderer.updateBreakpoints();
};
this.onChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onChangeMode = function(e) {
this.renderer.updateText();
this._emit("changeMode", e);
};
this.onChangeWrapLimit = function() {
this.renderer.updateFull();
};
this.onChangeWrapMode = function() {
this.renderer.onResize(true);
};
this.onChangeFold = function() {
// Update the active line marker as due to folding changes the current
// line range on the screen might have changed.
this.$updateHighlightActiveLine();
// TODO: This might be too much updating. Okay for now.
this.renderer.updateFull();
};
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
this.getSelectedText = function() {
return this.session.getTextRange(this.getSelectionRange());
};
/**
* Emitted when text is copied.
* @event copy
* @param {String} text The copied text
*
**/
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
this.getCopyText = function() {
var text = this.getSelectedText();
var nl = this.session.doc.getNewLineCharacter();
var copyLine= false;
if (!text && this.$copyWithEmptySelection) {
copyLine = true;
var ranges = this.selection.getAllRanges();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (i && ranges[i - 1].start.row == range.start.row)
continue;
text += this.session.getLine(range.start.row) + nl;
}
}
var e = {text: text};
this._signal("copy", e);
clipboard.lineMode = copyLine ? e.text : false;
return e.text;
};
/**
* Called whenever a text "copy" happens.
**/
this.onCopy = function() {
this.commands.exec("copy", this);
};
/**
* Called whenever a text "cut" happens.
**/
this.onCut = function() {
this.commands.exec("cut", this);
};
/**
* Emitted when text is pasted.
* @event paste
* @param {Object} an object which contains one property, `text`, that represents the text to be pasted. Editing this property will alter the text that is pasted.
*
*
**/
/**
* Called whenever a text "paste" happens.
* @param {String} text The pasted text
*
*
**/
this.onPaste = function(text, event) {
var e = {text: text, event: event};
this.commands.exec("paste", this, e);
};
this.$handlePaste = function(e) {
if (typeof e == "string")
e = {text: e};
this._signal("paste", e);
var text = e.text;
var lineMode = text === clipboard.lineMode;
var session = this.session;
if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
if (lineMode)
session.insert({ row: this.selection.lead.row, column: 0 }, text);
else
this.insert(text);
} else if (lineMode) {
this.selection.rangeList.ranges.forEach(function(range) {
session.insert({ row: range.start.row, column: 0 }, text);
});
} else {
var lines = text.split(/\r\n|\r|\n/);
var ranges = this.selection.rangeList.ranges;
var isFullLine = lines.length == 2 && (!lines[0] || !lines[1]);
if (lines.length != ranges.length || isFullLine)
return this.commands.exec("insertstring", this, text);
for (var i = ranges.length; i--;) {
var range = ranges[i];
if (!range.isEmpty())
session.remove(range);
session.insert(range.start, lines[i]);
}
}
};
this.execCommand = function(command, args) {
return this.commands.exec(command, this, args);
};
/**
* Inserts `text` into wherever the cursor is pointing.
* @param {String} text The new text to add
*
**/
this.insert = function(text, pasted) {
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled() && !pasted) {
// Get a transform if the current mode wants one.
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform) {
if (text !== transform.text) {
// keep automatic insertion in a separate delta, unless it is in multiselect mode
if (!this.inVirtualSelectionMode) {
this.session.mergeUndoDeltas = false;
this.mergeNextCommand = false;
}
}
text = transform.text;
}
}
if (text == "\t")
text = this.session.getTabString();
// remove selected text
if (!this.selection.isEmpty()) {
var range = this.getSelectionRange();
cursor = this.session.remove(range);
this.clearSelection();
}
else if (this.session.getOverwrite() && text.indexOf("\n") == -1) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
if (text == "\n" || text == "\r\n") {
var line = session.getLine(cursor.row);
if (cursor.column > line.search(/\S|$/)) {
var d = line.substr(cursor.column).search(/\S|$/);
session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
}
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var line = session.getLine(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, line, text);
session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
if (this.$enableAutoIndent) {
if (session.getDocument().isNewLine(text)) {
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
session.insert({row: cursor.row+1, column: 0}, lineIndent);
}
if (shouldOutdent)
mode.autoOutdent(lineState, session, cursor.row);
}
};
this.autoIndent = function () {
var session = this.session;
var mode = session.getMode();
var startRow, endRow;
if (this.selection.isEmpty()) {
startRow = 0;
endRow = session.doc.getLength() - 1;
} else {
var selectedRange = this.getSelectionRange();
startRow = selectedRange.start.row;
endRow = selectedRange.end.row;
}
var prevLineState = "";
var prevLine = "";
var lineIndent = "";
var line, currIndent, range;
var tab = session.getTabString();
for (var row = startRow; row <= endRow; row++) {
if (row > 0) {
prevLineState = session.getState(row - 1);
prevLine = session.getLine(row - 1);
lineIndent = mode.getNextLineIndent(prevLineState, prevLine, tab);
}
line = session.getLine(row);
currIndent = mode.$getIndent(line);
if (lineIndent !== currIndent) {
if (currIndent.length > 0) {
range = new Range(row, 0, row, currIndent.length);
session.remove(range);
}
if (lineIndent.length > 0) {
session.insert({row: row, column: 0}, lineIndent);
}
}
mode.autoOutdent(prevLineState, session, row);
}
};
this.onTextInput = function(text, composition) {
if (!composition)
return this.keyBinding.onTextInput(text);
this.startOperation({command: { name: "insertstring" }});
var applyComposition = this.applyComposition.bind(this, text, composition);
if (this.selection.rangeCount)
this.forEachSelection(applyComposition);
else
applyComposition();
this.endOperation();
};
this.applyComposition = function(text, composition) {
if (composition.extendLeft || composition.extendRight) {
var r = this.selection.getRange();
r.start.column -= composition.extendLeft;
r.end.column += composition.extendRight;
if (r.start.column < 0) {
r.start.row--;
r.start.column += this.session.getLine(r.start.row).length + 1;
}
this.selection.setRange(r);
if (!text && !r.isEmpty())
this.remove();
}
if (text || !this.selection.isEmpty())
this.insert(text, true);
if (composition.restoreStart || composition.restoreEnd) {
var r = this.selection.getRange();
r.start.column -= composition.restoreStart;
r.end.column -= composition.restoreEnd;
this.selection.setRange(r);
}
};
this.onCommandKey = function(e, hashId, keyCode) {
return this.keyBinding.onCommandKey(e, hashId, keyCode);
};
/**
* Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emits the `changeOverwrite` event.
* @param {Boolean} overwrite Defines whether or not to set overwrites
*
*
* @related EditSession.setOverwrite
**/
this.setOverwrite = function(overwrite) {
this.session.setOverwrite(overwrite);
};
/**
* Returns `true` if overwrites are enabled; `false` otherwise.
* @returns {Boolean}
* @related EditSession.getOverwrite
**/
this.getOverwrite = function() {
return this.session.getOverwrite();
};
/**
* Sets the value of overwrite to the opposite of whatever it currently is.
* @related EditSession.toggleOverwrite
**/
this.toggleOverwrite = function() {
this.session.toggleOverwrite();
};
/**
* Sets how fast the mouse scrolling should do.
* @param {Number} speed A value indicating the new speed (in milliseconds)
**/
this.setScrollSpeed = function(speed) {
this.setOption("scrollSpeed", speed);
};
/**
* Returns the value indicating how fast the mouse scroll speed is (in milliseconds).
* @returns {Number}
**/
this.getScrollSpeed = function() {
return this.getOption("scrollSpeed");
};
/**
* Sets the delay (in milliseconds) of the mouse drag.
* @param {Number} dragDelay A value indicating the new delay
**/
this.setDragDelay = function(dragDelay) {
this.setOption("dragDelay", dragDelay);
};
/**
* Returns the current mouse drag delay.
* @returns {Number}
**/
this.getDragDelay = function() {
return this.getOption("dragDelay");
};
/**
* Emitted when the selection style changes, via [[Editor.setSelectionStyle]].
* @event changeSelectionStyle
* @param {Object} data Contains one property, `data`, which indicates the new selection style
**/
/**
* Draw selection markers spanning whole line, or only over selected text. Default value is "line"
* @param {String} style The new selection style "line"|"text"
*
**/
this.setSelectionStyle = function(val) {
this.setOption("selectionStyle", val);
};
/**
* Returns the current selection style.
* @returns {String}
**/
this.getSelectionStyle = function() {
return this.getOption("selectionStyle");
};
/**
* Determines whether or not the current line should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the current line
**/
this.setHighlightActiveLine = function(shouldHighlight) {
this.setOption("highlightActiveLine", shouldHighlight);
};
/**
* Returns `true` if current lines are always highlighted.
* @return {Boolean}
**/
this.getHighlightActiveLine = function() {
return this.getOption("highlightActiveLine");
};
this.setHighlightGutterLine = function(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
};
this.getHighlightGutterLine = function() {
return this.getOption("highlightGutterLine");
};
/**
* Determines if the currently selected word should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the currently selected word
*
**/
this.setHighlightSelectedWord = function(shouldHighlight) {
this.setOption("highlightSelectedWord", shouldHighlight);
};
/**
* Returns `true` if currently highlighted words are to be highlighted.
* @returns {Boolean}
**/
this.getHighlightSelectedWord = function() {
return this.$highlightSelectedWord;
};
this.setAnimatedScroll = function(shouldAnimate){
this.renderer.setAnimatedScroll(shouldAnimate);
};
this.getAnimatedScroll = function(){
return this.renderer.getAnimatedScroll();
};
/**
* If `showInvisibles` is set to `true`, invisible characters—like spaces or new lines—are show in the editor.
* @param {Boolean} showInvisibles Specifies whether or not to show invisible characters
*
**/
this.setShowInvisibles = function(showInvisibles) {
this.renderer.setShowInvisibles(showInvisibles);
};
/**
* Returns `true` if invisible characters are being shown.
* @returns {Boolean}
**/
this.getShowInvisibles = function() {
return this.renderer.getShowInvisibles();
};
this.setDisplayIndentGuides = function(display) {
this.renderer.setDisplayIndentGuides(display);
};
this.getDisplayIndentGuides = function() {
return this.renderer.getDisplayIndentGuides();
};
this.setHighlightIndentGuides = function(highlight) {
this.renderer.setHighlightIndentGuides(highlight);
};
this.getHighlightIndentGuides = function() {
return this.renderer.getHighlightIndentGuides();
};
/**
* If `showPrintMargin` is set to `true`, the print margin is shown in the editor.
* @param {Boolean} showPrintMargin Specifies whether or not to show the print margin
*
**/
this.setShowPrintMargin = function(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
};
/**
* Returns `true` if the print margin is being shown.
* @returns {Boolean}
**/
this.getShowPrintMargin = function() {
return this.renderer.getShowPrintMargin();
};
/**
* Sets the column defining where the print margin should be.
* @param {Number} showPrintMargin Specifies the new print margin
*
**/
this.setPrintMarginColumn = function(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
};
/**
* Returns the column number of where the print margin is.
* @returns {Number}
**/
this.getPrintMarginColumn = function() {
return this.renderer.getPrintMarginColumn();
};
/**
* If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change.
* @param {Boolean} readOnly Specifies whether the editor can be modified or not
*
**/
this.setReadOnly = function(readOnly) {
this.setOption("readOnly", readOnly);
};
/**
* Returns `true` if the editor is set to read-only mode.
* @returns {Boolean}
**/
this.getReadOnly = function() {
return this.getOption("readOnly");
};
/**
* Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef}
* @param {Boolean} enabled Enables or disables behaviors
*
**/
this.setBehavioursEnabled = function (enabled) {
this.setOption("behavioursEnabled", enabled);
};
/**
* Returns `true` if the behaviors are currently enabled. {:BehaviorsDef}
*
* @returns {Boolean}
**/
this.getBehavioursEnabled = function () {
return this.getOption("behavioursEnabled");
};
/**
* Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets
* when such a character is typed in.
* @param {Boolean} enabled Enables or disables wrapping behaviors
*
**/
this.setWrapBehavioursEnabled = function (enabled) {
this.setOption("wrapBehavioursEnabled", enabled);
};
/**
* Returns `true` if the wrapping behaviors are currently enabled.
**/
this.getWrapBehavioursEnabled = function () {
return this.getOption("wrapBehavioursEnabled");
};
/**
* Indicates whether the fold widgets should be shown or not.
* @param {Boolean} show Specifies whether the fold widgets are shown
**/
this.setShowFoldWidgets = function(show) {
this.setOption("showFoldWidgets", show);
};
/**
* Returns `true` if the fold widgets are shown.
* @return {Boolean}
**/
this.getShowFoldWidgets = function() {
return this.getOption("showFoldWidgets");
};
this.setFadeFoldWidgets = function(fade) {
this.setOption("fadeFoldWidgets", fade);
};
this.getFadeFoldWidgets = function() {
return this.getOption("fadeFoldWidgets");
};
/**
* Removes the current selection or one character.
* @param {String} dir The direction of the deletion to occur, either "left" or "right"
*
**/
this.remove = function(dir) {
if (this.selection.isEmpty()){
if (dir == "left")
this.selection.selectLeft();
else
this.selection.selectRight();
}
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (range.end.column === 0) {
var text = session.getTextRange(range);
if (text[text.length - 1] == "\n") {
var line = session.getLine(range.end.row);
if (/^\s+$/.test(line)) {
range.end.column = line.length;
}
}
}
if (new_range)
range = new_range;
}
this.session.remove(range);
this.clearSelection();
};
/**
* Removes the word directly to the right of the current selection.
**/
this.removeWordRight = function() {
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
/**
* Removes the word directly to the left of the current selection.
**/
this.removeWordLeft = function() {
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
/**
* Removes all the words to the left of the current selection, until the start of the line.
**/
this.removeToLineStart = function() {
if (this.selection.isEmpty())
this.selection.selectLineStart();
if (this.selection.isEmpty())
this.selection.selectLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
/**
* Removes all the words to the right of the current selection, until the end of the line.
**/
this.removeToLineEnd = function() {
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
};
/**
* Splits the line at the current selection (by inserting an `'\n'`).
**/
this.splitLine = function() {
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
};
/**
* Set the "ghost" text in provided position. "Ghost" text is a kind of
* preview text inside the editor which can be used to preview some code
* inline in the editor such as, for example, code completions.
*
* @param {String} text Text to be inserted as "ghost" text
* @param {object} position Position to insert text to
*/
this.setGhostText = function(text, position) {
if (!this.session.widgetManager) {
this.session.widgetManager = new LineWidgets(this.session);
this.session.widgetManager.attach(this);
}
this.renderer.setGhostText(text, position);
};
/**
* Removes "ghost" text currently displayed in the editor.
*/
this.removeGhostText = function() {
if (!this.session.widgetManager) return;
this.renderer.removeGhostText();
};
/**
* Transposes current line.
**/
this.transposeLetters = function() {
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column === 0)
return;
var line = this.session.getLine(cursor.row);
var swap, range;
if (column < line.length) {
swap = line.charAt(column) + line.charAt(column-1);
range = new Range(cursor.row, column-1, cursor.row, column+1);
}
else {
swap = line.charAt(column-1) + line.charAt(column-2);
range = new Range(cursor.row, column-2, cursor.row, column);
}
this.session.replace(range, swap);
this.session.selection.moveToPosition(range.end);
};
/**
* Converts the current selection entirely into lowercase.
**/
this.toLowerCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toLowerCase());
this.selection.setSelectionRange(originalRange);
};
/**
* Converts the current selection entirely into uppercase.
**/
this.toUpperCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toUpperCase());
this.selection.setSelectionRange(originalRange);
};
/**
* Inserts an indentation into the current cursor position or indents the selected lines.
*
* @related EditSession.indentRows
**/
this.indent = function() {
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
} else if (range.start.column < range.end.column) {
var text = session.getTextRange(range);
if (!/^\s+$/.test(text)) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
}
}
var line = session.getLine(range.start.row);
var position = range.start;
var size = session.getTabSize();
var column = session.documentToScreenColumn(position.row, position.column);
if (this.session.getUseSoftTabs()) {
var count = (size - column % size);
var indentString = lang.stringRepeat(" ", count);
} else {
var count = column % size;
while (line[range.start.column - 1] == " " && count) {
range.start.column--;
count--;
}
this.selection.setSelectionRange(range);
indentString = "\t";
}
return this.insert(indentString);
};
/**
* Indents the current line.
* @related EditSession.indentRows
**/
this.blockIndent = function() {
var rows = this.$getSelectedRows();
this.session.indentRows(rows.first, rows.last, "\t");
};
/**
* Outdents the current line.
* @related EditSession.outdentRows
**/
this.blockOutdent = function() {
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
};
// TODO: move out of core when we have good mechanism for managing extensions
this.sortLines = function() {
var rows = this.$getSelectedRows();
var session = this.session;
var lines = [];
for (var i = rows.first; i <= rows.last; i++)
lines.push(session.getLine(i));
lines.sort(function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
var deleteRange = new Range(0, 0, 0, 0);
for (var i = rows.first; i <= rows.last; i++) {
var line = session.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = line.length;
session.replace(deleteRange, lines[i-rows.first]);
}
};
/**
* Given the currently selected range, this function either comments all the lines, or uncomments all of them.
**/
this.toggleCommentLines = function() {
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows();
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
};
this.toggleBlockComment = function() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
};
/**
* Works like [[EditSession.getTokenAt]], except it returns a number.
* @returns {Number}
**/
this.getNumberAt = function(row, column) {
var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
_numberRx.lastIndex = 0;
var s = this.session.getLine(row);
while (_numberRx.lastIndex < column) {
var m = _numberRx.exec(s);
if(m.index <= column && m.index+m[0].length >= column){
var number = {
value: m[0],
start: m.index,
end: m.index+m[0].length
};
return number;
}
}
return null;
};
/**
* If the character before the cursor is a number, this functions changes its value by `amount`.
* @param {Number} amount The value to change the numeral by (can be negative to decrease value)
*
**/
this.modifyNumber = function(amount) {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
// get the char before the cursor
var charRange = new Range(row, column-1, row, column);
var c = this.session.getTextRange(charRange);
// if the char is a digit
if (!isNaN(parseFloat(c)) && isFinite(c)) {
// get the whole number the digit is part of
var nr = this.getNumberAt(row, column);
// if number found
if (nr) {
var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
var decimals = nr.start + nr.value.length - fp;
var t = parseFloat(nr.value);
t *= Math.pow(10, decimals);
if(fp !== nr.end && column < fp){
amount *= Math.pow(10, nr.end - column - 1);
} else {
amount *= Math.pow(10, nr.end - column);
}
t += amount;
t /= Math.pow(10, decimals);
var nnr = t.toFixed(decimals);
//update number
var replaceRange = new Range(row, nr.start, row, nr.end);
this.session.replace(replaceRange, nnr);
//reposition the cursor
this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
}
} else {
this.toggleWord();
}
};
this.$toggleWordPairs = [
["first", "last"],
["true", "false"],
["yes", "no"],
["width", "height"],
["top", "bottom"],
["right", "left"],
["on", "off"],
["x", "y"],
["get", "set"],
["max", "min"],
["horizontal", "vertical"],
["show", "hide"],
["add", "remove"],
["up", "down"],
["before", "after"],
["even", "odd"],
["in", "out"],
["inside", "outside"],
["next", "previous"],
["increase", "decrease"],
["attach", "detach"],
["&&", "||"],
["==", "!="]
];
this.toggleWord = function () {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
this.selection.selectWord();
var currentState = this.getSelectedText();
var currWordStart = this.selection.getWordRange().start.column;
var wordParts = currentState.replace(/([a-z]+|[A-Z]+)(?=[A-Z_]|$)/g, '$1 ').split(/\s/);
var delta = column - currWordStart - 1;
if (delta < 0) delta = 0;
var curLength = 0, itLength = 0;
var that = this;
if (currentState.match(/[A-Za-z0-9_]+/)) {
wordParts.forEach(function (item, i) {
itLength = curLength + item.length;
if (delta >= curLength && delta <= itLength) {
currentState = item;
that.selection.clearSelection();
that.moveCursorTo(row, curLength + currWordStart);
that.selection.selectTo(row, itLength + currWordStart);
}
curLength = itLength;
});
}
var wordPairs = this.$toggleWordPairs;
var reg;
for (var i = 0; i < wordPairs.length; i++) {
var item = wordPairs[i];
for (var j = 0; j <= 1; j++) {
var negate = +!j;
var firstCondition = currentState.match(new RegExp('^\\s?_?(' + lang.escapeRegExp(item[j]) + ')\\s?$', 'i'));
if (firstCondition) {
var secondCondition = currentState.match(new RegExp('([_]|^|\\s)(' + lang.escapeRegExp(firstCondition[1]) + ')($|\\s)', 'g'));
if (secondCondition) {
reg = currentState.replace(new RegExp(lang.escapeRegExp(item[j]), 'i'), function (result) {
var res = item[negate];
if (result.toUpperCase() == result) {
res = res.toUpperCase();
} else if (result.charAt(0).toUpperCase() == result.charAt(0)) {
res = res.substr(0, 0) + item[negate].charAt(0).toUpperCase() + res.substr(1);
}
return res;
});
this.insert(reg);
reg = "";
}
}
}
}
};
/**
* Finds link at defined {row} and {column}
* @returns {String}
**/
this.findLinkAt = function (row, column) {
var line = this.session.getLine(row);
var wordParts = line.split(/((?:https?|ftp):\/\/[\S]+)/);
var columnPosition = column;
if (columnPosition < 0) columnPosition = 0;
var previousPosition = 0, currentPosition = 0, match;
for (let item of wordParts) {
currentPosition = previousPosition + item.length;
if (columnPosition >= previousPosition && columnPosition <= currentPosition) {
if (item.match(/((?:https?|ftp):\/\/[\S]+)/)) {
match = item.replace(/[\s:.,'";}\]]+$/, "");
break;
}
}
previousPosition = currentPosition;
}
return match;
};
/**
* Open valid url under cursor in another tab
* @returns {Boolean}
**/
this.openLink = function () {
var cursor = this.selection.getCursor();
var url = this.findLinkAt(cursor.row, cursor.column);
if (url)
window.open(url, '_blank');
return url != null;
};
/**
* Removes all the lines in the current selection
* @related EditSession.remove
**/
this.removeLines = function() {
var rows = this.$getSelectedRows();
this.session.removeFullLines(rows.first, rows.last);
this.clearSelection();
};
this.duplicateSelection = function() {
var sel = this.selection;
var doc = this.session;
var range = sel.getRange();
var reverse = sel.isBackwards();
if (range.isEmpty()) {
var row = range.start.row;
doc.duplicateLines(row, row);
} else {
var point = reverse ? range.start : range.end;
var endPoint = doc.insert(point, doc.getTextRange(range), false);
range.start = point;
range.end = endPoint;
sel.setSelectionRange(range, reverse);
}
};
/**
* Shifts all the selected lines down one row.
*
* @returns {Number} On success, it returns -1.
* @related EditSession.moveLinesUp
**/
this.moveLinesDown = function() {
this.$moveLines(1, false);
};
/**
* Shifts all the selected lines up one row.
* @returns {Number} On success, it returns -1.
* @related EditSession.moveLinesDown
**/
this.moveLinesUp = function() {
this.$moveLines(-1, false);
};
/**
* Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this:
* ```json
* { row: newRowLocation, column: newColumnLocation }
* ```
* @param {Range} fromRange The range of text you want moved within the document
* @param {Object} toPosition The location (row and column) where you want to move the text to
*
* @returns {Range} The new range where the text was moved to.
* @related EditSession.moveText
**/
this.moveText = function(range, toPosition, copy) {
return this.session.moveText(range, toPosition, copy);
};
/**
* Copies all the selected lines up one row.
* @returns {Number} On success, returns 0.
*
**/
this.copyLinesUp = function() {
this.$moveLines(-1, true);
};
/**
* Copies all the selected lines down one row.
* @returns {Number} On success, returns the number of new rows added; in other words, `lastRow - firstRow + 1`.
* @related EditSession.duplicateLines
*
**/
this.copyLinesDown = function() {
this.$moveLines(1, true);
};
/**
* for internal use
* @ignore
*
**/
this.$moveLines = function(dir, copy) {
var rows, moved;
var selection = this.selection;
if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
var range = selection.toOrientedRange();
rows = this.$getSelectedRows(range);
moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
if (copy && dir == -1) moved = 0;
range.moveBy(moved, 0);
selection.fromOrientedRange(range);
} else {
var ranges = selection.rangeList.ranges;
selection.rangeList.detach(this.session);
this.inVirtualSelectionMode = true;
var diff = 0;
var totalDiff = 0;
var l = ranges.length;
for (var i = 0; i < l; i++) {
var rangeIndex = i;
ranges[i].moveBy(diff, 0);
rows = this.$getSelectedRows(ranges[i]);
var first = rows.first;
var last = rows.last;
while (++i < l) {
if (totalDiff) ranges[i].moveBy(totalDiff, 0);
var subRows = this.$getSelectedRows(ranges[i]);
if (copy && subRows.first != last)
break;
else if (!copy && subRows.first > last + 1)
break;
last = subRows.last;
}
i--;
diff = this.session.$moveLines(first, last, copy ? 0 : dir);
if (copy && dir == -1) rangeIndex = i + 1;
while (rangeIndex <= i) {
ranges[rangeIndex].moveBy(diff, 0);
rangeIndex++;
}
if (!copy) diff = 0;
totalDiff += diff;
}
selection.fromOrientedRange(selection.ranges[0]);
selection.rangeList.attach(this.session);
this.inVirtualSelectionMode = false;
}
};
/**
* Returns an object indicating the currently selected rows. The object looks like this:
*
* ```json
* { first: range.start.row, last: range.end.row }
* ```
*
* @returns {Object}
**/
this.$getSelectedRows = function(range) {
range = (range || this.getSelectionRange()).collapseRows();
return {
first: this.session.getRowFoldStart(range.start.row),
last: this.session.getRowFoldEnd(range.end.row)
};
};
this.onCompositionStart = function(compositionState) {
this.renderer.showComposition(compositionState);
};
this.onCompositionUpdate = function(text) {
this.renderer.setCompositionText(text);
};
this.onCompositionEnd = function() {
this.renderer.hideComposition();
};
/**
* {:VirtualRenderer.getFirstVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getFirstVisibleRow
**/
this.getFirstVisibleRow = function() {
return this.renderer.getFirstVisibleRow();
};
/**
* {:VirtualRenderer.getLastVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getLastVisibleRow
**/
this.getLastVisibleRow = function() {
return this.renderer.getLastVisibleRow();
};
/**
* Indicates if the row is currently visible on the screen.
* @param {Number} row The row to check
*
* @returns {Boolean}
**/
this.isRowVisible = function(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
};
/**
* Indicates if the entire row is currently visible on the screen.
* @param {Number} row The row to check
*
*
* @returns {Boolean}
**/
this.isRowFullyVisible = function(row) {
return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
};
/**
* Returns the number of currently visible rows.
* @returns {Number}
**/
this.$getVisibleRowCount = function() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
};
this.$moveByPage = function(dir, select) {
var renderer = this.renderer;
var config = this.renderer.layerConfig;
var rows = dir * Math.floor(config.height / config.lineHeight);
if (select === true) {
this.selection.$moveSelection(function(){
this.moveCursorBy(rows, 0);
});
} else if (select === false) {
this.selection.moveCursorBy(rows, 0);
this.selection.clearSelection();
}
var scrollTop = renderer.scrollTop;
renderer.scrollBy(0, rows * config.lineHeight);
if (select != null)
renderer.scrollCursorIntoView(null, 0.5);
renderer.animateScrolling(scrollTop);
};
/**
* Selects the text from the current position of the document until where a "page down" finishes.
**/
this.selectPageDown = function() {
this.$moveByPage(1, true);
};
/**
* Selects the text from the current position of the document until where a "page up" finishes.
**/
this.selectPageUp = function() {
this.$moveByPage(-1, true);
};
/**
* Shifts the document to wherever "page down" is, as well as moving the cursor position.
**/
this.gotoPageDown = function() {
this.$moveByPage(1, false);
};
/**
* Shifts the document to wherever "page up" is, as well as moving the cursor position.
**/
this.gotoPageUp = function() {
this.$moveByPage(-1, false);
};
/**
* Scrolls the document to wherever "page down" is, without changing the cursor position.
**/
this.scrollPageDown = function() {
this.$moveByPage(1);
};
/**
* Scrolls the document to wherever "page up" is, without changing the cursor position.
**/
this.scrollPageUp = function() {
this.$moveByPage(-1);
};
/**
* Moves the editor to the specified row.
* @related VirtualRenderer.scrollToRow
**/
this.scrollToRow = function(row) {
this.renderer.scrollToRow(row);
};
/**
* Scrolls to a line. If `center` is `true`, it puts the line in middle of screen (or attempts to).
* @param {Number} line The line to scroll to
* @param {Boolean} center If `true`
* @param {Boolean} animate If `true` animates scrolling
* @param {Function} callback Function to be called when the animation has finished
*
*
* @related VirtualRenderer.scrollToLine
**/
this.scrollToLine = function(line, center, animate, callback) {
this.renderer.scrollToLine(line, center, animate, callback);
};
/**
* Attempts to center the current selection on the screen.
**/
this.centerSelection = function() {
var range = this.getSelectionRange();
var pos = {
row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
};
this.renderer.alignCursor(pos, 0.5);
};
/**
* Gets the current position of the cursor.
* @returns {Object} An object that looks something like this:
*
* ```json
* { row: currRow, column: currCol }
* ```
*
* @related Selection.getCursor
**/
this.getCursorPosition = function() {
return this.selection.getCursor();
};
/**
* Returns the screen position of the cursor.
* @returns {Number}
* @related EditSession.documentToScreenPosition
**/
this.getCursorPositionScreen = function() {
return this.session.documentToScreenPosition(this.getCursorPosition());
};
/**
* {:Selection.getRange}
* @returns {Range}
* @related Selection.getRange
**/
this.getSelectionRange = function() {
return this.selection.getRange();
};
/**
* Selects all the text in editor.
* @related Selection.selectAll
**/
this.selectAll = function() {
this.selection.selectAll();
};
/**
* {:Selection.clearSelection}
* @related Selection.clearSelection
**/
this.clearSelection = function() {
this.selection.clearSelection();
};
/**
* Moves the cursor to the specified row and column. Note that this does not de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
*
*
* @related Selection.moveCursorTo
**/
this.moveCursorTo = function(row, column) {
this.selection.moveCursorTo(row, column);
};
/**
* Moves the cursor to the position indicated by `pos.row` and `pos.column`.
* @param {Object} pos An object with two properties, row and column
*
*
* @related Selection.moveCursorToPosition
**/
this.moveCursorToPosition = function(pos) {
this.selection.moveCursorToPosition(pos);
};
/**
* Moves the cursor's row and column to the next matching bracket or HTML tag.
*
**/
this.jumpToMatching = function (select, expand) {
var cursor = this.getCursorPosition();
var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
var prevToken = iterator.getCurrentToken();
var tokenCount = 0;
if (prevToken && prevToken.type.indexOf('tag-name') !== -1) {
prevToken = iterator.stepBackward();
}
var token = prevToken || iterator.stepForward();
if (!token) return;
//get next closing tag or bracket
var matchType;
var found = false;
var depth = {};
var i = cursor.column - token.start;
var bracketType;
var brackets = {
")": "(",
"(": "(",
"]": "[",
"[": "[",
"{": "{",
"}": "{"
};
do {
if (token.value.match(/[{}()\[\]]/g)) {
for (; i < token.value.length && !found; i++) {
if (!brackets[token.value[i]]) {
continue;
}
bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
if (isNaN(depth[bracketType])) {
depth[bracketType] = 0;
}
switch (token.value[i]) {
case '(':
case '[':
case '{':
depth[bracketType]++;
break;
case ')':
case ']':
case '}':
depth[bracketType]--;
if (depth[bracketType] === -1) {
matchType = 'bracket';
found = true;
}
break;
}
}
}
else if (token.type.indexOf('tag-name') !== -1) {
if (isNaN(depth[token.value])) {
depth[token.value] = 0;
}
if (prevToken.value === '<' && tokenCount > 1) {
depth[token.value]++;
}
else if (prevToken.value === '') {
depth[token.value]--;
}
if (depth[token.value] === -1) {
matchType = 'tag';
found = true;
}
}
if (!found) {
prevToken = token;
tokenCount++;
token = iterator.stepForward();
i = 0;
}
} while (token && !found);
//no match found
if (!matchType) return;
var range, pos;
if (matchType === 'bracket') {
range = this.session.getBracketRange(cursor);
if (!range) {
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1
);
pos = range.start;
if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column)
< 2) range = this.session.getBracketRange(pos);
}
}
else if (matchType === 'tag') {
if (!token || token.type.indexOf('tag-name') === -1) return;
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2
);
//find matching tag
if (range.compare(cursor.row, cursor.column) === 0) {
var tagsRanges = this.session.getMatchingTags(cursor);
if (tagsRanges) {
if (tagsRanges.openTag.contains(cursor.row, cursor.column)) {
range = tagsRanges.closeTag;
pos = range.start;
}
else {
range = tagsRanges.openTag;
if (tagsRanges.closeTag.start.row === cursor.row && tagsRanges.closeTag.start.column
=== cursor.column) pos = range.end; else pos = range.start;
}
}
}
//we found it
pos = pos || range.start;
}
pos = range && range.cursor || pos;
if (pos) {
if (select) {
if (range && expand) {
this.selection.setRange(range);
}
else if (range && range.isEqual(this.getSelectionRange())) {
this.clearSelection();
}
else {
this.selection.selectTo(pos.row, pos.column);
}
}
else {
this.selection.moveTo(pos.row, pos.column);
}
}
};
/**
* Moves the cursor to the specified line number, and also into the indicated column.
* @param {Number} lineNumber The line number to go to
* @param {Number} column A column number to go to
* @param {Boolean} animate If `true` animates scolling
*
**/
this.gotoLine = function(lineNumber, column, animate) {
this.selection.clearSelection();
this.session.unfold({row: lineNumber - 1, column: column || 0});
// todo: find a way to automatically exit multiselect mode
this.exitMultiSelectMode && this.exitMultiSelectMode();
this.moveCursorTo(lineNumber - 1, column || 0);
if (!this.isRowFullyVisible(lineNumber - 1))
this.scrollToLine(lineNumber - 1, true, animate);
};
/**
* Moves the cursor to the specified row and column. Note that this does de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
*
*
* @related Editor.moveCursorTo
**/
this.navigateTo = function(row, column) {
this.selection.moveTo(row, column);
};
/**
* Moves the cursor up in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
this.navigateUp = function(times) {
if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
var selectionStart = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionStart);
}
this.selection.clearSelection();
this.selection.moveCursorBy(-times || -1, 0);
};
/**
* Moves the cursor down in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
this.navigateDown = function(times) {
if (this.selection.isMultiLine() && this.selection.isBackwards()) {
var selectionEnd = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionEnd);
}
this.selection.clearSelection();
this.selection.moveCursorBy(times || 1, 0);
};
/**
* Moves the cursor left in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
this.navigateLeft = function(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
};
/**
* Moves the cursor right in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
this.navigateRight = function(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
};
/**
*
* Moves the cursor to the start of the current line. Note that this does de-select the current selection.
**/
this.navigateLineStart = function() {
this.selection.moveCursorLineStart();
this.clearSelection();
};
/**
*
* Moves the cursor to the end of the current line. Note that this does de-select the current selection.
**/
this.navigateLineEnd = function() {
this.selection.moveCursorLineEnd();
this.clearSelection();
};
/**
*
* Moves the cursor to the end of the current file. Note that this does de-select the current selection.
**/
this.navigateFileEnd = function() {
this.selection.moveCursorFileEnd();
this.clearSelection();
};
/**
*
* Moves the cursor to the start of the current file. Note that this does de-select the current selection.
**/
this.navigateFileStart = function() {
this.selection.moveCursorFileStart();
this.clearSelection();
};
/**
*
* Moves the cursor to the word immediately to the right of the current position. Note that this does de-select the current selection.
**/
this.navigateWordRight = function() {
this.selection.moveCursorWordRight();
this.clearSelection();
};
/**
*
* Moves the cursor to the word immediately to the left of the current position. Note that this does de-select the current selection.
**/
this.navigateWordLeft = function() {
this.selection.moveCursorWordLeft();
this.clearSelection();
};
/**
* Replaces the first occurrence of `options.needle` with the value in `replacement`.
* @param {String} replacement The text to replace with
* @param {Object} options The [[Search `Search`]] options to use
*
*
**/
this.replace = function(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
var replaced = 0;
if (!range)
return replaced;
if (this.$tryReplace(range, replacement)) {
replaced = 1;
}
this.selection.setSelectionRange(range);
this.renderer.scrollSelectionIntoView(range.start, range.end);
return replaced;
};
/**
* Replaces all occurrences of `options.needle` with the value in `replacement`.
* @param {String} replacement The text to replace with
* @param {Object} options The [[Search `Search`]] options to use
*
*
**/
this.replaceAll = function(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
var replaced = 0;
if (!ranges.length)
return replaced;
var selection = this.getSelectionRange();
this.selection.moveTo(0, 0);
for (var i = ranges.length - 1; i >= 0; --i) {
if(this.$tryReplace(ranges[i], replacement)) {
replaced++;
}
}
this.selection.setSelectionRange(selection);
return replaced;
};
this.$tryReplace = function(range, replacement) {
var input = this.session.getTextRange(range);
replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
};
/**
* {:Search.getOptions} For more information on `options`, see [[Search `Search`]].
* @related Search.getOptions
* @returns {Object}
**/
this.getLastSearchOptions = function() {
return this.$search.getOptions();
};
/**
* Attempts to find `needle` within the document. For more information on `options`, see [[Search `Search`]].
* @param {String} needle The text to search for (optional)
* @param {Object} options An object defining various search properties
* @param {Boolean} animate If `true` animate scrolling
*
*
* @related Search.find
**/
this.find = function(needle, options, animate) {
if (!options)
options = {};
if (typeof needle == "string" || needle instanceof RegExp)
options.needle = needle;
else if (typeof needle == "object")
oop.mixin(options, needle);
var range = this.selection.getRange();
if (options.needle == null) {
needle = this.session.getTextRange(range)
|| this.$search.$options.needle;
if (!needle) {
range = this.session.getWordRange(range.start.row, range.start.column);
needle = this.session.getTextRange(range);
}
this.$search.set({needle: needle});
}
this.$search.set(options);
if (!options.start)
this.$search.set({start: range});
var newRange = this.$search.find(this.session);
if (options.preventScroll)
return newRange;
if (newRange) {
this.revealRange(newRange, animate);
return newRange;
}
// clear selection if nothing is found
if (options.backwards)
range.start = range.end;
else
range.end = range.start;
this.selection.setRange(range);
};
/**
* Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]].
* @param {Object} options search options
* @param {Boolean} animate If `true` animate scrolling
*
*
* @related Editor.find
**/
this.findNext = function(options, animate) {
this.find({skipCurrent: true, backwards: false}, options, animate);
};
/**
* Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]].
* @param {Object} options search options
* @param {Boolean} animate If `true` animate scrolling
*
*
* @related Editor.find
**/
this.findPrevious = function(options, animate) {
this.find(options, {skipCurrent: true, backwards: true}, animate);
};
this.revealRange = function(range, animate) {
this.session.unfold(range);
this.selection.setSelectionRange(range);
var scrollTop = this.renderer.scrollTop;
this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
if (animate !== false)
this.renderer.animateScrolling(scrollTop);
};
/**
* {:UndoManager.undo}
* @related UndoManager.undo
**/
this.undo = function() {
this.session.getUndoManager().undo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
};
/**
* {:UndoManager.redo}
* @related UndoManager.redo
**/
this.redo = function() {
this.session.getUndoManager().redo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
};
/**
*
* Cleans up the entire editor.
**/
this.destroy = function() {
if (this.$toDestroy) {
this.$toDestroy.forEach(function(el) {
el.destroy();
});
this.$toDestroy = null;
}
if (this.$mouseHandler)
this.$mouseHandler.destroy();
this.renderer.destroy();
this._signal("destroy", this);
if (this.session)
this.session.destroy();
if (this._$emitInputEvent)
this._$emitInputEvent.cancel();
this.removeAllListeners();
};
/**
* Enables automatic scrolling of the cursor into view when editor itself is inside scrollable element
* @param {Boolean} enable default true
**/
this.setAutoScrollEditorIntoView = function(enable) {
if (!enable)
return;
var rect;
var self = this;
var shouldScroll = false;
if (!this.$scrollAnchor)
this.$scrollAnchor = document.createElement("div");
var scrollAnchor = this.$scrollAnchor;
scrollAnchor.style.cssText = "position:absolute";
this.container.insertBefore(scrollAnchor, this.container.firstChild);
var onChangeSelection = this.on("changeSelection", function() {
shouldScroll = true;
});
// needed to not trigger sync reflow
var onBeforeRender = this.renderer.on("beforeRender", function() {
if (shouldScroll)
rect = self.renderer.container.getBoundingClientRect();
});
var onAfterRender = this.renderer.on("afterRender", function() {
if (shouldScroll && rect && (self.isFocused()
|| self.searchBox && self.searchBox.isFocused())
) {
var renderer = self.renderer;
var pos = renderer.$cursorLayer.$pixelPos;
var config = renderer.layerConfig;
var top = pos.top - config.offset;
if (pos.top >= 0 && top + rect.top < 0) {
shouldScroll = true;
} else if (pos.top < config.height &&
pos.top + rect.top + config.lineHeight > window.innerHeight) {
shouldScroll = false;
} else {
shouldScroll = null;
}
if (shouldScroll != null) {
scrollAnchor.style.top = top + "px";
scrollAnchor.style.left = pos.left + "px";
scrollAnchor.style.height = config.lineHeight + "px";
scrollAnchor.scrollIntoView(shouldScroll);
}
shouldScroll = rect = null;
}
});
this.setAutoScrollEditorIntoView = function(enable) {
if (enable)
return;
delete this.setAutoScrollEditorIntoView;
this.off("changeSelection", onChangeSelection);
this.renderer.off("afterRender", onAfterRender);
this.renderer.off("beforeRender", onBeforeRender);
};
};
this.$resetCursorStyle = function() {
var style = this.$cursorStyle || "ace";
var cursorLayer = this.renderer.$cursorLayer;
if (!cursorLayer)
return;
cursorLayer.setSmoothBlinking(/smooth/.test(style));
cursorLayer.isBlinking = !this.$readOnly && style != "wide";
dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
};
/**
* opens a prompt displaying message
**/
this.prompt = function(message, options, callback) {
var editor = this;
config.loadModule("ace/ext/prompt", function (module) {
module.prompt(editor, message, options, callback);
});
};
}).call(Editor.prototype);
config.defineOptions(Editor.prototype, "editor", {
selectionStyle: {
set: function(style) {
this.onSelectionChange();
this._signal("changeSelectionStyle", {data: style});
},
initialValue: "line"
},
highlightActiveLine: {
set: function() {this.$updateHighlightActiveLine();},
initialValue: true
},
highlightSelectedWord: {
set: function(shouldHighlight) {this.$onSelectionChange();},
initialValue: true
},
readOnly: {
set: function(readOnly) {
this.textInput.setReadOnly(readOnly);
this.$resetCursorStyle();
},
initialValue: false
},
copyWithEmptySelection: {
set: function(value) {
this.textInput.setCopyWithEmptySelection(value);
},
initialValue: false
},
cursorStyle: {
set: function(val) { this.$resetCursorStyle(); },
values: ["ace", "slim", "smooth", "wide"],
initialValue: "ace"
},
mergeUndoDeltas: {
values: [false, true, "always"],
initialValue: true
},
behavioursEnabled: {initialValue: true},
wrapBehavioursEnabled: {initialValue: true},
enableAutoIndent: {initialValue: true},
autoScrollEditorIntoView: {
set: function(val) {this.setAutoScrollEditorIntoView(val);}
},
keyboardHandler: {
set: function(val) { this.setKeyboardHandler(val); },
get: function() { return this.$keybindingId; },
handlesSet: true
},
value: {
set: function(val) { this.session.setValue(val); },
get: function() { return this.getValue(); },
handlesSet: true,
hidden: true
},
session: {
set: function(val) { this.setSession(val); },
get: function() { return this.session; },
handlesSet: true,
hidden: true
},
showLineNumbers: {
set: function(show) {
this.renderer.$gutterLayer.setShowLineNumbers(show);
this.renderer.$loop.schedule(this.renderer.CHANGE_GUTTER);
if (show && this.$relativeLineNumbers)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
},
initialValue: true
},
relativeLineNumbers: {
set: function(value) {
if (this.$showLineNumbers && value)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
}
},
placeholder: {
set: function(message) {
if (!this.$updatePlaceholder) {
this.$updatePlaceholder = function() {
var value = this.session && (this.renderer.$composition || this.getValue());
if (value && this.renderer.placeholderNode) {
this.renderer.off("afterRender", this.$updatePlaceholder);
dom.removeCssClass(this.container, "ace_hasPlaceholder");
this.renderer.placeholderNode.remove();
this.renderer.placeholderNode = null;
} else if (!value && !this.renderer.placeholderNode) {
this.renderer.on("afterRender", this.$updatePlaceholder);
dom.addCssClass(this.container, "ace_hasPlaceholder");
var el = dom.createElement("div");
el.className = "ace_placeholder";
el.textContent = this.$placeholder || "";
this.renderer.placeholderNode = el;
this.renderer.content.appendChild(this.renderer.placeholderNode);
} else if (!value && this.renderer.placeholderNode) {
this.renderer.placeholderNode.textContent = this.$placeholder || "";
}
}.bind(this);
this.on("input", this.$updatePlaceholder);
}
this.$updatePlaceholder();
}
},
customScrollbar: "renderer",
hScrollBarAlwaysVisible: "renderer",
vScrollBarAlwaysVisible: "renderer",
highlightGutterLine: "renderer",
animatedScroll: "renderer",
showInvisibles: "renderer",
showPrintMargin: "renderer",
printMarginColumn: "renderer",
printMargin: "renderer",
fadeFoldWidgets: "renderer",
showFoldWidgets: "renderer",
displayIndentGuides: "renderer",
highlightIndentGuides: "renderer",
showGutter: "renderer",
fontSize: "renderer",
fontFamily: "renderer",
maxLines: "renderer",
minLines: "renderer",
scrollPastEnd: "renderer",
fixedWidthGutter: "renderer",
theme: "renderer",
hasCssTransforms: "renderer",
maxPixelHeight: "renderer",
useTextareaForIME: "renderer",
scrollSpeed: "$mouseHandler",
dragDelay: "$mouseHandler",
dragEnabled: "$mouseHandler",
focusTimeout: "$mouseHandler",
tooltipFollowsMouse: "$mouseHandler",
firstLineNumber: "session",
overwrite: "session",
newLineMode: "session",
useWorker: "session",
useSoftTabs: "session",
navigateWithinSoftTabs: "session",
tabSize: "session",
wrap: "session",
indentedSoftWrap: "session",
foldStyle: "session",
mode: "session"
});
var relativeNumberRenderer = {
getText: function(session, row) {
return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9 ? "\xb7" : ""))) + "";
},
getWidth: function(session, lastLineNumber, config) {
return Math.max(
lastLineNumber.toString().length,
(config.lastRow + 1).toString().length,
2
) * config.characterWidth;
},
update: function(e, editor) {
editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER);
},
attach: function(editor) {
editor.renderer.$gutterLayer.$renderer = this;
editor.on("changeSelection", this.update);
this.update(null, editor);
},
detach: function(editor) {
if (editor.renderer.$gutterLayer.$renderer == this)
editor.renderer.$gutterLayer.$renderer = null;
editor.off("changeSelection", this.update);
this.update(null, editor);
}
};
exports.Editor = Editor;
================================================
FILE: demo/diff/examples/editor.17.js
================================================
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var lang = require("./lib/lang");
var useragent = require("./lib/useragent");
var TextInput = require("./keyboard/textinput").TextInput;
var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
var FoldHandler = require("./mouse/fold_handler").FoldHandler;
var KeyBinding = require("./keyboard/keybinding").KeyBinding;
var EditSession = require("./edit_session").EditSession;
var Search = require("./search").Search;
var Range = require("./range").Range;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var CommandManager = require("./commands/command_manager").CommandManager;
var defaultCommands = require("./commands/default_commands").commands;
var config = require("./config");
var TokenIterator = require("./token_iterator").TokenIterator;
var LineWidgets = require("./line_widgets").LineWidgets;
var clipboard = require("./clipboard");
var keys = require('./lib/keys');
/**
* The main entry point into the Ace functionality.
*
* The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen.
*
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
class Editor {
/**
* Creates a new `Editor` object.
*
* @param {VirtualRenderer} renderer Associated `VirtualRenderer` that draws everything
* @param {EditSession} session The `EditSession` to refer to
**/
constructor(renderer, session, options) {
this.$toDestroy = [];
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.id = "editor" + (++Editor.$uid);
this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
if (typeof document == "object") {
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.renderer.textarea = this.textInput.getElement();
// TODO detect touch event support
this.$mouseHandler = new MouseHandler(this);
new FoldHandler(this);
}
this.keyBinding = new KeyBinding(this);
this.$search = new Search().set({
wrap: true
});
this.$historyTracker = this.$historyTracker.bind(this);
this.commands.on("exec", this.$historyTracker);
this.$initOperationListeners();
this._$emitInputEvent = lang.delayedCall(function() {
this._signal("input", {});
if (this.session && !this.session.destroyed)
this.session.bgTokenizer.scheduleStart();
}.bind(this));
this.on("change", function(_, _self) {
_self._$emitInputEvent.schedule(31);
});
this.setSession(session || options && options.session || new EditSession(""));
config.resetOptions(this);
if (options)
this.setOptions(options);
config._signal("editor", this);
}
$initOperationListeners() {
this.commands.on("exec", this.startOperation.bind(this), true);
this.commands.on("afterExec", this.endOperation.bind(this), true);
this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this, true));
// todo: add before change events?
this.on("change", function() {
if (!this.curOp) {
this.startOperation();
this.curOp.selectionBefore = this.$lastSel;
}
this.curOp.docChanged = true;
}.bind(this), true);
this.on("changeSelection", function() {
if (!this.curOp) {
this.startOperation();
this.curOp.selectionBefore = this.$lastSel;
}
this.curOp.selectionChanged = true;
}.bind(this), true);
}
startOperation(commandEvent) {
if (this.curOp) {
if (!commandEvent || this.curOp.command)
return;
this.prevOp = this.curOp;
}
if (!commandEvent) {
this.previousCommand = null;
commandEvent = {};
}
this.$opResetTimer.schedule();
this.curOp = this.session.curOp = {
command: commandEvent.command || {},
args: commandEvent.args,
scrollTop: this.renderer.scrollTop
};
this.curOp.selectionBefore = this.selection.toJSON();
}
endOperation(e) {
if (this.curOp && this.session) {
if (e && e.returnValue === false || !this.session)
return (this.curOp = null);
if (e == true && this.curOp.command && this.curOp.command.name == "mouse")
return;
this._signal("beforeEndOperation");
if (!this.curOp) return;
var command = this.curOp.command;
var scrollIntoView = command && command.scrollIntoView;
if (scrollIntoView) {
switch (scrollIntoView) {
case "center-animate":
scrollIntoView = "animate";
/* fall through */
case "center":
this.renderer.scrollCursorIntoView(null, 0.5);
break;
case "animate":
case "cursor":
this.renderer.scrollCursorIntoView();
break;
case "selectionPart":
var range = this.selection.getRange();
var config = this.renderer.layerConfig;
if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
}
break;
default:
break;
}
if (scrollIntoView == "animate")
this.renderer.animateScrolling(this.curOp.scrollTop);
}
var sel = this.selection.toJSON();
this.curOp.selectionAfter = sel;
this.$lastSel = this.selection.toJSON();
// console.log(this.$lastSel+" endOP")
this.session.getUndoManager().addSelection(sel);
this.prevOp = this.curOp;
this.curOp = null;
}
}
$historyTracker(e) {
if (!this.$mergeUndoDeltas)
return;
var prev = this.prevOp;
var mergeableCommands = this.$mergeableCommands;
// previous command was the same
var shouldMerge = prev.command && (e.command.name == prev.command.name);
if (e.command.name == "insertstring") {
var text = e.args;
if (this.mergeNextCommand === undefined)
this.mergeNextCommand = true;
shouldMerge = shouldMerge
&& this.mergeNextCommand // previous command allows to coalesce with
&& (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
this.mergeNextCommand = true;
} else {
shouldMerge = shouldMerge
&& mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
}
if (
this.$mergeUndoDeltas != "always"
&& Date.now() - this.sequenceStartTime > 2000
) {
shouldMerge = false; // the sequence is too long
}
if (shouldMerge)
this.session.mergeUndoDeltas = true;
else if (mergeableCommands.indexOf(e.command.name) !== -1)
this.sequenceStartTime = Date.now();
}
/**
* Sets a new key handler, such as "vim" or "windows".
* @param {String} keyboardHandler The new key handler
*
**/
setKeyboardHandler(keyboardHandler, cb) {
if (keyboardHandler && typeof keyboardHandler === "string" && keyboardHandler != "ace") {
this.$keybindingId = keyboardHandler;
var _self = this;
config.loadModule(["keybinding", keyboardHandler], function(module) {
if (_self.$keybindingId == keyboardHandler)
_self.keyBinding.setKeyboardHandler(module && module.handler);
cb && cb();
});
} else {
this.$keybindingId = null;
this.keyBinding.setKeyboardHandler(keyboardHandler);
cb && cb();
}
}
/**
* Returns the keyboard handler, such as "vim" or "windows".
*
* @returns {String}
*
**/
getKeyboardHandler() {
return this.keyBinding.getKeyboardHandler();
}
/**
* Emitted whenever the [[EditSession]] changes.
* @event changeSession
* @param {Object} e An object with two properties, `oldSession` and `session`, that represent the old and new [[EditSession]]s.
*
**/
/**
* Sets a new editsession to use. This method also emits the `'changeSession'` event.
* @param {EditSession} session The new session to use
*
**/
setSession(session) {
if (this.session == session)
return;
// make sure operationEnd events are not emitted to wrong session
if (this.curOp) this.endOperation();
this.curOp = {};
var oldSession = this.session;
if (oldSession) {
this.session.off("change", this.$onDocumentChange);
this.session.off("changeMode", this.$onChangeMode);
this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.off("changeTabSize", this.$onChangeTabSize);
this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
this.session.off("changeWrapMode", this.$onChangeWrapMode);
this.session.off("changeFold", this.$onChangeFold);
this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
this.session.off("changeBackMarker", this.$onChangeBackMarker);
this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
this.session.off("changeAnnotation", this.$onChangeAnnotation);
this.session.off("changeOverwrite", this.$onCursorChange);
this.session.off("changeScrollTop", this.$onScrollTopChange);
this.session.off("changeScrollLeft", this.$onScrollLeftChange);
var selection = this.session.getSelection();
selection.off("changeCursor", this.$onCursorChange);
selection.off("changeSelection", this.$onSelectionChange);
}
this.session = session;
if (session) {
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.on("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.on("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.on("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
session.on("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.on("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.on("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.on("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.on("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.on("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.on("changeOverwrite", this.$onCursorChange);
this.$onScrollTopChange = this.onScrollTopChange.bind(this);
this.session.on("changeScrollTop", this.$onScrollTopChange);
this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
this.session.on("changeScrollLeft", this.$onScrollLeftChange);
this.selection = session.getSelection();
this.selection.on("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.on("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.onCursorChange();
this.onScrollTopChange();
this.onScrollLeftChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.updateFull();
} else {
this.selection = null;
this.renderer.setSession(session);
}
this._signal("changeSession", {
session: session,
oldSession: oldSession
});
this.curOp = null;
oldSession && oldSession._signal("changeEditor", {oldEditor: this});
session && session._signal("changeEditor", {editor: this});
if (session && !session.destroyed)
session.bgTokenizer.scheduleStart();
}
/**
* Returns the current session being used.
* @returns {EditSession}
**/
getSession() {
return this.session;
}
/**
* Sets the current document to `val`.
* @param {String} val The new value to set for the document
* @param {Number} cursorPos Where to set the new value. `undefined` or 0 is selectAll, -1 is at the document start, and 1 is at the end
*
* @returns {String} The current document value
* @related Document.setValue
**/
setValue(val, cursorPos) {
this.session.doc.setValue(val);
if (!cursorPos)
this.selectAll();
else if (cursorPos == 1)
this.navigateFileEnd();
else if (cursorPos == -1)
this.navigateFileStart();
return val;
}
/**
* Returns the current session's content.
*
* @returns {String}
* @related EditSession.getValue
**/
getValue() {
return this.session.getValue();
}
/**
*
* Returns the currently highlighted selection.
* @returns {Selection} The selection object
**/
getSelection() {
return this.selection;
}
/**
* {:VirtualRenderer.onResize}
* @param {Boolean} force If `true`, recomputes the size, even if the height and width haven't changed
*
*
* @related VirtualRenderer.onResize
**/
resize(force) {
this.renderer.onResize(force);
}
/**
* {:VirtualRenderer.setTheme}
* @param {String} theme The path to a theme
* @param {Function} cb optional callback called when theme is loaded
**/
setTheme(theme, cb) {
this.renderer.setTheme(theme, cb);
}
/**
* {:VirtualRenderer.getTheme}
*
* @returns {String} The set theme
* @related VirtualRenderer.getTheme
**/
getTheme() {
return this.renderer.getTheme();
}
/**
* {:VirtualRenderer.setStyle}
* @param {String} style A class name
*
*
* @related VirtualRenderer.setStyle
**/
setStyle(style) {
this.renderer.setStyle(style);
}
/**
* {:VirtualRenderer.unsetStyle}
* @related VirtualRenderer.unsetStyle
**/
unsetStyle(style) {
this.renderer.unsetStyle(style);
}
/**
* Gets the current font size of the editor text.
*/
getFontSize() {
return this.getOption("fontSize") ||
dom.computedStyle(this.container).fontSize;
}
/**
* Set a new font size (in pixels) for the editor text.
* @param {String} size A font size ( _e.g._ "12px")
*
*
**/
setFontSize(size) {
this.setOption("fontSize", size);
}
$highlightBrackets() {
if (this.$highlightPending) {
return;
}
// perform highlight async to not block the browser during navigation
var self = this;
this.$highlightPending = true;
setTimeout(function () {
self.$highlightPending = false;
var session = self.session;
if (!session || session.destroyed) return;
if (session.$bracketHighlight) {
session.$bracketHighlight.markerIds.forEach(function(id) {
session.removeMarker(id);
});
session.$bracketHighlight = null;
}
var pos = self.getCursorPosition();
var handler = self.getKeyboardHandler();
var isBackwards = handler && handler.$getDirectionForHighlight && handler.$getDirectionForHighlight(self);
var ranges = session.getMatchingBracketRanges(pos, isBackwards);
if (!ranges) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
if (token && /\b(?:tag-open|tag-name)/.test(token.type)) {
var tagNamesRanges = session.getMatchingTags(pos);
if (tagNamesRanges) ranges = [tagNamesRanges.openTagName, tagNamesRanges.closeTagName];
}
}
if (!ranges && session.$mode.getMatching)
ranges = session.$mode.getMatching(self.session);
if (!ranges) {
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
return;
}
var markerType = "ace_bracket";
if (!Array.isArray(ranges)) {
ranges = [ranges];
} else if (ranges.length == 1) {
markerType = "ace_error_bracket";
}
// show adjacent ranges as one
if (ranges.length == 2) {
if (Range.comparePoints(ranges[0].end, ranges[1].start) == 0)
ranges = [Range.fromPoints(ranges[0].start, ranges[1].end)];
else if (Range.comparePoints(ranges[0].start, ranges[1].end) == 0)
ranges = [Range.fromPoints(ranges[1].start, ranges[0].end)];
}
session.$bracketHighlight = {
ranges: ranges,
markerIds: ranges.map(function(range) {
return session.addMarker(range, markerType, "text");
})
};
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
}, 50);
}
/**
*
* Brings the current `textInput` into focus.
**/
focus() {
this.textInput.focus();
}
/**
* Returns `true` if the current `textInput` is in focus.
* @return {Boolean}
**/
isFocused() {
return this.textInput.isFocused();
}
/**
*
* Blurs the current `textInput`.
**/
blur() {
this.textInput.blur();
}
/**
* Emitted once the editor comes into focus.
* @event focus
*
*
**/
onFocus(e) {
if (this.$isFocused)
return;
this.$isFocused = true;
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._emit("focus", e);
}
/**
* Emitted once the editor has been blurred.
* @event blur
*
*
**/
onBlur(e) {
if (!this.$isFocused)
return;
this.$isFocused = false;
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._emit("blur", e);
}
$cursorChange() {
this.renderer.updateCursor();
this.$highlightBrackets();
this.$updateHighlightActiveLine();
}
/**
* Emitted whenever the document is changed.
* @event change
* @param {Object} delta Contains a single property, `data`, which has the delta of changes
*
*
*
**/
onDocumentChange(delta) {
// Rerender and emit "change" event.
var wrap = this.session.$useWrapMode;
var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
this.renderer.updateLines(delta.start.row, lastRow, wrap);
this._signal("change", delta);
// Update cursor because tab characters can influence the cursor position.
this.$cursorChange();
}
onTokenizerUpdate(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
}
onScrollTopChange() {
this.renderer.scrollToY(this.session.getScrollTop());
}
onScrollLeftChange() {
this.renderer.scrollToX(this.session.getScrollLeft());
}
/**
* Emitted when the selection changes.
*
**/
onCursorChange() {
this.$cursorChange();
this._signal("changeSelection");
}
$updateHighlightActiveLine() {
var session = this.getSession();
var highlight;
if (this.$highlightActiveLine) {
if (this.$selectionStyle != "line" || !this.selection.isMultiLine())
highlight = this.getCursorPosition();
if (this.renderer.theme && this.renderer.theme.$selectionColorConflict && !this.selection.isEmpty())
highlight = false;
if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
highlight = false;
}
if (session.$highlightLineMarker && !highlight) {
session.removeMarker(session.$highlightLineMarker.id);
session.$highlightLineMarker = null;
} else if (!session.$highlightLineMarker && highlight) {
var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
range.id = session.addMarker(range, "ace_active-line", "screenLine");
session.$highlightLineMarker = range;
} else if (highlight) {
session.$highlightLineMarker.start.row = highlight.row;
session.$highlightLineMarker.end.row = highlight.row;
session.$highlightLineMarker.start.column = highlight.column;
session._signal("changeBackMarker");
}
}
onSelectionChange(e) {
var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
this.session.highlight(re);
this._signal("changeSelection");
}
$getSelectionHighLightRegexp() {
var session = this.session;
var selection = this.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startColumn = selection.start.column;
var endColumn = selection.end.column;
var line = session.getLine(selection.start.row);
var needle = line.substring(startColumn, endColumn);
// maximum allowed size for regular expressions in 32000,
// but getting close to it has significant impact on the performance
if (needle.length > 5000 || !/[\w\d]/.test(needle))
return;
var re = this.$search.$assembleRegExp({
wholeWord: true,
caseSensitive: true,
needle: needle
});
var wordWithBoundary = line.substring(startColumn - 1, endColumn + 1);
if (!re.test(wordWithBoundary))
return;
return re;
}
onChangeFrontMarker() {
this.renderer.updateFrontMarkers();
}
onChangeBackMarker() {
this.renderer.updateBackMarkers();
}
onChangeBreakpoint() {
this.renderer.updateBreakpoints();
}
onChangeAnnotation() {
this.renderer.setAnnotations(this.session.getAnnotations());
}
onChangeMode (e) {
this.renderer.updateText();
this._emit("changeMode", e);
}
onChangeWrapLimit() {
this.renderer.updateFull();
}
onChangeWrapMode() {
this.renderer.onResize(true);
}
onChangeFold() {
// Update the active line marker as due to folding changes the current
// line range on the screen might have changed.
this.$updateHighlightActiveLine();
// TODO: This might be too much updating. Okay for now.
this.renderer.updateFull();
}
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
getSelectedText() {
return this.session.getTextRange(this.getSelectionRange());
}
/**
* Emitted when text is copied.
* @event copy
* @param {String} text The copied text
*
**/
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
getCopyText () {
var text = this.getSelectedText();
var nl = this.session.doc.getNewLineCharacter();
var copyLine= false;
if (!text && this.$copyWithEmptySelection) {
copyLine = true;
var ranges = this.selection.getAllRanges();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (i && ranges[i - 1].start.row == range.start.row)
continue;
text += this.session.getLine(range.start.row) + nl;
}
}
var e = {text: text};
this._signal("copy", e);
clipboard.lineMode = copyLine ? e.text : false;
return e.text;
}
/**
* Called whenever a text "copy" happens.
**/
onCopy() {
this.commands.exec("copy", this);
}
/**
* Called whenever a text "cut" happens.
**/
onCut() {
this.commands.exec("cut", this);
}
/**
* Emitted when text is pasted.
* @event paste
* @param {Object} an object which contains one property, `text`, that represents the text to be pasted. Editing this property will alter the text that is pasted.
*
*
**/
/**
* Called whenever a text "paste" happens.
* @param {String} text The pasted text
*
*
**/
onPaste(text, event) {
var e = {text: text, event: event};
this.commands.exec("paste", this, e);
}
$handlePaste(e) {
if (typeof e == "string")
e = {text: e};
this._signal("paste", e);
var text = e.text;
var lineMode = text === clipboard.lineMode;
var session = this.session;
if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
if (lineMode)
session.insert({ row: this.selection.lead.row, column: 0 }, text);
else
this.insert(text);
} else if (lineMode) {
this.selection.rangeList.ranges.forEach(function(range) {
session.insert({ row: range.start.row, column: 0 }, text);
});
} else {
var lines = text.split(/\r\n|\r|\n/);
var ranges = this.selection.rangeList.ranges;
var isFullLine = lines.length == 2 && (!lines[0] || !lines[1]);
if (lines.length != ranges.length || isFullLine)
return this.commands.exec("insertstring", this, text);
for (var i = ranges.length; i--;) {
var range = ranges[i];
if (!range.isEmpty())
session.remove(range);
session.insert(range.start, lines[i]);
}
}
}
execCommand(command, args) {
return this.commands.exec(command, this, args);
}
/**
* Inserts `text` into wherever the cursor is pointing.
* @param {String} text The new text to add
*
**/
insert(text, pasted) {
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled() && !pasted) {
// Get a transform if the current mode wants one.
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform) {
if (text !== transform.text) {
// keep automatic insertion in a separate delta, unless it is in multiselect mode
if (!this.inVirtualSelectionMode) {
this.session.mergeUndoDeltas = false;
this.mergeNextCommand = false;
}
}
text = transform.text;
}
}
if (text == "\t")
text = this.session.getTabString();
// remove selected text
if (!this.selection.isEmpty()) {
var range = this.getSelectionRange();
cursor = this.session.remove(range);
this.clearSelection();
}
else if (this.session.getOverwrite() && text.indexOf("\n") == -1) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
if (text == "\n" || text == "\r\n") {
var line = session.getLine(cursor.row);
if (cursor.column > line.search(/\S|$/)) {
var d = line.substr(cursor.column).search(/\S|$/);
session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
}
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var line = session.getLine(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, line, text);
session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
if (this.$enableAutoIndent) {
if (session.getDocument().isNewLine(text)) {
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
session.insert({row: cursor.row+1, column: 0}, lineIndent);
}
if (shouldOutdent)
mode.autoOutdent(lineState, session, cursor.row);
}
}
autoIndent() {
var session = this.session;
var mode = session.getMode();
var startRow, endRow;
if (this.selection.isEmpty()) {
startRow = 0;
endRow = session.doc.getLength() - 1;
} else {
var selectedRange = this.getSelectionRange();
startRow = selectedRange.start.row;
endRow = selectedRange.end.row;
}
var prevLineState = "";
var prevLine = "";
var lineIndent = "";
var line, currIndent, range;
var tab = session.getTabString();
for (var row = startRow; row <= endRow; row++) {
if (row > 0) {
prevLineState = session.getState(row - 1);
prevLine = session.getLine(row - 1);
lineIndent = mode.getNextLineIndent(prevLineState, prevLine, tab);
}
line = session.getLine(row);
currIndent = mode.$getIndent(line);
if (lineIndent !== currIndent) {
if (currIndent.length > 0) {
range = new Range(row, 0, row, currIndent.length);
session.remove(range);
}
if (lineIndent.length > 0) {
session.insert({row: row, column: 0}, lineIndent);
}
}
mode.autoOutdent(prevLineState, session, row);
}
}
onTextInput(text, composition) {
if (!composition)
return this.keyBinding.onTextInput(text);
this.startOperation({command: { name: "insertstring" }});
var applyComposition = this.applyComposition.bind(this, text, composition);
if (this.selection.rangeCount)
this.forEachSelection(applyComposition);
else
applyComposition();
this.endOperation();
}
applyComposition(text, composition) {
if (composition.extendLeft || composition.extendRight) {
var r = this.selection.getRange();
r.start.column -= composition.extendLeft;
r.end.column += composition.extendRight;
if (r.start.column < 0) {
r.start.row--;
r.start.column += this.session.getLine(r.start.row).length + 1;
}
this.selection.setRange(r);
if (!text && !r.isEmpty())
this.remove();
}
if (text || !this.selection.isEmpty())
this.insert(text, true);
if (composition.restoreStart || composition.restoreEnd) {
var r = this.selection.getRange();
r.start.column -= composition.restoreStart;
r.end.column -= composition.restoreEnd;
this.selection.setRange(r);
}
}
onCommandKey(e, hashId, keyCode) {
return this.keyBinding.onCommandKey(e, hashId, keyCode);
}
/**
* Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emits the `changeOverwrite` event.
* @param {Boolean} overwrite Defines whether or not to set overwrites
*
*
* @related EditSession.setOverwrite
**/
setOverwrite(overwrite) {
this.session.setOverwrite(overwrite);
}
/**
* Returns `true` if overwrites are enabled; `false` otherwise.
* @returns {Boolean}
* @related EditSession.getOverwrite
**/
getOverwrite() {
return this.session.getOverwrite();
}
/**
* Sets the value of overwrite to the opposite of whatever it currently is.
* @related EditSession.toggleOverwrite
**/
toggleOverwrite() {
this.session.toggleOverwrite();
}
/**
* Sets how fast the mouse scrolling should do.
* @param {Number} speed A value indicating the new speed (in milliseconds)
**/
setScrollSpeed(speed) {
this.setOption("scrollSpeed", speed);
}
/**
* Returns the value indicating how fast the mouse scroll speed is (in milliseconds).
* @returns {Number}
**/
getScrollSpeed() {
return this.getOption("scrollSpeed");
}
/**
* Sets the delay (in milliseconds) of the mouse drag.
* @param {Number} dragDelay A value indicating the new delay
**/
setDragDelay(dragDelay) {
this.setOption("dragDelay", dragDelay);
}
/**
* Returns the current mouse drag delay.
* @returns {Number}
**/
getDragDelay() {
return this.getOption("dragDelay");
}
/**
* Emitted when the selection style changes, via [[Editor.setSelectionStyle]].
* @event changeSelectionStyle
* @param {Object} data Contains one property, `data`, which indicates the new selection style
**/
/**
* Draw selection markers spanning whole line, or only over selected text. Default value is "line"
* @param {String} val The new selection style "line"|"text"
*
**/
setSelectionStyle(val) {
this.setOption("selectionStyle", val);
}
/**
* Returns the current selection style.
* @returns {String}
**/
getSelectionStyle() {
return this.getOption("selectionStyle");
}
/**
* Determines whether or not the current line should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the current line
**/
setHighlightActiveLine(shouldHighlight) {
this.setOption("highlightActiveLine", shouldHighlight);
}
/**
* Returns `true` if current lines are always highlighted.
* @return {Boolean}
**/
getHighlightActiveLine() {
return this.getOption("highlightActiveLine");
}
setHighlightGutterLine(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
}
getHighlightGutterLine() {
return this.getOption("highlightGutterLine");
}
/**
* Determines if the currently selected word should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the currently selected word
*
**/
setHighlightSelectedWord(shouldHighlight) {
this.setOption("highlightSelectedWord", shouldHighlight);
}
/**
* Returns `true` if currently highlighted words are to be highlighted.
* @returns {Boolean}
**/
getHighlightSelectedWord() {
return this.$highlightSelectedWord;
}
setAnimatedScroll(shouldAnimate){
this.renderer.setAnimatedScroll(shouldAnimate);
}
getAnimatedScroll(){
return this.renderer.getAnimatedScroll();
}
/**
* If `showInvisibles` is set to `true`, invisible characters—like spaces or new lines—are show in the editor.
* @param {Boolean} showInvisibles Specifies whether or not to show invisible characters
*
**/
setShowInvisibles(showInvisibles) {
this.renderer.setShowInvisibles(showInvisibles);
}
/**
* Returns `true` if invisible characters are being shown.
* @returns {Boolean}
**/
getShowInvisibles() {
return this.renderer.getShowInvisibles();
}
setDisplayIndentGuides(display) {
this.renderer.setDisplayIndentGuides(display);
}
getDisplayIndentGuides() {
return this.renderer.getDisplayIndentGuides();
}
setHighlightIndentGuides(highlight) {
this.renderer.setHighlightIndentGuides(highlight);
}
getHighlightIndentGuides() {
return this.renderer.getHighlightIndentGuides();
}
/**
* If `showPrintMargin` is set to `true`, the print margin is shown in the editor.
* @param {Boolean} showPrintMargin Specifies whether or not to show the print margin
*
**/
setShowPrintMargin(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
}
/**
* Returns `true` if the print margin is being shown.
* @returns {Boolean}
**/
getShowPrintMargin() {
return this.renderer.getShowPrintMargin();
}
/**
* Sets the column defining where the print margin should be.
* @param {Number} showPrintMargin Specifies the new print margin
*
**/
setPrintMarginColumn(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
}
/**
* Returns the column number of where the print margin is.
* @returns {Number}
**/
getPrintMarginColumn() {
return this.renderer.getPrintMarginColumn();
}
/**
* If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change.
* @param {Boolean} readOnly Specifies whether the editor can be modified or not
*
**/
setReadOnly(readOnly) {
this.setOption("readOnly", readOnly);
}
/**
* Returns `true` if the editor is set to read-only mode.
* @returns {Boolean}
**/
getReadOnly() {
return this.getOption("readOnly");
}
/**
* Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef}
* @param {Boolean} enabled Enables or disables behaviors
*
**/
setBehavioursEnabled(enabled) {
this.setOption("behavioursEnabled", enabled);
}
/**
* Returns `true` if the behaviors are currently enabled. {:BehaviorsDef}
*
* @returns {Boolean}
**/
getBehavioursEnabled() {
return this.getOption("behavioursEnabled");
}
/**
* Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets
* when such a character is typed in.
* @param {Boolean} enabled Enables or disables wrapping behaviors
*
**/
setWrapBehavioursEnabled(enabled) {
this.setOption("wrapBehavioursEnabled", enabled);
}
/**
* Returns `true` if the wrapping behaviors are currently enabled.
**/
getWrapBehavioursEnabled() {
return this.getOption("wrapBehavioursEnabled");
}
/**
* Indicates whether the fold widgets should be shown or not.
* @param {Boolean} show Specifies whether the fold widgets are shown
**/
setShowFoldWidgets(show) {
this.setOption("showFoldWidgets", show);
}
/**
* Returns `true` if the fold widgets are shown.
* @return {Boolean}
**/
getShowFoldWidgets() {
return this.getOption("showFoldWidgets");
}
setFadeFoldWidgets(fade) {
this.setOption("fadeFoldWidgets", fade);
}
getFadeFoldWidgets() {
return this.getOption("fadeFoldWidgets");
}
/**
* Removes the current selection or one character.
* @param {String} dir The direction of the deletion to occur, either "left" or "right"
*
**/
remove(dir) {
if (this.selection.isEmpty()){
if (dir == "left")
this.selection.selectLeft();
else
this.selection.selectRight();
}
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (range.end.column === 0) {
var text = session.getTextRange(range);
if (text[text.length - 1] == "\n") {
var line = session.getLine(range.end.row);
if (/^\s+$/.test(line)) {
range.end.column = line.length;
}
}
}
if (new_range)
range = new_range;
}
this.session.remove(range);
this.clearSelection();
}
/**
* Removes the word directly to the right of the current selection.
**/
removeWordRight() {
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes the word directly to the left of the current selection.
**/
removeWordLeft() {
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes all the words to the left of the current selection, until the start of the line.
**/
removeToLineStart() {
if (this.selection.isEmpty())
this.selection.selectLineStart();
if (this.selection.isEmpty())
this.selection.selectLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes all the words to the right of the current selection, until the end of the line.
**/
removeToLineEnd() {
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
}
/**
* Splits the line at the current selection (by inserting an `'\n'`).
**/
splitLine() {
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
}
/**
* Set the "ghost" text in provided position. "Ghost" text is a kind of
* preview text inside the editor which can be used to preview some code
* inline in the editor such as, for example, code completions.
*
* @param {String} text Text to be inserted as "ghost" text
* @param {object} position Position to insert text to
*/
setGhostText(text, position) {
if (!this.session.widgetManager) {
this.session.widgetManager = new LineWidgets(this.session);
this.session.widgetManager.attach(this);
}
this.renderer.setGhostText(text, position);
}
/**
* Removes "ghost" text currently displayed in the editor.
*/
removeGhostText() {
if (!this.session.widgetManager) return;
this.renderer.removeGhostText();
}
/**
* Transposes current line.
**/
transposeLetters() {
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column === 0)
return;
var line = this.session.getLine(cursor.row);
var swap, range;
if (column < line.length) {
swap = line.charAt(column) + line.charAt(column-1);
range = new Range(cursor.row, column-1, cursor.row, column+1);
}
else {
swap = line.charAt(column-1) + line.charAt(column-2);
range = new Range(cursor.row, column-2, cursor.row, column);
}
this.session.replace(range, swap);
this.session.selection.moveToPosition(range.end);
}
/**
* Converts the current selection entirely into lowercase.
**/
toLowerCase() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toLowerCase());
this.selection.setSelectionRange(originalRange);
}
/**
* Converts the current selection entirely into uppercase.
**/
toUpperCase() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toUpperCase());
this.selection.setSelectionRange(originalRange);
}
/**
* Inserts an indentation into the current cursor position or indents the selected lines.
*
* @related EditSession.indentRows
**/
indent() {
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
} else if (range.start.column < range.end.column) {
var text = session.getTextRange(range);
if (!/^\s+$/.test(text)) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
}
}
var line = session.getLine(range.start.row);
var position = range.start;
var size = session.getTabSize();
var column = session.documentToScreenColumn(position.row, position.column);
if (this.session.getUseSoftTabs()) {
var count = (size - column % size);
var indentString = lang.stringRepeat(" ", count);
} else {
var count = column % size;
while (line[range.start.column - 1] == " " && count) {
range.start.column--;
count--;
}
this.selection.setSelectionRange(range);
indentString = "\t";
}
return this.insert(indentString);
}
/**
* Indents the current line.
* @related EditSession.indentRows
**/
blockIndent() {
var rows = this.$getSelectedRows();
this.session.indentRows(rows.first, rows.last, "\t");
}
/**
* Outdents the current line.
* @related EditSession.outdentRows
**/
blockOutdent() {
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
}
// TODO: move out of core when we have good mechanism for managing extensions
sortLines() {
var rows = this.$getSelectedRows();
var session = this.session;
var lines = [];
for (var i = rows.first; i <= rows.last; i++)
lines.push(session.getLine(i));
lines.sort(function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
var deleteRange = new Range(0, 0, 0, 0);
for (var i = rows.first; i <= rows.last; i++) {
var line = session.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = line.length;
session.replace(deleteRange, lines[i-rows.first]);
}
}
/**
* Given the currently selected range, this function either comments all the lines, or uncomments all of them.
**/
toggleCommentLines() {
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows();
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
}
toggleBlockComment() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
}
/**
* Works like [[EditSession.getTokenAt]], except it returns a number.
* @returns {Number}
**/
getNumberAt(row, column) {
var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
_numberRx.lastIndex = 0;
var s = this.session.getLine(row);
while (_numberRx.lastIndex < column) {
var m = _numberRx.exec(s);
if(m.index <= column && m.index+m[0].length >= column){
var number = {
value: m[0],
start: m.index,
end: m.index+m[0].length
};
return number;
}
}
return null;
}
/**
* If the character before the cursor is a number, this functions changes its value by `amount`.
* @param {Number} amount The value to change the numeral by (can be negative to decrease value)
*
**/
modifyNumber(amount) {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
// get the char before the cursor
var charRange = new Range(row, column-1, row, column);
var c = this.session.getTextRange(charRange);
// if the char is a digit
if (!isNaN(parseFloat(c)) && isFinite(c)) {
// get the whole number the digit is part of
var nr = this.getNumberAt(row, column);
// if number found
if (nr) {
var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
var decimals = nr.start + nr.value.length - fp;
var t = parseFloat(nr.value);
t *= Math.pow(10, decimals);
if(fp !== nr.end && column < fp){
amount *= Math.pow(10, nr.end - column - 1);
} else {
amount *= Math.pow(10, nr.end - column);
}
t += amount;
t /= Math.pow(10, decimals);
var nnr = t.toFixed(decimals);
//update number
var replaceRange = new Range(row, nr.start, row, nr.end);
this.session.replace(replaceRange, nnr);
//reposition the cursor
this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
}
} else {
this.toggleWord();
}
}
toggleWord() {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
this.selection.selectWord();
var currentState = this.getSelectedText();
var currWordStart = this.selection.getWordRange().start.column;
var wordParts = currentState.replace(/([a-z]+|[A-Z]+)(?=[A-Z_]|$)/g, '$1 ').split(/\s/);
var delta = column - currWordStart - 1;
if (delta < 0) delta = 0;
var curLength = 0, itLength = 0;
var that = this;
if (currentState.match(/[A-Za-z0-9_]+/)) {
wordParts.forEach(function (item, i) {
itLength = curLength + item.length;
if (delta >= curLength && delta <= itLength) {
currentState = item;
that.selection.clearSelection();
that.moveCursorTo(row, curLength + currWordStart);
that.selection.selectTo(row, itLength + currWordStart);
}
curLength = itLength;
});
}
var wordPairs = this.$toggleWordPairs;
var reg;
for (var i = 0; i < wordPairs.length; i++) {
var item = wordPairs[i];
for (var j = 0; j <= 1; j++) {
var negate = +!j;
var firstCondition = currentState.match(new RegExp('^\\s?_?(' + lang.escapeRegExp(item[j]) + ')\\s?$', 'i'));
if (firstCondition) {
var secondCondition = currentState.match(new RegExp('([_]|^|\\s)(' + lang.escapeRegExp(firstCondition[1]) + ')($|\\s)', 'g'));
if (secondCondition) {
reg = currentState.replace(new RegExp(lang.escapeRegExp(item[j]), 'i'), function (result) {
var res = item[negate];
if (result.toUpperCase() == result) {
res = res.toUpperCase();
} else if (result.charAt(0).toUpperCase() == result.charAt(0)) {
res = res.substr(0, 0) + item[negate].charAt(0).toUpperCase() + res.substr(1);
}
return res;
});
this.insert(reg);
reg = "";
}
}
}
}
}
/**
* Finds link at defined {row} and {column}
* @returns {String}
**/
findLinkAt(row, column) {
var line = this.session.getLine(row);
var wordParts = line.split(/((?:https?|ftp):\/\/[\S]+)/);
var columnPosition = column;
if (columnPosition < 0) columnPosition = 0;
var previousPosition = 0, currentPosition = 0, match;
for (let item of wordParts) {
currentPosition = previousPosition + item.length;
if (columnPosition >= previousPosition && columnPosition <= currentPosition) {
if (item.match(/((?:https?|ftp):\/\/[\S]+)/)) {
match = item.replace(/[\s:.,'";}\]]+$/, "");
break;
}
}
previousPosition = currentPosition;
}
return match;
}
/**
* Open valid url under cursor in another tab
* @returns {Boolean}
**/
openLink() {
var cursor = this.selection.getCursor();
var url = this.findLinkAt(cursor.row, cursor.column);
if (url)
window.open(url, '_blank');
return url != null;
}
/**
* Removes all the lines in the current selection
* @related EditSession.remove
**/
removeLines() {
var rows = this.$getSelectedRows();
this.session.removeFullLines(rows.first, rows.last);
this.clearSelection();
}
duplicateSelection() {
var sel = this.selection;
var doc = this.session;
var range = sel.getRange();
var reverse = sel.isBackwards();
if (range.isEmpty()) {
var row = range.start.row;
doc.duplicateLines(row, row);
} else {
var point = reverse ? range.start : range.end;
var endPoint = doc.insert(point, doc.getTextRange(range), false);
range.start = point;
range.end = endPoint;
sel.setSelectionRange(range, reverse);
}
}
/**
* Shifts all the selected lines down one row.
*
* @returns {Number} On success, it returns -1.
* @related EditSession.moveLinesUp
**/
moveLinesDown() {
this.$moveLines(1, false);
}
/**
* Shifts all the selected lines up one row.
* @returns {Number} On success, it returns -1.
* @related EditSession.moveLinesDown
**/
moveLinesUp() {
this.$moveLines(-1, false);
}
/**
* Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this:
* ```json
* { row: newRowLocation, column: newColumnLocation }
* ```
* @param {Range} range The range of text you want moved within the document
* @param {Object} toPosition The location (row and column) where you want to move the text to
*
* @returns {Range} The new range where the text was moved to.
* @related EditSession.moveText
**/
moveText(range, toPosition, copy) {
return this.session.moveText(range, toPosition, copy);
}
/**
* Copies all the selected lines up one row.
* @returns {Number} On success, returns 0.
*
**/
copyLinesUp() {
this.$moveLines(-1, true);
}
/**
* Copies all the selected lines down one row.
* @returns {Number} On success, returns the number of new rows added; in other words, `lastRow - firstRow + 1`.
* @related EditSession.duplicateLines
*
**/
copyLinesDown() {
this.$moveLines(1, true);
}
/**
* for internal use
* @ignore
*
**/
$moveLines(dir, copy) {
var rows, moved;
var selection = this.selection;
if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
var range = selection.toOrientedRange();
rows = this.$getSelectedRows(range);
moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
if (copy && dir == -1) moved = 0;
range.moveBy(moved, 0);
selection.fromOrientedRange(range);
} else {
var ranges = selection.rangeList.ranges;
selection.rangeList.detach(this.session);
this.inVirtualSelectionMode = true;
var diff = 0;
var totalDiff = 0;
var l = ranges.length;
for (var i = 0; i < l; i++) {
var rangeIndex = i;
ranges[i].moveBy(diff, 0);
rows = this.$getSelectedRows(ranges[i]);
var first = rows.first;
var last = rows.last;
while (++i < l) {
if (totalDiff) ranges[i].moveBy(totalDiff, 0);
var subRows = this.$getSelectedRows(ranges[i]);
if (copy && subRows.first != last)
break;
else if (!copy && subRows.first > last + 1)
break;
last = subRows.last;
}
i--;
diff = this.session.$moveLines(first, last, copy ? 0 : dir);
if (copy && dir == -1) rangeIndex = i + 1;
while (rangeIndex <= i) {
ranges[rangeIndex].moveBy(diff, 0);
rangeIndex++;
}
if (!copy) diff = 0;
totalDiff += diff;
}
selection.fromOrientedRange(selection.ranges[0]);
selection.rangeList.attach(this.session);
this.inVirtualSelectionMode = false;
}
}
/**
* Returns an object indicating the currently selected rows. The object looks like this:
*
* ```json
* { first: range.start.row, last: range.end.row }
* ```
*
* @returns {Object}
**/
$getSelectedRows(range) {
range = (range || this.getSelectionRange()).collapseRows();
return {
first: this.session.getRowFoldStart(range.start.row),
last: this.session.getRowFoldEnd(range.end.row)
};
}
onCompositionStart(compositionState) {
this.renderer.showComposition(compositionState);
}
onCompositionUpdate(text) {
this.renderer.setCompositionText(text);
}
onCompositionEnd() {
this.renderer.hideComposition();
}
/**
* {:VirtualRenderer.getFirstVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getFirstVisibleRow
**/
getFirstVisibleRow() {
return this.renderer.getFirstVisibleRow();
}
/**
* {:VirtualRenderer.getLastVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getLastVisibleRow
**/
getLastVisibleRow() {
return this.renderer.getLastVisibleRow();
}
/**
* Indicates if the row is currently visible on the screen.
* @param {Number} row The row to check
*
* @returns {Boolean}
**/
isRowVisible(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
}
/**
* Indicates if the entire row is currently visible on the screen.
* @param {Number} row The row to check
*
*
* @returns {Boolean}
**/
isRowFullyVisible(row) {
return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
}
/**
* Returns the number of currently visible rows.
* @returns {Number}
**/
$getVisibleRowCount() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
}
$moveByPage(dir, select) {
var renderer = this.renderer;
var config = this.renderer.layerConfig;
var rows = dir * Math.floor(config.height / config.lineHeight);
if (select === true) {
this.selection.$moveSelection(function(){
this.moveCursorBy(rows, 0);
});
} else if (select === false) {
this.selection.moveCursorBy(rows, 0);
this.selection.clearSelection();
}
var scrollTop = renderer.scrollTop;
renderer.scrollBy(0, rows * config.lineHeight);
if (select != null)
renderer.scrollCursorIntoView(null, 0.5);
renderer.animateScrolling(scrollTop);
}
/**
* Selects the text from the current position of the document until where a "page down" finishes.
**/
selectPageDown() {
this.$moveByPage(1, true);
}
/**
* Selects the text from the current position of the document until where a "page up" finishes.
**/
selectPageUp() {
this.$moveByPage(-1, true);
}
/**
* Shifts the document to wherever "page down" is, as well as moving the cursor position.
**/
gotoPageDown() {
this.$moveByPage(1, false);
}
/**
* Shifts the document to wherever "page up" is, as well as moving the cursor position.
**/
gotoPageUp() {
this.$moveByPage(-1, false);
}
/**
* Scrolls the document to wherever "page down" is, without changing the cursor position.
**/
scrollPageDown() {
this.$moveByPage(1);
}
/**
* Scrolls the document to wherever "page up" is, without changing the cursor position.
**/
scrollPageUp() {
this.$moveByPage(-1);
}
/**
* Moves the editor to the specified row.
* @related VirtualRenderer.scrollToRow
**/
scrollToRow(row) {
this.renderer.scrollToRow(row);
}
/**
* Scrolls to a line. If `center` is `true`, it puts the line in middle of screen (or attempts to).
* @param {Number} line The line to scroll to
* @param {Boolean} center If `true`
* @param {Boolean} animate If `true` animates scrolling
* @param {Function} callback Function to be called when the animation has finished
*
*
* @related VirtualRenderer.scrollToLine
**/
scrollToLine(line, center, animate, callback) {
this.renderer.scrollToLine(line, center, animate, callback);
}
/**
* Attempts to center the current selection on the screen.
**/
centerSelection() {
var range = this.getSelectionRange();
var pos = {
row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
};
this.renderer.alignCursor(pos, 0.5);
}
/**
* Gets the current position of the cursor.
* @returns {Object} An object that looks something like this:
*
* ```json
* { row: currRow, column: currCol }
* ```
*
* @related Selection.getCursor
**/
getCursorPosition() {
return this.selection.getCursor();
}
/**
* Returns the screen position of the cursor.
* @returns {Position}
* @related EditSession.documentToScreenPosition
**/
getCursorPositionScreen() {
return this.session.documentToScreenPosition(this.getCursorPosition());
}
/**
* {:Selection.getRange}
* @returns {Range}
* @related Selection.getRange
**/
getSelectionRange() {
return this.selection.getRange();
}
/**
* Selects all the text in editor.
* @related Selection.selectAll
**/
selectAll() {
this.selection.selectAll();
}
/**
* {:Selection.clearSelection}
* @related Selection.clearSelection
**/
clearSelection() {
this.selection.clearSelection();
}
/**
* Moves the cursor to the specified row and column. Note that this does not de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
* @related Selection.moveCursorTo
**/
moveCursorTo(row, column) {
this.selection.moveCursorTo(row, column);
}
/**
* Moves the cursor to the position indicated by `pos.row` and `pos.column`.
* @param {Position} pos An object with two properties, row and column
* @related Selection.moveCursorToPosition
**/
moveCursorToPosition(pos) {
this.selection.moveCursorToPosition(pos);
}
/**
* Moves the cursor's row and column to the next matching bracket or HTML tag.
*
**/
jumpToMatching(select, expand) {
var cursor = this.getCursorPosition();
var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
var prevToken = iterator.getCurrentToken();
var tokenCount = 0;
if (prevToken && prevToken.type.indexOf('tag-name') !== -1) {
prevToken = iterator.stepBackward();
}
var token = prevToken || iterator.stepForward();
if (!token) return;
//get next closing tag or bracket
var matchType;
var found = false;
var depth = {};
var i = cursor.column - token.start;
var bracketType;
var brackets = {
")": "(",
"(": "(",
"]": "[",
"[": "[",
"{": "{",
"}": "{"
};
do {
if (token.value.match(/[{}()\[\]]/g)) {
for (; i < token.value.length && !found; i++) {
if (!brackets[token.value[i]]) {
continue;
}
bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
if (isNaN(depth[bracketType])) {
depth[bracketType] = 0;
}
switch (token.value[i]) {
case '(':
case '[':
case '{':
depth[bracketType]++;
break;
case ')':
case ']':
case '}':
depth[bracketType]--;
if (depth[bracketType] === -1) {
matchType = 'bracket';
found = true;
}
break;
}
}
}
else if (token.type.indexOf('tag-name') !== -1) {
if (isNaN(depth[token.value])) {
depth[token.value] = 0;
}
if (prevToken.value === '<' && tokenCount > 1) {
depth[token.value]++;
}
else if (prevToken.value === '') {
depth[token.value]--;
}
if (depth[token.value] === -1) {
matchType = 'tag';
found = true;
}
}
if (!found) {
prevToken = token;
tokenCount++;
token = iterator.stepForward();
i = 0;
}
} while (token && !found);
//no match found
if (!matchType) return;
var range, pos;
if (matchType === 'bracket') {
range = this.session.getBracketRange(cursor);
if (!range) {
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1
);
pos = range.start;
if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column)
< 2) range = this.session.getBracketRange(pos);
}
}
else if (matchType === 'tag') {
if (!token || token.type.indexOf('tag-name') === -1) return;
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2
);
//find matching tag
if (range.compare(cursor.row, cursor.column) === 0) {
var tagsRanges = this.session.getMatchingTags(cursor);
if (tagsRanges) {
if (tagsRanges.openTag.contains(cursor.row, cursor.column)) {
range = tagsRanges.closeTag;
pos = range.start;
}
else {
range = tagsRanges.openTag;
if (tagsRanges.closeTag.start.row === cursor.row && tagsRanges.closeTag.start.column
=== cursor.column) pos = range.end; else pos = range.start;
}
}
}
//we found it
pos = pos || range.start;
}
pos = range && range.cursor || pos;
if (pos) {
if (select) {
if (range && expand) {
this.selection.setRange(range);
}
else if (range && range.isEqual(this.getSelectionRange())) {
this.clearSelection();
}
else {
this.selection.selectTo(pos.row, pos.column);
}
}
else {
this.selection.moveTo(pos.row, pos.column);
}
}
}
/**
* Moves the cursor to the specified line number, and also into the indicated column.
* @param {Number} lineNumber The line number to go to
* @param {Number} column A column number to go to
* @param {Boolean} animate If `true` animates scolling
*
**/
gotoLine(lineNumber, column, animate) {
this.selection.clearSelection();
this.session.unfold({row: lineNumber - 1, column: column || 0});
// todo: find a way to automatically exit multiselect mode
this.exitMultiSelectMode && this.exitMultiSelectMode();
this.moveCursorTo(lineNumber - 1, column || 0);
if (!this.isRowFullyVisible(lineNumber - 1))
this.scrollToLine(lineNumber - 1, true, animate);
}
/**
* Moves the cursor to the specified row and column. Note that this does de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
*
*
* @related Editor.moveCursorTo
**/
navigateTo(row, column) {
this.selection.moveTo(row, column);
}
/**
* Moves the cursor up in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
navigateUp(times) {
if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
var selectionStart = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionStart);
}
this.selection.clearSelection();
this.selection.moveCursorBy(-times || -1, 0);
}
/**
* Moves the cursor down in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
navigateDown(times) {
if (this.selection.isMultiLine() && this.selection.isBackwards()) {
var selectionEnd = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionEnd);
}
this.selection.clearSelection();
this.selection.moveCursorBy(times || 1, 0);
}
/**
* Moves the cursor left in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
navigateLeft(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
}
/**
* Moves the cursor right in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} times The number of times to change navigation
*
*
**/
navigateRight(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
}
/**
*
* Moves the cursor to the start of the current line. Note that this does de-select the current selection.
**/
navigateLineStart() {
this.selection.moveCursorLineStart();
this.clearSelection();
}
/**
*
* Moves the cursor to the end of the current line. Note that this does de-select the current selection.
**/
navigateLineEnd() {
this.selection.moveCursorLineEnd();
this.clearSelection();
}
/**
*
* Moves the cursor to the end of the current file. Note that this does de-select the current selection.
**/
navigateFileEnd() {
this.selection.moveCursorFileEnd();
this.clearSelection();
}
/**
*
* Moves the cursor to the start of the current file. Note that this does de-select the current selection.
**/
navigateFileStart() {
this.selection.moveCursorFileStart();
this.clearSelection();
}
/**
*
* Moves the cursor to the word immediately to the right of the current position. Note that this does de-select the current selection.
**/
navigateWordRight() {
this.selection.moveCursorWordRight();
this.clearSelection();
}
/**
*
* Moves the cursor to the word immediately to the left of the current position. Note that this does de-select the current selection.
**/
navigateWordLeft() {
this.selection.moveCursorWordLeft();
this.clearSelection();
}
/**
* Replaces the first occurrence of `options.needle` with the value in `replacement`.
* @param {String} replacement The text to replace with
* @param {Object} options The [[Search `Search`]] options to use
*
*
**/
replace(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
var replaced = 0;
if (!range)
return replaced;
if (this.$tryReplace(range, replacement)) {
replaced = 1;
}
this.selection.setSelectionRange(range);
this.renderer.scrollSelectionIntoView(range.start, range.end);
return replaced;
}
/**
* Replaces all occurrences of `options.needle` with the value in `replacement`.
* @param {String} replacement The text to replace with
* @param {Object} options The [[Search `Search`]] options to use
*
*
**/
replaceAll(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
var replaced = 0;
if (!ranges.length)
return replaced;
var selection = this.getSelectionRange();
this.selection.moveTo(0, 0);
for (var i = ranges.length - 1; i >= 0; --i) {
if(this.$tryReplace(ranges[i], replacement)) {
replaced++;
}
}
this.selection.setSelectionRange(selection);
return replaced;
}
$tryReplace(range, replacement) {
var input = this.session.getTextRange(range);
replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
}
/**
* {:Search.getOptions} For more information on `options`, see [[Search `Search`]].
* @related Search.getOptions
* @returns {Object}
**/
getLastSearchOptions() {
return this.$search.getOptions();
}
/**
* Attempts to find `needle` within the document. For more information on `options`, see [[Search `Search`]].
* @param {String|RegExp|Object} needle The text to search for (optional)
* @param {Object} options An object defining various search properties
* @param {Boolean} animate If `true` animate scrolling
* @related Search.find
**/
find(needle, options, animate) {
if (!options)
options = {};
if (typeof needle == "string" || needle instanceof RegExp)
options.needle = needle;
else if (typeof needle == "object")
oop.mixin(options, needle);
var range = this.selection.getRange();
if (options.needle == null) {
needle = this.session.getTextRange(range)
|| this.$search.$options.needle;
if (!needle) {
range = this.session.getWordRange(range.start.row, range.start.column);
needle = this.session.getTextRange(range);
}
this.$search.set({needle: needle});
}
this.$search.set(options);
if (!options.start)
this.$search.set({start: range});
var newRange = this.$search.find(this.session);
if (options.preventScroll)
return newRange;
if (newRange) {
this.revealRange(newRange, animate);
return newRange;
}
// clear selection if nothing is found
if (options.backwards)
range.start = range.end;
else
range.end = range.start;
this.selection.setRange(range);
}
/**
* Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]].
* @param {Object} options search options
* @param {Boolean} animate If `true` animate scrolling
*
*
* @related Editor.find
**/
findNext(options, animate) {
this.find({skipCurrent: true, backwards: false}, options, animate);
}
/**
* Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]].
* @param {Object} options search options
* @param {Boolean} animate If `true` animate scrolling
*
*
* @related Editor.find
**/
findPrevious(options, animate) {
this.find(options, {skipCurrent: true, backwards: true}, animate);
}
revealRange(range, animate) {
this.session.unfold(range);
this.selection.setSelectionRange(range);
var scrollTop = this.renderer.scrollTop;
this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
if (animate !== false)
this.renderer.animateScrolling(scrollTop);
}
/**
* {:UndoManager.undo}
* @related UndoManager.undo
**/
undo() {
this.session.getUndoManager().undo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
}
/**
* {:UndoManager.redo}
* @related UndoManager.redo
**/
redo() {
this.session.getUndoManager().redo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
}
/**
*
* Cleans up the entire editor.
**/
destroy() {
if (this.$toDestroy) {
this.$toDestroy.forEach(function(el) {
el.destroy();
});
this.$toDestroy = null;
}
if (this.$mouseHandler)
this.$mouseHandler.destroy();
this.renderer.destroy();
this._signal("destroy", this);
if (this.session)
this.session.destroy();
if (this._$emitInputEvent)
this._$emitInputEvent.cancel();
this.removeAllListeners();
}
/**
* Enables automatic scrolling of the cursor into view when editor itself is inside scrollable element
* @param {Boolean} enable default true
**/
setAutoScrollEditorIntoView(enable) {
if (!enable)
return;
var rect;
var self = this;
var shouldScroll = false;
if (!this.$scrollAnchor)
this.$scrollAnchor = document.createElement("div");
var scrollAnchor = this.$scrollAnchor;
scrollAnchor.style.cssText = "position:absolute";
this.container.insertBefore(scrollAnchor, this.container.firstChild);
var onChangeSelection = this.on("changeSelection", function() {
shouldScroll = true;
});
// needed to not trigger sync reflow
var onBeforeRender = this.renderer.on("beforeRender", function() {
if (shouldScroll)
rect = self.renderer.container.getBoundingClientRect();
});
var onAfterRender = this.renderer.on("afterRender", function() {
if (shouldScroll && rect && (self.isFocused()
|| self.searchBox && self.searchBox.isFocused())
) {
var renderer = self.renderer;
var pos = renderer.$cursorLayer.$pixelPos;
var config = renderer.layerConfig;
var top = pos.top - config.offset;
if (pos.top >= 0 && top + rect.top < 0) {
shouldScroll = true;
} else if (pos.top < config.height &&
pos.top + rect.top + config.lineHeight > window.innerHeight) {
shouldScroll = false;
} else {
shouldScroll = null;
}
if (shouldScroll != null) {
scrollAnchor.style.top = top + "px";
scrollAnchor.style.left = pos.left + "px";
scrollAnchor.style.height = config.lineHeight + "px";
scrollAnchor.scrollIntoView(shouldScroll);
}
shouldScroll = rect = null;
}
});
this.setAutoScrollEditorIntoView = function(enable) {
if (enable)
return;
delete this.setAutoScrollEditorIntoView;
this.off("changeSelection", onChangeSelection);
this.renderer.off("afterRender", onAfterRender);
this.renderer.off("beforeRender", onBeforeRender);
};
}
$resetCursorStyle() {
var style = this.$cursorStyle || "ace";
var cursorLayer = this.renderer.$cursorLayer;
if (!cursorLayer)
return;
cursorLayer.setSmoothBlinking(/smooth/.test(style));
cursorLayer.isBlinking = !this.$readOnly && style != "wide";
dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
}
/**
* opens a prompt displaying message
**/
prompt(message, options, callback) {
var editor = this;
config.loadModule("ace/ext/prompt", function (module) {
module.prompt(editor, message, options, callback);
});
}
}
Editor.$uid = 0;
Editor.prototype.curOp = null;
Editor.prototype.prevOp = {};
// TODO use property on commands instead of this
Editor.prototype.$mergeableCommands = ["backspace", "del", "insertstring"];
Editor.prototype.$toggleWordPairs = [
["first", "last"],
["true", "false"],
["yes", "no"],
["width", "height"],
["top", "bottom"],
["right", "left"],
["on", "off"],
["x", "y"],
["get", "set"],
["max", "min"],
["horizontal", "vertical"],
["show", "hide"],
["add", "remove"],
["up", "down"],
["before", "after"],
["even", "odd"],
["in", "out"],
["inside", "outside"],
["next", "previous"],
["increase", "decrease"],
["attach", "detach"],
["&&", "||"],
["==", "!="]
];
oop.implement(Editor.prototype, EventEmitter);
config.defineOptions(Editor.prototype, "editor", {
selectionStyle: {
set: function(style) {
this.onSelectionChange();
this._signal("changeSelectionStyle", {data: style});
},
initialValue: "line"
},
highlightActiveLine: {
set: function() {this.$updateHighlightActiveLine();},
initialValue: true
},
highlightSelectedWord: {
set: function(shouldHighlight) {this.$onSelectionChange();},
initialValue: true
},
readOnly: {
set: function(readOnly) {
this.textInput.setReadOnly(readOnly);
this.$resetCursorStyle();
},
initialValue: false
},
copyWithEmptySelection: {
set: function(value) {
this.textInput.setCopyWithEmptySelection(value);
},
initialValue: false
},
cursorStyle: {
set: function(val) { this.$resetCursorStyle(); },
values: ["ace", "slim", "smooth", "wide"],
initialValue: "ace"
},
mergeUndoDeltas: {
values: [false, true, "always"],
initialValue: true
},
behavioursEnabled: {initialValue: true},
wrapBehavioursEnabled: {initialValue: true},
enableAutoIndent: {initialValue: true},
autoScrollEditorIntoView: {
set: function(val) {this.setAutoScrollEditorIntoView(val);}
},
keyboardHandler: {
set: function(val) { this.setKeyboardHandler(val); },
get: function() { return this.$keybindingId; },
handlesSet: true
},
value: {
set: function(val) { this.session.setValue(val); },
get: function() { return this.getValue(); },
handlesSet: true,
hidden: true
},
session: {
set: function(val) { this.setSession(val); },
get: function() { return this.session; },
handlesSet: true,
hidden: true
},
showLineNumbers: {
set: function(show) {
this.renderer.$gutterLayer.setShowLineNumbers(show);
this.renderer.$loop.schedule(this.renderer.CHANGE_GUTTER);
if (show && this.$relativeLineNumbers)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
},
initialValue: true
},
relativeLineNumbers: {
set: function(value) {
if (this.$showLineNumbers && value)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
}
},
placeholder: {
set: function(message) {
if (!this.$updatePlaceholder) {
this.$updatePlaceholder = function() {
var value = this.session && (this.renderer.$composition || this.getValue());
if (value && this.renderer.placeholderNode) {
this.renderer.off("afterRender", this.$updatePlaceholder);
dom.removeCssClass(this.container, "ace_hasPlaceholder");
this.renderer.placeholderNode.remove();
this.renderer.placeholderNode = null;
} else if (!value && !this.renderer.placeholderNode) {
this.renderer.on("afterRender", this.$updatePlaceholder);
dom.addCssClass(this.container, "ace_hasPlaceholder");
var el = dom.createElement("div");
el.className = "ace_placeholder";
el.textContent = this.$placeholder || "";
this.renderer.placeholderNode = el;
this.renderer.content.appendChild(this.renderer.placeholderNode);
} else if (!value && this.renderer.placeholderNode) {
this.renderer.placeholderNode.textContent = this.$placeholder || "";
}
}.bind(this);
this.on("input", this.$updatePlaceholder);
}
this.$updatePlaceholder();
}
},
enableKeyboardAccessibility: {
set: function(value) {
var blurCommand = {
name: "blurTextInput",
description: "Set focus to the editor content div to allow tabbing through the page",
bindKey: "Esc",
exec: function(editor) {
editor.blur();
editor.renderer.content.focus();
},
readOnly: true
};
var focusOnEnterKeyup = function (e) {
if (e.target == this.renderer.content && e.keyCode === keys['enter']){
e.stopPropagation();
e.preventDefault();
this.focus();
}
};
var keyboardFocusClassName = "ace_keyboard-focus";
// Prevent focus to be captured when tabbing through the page. When focus is set to the content div,
// press Enter key to give focus to Ace and press Esc to again allow to tab through the page.
if (value){
this.textInput.getElement().setAttribute("tabindex", -1);
this.renderer.content.setAttribute("tabindex", 0);
this.renderer.content.classList.add(keyboardFocusClassName);
this.renderer.content.setAttribute("aria-label",
"Editor, press Enter key to start editing, press Escape key to exit"
);
this.renderer.content.addEventListener("keyup", focusOnEnterKeyup.bind(this));
this.commands.addCommand(blurCommand);
} else {
this.textInput.getElement().setAttribute("tabindex", 0);
this.renderer.content.setAttribute("tabindex", -1);
this.renderer.content.classList.remove(keyboardFocusClassName);
this.renderer.content.setAttribute("aria-label", "");
this.renderer.content.removeEventListener("keyup", focusOnEnterKeyup.bind(this));
this.commands.removeCommand(blurCommand);
}
},
initialValue: false
},
customScrollbar: "renderer",
hScrollBarAlwaysVisible: "renderer",
vScrollBarAlwaysVisible: "renderer",
highlightGutterLine: "renderer",
animatedScroll: "renderer",
showInvisibles: "renderer",
showPrintMargin: "renderer",
printMarginColumn: "renderer",
printMargin: "renderer",
fadeFoldWidgets: "renderer",
showFoldWidgets: "renderer",
displayIndentGuides: "renderer",
highlightIndentGuides: "renderer",
showGutter: "renderer",
fontSize: "renderer",
fontFamily: "renderer",
maxLines: "renderer",
minLines: "renderer",
scrollPastEnd: "renderer",
fixedWidthGutter: "renderer",
theme: "renderer",
hasCssTransforms: "renderer",
maxPixelHeight: "renderer",
useTextareaForIME: "renderer",
useResizeObserver: "renderer",
useSvgGutterIcons: "renderer",
scrollSpeed: "$mouseHandler",
dragDelay: "$mouseHandler",
dragEnabled: "$mouseHandler",
focusTimeout: "$mouseHandler",
tooltipFollowsMouse: "$mouseHandler",
firstLineNumber: "session",
overwrite: "session",
newLineMode: "session",
useWorker: "session",
useSoftTabs: "session",
navigateWithinSoftTabs: "session",
tabSize: "session",
wrap: "session",
indentedSoftWrap: "session",
foldStyle: "session",
mode: "session"
});
var relativeNumberRenderer = {
getText: function(session, row) {
return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9 ? "\xb7" : ""))) + "";
},
getWidth: function(session, lastLineNumber, config) {
return Math.max(
lastLineNumber.toString().length,
(config.lastRow + 1).toString().length,
2
) * config.characterWidth;
},
update: function(e, editor) {
editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER);
},
attach: function(editor) {
editor.renderer.$gutterLayer.$renderer = this;
editor.on("changeSelection", this.update);
this.update(null, editor);
},
detach: function(editor) {
if (editor.renderer.$gutterLayer.$renderer == this)
editor.renderer.$gutterLayer.$renderer = null;
editor.off("changeSelection", this.update);
this.update(null, editor);
}
};
exports.Editor = Editor;
================================================
FILE: demo/diff/examples/editor.40.js
================================================
"use strict";
/**
* @typedef {import("./virtual_renderer").VirtualRenderer} VirtualRenderer
* @typedef {import("./selection").Selection} Selection
* @typedef {import("../ace-internal").Ace.Point} Point
* @typedef {import("../ace-internal").Ace.SearchOptions} SearchOptions
*/
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var lang = require("./lib/lang");
var useragent = require("./lib/useragent");
var TextInput = require("./keyboard/textinput").TextInput;
var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
var FoldHandler = require("./mouse/fold_handler").FoldHandler;
var KeyBinding = require("./keyboard/keybinding").KeyBinding;
var EditSession = require("./edit_session").EditSession;
var Search = require("./search").Search;
var Range = require("./range").Range;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var CommandManager = require("./commands/command_manager").CommandManager;
var defaultCommands = require("./commands/default_commands").commands;
var config = require("./config");
var TokenIterator = require("./token_iterator").TokenIterator;
var GutterKeyboardHandler = require("./keyboard/gutter_handler").GutterKeyboardHandler;
var nls = require("./config").nls;
var clipboard = require("./clipboard");
var keys = require('./lib/keys');
var event = require("./lib/event");
var HoverTooltip = require("./tooltip").HoverTooltip;
/**
* The main entry point into the Ace functionality.
*
* The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen.
*
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
class Editor {
/**
* Creates a new `Editor` object.
*
* @param {VirtualRenderer} renderer Associated `VirtualRenderer` that draws everything
* @param {EditSession} [session] The `EditSession` to refer to
* @param {Partial} [options] The default options
**/
constructor(renderer, session, options) {
/**@type{EditSession}*/this.session;
this.$toDestroy = [];
var container = renderer.getContainerElement();
/**@type {HTMLElement & {env?:any, value?:any}}*/
this.container = container;
/**@type {VirtualRenderer}*/
this.renderer = renderer;
/**@type {string}*/
this.id = "editor" + (++Editor.$uid);
this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
if (typeof document == "object") {
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.renderer.textarea = this.textInput.getElement();
// TODO detect touch event support
/**@type {MouseHandler}*/
this.$mouseHandler = new MouseHandler(this);
new FoldHandler(this);
}
/**@type {KeyBinding}*/
this.keyBinding = new KeyBinding(this);
/**@type {Search}*/
this.$search = new Search().set({
wrap: true
});
this.$historyTracker = this.$historyTracker.bind(this);
this.commands.on("exec", this.$historyTracker);
this.$initOperationListeners();
this._$emitInputEvent = lang.delayedCall(function() {
this._signal("input", {});
if (this.session && !this.session.destroyed)
this.session.bgTokenizer.scheduleStart();
}.bind(this));
this.on("change", function(_, _self) {
_self._$emitInputEvent.schedule(31);
});
this.setSession(session || options && options.session || new EditSession(""));
config.resetOptions(this);
if (options)
this.setOptions(options);
config._signal("editor", this);
}
$initOperationListeners() {
this.commands.on("exec", this.startOperation.bind(this), true);
this.commands.on("afterExec", this.endOperation.bind(this), true);
}
startOperation(commandEvent) {
this.session.startOperation(commandEvent);
}
/**
* @arg e
*/
endOperation(e) {
this.session.endOperation(e);
}
onStartOperation(commandEvent) {
this.curOp = this.session.curOp;
this.curOp.scrollTop = this.renderer.scrollTop;
this.prevOp = this.session.prevOp;
if (!commandEvent) {
this.previousCommand = null;
}
}
/**
* @arg e
*/
onEndOperation(e) {
if (this.curOp && this.session) {
if (e && e.returnValue === false) {
this.curOp = null;
return;
}
this._signal("beforeEndOperation");
if (!this.curOp) return;
var command = this.curOp.command;
var scrollIntoView = command && command.scrollIntoView;
if (scrollIntoView) {
switch (scrollIntoView) {
case "center-animate":
scrollIntoView = "animate";
/* fall through */
case "center":
this.renderer.scrollCursorIntoView(null, 0.5);
break;
case "animate":
case "cursor":
this.renderer.scrollCursorIntoView();
break;
case "selectionPart":
var range = this.selection.getRange();
var config = this.renderer.layerConfig;
if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
}
break;
default:
break;
}
if (scrollIntoView == "animate")
this.renderer.animateScrolling(this.curOp.scrollTop);
}
this.$lastSel = this.session.selection.toJSON();
this.prevOp = this.curOp;
this.curOp = null;
}
}
/**
* @param e
*/
$historyTracker(e) {
if (!this.$mergeUndoDeltas)
return;
var prev = this.prevOp;
var mergeableCommands = this.$mergeableCommands;
// previous command was the same
var shouldMerge = prev.command && (e.command.name == prev.command.name);
if (e.command.name == "insertstring") {
var text = e.args;
if (this.mergeNextCommand === undefined)
this.mergeNextCommand = true;
shouldMerge = shouldMerge
&& this.mergeNextCommand // previous command allows to coalesce with
&& (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
this.mergeNextCommand = true;
} else {
shouldMerge = shouldMerge
&& mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
}
if (
this.$mergeUndoDeltas != "always"
&& Date.now() - this.sequenceStartTime > 2000
) {
shouldMerge = false; // the sequence is too long
}
if (shouldMerge)
this.session.mergeUndoDeltas = true;
else if (mergeableCommands.indexOf(e.command.name) !== -1)
this.sequenceStartTime = Date.now();
}
/**
* Sets a new key handler, such as "vim" or "windows".
* @param {String | import("../ace-internal").Ace.KeyboardHandler | null} keyboardHandler The new key handler
* @param {() => void} [cb]
**/
setKeyboardHandler(keyboardHandler, cb) {
if (keyboardHandler && typeof keyboardHandler === "string" && keyboardHandler != "ace") {
this.$keybindingId = keyboardHandler;
var _self = this;
config.loadModule(["keybinding", keyboardHandler], function(module) {
if (_self.$keybindingId == keyboardHandler)
_self.keyBinding.setKeyboardHandler(module && module.handler);
cb && cb();
});
} else {
this.$keybindingId = null;
// @ts-ignore
this.keyBinding.setKeyboardHandler(keyboardHandler);
cb && cb();
}
}
/**
* Returns the keyboard handler, such as "vim" or "windows".
* @returns {Object}
**/
getKeyboardHandler() {
return this.keyBinding.getKeyboardHandler();
}
/**
* Sets a new editsession to use. This method also emits the `'changeSession'` event.
* @param {EditSession} [session] The new session to use
**/
setSession(session) {
if (this.session == session)
return;
// make sure operationEnd events are not emitted to wrong session
if (this.curOp) this.endOperation();
this.curOp = {};
var oldSession = this.session;
if (oldSession) {
this.session.off("change", this.$onDocumentChange);
this.session.off("changeMode", this.$onChangeMode);
this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.off("changeTabSize", this.$onChangeTabSize);
this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
this.session.off("changeWrapMode", this.$onChangeWrapMode);
this.session.off("changeFold", this.$onChangeFold);
this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
this.session.off("changeBackMarker", this.$onChangeBackMarker);
this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
this.session.off("changeAnnotation", this.$onChangeAnnotation);
this.session.off("changeOverwrite", this.$onCursorChange);
this.session.off("changeScrollTop", this.$onScrollTopChange);
this.session.off("changeScrollLeft", this.$onScrollLeftChange);
this.session.off("startOperation", this.$onStartOperation);
this.session.off("endOperation", this.$onEndOperation);
var selection = this.session.getSelection();
selection.off("changeCursor", this.$onCursorChange);
selection.off("changeSelection", this.$onSelectionChange);
}
this.session = session;
if (session) {
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.on("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.on("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.on("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
session.on("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.on("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.on("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.on("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.on("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.on("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.on("changeOverwrite", this.$onCursorChange);
this.$onScrollTopChange = this.onScrollTopChange.bind(this);
this.session.on("changeScrollTop", this.$onScrollTopChange);
this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
this.session.on("changeScrollLeft", this.$onScrollLeftChange);
this.selection = session.getSelection();
this.selection.on("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.on("changeSelection", this.$onSelectionChange);
this.$onStartOperation = this.onStartOperation.bind(this);
this.session.on("startOperation", this.$onStartOperation);
this.$onEndOperation = this.onEndOperation.bind(this);
this.session.on("endOperation", this.$onEndOperation);
this.onChangeMode();
this.onCursorChange();
this.onScrollTopChange();
this.onScrollLeftChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.updateFull();
} else {
this.selection = null;
this.renderer.setSession(session);
}
this._signal("changeSession", {
session: session,
oldSession: oldSession
});
this.curOp = null;
oldSession && oldSession._signal("changeEditor", {oldEditor: this});
if (oldSession) oldSession.$editor = null;
session && session._signal("changeEditor", {editor: this});
if (session) session.$editor = this;
if (session && !session.destroyed)
session.bgTokenizer.scheduleStart();
}
/**
* Returns the current session being used.
* @returns {EditSession}
**/
getSession() {
return this.session;
}
/**
* Sets the current document to `val`.
* @param {String} val The new value to set for the document
* @param {Number} [cursorPos] Where to set the new value. `undefined` or 0 is selectAll, -1 is at the document start, and 1 is at the end
*
* @returns {String} The current document value
* @related Document.setValue
**/
setValue(val, cursorPos) {
this.session.doc.setValue(val);
if (!cursorPos)
this.selectAll();
else if (cursorPos == 1)
this.navigateFileEnd();
else if (cursorPos == -1)
this.navigateFileStart();
return val;
}
/**
* Returns the current session's content.
*
* @returns {String}
* @related EditSession.getValue
**/
getValue() {
return this.session.getValue();
}
/**
*
* Returns the currently highlighted selection.
* @returns {Selection} The selection object
**/
getSelection() {
return this.selection;
}
/**
* {:VirtualRenderer.onResize}
* @param {Boolean} [force] If `true`, recomputes the size, even if the height and width haven't changed
* @related VirtualRenderer.onResize
**/
resize(force) {
this.renderer.onResize(force);
}
/**
* {:VirtualRenderer.setTheme}
* @param {string | import("../ace-internal").Ace.Theme} theme The path to a theme
* @param {() => void} [cb] optional callback called when theme is loaded
**/
setTheme(theme, cb) {
this.renderer.setTheme(theme, cb);
}
/**
* {:VirtualRenderer.getTheme}
*
* @returns {String} The set theme
* @related VirtualRenderer.getTheme
**/
getTheme() {
return this.renderer.getTheme();
}
/**
* {:VirtualRenderer.setStyle}
* @param {String} style A class name
* @related VirtualRenderer.setStyle
**/
setStyle(style) {
this.renderer.setStyle(style);
}
/**
* {:VirtualRenderer.unsetStyle}
* @related VirtualRenderer.unsetStyle
* @param {string} style
*/
unsetStyle(style) {
this.renderer.unsetStyle(style);
}
/**
* Gets the current font size of the editor text.
* @return {string | number}
*/
getFontSize() {
return this.getOption("fontSize") ||
dom.computedStyle(this.container).fontSize;
}
/**
* Set a new font size (in pixels) for the editor text.
* @param {String | number} size A font size ( _e.g._ "12px")
**/
setFontSize(size) {
this.setOption("fontSize", size);
}
$highlightBrackets() {
if (this.$highlightPending) {
return;
}
// perform highlight async to not block the browser during navigation
var self = this;
this.$highlightPending = true;
setTimeout(function () {
self.$highlightPending = false;
var session = self.session;
if (!session || session.destroyed) return;
if (session.$bracketHighlight) {
session.$bracketHighlight.markerIds.forEach(function(id) {
session.removeMarker(id);
});
session.$bracketHighlight = null;
}
var pos = self.getCursorPosition();
var handler = self.getKeyboardHandler();
var isBackwards = handler && handler.$getDirectionForHighlight && handler.$getDirectionForHighlight(self);
var ranges = session.getMatchingBracketRanges(pos, isBackwards);
if (!ranges) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
if (token && /\b(?:tag-open|tag-name)/.test(token.type)) {
var tagNamesRanges = session.getMatchingTags(pos);
if (tagNamesRanges) {
ranges = [
tagNamesRanges.openTagName.isEmpty() ? tagNamesRanges.openTag : tagNamesRanges.openTagName,
tagNamesRanges.closeTagName.isEmpty() ? tagNamesRanges.closeTag : tagNamesRanges.closeTagName
];
}
}
}
if (!ranges && session.$mode.getMatching)
ranges = session.$mode.getMatching(self.session);
if (!ranges) {
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
return;
}
var markerType = "ace_bracket";
if (!Array.isArray(ranges)) {
ranges = [ranges];
} else if (ranges.length == 1) {
markerType = "ace_error_bracket";
}
// show adjacent ranges as one
if (ranges.length == 2) {
if (Range.comparePoints(ranges[0].end, ranges[1].start) == 0)
ranges = [Range.fromPoints(ranges[0].start, ranges[1].end)];
else if (Range.comparePoints(ranges[0].start, ranges[1].end) == 0)
ranges = [Range.fromPoints(ranges[1].start, ranges[0].end)];
}
session.$bracketHighlight = {
ranges: ranges,
markerIds: ranges.map(function(range) {
return session.addMarker(range, markerType, "text");
})
};
if (self.getHighlightIndentGuides()) self.renderer.$textLayer.$highlightIndentGuide();
}, 50);
}
/**
*
* Brings the current `textInput` into focus.
**/
focus() {
this.textInput.focus();
}
/**
* Returns `true` if the current `textInput` is in focus.
* @return {Boolean}
**/
isFocused() {
return this.textInput.isFocused();
}
/**
*
* Blurs the current `textInput`.
**/
blur() {
this.textInput.blur();
}
/**
* Emitted once the editor comes into focus.
* @internal
**/
onFocus(e) {
if (this.$isFocused)
return;
this.$isFocused = true;
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._emit("focus", e);
}
/**
* Emitted once the editor has been blurred.
* @internal
**/
onBlur(e) {
if (!this.$isFocused)
return;
this.$isFocused = false;
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._emit("blur", e);
}
/**
*/
$cursorChange() {
this.renderer.updateCursor();
this.$highlightBrackets();
this.$updateHighlightActiveLine();
}
/**
* Emitted whenever the document is changed.
* @param {import("../ace-internal").Ace.Delta} delta Contains a single property, `data`, which has the delta of changes
* @internal
**/
onDocumentChange(delta) {
// Rerender and emit "change" event.
var wrap = this.session.$useWrapMode;
var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
this.renderer.updateLines(delta.start.row, lastRow, wrap);
this._signal("change", delta);
// Update cursor because tab characters can influence the cursor position.
this.$cursorChange();
}
/**
* @internal
*/
onTokenizerUpdate(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
}
/**
* @internal
*/
onScrollTopChange() {
this.renderer.scrollToY(this.session.getScrollTop());
}
/**
* @internal
*/
onScrollLeftChange() {
this.renderer.scrollToX(this.session.getScrollLeft());
}
/**
* Emitted when the selection changes.
* @internal
**/
onCursorChange() {
this.$cursorChange();
this._signal("changeSelection");
}
/**
*/
$updateHighlightActiveLine() {
var session = this.getSession();
/**@type {Point|false}*/
var highlight;
if (this.$highlightActiveLine) {
if (this.$selectionStyle != "line" || !this.selection.isMultiLine())
highlight = this.getCursorPosition();
if (this.renderer.theme && this.renderer.theme.$selectionColorConflict && !this.selection.isEmpty())
highlight = false;
if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
highlight = false;
}
if (session.$highlightLineMarker && !highlight) {
session.removeMarker(session.$highlightLineMarker.id);
session.$highlightLineMarker = null;
} else if (!session.$highlightLineMarker && highlight) {
var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
range.id = session.addMarker(range, "ace_active-line", "screenLine");
session.$highlightLineMarker = range;
} else if (highlight) {
session.$highlightLineMarker.start.row = highlight.row;
session.$highlightLineMarker.end.row = highlight.row;
session.$highlightLineMarker.start.column = highlight.column;
session._signal("changeBackMarker");
}
}
/**
* @param e
* @internal
*/
onSelectionChange(e) {
var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
this.session.highlight(re);
this._signal("changeSelection");
}
$getSelectionHighLightRegexp() {
var session = this.session;
var selection = this.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startColumn = selection.start.column;
var endColumn = selection.end.column;
var line = session.getLine(selection.start.row);
var needle = line.substring(startColumn, endColumn);
// maximum allowed size for regular expressions in 32000,
// but getting close to it has significant impact on the performance
if (needle.length > 5000 || !/[\w\d]/.test(needle))
return;
var re = this.$search.$assembleRegExp({
wholeWord: true,
caseSensitive: true,
needle: needle
});
var wordWithBoundary = line.substring(startColumn - 1, endColumn + 1);
if (!re.test(wordWithBoundary))
return;
return re;
}
/**
* @internal
*/
onChangeFrontMarker() {
this.renderer.updateFrontMarkers();
}
/**
* @internal
*/
onChangeBackMarker() {
this.renderer.updateBackMarkers();
}
/**
* @internal
*/
onChangeBreakpoint() {
this.renderer.updateBreakpoints();
}
/**
* @internal
*/
onChangeAnnotation() {
this.renderer.setAnnotations(this.session.getAnnotations());
}
/**
* @param e
* @internal
*/
onChangeMode (e) {
this.renderer.updateText();
this._emit("changeMode", e);
}
/**
* @internal
*/
onChangeWrapLimit() {
this.renderer.updateFull();
}
/**
* @internal
*/
onChangeWrapMode() {
this.renderer.onResize(true);
}
/**
* @internal
*/
onChangeFold() {
// Update the active line marker as due to folding changes the current
// line range on the screen might have changed.
this.$updateHighlightActiveLine();
// TODO: This might be too much updating. Okay for now.
this.renderer.updateFull();
}
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
getSelectedText() {
return this.session.getTextRange(this.getSelectionRange());
}
/**
* Returns the string of text currently highlighted.
* @returns {String}
**/
getCopyText () {
var text = this.getSelectedText();
var nl = this.session.doc.getNewLineCharacter();
var copyLine= false;
if (!text && this.$copyWithEmptySelection) {
copyLine = true;
var ranges = this.selection.getAllRanges();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (i && ranges[i - 1].start.row == range.start.row)
continue;
text += this.session.getLine(range.start.row) + nl;
}
}
var e = {text: text};
this._signal("copy", e);
clipboard.lineMode = copyLine ? e.text : false;
return e.text;
}
/**
* Called whenever a text "copy" happens.
* @internal
**/
onCopy() {
this.commands.exec("copy", this);
}
/**
* Called whenever a text "cut" happens.
* @internal
**/
onCut() {
this.commands.exec("cut", this);
}
/**
* Called whenever a text "paste" happens.
* @param {String} text The pasted text
* @param {ClipboardEvent} [event]
* @internal
**/
onPaste(text, event) {
var e = {text: text, event: event};
this.commands.exec("paste", this, e);
}
/**
*
* @param {string | {text: string, event?: ClipboardEvent}} e
* @returns {boolean}
*/
$handlePaste(e) {
if (typeof e == "string")
e = {text: e};
this._signal("paste", e);
var text = e.text;
var lineMode = text === clipboard.lineMode;
var session = this.session;
if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
if (lineMode)
session.insert({ row: this.selection.lead.row, column: 0 }, text);
else
this.insert(text);
} else if (lineMode) {
this.selection.rangeList.ranges.forEach(function(range) {
session.insert({ row: range.start.row, column: 0 }, text);
});
} else {
var lines = text.split(/\r\n|\r|\n/);
var ranges = this.selection.rangeList.ranges;
var isFullLine = lines.length == 2 && (!lines[0] || !lines[1]);
if (lines.length != ranges.length || isFullLine)
return this.commands.exec("insertstring", this, text);
for (var i = ranges.length; i--;) {
var range = ranges[i];
if (!range.isEmpty())
session.remove(range);
session.insert(range.start, lines[i]);
}
}
}
/**
*
* @param {string | string[]} command
* @param [args]
* @return {boolean}
*/
execCommand(command, args) {
return this.commands.exec(command, this, args);
}
/**
* Inserts `text` into wherever the cursor is pointing.
* @param {String} text The new text to add
* @param {boolean} [pasted]
**/
insert(text, pasted) {
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled() && !pasted) {
// Get a transform if the current mode wants one.
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform) {
if (text !== transform.text) {
// keep automatic insertion in a separate delta, unless it is in multiselect mode
if (!this.inVirtualSelectionMode) {
this.session.mergeUndoDeltas = false;
this.mergeNextCommand = false;
}
}
text = transform.text;
}
}
if (text == "\t")
text = this.session.getTabString();
// remove selected text
if (!this.selection.isEmpty()) {
var range = this.getSelectionRange();
cursor = this.session.remove(range);
this.clearSelection();
}
else if (this.session.getOverwrite() && text.indexOf("\n") == -1) {
var range = Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
if (text == "\n" || text == "\r\n") {
var line = session.getLine(cursor.row);
if (cursor.column > line.search(/\S|$/)) {
var d = line.substr(cursor.column).search(/\S|$/);
session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
}
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var line = session.getLine(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, line, text);
session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
if (this.$enableAutoIndent) {
if (session.getDocument().isNewLine(text)) {
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
session.insert({row: cursor.row+1, column: 0}, lineIndent);
}
if (shouldOutdent)
mode.autoOutdent(lineState, session, cursor.row);
}
}
autoIndent() {
var session = this.session;
var mode = session.getMode();
var ranges = this.selection.isEmpty()
? [new Range(0, 0, session.doc.getLength() - 1, 0)]
: this.selection.getAllRanges();
/**@type{string|string[]}*/
var prevLineState = "";
var prevLine = "";
var lineIndent = "";
var tab = session.getTabString();
for (var i = 0; i < ranges.length; i++) {
var startRow = ranges[i].start.row;
var endRow = ranges[i].end.row;
for (var row = startRow; row <= endRow; row++) {
if (row > 0) {
prevLineState = session.getState(row - 1);
prevLine = session.getLine(row - 1);
lineIndent = mode.getNextLineIndent(prevLineState, prevLine, tab);
}
var line = session.getLine(row);
var currIndent = mode.$getIndent(line);
if (lineIndent !== currIndent) {
if (currIndent.length > 0) {
var range = new Range(row, 0, row, currIndent.length);
session.remove(range);
}
if (lineIndent.length > 0) {
session.insert({row: row, column: 0}, lineIndent);
}
}
mode.autoOutdent(prevLineState, session, row);
}
}
}
/**
*
* @param text
* @param composition
* @returns {*}
* @internal
*/
onTextInput(text, composition) {
if (!composition)
return this.keyBinding.onTextInput(text);
this.startOperation({command: { name: "insertstring" }});
var applyComposition = this.applyComposition.bind(this, text, composition);
if (this.selection.rangeCount)
this.forEachSelection(applyComposition);
else
applyComposition();
this.endOperation();
}
/**
* @param {string} [text]
* @param {any} [composition]
*/
applyComposition(text, composition) {
if (composition.extendLeft || composition.extendRight) {
var r = this.selection.getRange();
r.start.column -= composition.extendLeft;
r.end.column += composition.extendRight;
if (r.start.column < 0) {
r.start.row--;
r.start.column += this.session.getLine(r.start.row).length + 1;
}
this.selection.setRange(r);
if (!text && !r.isEmpty())
this.remove();
}
if (text || !this.selection.isEmpty())
this.insert(text, true);
if (composition.restoreStart || composition.restoreEnd) {
var r = this.selection.getRange();
r.start.column -= composition.restoreStart;
r.end.column -= composition.restoreEnd;
this.selection.setRange(r);
}
}
/**
* @internal
*/
onCommandKey(e, hashId, keyCode) {
return this.keyBinding.onCommandKey(e, hashId, keyCode);
}
/**
* Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emits the `changeOverwrite` event.
* @param {Boolean} overwrite Defines whether or not to set overwrites
* @related EditSession.setOverwrite
**/
setOverwrite(overwrite) {
this.session.setOverwrite(overwrite);
}
/**
* Returns `true` if overwrites are enabled; `false` otherwise.
* @returns {Boolean}
* @related EditSession.getOverwrite
**/
getOverwrite() {
return this.session.getOverwrite();
}
/**
* Sets the value of overwrite to the opposite of whatever it currently is.
* @related EditSession.toggleOverwrite
**/
toggleOverwrite() {
this.session.toggleOverwrite();
}
/**
* Sets how fast the mouse scrolling should do.
* @param {Number} speed A value indicating the new speed (in milliseconds)
**/
setScrollSpeed(speed) {
this.setOption("scrollSpeed", speed);
}
/**
* Returns the value indicating how fast the mouse scroll speed is (in milliseconds).
* @returns {Number}
**/
getScrollSpeed() {
return this.getOption("scrollSpeed");
}
/**
* Sets the delay (in milliseconds) of the mouse drag.
* @param {Number} dragDelay A value indicating the new delay
**/
setDragDelay(dragDelay) {
this.setOption("dragDelay", dragDelay);
}
/**
* Returns the current mouse drag delay.
* @returns {Number}
**/
getDragDelay() {
return this.getOption("dragDelay");
}
/**
* Draw selection markers spanning whole line, or only over selected text. Default value is "line"
* @param {"fullLine" | "screenLine" | "text" | "line"} val The new selection style "line"|"text"
**/
setSelectionStyle(val) {
this.setOption("selectionStyle", val);
}
/**
* Returns the current selection style.
* @returns {import("../ace-internal").Ace.EditorOptions["selectionStyle"]}
**/
getSelectionStyle() {
return this.getOption("selectionStyle");
}
/**
* Determines whether or not the current line should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the current line
**/
setHighlightActiveLine(shouldHighlight) {
this.setOption("highlightActiveLine", shouldHighlight);
}
/**
* Returns `true` if current lines are always highlighted.
* @return {Boolean}
**/
getHighlightActiveLine() {
return this.getOption("highlightActiveLine");
}
/**
* @param {boolean} shouldHighlight
*/
setHighlightGutterLine(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
}
/**
* @returns {Boolean}
*/
getHighlightGutterLine() {
return this.getOption("highlightGutterLine");
}
/**
* Determines if the currently selected word should be highlighted.
* @param {Boolean} shouldHighlight Set to `true` to highlight the currently selected word
**/
setHighlightSelectedWord(shouldHighlight) {
this.setOption("highlightSelectedWord", shouldHighlight);
}
/**
* Returns `true` if currently highlighted words are to be highlighted.
* @returns {Boolean}
**/
getHighlightSelectedWord() {
return this.$highlightSelectedWord;
}
/**
* @param {boolean} shouldAnimate
*/
setAnimatedScroll(shouldAnimate){
this.renderer.setAnimatedScroll(shouldAnimate);
}
/**
* @return {boolean}
*/
getAnimatedScroll(){
return this.renderer.getAnimatedScroll();
}
/**
* If `showInvisibles` is set to `true`, invisible characters—like spaces or new lines—are show in the editor.
* @param {Boolean} showInvisibles Specifies whether or not to show invisible characters
**/
setShowInvisibles(showInvisibles) {
this.renderer.setShowInvisibles(showInvisibles);
}
/**
* Returns `true` if invisible characters are being shown.
* @returns {Boolean}
**/
getShowInvisibles() {
return this.renderer.getShowInvisibles();
}
/**
* @param {boolean} display
*/
setDisplayIndentGuides(display) {
this.renderer.setDisplayIndentGuides(display);
}
/**
* @return {boolean}
*/
getDisplayIndentGuides() {
return this.renderer.getDisplayIndentGuides();
}
/**
* @param {boolean} highlight
*/
setHighlightIndentGuides(highlight) {
this.renderer.setHighlightIndentGuides(highlight);
}
/**
* @return {boolean}
*/
getHighlightIndentGuides() {
return this.renderer.getHighlightIndentGuides();
}
/**
* If `showPrintMargin` is set to `true`, the print margin is shown in the editor.
* @param {Boolean} showPrintMargin Specifies whether or not to show the print margin
*
**/
setShowPrintMargin(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
}
/**
* Returns `true` if the print margin is being shown.
* @returns {Boolean}
**/
getShowPrintMargin() {
return this.renderer.getShowPrintMargin();
}
/**
* Sets the column defining where the print margin should be.
* @param {Number} showPrintMargin Specifies the new print margin
*
**/
setPrintMarginColumn(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
}
/**
* Returns the column number of where the print margin is.
* @returns {Number}
**/
getPrintMarginColumn() {
return this.renderer.getPrintMarginColumn();
}
/**
* If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change.
* @param {Boolean} readOnly Specifies whether the editor can be modified or not
**/
setReadOnly(readOnly) {
this.setOption("readOnly", readOnly);
}
/**
* Returns `true` if the editor is set to read-only mode.
* @returns {Boolean}
**/
getReadOnly() {
return this.getOption("readOnly");
}
/**
* Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef}
* @param {Boolean} enabled Enables or disables behaviors
**/
setBehavioursEnabled(enabled) {
this.setOption("behavioursEnabled", enabled);
}
/**
* Returns `true` if the behaviors are currently enabled. {:BehaviorsDef}
* @returns {Boolean}
**/
getBehavioursEnabled() {
return this.getOption("behavioursEnabled");
}
/**
* Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets
* when such a character is typed in.
* @param {Boolean} enabled Enables or disables wrapping behaviors
**/
setWrapBehavioursEnabled(enabled) {
this.setOption("wrapBehavioursEnabled", enabled);
}
/**
* Returns `true` if the wrapping behaviors are currently enabled.
* @returns {boolean}
**/
getWrapBehavioursEnabled() {
return this.getOption("wrapBehavioursEnabled");
}
/**
* Indicates whether the fold widgets should be shown or not.
* @param {Boolean} show Specifies whether the fold widgets are shown
**/
setShowFoldWidgets(show) {
this.setOption("showFoldWidgets", show);
}
/**
* Returns `true` if the fold widgets are shown.
* @return {Boolean}
**/
getShowFoldWidgets() {
return this.getOption("showFoldWidgets");
}
/**
* @param {boolean} fade
*/
setFadeFoldWidgets(fade) {
this.setOption("fadeFoldWidgets", fade);
}
/**
* @returns {boolean}
*/
getFadeFoldWidgets() {
return this.getOption("fadeFoldWidgets");
}
/**
* Removes the current selection or one character.
* @param {'left' | 'right'} [dir] The direction of the deletion to occur, either "left" or "right"
**/
remove(dir) {
if (this.selection.isEmpty()){
if (dir == "left")
this.selection.selectLeft();
else
this.selection.selectRight();
}
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (range.end.column === 0) {
var text = session.getTextRange(range);
if (text[text.length - 1] == "\n") {
var line = session.getLine(range.end.row);
if (/^\s+$/.test(line)) {
range.end.column = line.length;
}
}
}
if (new_range)
// @ts-expect-error TODO: possible bug, new_range could be not a Range
range = new_range;
}
this.session.remove(range);
this.clearSelection();
}
/**
* Removes the word directly to the right of the current selection.
**/
removeWordRight() {
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes the word directly to the left of the current selection.
**/
removeWordLeft() {
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes all the words to the left of the current selection, until the start of the line.
**/
removeToLineStart() {
if (this.selection.isEmpty())
this.selection.selectLineStart();
if (this.selection.isEmpty())
this.selection.selectLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
/**
* Removes all the words to the right of the current selection, until the end of the line.
**/
removeToLineEnd() {
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
}
/**
* Splits the line at the current selection (by inserting an `'\n'`).
**/
splitLine() {
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
}
/**
* Set the "ghost" text in provided position. "Ghost" text is a kind of
* preview text inside the editor which can be used to preview some code
* inline in the editor such as, for example, code completions.
*
* @param {String} text Text to be inserted as "ghost" text
* @param {Point} [position] Position to insert text to
*/
setGhostText(text, position) {
this.renderer.setGhostText(text, position);
}
/**
* Removes "ghost" text currently displayed in the editor.
*/
removeGhostText() {
this.renderer.removeGhostText();
}
/**
* Transposes current line.
**/
transposeLetters() {
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column === 0)
return;
var line = this.session.getLine(cursor.row);
var swap, range;
if (column < line.length) {
swap = line.charAt(column) + line.charAt(column-1);
range = new Range(cursor.row, column-1, cursor.row, column+1);
}
else {
swap = line.charAt(column-1) + line.charAt(column-2);
range = new Range(cursor.row, column-2, cursor.row, column);
}
this.session.replace(range, swap);
this.session.selection.moveToPosition(range.end);
}
/**
* Converts the current selection entirely into lowercase.
**/
toLowerCase() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toLowerCase());
this.selection.setSelectionRange(originalRange);
}
/**
* Converts the current selection entirely into uppercase.
**/
toUpperCase() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toUpperCase());
this.selection.setSelectionRange(originalRange);
}
/**
* Inserts an indentation into the current cursor position or indents the selected lines.
*
* @related EditSession.indentRows
**/
indent() {
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
} else if (range.start.column < range.end.column) {
var text = session.getTextRange(range);
if (!/^\s+$/.test(text)) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
}
}
var line = session.getLine(range.start.row);
var position = range.start;
var size = session.getTabSize();
var column = session.documentToScreenColumn(position.row, position.column);
if (this.session.getUseSoftTabs()) {
var count = (size - column % size);
var indentString = lang.stringRepeat(" ", count);
} else {
var count = column % size;
while (line[range.start.column - 1] == " " && count) {
range.start.column--;
count--;
}
this.selection.setSelectionRange(range);
indentString = "\t";
}
return this.insert(indentString);
}
/**
* Indents the current line.
* @related EditSession.indentRows
**/
blockIndent() {
var rows = this.$getSelectedRows();
this.session.indentRows(rows.first, rows.last, "\t");
}
/**
* Outdents the current line.
* @related EditSession.outdentRows
**/
blockOutdent() {
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
}
// TODO: move out of core when we have good mechanism for managing extensions
sortLines() {
var rows = this.$getSelectedRows();
var session = this.session;
var lines = [];
for (var i = rows.first; i <= rows.last; i++)
lines.push(session.getLine(i));
lines.sort(function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
var deleteRange = new Range(0, 0, 0, 0);
for (var i = rows.first; i <= rows.last; i++) {
var line = session.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = line.length;
session.replace(deleteRange, lines[i-rows.first]);
}
}
/**
* Given the currently selected range, this function either comments all the lines, or uncomments all of them.
**/
toggleCommentLines() {
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows();
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
}
toggleBlockComment() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
}
/**
* Works like [[EditSession.getTokenAt]], except it returns a number.
* @returns {any}
**/
getNumberAt(row, column) {
var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
_numberRx.lastIndex = 0;
var s = this.session.getLine(row);
while (_numberRx.lastIndex < column) {
var m = _numberRx.exec(s);
if(m.index <= column && m.index+m[0].length >= column){
var number = {
value: m[0],
start: m.index,
end: m.index+m[0].length
};
return number;
}
}
return null;
}
/**
* If the character before the cursor is a number, this functions changes its value by `amount`.
* @param {Number} amount The value to change the numeral by (can be negative to decrease value)
**/
modifyNumber(amount) {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
// get the char before the cursor
var charRange = new Range(row, column-1, row, column);
var c = this.session.getTextRange(charRange);
// if the char is a digit
// @ts-ignore
if (!isNaN(parseFloat(c)) && isFinite(c)) {
// get the whole number the digit is part of
var nr = this.getNumberAt(row, column);
// if number found
if (nr) {
var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
var decimals = nr.start + nr.value.length - fp;
var t = parseFloat(nr.value);
t *= Math.pow(10, decimals);
if(fp !== nr.end && column < fp){
amount *= Math.pow(10, nr.end - column - 1);
} else {
amount *= Math.pow(10, nr.end - column);
}
t += amount;
t /= Math.pow(10, decimals);
var nnr = t.toFixed(decimals);
//update number
var replaceRange = new Range(row, nr.start, row, nr.end);
this.session.replace(replaceRange, nnr);
//reposition the cursor
this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
}
} else {
this.toggleWord();
}
}
/**
*/
toggleWord() {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
this.selection.selectWord();
var currentState = this.getSelectedText();
var currWordStart = this.selection.getWordRange().start.column;
var wordParts = currentState.replace(/([a-z]+|[A-Z]+)(?=[A-Z_]|$)/g, '$1 ').split(/\s/);
var delta = column - currWordStart - 1;
if (delta < 0) delta = 0;
var curLength = 0, itLength = 0;
var that = this;
if (currentState.match(/[A-Za-z0-9_]+/)) {
wordParts.forEach(function (item, i) {
itLength = curLength + item.length;
if (delta >= curLength && delta <= itLength) {
currentState = item;
that.selection.clearSelection();
that.moveCursorTo(row, curLength + currWordStart);
that.selection.selectTo(row, itLength + currWordStart);
}
curLength = itLength;
});
}
var wordPairs = this.$toggleWordPairs;
var reg;
for (var i = 0; i < wordPairs.length; i++) {
var item = wordPairs[i];
for (var j = 0; j <= 1; j++) {
var negate = +!j;
var firstCondition = currentState.match(new RegExp('^\\s?_?(' + lang.escapeRegExp(item[j]) + ')\\s?$', 'i'));
if (firstCondition) {
var secondCondition = currentState.match(new RegExp('([_]|^|\\s)(' + lang.escapeRegExp(firstCondition[1]) + ')($|\\s)', 'g'));
if (secondCondition) {
reg = currentState.replace(new RegExp(lang.escapeRegExp(item[j]), 'i'), function (result) {
var res = item[negate];
if (result.toUpperCase() == result) {
res = res.toUpperCase();
} else if (result.charAt(0).toUpperCase() == result.charAt(0)) {
res = res.substr(0, 0) + item[negate].charAt(0).toUpperCase() + res.substr(1);
}
return res;
});
this.insert(reg);
reg = "";
}
}
}
}
}
/**
* Finds link at defined {row} and {column}
* @returns {String}
**/
findLinkAt(row, column) {
var line = this.session.getLine(row);
var wordParts = line.split(/((?:https?|ftp):\/\/[\S]+)/);
var columnPosition = column;
if (columnPosition < 0) columnPosition = 0;
var previousPosition = 0, currentPosition = 0, match;
for (let item of wordParts) {
currentPosition = previousPosition + item.length;
if (columnPosition >= previousPosition && columnPosition <= currentPosition) {
if (item.match(/((?:https?|ftp):\/\/[\S]+)/)) {
match = item.replace(/[\s:.,'";}\]]+$/, "");
break;
}
}
previousPosition = currentPosition;
}
return match;
}
/**
* Open valid url under cursor in another tab
* @returns {Boolean}
**/
openLink() {
var cursor = this.selection.getCursor();
var url = this.findLinkAt(cursor.row, cursor.column);
if (url)
window.open(url, '_blank');
return url != null;
}
/**
* Removes all the lines in the current selection
* @related EditSession.remove
**/
removeLines() {
var rows = this.$getSelectedRows();
this.session.removeFullLines(rows.first, rows.last);
this.clearSelection();
}
duplicateSelection() {
var sel = this.selection;
var doc = this.session;
var range = sel.getRange();
var reverse = sel.isBackwards();
if (range.isEmpty()) {
var row = range.start.row;
doc.duplicateLines(row, row);
} else {
var point = reverse ? range.start : range.end;
var endPoint = doc.insert(point, doc.getTextRange(range));
range.start = point;
range.end = endPoint;
sel.setSelectionRange(range, reverse);
}
}
/**
* Shifts all the selected lines down one row.
*
* @related EditSession.moveLinesUp
**/
moveLinesDown() {
this.$moveLines(1, false);
}
/**
* Shifts all the selected lines up one row.
* @related EditSession.moveLinesDown
**/
moveLinesUp() {
this.$moveLines(-1, false);
}
/**
* Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this:
* ```json
* { row: newRowLocation, column: newColumnLocation }
* ```
* @param {Range} range The range of text you want moved within the document
* @param {Point} toPosition The location (row and column) where you want to move the text to
* @param {boolean} [copy]
*
* @returns {Range} The new range where the text was moved to.
* @related EditSession.moveText
**/
moveText(range, toPosition, copy) {
return this.session.moveText(range, toPosition, copy);
}
/**
* Copies all the selected lines up one row.
*
**/
copyLinesUp() {
this.$moveLines(-1, true);
}
/**
* Copies all the selected lines down one row.
* @related EditSession.duplicateLines
*
**/
copyLinesDown() {
this.$moveLines(1, true);
}
/**
* for internal use
* @ignore
*
**/
$moveLines(dir, copy) {
var rows, moved;
var selection = this.selection;
if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
var range = selection.toOrientedRange();
rows = this.$getSelectedRows(range);
moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
if (copy && dir == -1) moved = 0;
range.moveBy(moved, 0);
selection.fromOrientedRange(range);
} else {
var ranges = selection.rangeList.ranges;
// @ts-expect-error TODO: possible bug, no args in parameters
selection.rangeList.detach(this.session);
this.inVirtualSelectionMode = true;
var diff = 0;
var totalDiff = 0;
var l = ranges.length;
for (var i = 0; i < l; i++) {
var rangeIndex = i;
ranges[i].moveBy(diff, 0);
rows = this.$getSelectedRows(ranges[i]);
var first = rows.first;
var last = rows.last;
while (++i < l) {
if (totalDiff) ranges[i].moveBy(totalDiff, 0);
var subRows = this.$getSelectedRows(ranges[i]);
if (copy && subRows.first != last)
break;
else if (!copy && subRows.first > last + 1)
break;
last = subRows.last;
}
i--;
diff = this.session.$moveLines(first, last, copy ? 0 : dir);
if (copy && dir == -1) rangeIndex = i + 1;
while (rangeIndex <= i) {
ranges[rangeIndex].moveBy(diff, 0);
rangeIndex++;
}
if (!copy) diff = 0;
totalDiff += diff;
}
selection.fromOrientedRange(selection.ranges[0]);
selection.rangeList.attach(this.session);
this.inVirtualSelectionMode = false;
}
}
/**
* Returns an object indicating the currently selected rows. The object looks like this:
*
* ```json
* { first: range.start.row, last: range.end.row }
* ```
*
* @returns {Object}
**/
$getSelectedRows(range) {
range = (range || this.getSelectionRange()).collapseRows();
return {
first: this.session.getRowFoldStart(range.start.row),
last: this.session.getRowFoldEnd(range.end.row)
};
}
/**
* @internal
*/
onCompositionStart(compositionState) {
this.renderer.showComposition(compositionState);
}
/**
* @internal
*/
onCompositionUpdate(text) {
this.renderer.setCompositionText(text);
}
/**
* @internal
*/
onCompositionEnd() {
this.renderer.hideComposition();
}
/**
* {:VirtualRenderer.getFirstVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getFirstVisibleRow
**/
getFirstVisibleRow() {
return this.renderer.getFirstVisibleRow();
}
/**
* {:VirtualRenderer.getLastVisibleRow}
*
* @returns {Number}
* @related VirtualRenderer.getLastVisibleRow
**/
getLastVisibleRow() {
return this.renderer.getLastVisibleRow();
}
/**
* Indicates if the row is currently visible on the screen.
* @param {Number} row The row to check
*
* @returns {Boolean}
**/
isRowVisible(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
}
/**
* Indicates if the entire row is currently visible on the screen.
* @param {Number} row The row to check
*
*
* @returns {Boolean}
**/
isRowFullyVisible(row) {
return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
}
/**
* Returns the number of currently visible rows.
* @returns {Number}
**/
$getVisibleRowCount() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
}
$moveByPage(dir, select) {
var renderer = this.renderer;
var config = this.renderer.layerConfig;
var rows = dir * Math.floor(config.height / config.lineHeight);
if (select === true) {
this.selection.$moveSelection(function(){
this.moveCursorBy(rows, 0);
});
} else if (select === false) {
this.selection.moveCursorBy(rows, 0);
this.selection.clearSelection();
}
var scrollTop = renderer.scrollTop;
renderer.scrollBy(0, rows * config.lineHeight);
if (select != null)
renderer.scrollCursorIntoView(null, 0.5);
renderer.animateScrolling(scrollTop);
}
/**
* Selects the text from the current position of the document until where a "page down" finishes.
**/
selectPageDown() {
this.$moveByPage(1, true);
}
/**
* Selects the text from the current position of the document until where a "page up" finishes.
**/
selectPageUp() {
this.$moveByPage(-1, true);
}
/**
* Shifts the document to wherever "page down" is, as well as moving the cursor position.
**/
gotoPageDown() {
this.$moveByPage(1, false);
}
/**
* Shifts the document to wherever "page up" is, as well as moving the cursor position.
**/
gotoPageUp() {
this.$moveByPage(-1, false);
}
/**
* Scrolls the document to wherever "page down" is, without changing the cursor position.
**/
scrollPageDown() {
this.$moveByPage(1);
}
/**
* Scrolls the document to wherever "page up" is, without changing the cursor position.
**/
scrollPageUp() {
this.$moveByPage(-1);
}
/**
* Moves the editor to the specified row.
* @related VirtualRenderer.scrollToRow
* @param {number} row
*/
scrollToRow(row) {
this.renderer.scrollToRow(row);
}
/**
* Scrolls to a line. If `center` is `true`, it puts the line in middle of screen (or attempts to).
* @param {Number} line The line to scroll to
* @param {Boolean} center If `true`
* @param {Boolean} animate If `true` animates scrolling
* @param {() => void} [callback] Function to be called when the animation has finished
*
* @related VirtualRenderer.scrollToLine
**/
scrollToLine(line, center, animate, callback) {
this.renderer.scrollToLine(line, center, animate, callback);
}
/**
* Attempts to center the current selection on the screen.
**/
centerSelection() {
var range = this.getSelectionRange();
var pos = {
row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
};
this.renderer.alignCursor(pos, 0.5);
}
/**
* Gets the current position of the cursor.
* @returns {Point} An object that looks something like this:
*
* ```json
* { row: currRow, column: currCol }
* ```
*
* @related Selection.getCursor
**/
getCursorPosition() {
return this.selection.getCursor();
}
/**
* Returns the screen position of the cursor.
* @returns {Point}
* @related EditSession.documentToScreenPosition
**/
getCursorPositionScreen() {
return this.session.documentToScreenPosition(this.getCursorPosition());
}
/**
* {:Selection.getRange}
* @returns {Range}
* @related Selection.getRange
**/
getSelectionRange() {
return this.selection.getRange();
}
/**
* Selects all the text in editor.
* @related Selection.selectAll
**/
selectAll() {
this.selection.selectAll();
}
/**
* {:Selection.clearSelection}
* @related Selection.clearSelection
**/
clearSelection() {
this.selection.clearSelection();
}
/**
* Moves the cursor to the specified row and column. Note that this does not de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
* @related Selection.moveCursorTo
**/
moveCursorTo(row, column) {
this.selection.moveCursorTo(row, column);
}
/**
* Moves the cursor to the position indicated by `pos.row` and `pos.column`.
* @param {Point} pos An object with two properties, row and column
* @related Selection.moveCursorToPosition
**/
moveCursorToPosition(pos) {
this.selection.moveCursorToPosition(pos);
}
/**
* Moves the cursor's row and column to the next matching bracket or HTML tag.
* @param {boolean} [select]
* @param {boolean} [expand]
*/
jumpToMatching(select, expand) {
var cursor = this.getCursorPosition();
var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
var prevToken = iterator.getCurrentToken();
var tokenCount = 0;
if (prevToken && prevToken.type.indexOf('tag-name') !== -1) {
prevToken = iterator.stepBackward();
}
var token = prevToken || iterator.stepForward();
if (!token) return;
//get next closing tag or bracket
var matchType;
var found = false;
var depth = {};
var i = cursor.column - token.start;
var bracketType;
var brackets = {
")": "(",
"(": "(",
"]": "[",
"[": "[",
"{": "{",
"}": "{"
};
do {
if (token.value.match(/[{}()\[\]]/g)) {
for (; i < token.value.length && !found; i++) {
if (!brackets[token.value[i]]) {
continue;
}
bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
if (isNaN(depth[bracketType])) {
depth[bracketType] = 0;
}
switch (token.value[i]) {
case '(':
case '[':
case '{':
depth[bracketType]++;
break;
case ')':
case ']':
case '}':
depth[bracketType]--;
if (depth[bracketType] === -1) {
matchType = 'bracket';
found = true;
}
break;
}
}
}
else if (token.type.indexOf('tag-name') !== -1) {
if (isNaN(depth[token.value])) {
depth[token.value] = 0;
}
if (prevToken.value === '<' && tokenCount > 1) {
depth[token.value]++;
}
else if (prevToken.value === '') {
depth[token.value]--;
}
if (depth[token.value] === -1) {
matchType = 'tag';
found = true;
}
}
if (!found) {
prevToken = token;
tokenCount++;
token = iterator.stepForward();
i = 0;
}
} while (token && !found);
//no match found
if (!matchType) return;
var range, pos;
if (matchType === 'bracket') {
range = this.session.getBracketRange(cursor);
if (!range) {
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + i - 1
);
pos = range.start;
if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column)
< 2) range = this.session.getBracketRange(pos);
}
}
else if (matchType === 'tag') {
if (!token || token.type.indexOf('tag-name') === -1) return;
range = new Range(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2,
iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() - 2
);
//find matching tag
if (range.compare(cursor.row, cursor.column) === 0) {
var tagsRanges = this.session.getMatchingTags(cursor);
if (tagsRanges) {
if (tagsRanges.openTag.contains(cursor.row, cursor.column)) {
range = tagsRanges.closeTag;
pos = range.start;
}
else {
range = tagsRanges.openTag;
if (tagsRanges.closeTag.start.row === cursor.row && tagsRanges.closeTag.start.column
=== cursor.column) pos = range.end; else pos = range.start;
}
}
}
//we found it
pos = pos || range.start;
}
pos = range && range.cursor || pos;
if (pos) {
if (select) {
if (range && expand) {
this.selection.setRange(range);
}
else if (range && range.isEqual(this.getSelectionRange())) {
this.clearSelection();
}
else {
this.selection.selectTo(pos.row, pos.column);
}
}
else {
this.selection.moveTo(pos.row, pos.column);
}
}
}
/**
* Moves the cursor to the specified line number, and also into the indicated column.
* @param {Number} lineNumber The line number to go to
* @param {Number} [column] A column number to go to
* @param {Boolean} [animate] If `true` animates scolling
**/
gotoLine(lineNumber, column, animate) {
this.selection.clearSelection();
this.session.unfold({row: lineNumber - 1, column: column || 0});
// todo: find a way to automatically exit multiselect mode
this.exitMultiSelectMode && this.exitMultiSelectMode();
this.moveCursorTo(lineNumber - 1, column || 0);
if (!this.isRowFullyVisible(lineNumber - 1))
this.scrollToLine(lineNumber - 1, true, animate);
}
/**
* Moves the cursor to the specified row and column. Note that this does de-select the current selection.
* @param {Number} row The new row number
* @param {Number} column The new column number
*
* @related Editor.moveCursorTo
**/
navigateTo(row, column) {
this.selection.moveTo(row, column);
}
/**
* Moves the cursor up in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} [times] The number of times to change navigation
*
**/
navigateUp(times) {
if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
var selectionStart = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionStart);
}
this.selection.clearSelection();
this.selection.moveCursorBy(-times || -1, 0);
}
/**
* Moves the cursor down in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} [times] The number of times to change navigation
*
**/
navigateDown(times) {
if (this.selection.isMultiLine() && this.selection.isBackwards()) {
var selectionEnd = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionEnd);
}
this.selection.clearSelection();
this.selection.moveCursorBy(times || 1, 0);
}
/**
* Moves the cursor left in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} [times] The number of times to change navigation
*
**/
navigateLeft(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
}
/**
* Moves the cursor right in the document the specified number of times. Note that this does de-select the current selection.
* @param {Number} [times] The number of times to change navigation
*
**/
navigateRight(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
}
/**
*
* Moves the cursor to the start of the current line. Note that this does de-select the current selection.
**/
navigateLineStart() {
this.selection.moveCursorLineStart();
this.clearSelection();
}
/**
*
* Moves the cursor to the end of the current line. Note that this does de-select the current selection.
**/
navigateLineEnd() {
this.selection.moveCursorLineEnd();
this.clearSelection();
}
/**
*
* Moves the cursor to the end of the current file. Note that this does de-select the current selection.
**/
navigateFileEnd() {
this.selection.moveCursorFileEnd();
this.clearSelection();
}
/**
*
* Moves the cursor to the start of the current file. Note that this does de-select the current selection.
**/
navigateFileStart() {
this.selection.moveCursorFileStart();
this.clearSelection();
}
/**
*
* Moves the cursor to the word immediately to the right of the current position. Note that this does de-select the current selection.
**/
navigateWordRight() {
this.selection.moveCursorWordRight();
this.clearSelection();
}
/**
*
* Moves the cursor to the word immediately to the left of the current position. Note that this does de-select the current selection.
**/
navigateWordLeft() {
this.selection.moveCursorWordLeft();
this.clearSelection();
}
/**
* Replaces the first occurrence of `options.needle` with the value in `replacement`.
* @param {String} [replacement] The text to replace with
* @param {Partial} [options] The [[Search `Search`]] options to use
* @return {number}
**/
replace(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
var replaced = 0;
if (!range)
return replaced;
if (this.$tryReplace(range, replacement)) {
replaced = 1;
}
this.selection.setSelectionRange(range);
this.renderer.scrollSelectionIntoView(range.start, range.end);
return replaced;
}
/**
* Replaces all occurrences of `options.needle` with the value in `replacement`.
* @param {String} [replacement] The text to replace with
* @param {Partial} [options] The [[Search `Search`]] options to use
* @return {number}
**/
replaceAll(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
var replaced = 0;
if (!ranges.length)
return replaced;
var selection = this.getSelectionRange();
this.selection.moveTo(0, 0);
for (var i = ranges.length - 1; i >= 0; --i) {
if(this.$tryReplace(ranges[i], replacement)) {
replaced++;
}
}
this.selection.setSelectionRange(selection);
return replaced;
}
/**
* @param {import("../ace-internal").Ace.IRange} range
* @param {string} [replacement]
*/
$tryReplace(range, replacement) {
var input = this.session.getTextRange(range);
replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
}
/**
* {:Search.getOptions} For more information on `options`, see [[Search `Search`]].
* @related Search.getOptions
* @returns {Partial}
**/
getLastSearchOptions() {
return this.$search.getOptions();
}
/**
* Attempts to find `needle` within the document. For more information on `options`, see [[Search `Search`]].
* @param {String|RegExp|Object} needle The text to search for (optional)
* @param {Partial} [options] An object defining various search properties
* @param {Boolean} [animate] If `true` animate scrolling
* @related Search.find
**/
find(needle, options, animate) {
if (!options)
options = {};
if (typeof needle == "string" || needle instanceof RegExp)
options.needle = needle;
else if (typeof needle == "object")
oop.mixin(options, needle);
var range = this.selection.getRange();
if (options.needle == null) {
needle = this.session.getTextRange(range)
|| this.$search.$options.needle;
if (!needle) {
range = this.session.getWordRange(range.start.row, range.start.column);
needle = this.session.getTextRange(range);
}
this.$search.set({needle: needle});
}
this.$search.set(options);
if (!options.start)
this.$search.set({start: range});
var newRange = this.$search.find(this.session);
if (options.preventScroll)
return newRange;
if (newRange) {
this.revealRange(newRange, animate);
return newRange;
}
// clear selection if nothing is found
if (options.backwards)
range.start = range.end;
else
range.end = range.start;
this.selection.setRange(range);
}
/**
* Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]].
* @param {Partial} [options] search options
* @param {Boolean} [animate] If `true` animate scrolling
*
* @related Editor.find
**/
findNext(options, animate) {
this.find({skipCurrent: true, backwards: false}, options, animate);
}
/**
* Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]].
* @param {Partial} [options] search options
* @param {Boolean} [animate] If `true` animate scrolling
*
* @related Editor.find
**/
findPrevious(options, animate) {
this.find(options, {skipCurrent: true, backwards: true}, animate);
}
/**
*
* @param {Range} range
* @param {boolean} [animate]
*/
revealRange(range, animate) {
this.session.unfold(range);
this.selection.setSelectionRange(range);
var scrollTop = this.renderer.scrollTop;
this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
if (animate !== false)
this.renderer.animateScrolling(scrollTop);
}
/**
* {:UndoManager.undo}
* @related UndoManager.undo
**/
undo() {
this.session.getUndoManager().undo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
}
/**
* {:UndoManager.redo}
* @related UndoManager.redo
**/
redo() {
this.session.getUndoManager().redo(this.session);
this.renderer.scrollCursorIntoView(null, 0.5);
}
/**
*
* Cleans up the entire editor.
**/
destroy() {
if (this.$toDestroy) {
this.$toDestroy.forEach(function(el) {
el.destroy();
});
this.$toDestroy = null;
}
if (this.$mouseHandler)
this.$mouseHandler.destroy();
this.renderer.destroy();
this._signal("destroy", this);
if (this.session)
this.session.destroy();
if (this._$emitInputEvent)
this._$emitInputEvent.cancel();
this.removeAllListeners();
}
/**
* Enables automatic scrolling of the cursor into view when editor itself is inside scrollable element
* @param {Boolean} enable default true
**/
setAutoScrollEditorIntoView(enable) {
if (!enable)
return;
var rect;
var self = this;
var shouldScroll = false;
if (!this.$scrollAnchor)
this.$scrollAnchor = document.createElement("div");
var scrollAnchor = this.$scrollAnchor;
scrollAnchor.style.cssText = "position:absolute";
this.container.insertBefore(scrollAnchor, this.container.firstChild);
var onChangeSelection = this.on("changeSelection", function() {
shouldScroll = true;
});
// needed to not trigger sync reflow
var onBeforeRender = this.renderer.on("beforeRender", function() {
if (shouldScroll)
rect = self.renderer.container.getBoundingClientRect();
});
var onAfterRender = this.renderer.on("afterRender", function() {
if (shouldScroll && rect && (self.isFocused()
|| self.searchBox && self.searchBox.isFocused())
) {
var renderer = self.renderer;
var pos = renderer.$cursorLayer.$pixelPos;
var config = renderer.layerConfig;
var top = pos.top - config.offset;
if (pos.top >= 0 && top + rect.top < 0) {
shouldScroll = true;
} else if (pos.top < config.height &&
pos.top + rect.top + config.lineHeight > window.innerHeight) {
shouldScroll = false;
} else {
shouldScroll = null;
}
if (shouldScroll != null) {
scrollAnchor.style.top = top + "px";
scrollAnchor.style.left = pos.left + "px";
scrollAnchor.style.height = config.lineHeight + "px";
scrollAnchor.scrollIntoView(shouldScroll);
}
shouldScroll = rect = null;
}
});
this.setAutoScrollEditorIntoView = function(enable) {
if (enable)
return;
delete this.setAutoScrollEditorIntoView;
this.off("changeSelection", onChangeSelection);
this.renderer.off("afterRender", onAfterRender);
this.renderer.off("beforeRender", onBeforeRender);
};
}
$resetCursorStyle() {
var style = this.$cursorStyle || "ace";
var cursorLayer = this.renderer.$cursorLayer;
if (!cursorLayer)
return;
cursorLayer.setSmoothBlinking(/smooth/.test(style));
cursorLayer.isBlinking = !this.$readOnly && style != "wide";
dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
}
/**
* opens a prompt displaying message
**/
prompt(message, options, callback) {
var editor = this;
config.loadModule("ace/ext/prompt", function (module) {
module.prompt(editor, message, options, callback);
});
}
}
Editor.$uid = 0;
Editor.prototype.curOp = null;
Editor.prototype.prevOp = {};
// TODO use property on commands instead of this
Editor.prototype.$mergeableCommands = ["backspace", "del", "insertstring"];
Editor.prototype.$toggleWordPairs = [
["first", "last"],
["true", "false"],
["yes", "no"],
["width", "height"],
["top", "bottom"],
["right", "left"],
["on", "off"],
["x", "y"],
["get", "set"],
["max", "min"],
["horizontal", "vertical"],
["show", "hide"],
["add", "remove"],
["up", "down"],
["before", "after"],
["even", "odd"],
["in", "out"],
["inside", "outside"],
["next", "previous"],
["increase", "decrease"],
["attach", "detach"],
["&&", "||"],
["==", "!="]
];
oop.implement(Editor.prototype, EventEmitter);
config.defineOptions(Editor.prototype, "editor", {
selectionStyle: {
set: function(style) {
this.onSelectionChange();
this._signal("changeSelectionStyle", {data: style});
},
initialValue: "line"
},
highlightActiveLine: {
set: function() {this.$updateHighlightActiveLine();},
initialValue: true
},
highlightSelectedWord: {
set: function(shouldHighlight) {this.$onSelectionChange();},
initialValue: true
},
readOnly: {
set: function(/**@type{boolean}*/readOnly) {
this.textInput.setReadOnly(readOnly);
this.$resetCursorStyle();
if (!this.$readOnlyCallback) {
this.$readOnlyCallback = (e) => {
var shouldShow = false;
if (e && e.type == "keydown") {
shouldShow = e && e.key && e.key.length == 1 && !e.ctrlKey && !e.metaKey;
if (!shouldShow) return;
} else if (e && e.type !== "exec") {
shouldShow = true;
}
if (shouldShow) {
if (!this.hoverTooltip) {
this.hoverTooltip = new HoverTooltip();
}
var domNode = dom.createElement("div");
domNode.textContent = nls("editor.tooltip.disable-editing", "Editing is disabled");
if (!this.hoverTooltip.isOpen) {
this.hoverTooltip.showForRange(this, this.getSelectionRange(), domNode);
}
} else if (this.hoverTooltip && this.hoverTooltip.isOpen) {
this.hoverTooltip.hide();
}
};
}
var textArea = this.textInput.getElement();
if (readOnly) {
event.addListener(textArea, "keydown", this.$readOnlyCallback, this);
this.commands.on("exec", this.$readOnlyCallback);
this.commands.on("commandUnavailable", this.$readOnlyCallback);
} else {
event.removeListener(textArea, "keydown", this.$readOnlyCallback);
this.commands.off("exec", this.$readOnlyCallback);
this.commands.off("commandUnavailable", this.$readOnlyCallback);
if (this.hoverTooltip) {
this.hoverTooltip.destroy();
this.hoverTooltip = null;
}
}
},
initialValue: false
},
copyWithEmptySelection: {
set: function(value) {
this.textInput.setCopyWithEmptySelection(value);
},
initialValue: false
},
cursorStyle: {
set: function(val) { this.$resetCursorStyle(); },
values: ["ace", "slim", "smooth", "wide"],
initialValue: "ace"
},
mergeUndoDeltas: {
values: [false, true, "always"],
initialValue: true
},
behavioursEnabled: {initialValue: true},
wrapBehavioursEnabled: {initialValue: true},
enableAutoIndent: {initialValue: true},
autoScrollEditorIntoView: {
set: function(val) {this.setAutoScrollEditorIntoView(val);}
},
keyboardHandler: {
set: function(val) { this.setKeyboardHandler(val); },
get: function() { return this.$keybindingId; },
handlesSet: true
},
value: {
set: function(val) { this.session.setValue(val); },
get: function() { return this.getValue(); },
handlesSet: true,
hidden: true
},
session: {
set: function(val) { this.setSession(val); },
get: function() { return this.session; },
handlesSet: true,
hidden: true
},
showLineNumbers: {
set: function(show) {
this.renderer.$gutterLayer.setShowLineNumbers(show);
this.renderer.$loop.schedule(this.renderer.CHANGE_GUTTER);
if (show && this.$relativeLineNumbers)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
},
initialValue: true
},
relativeLineNumbers: {
set: function(value) {
if (this.$showLineNumbers && value)
relativeNumberRenderer.attach(this);
else
relativeNumberRenderer.detach(this);
}
},
placeholder: {
/**
* @param message
*/
set: function(message) {
if (!this.$updatePlaceholder) {
this.$updatePlaceholder = function() {
var hasValue = this.session && (this.renderer.$composition ||
this.session.getLength() > 1 || this.session.getLine(0).length > 0);
if (hasValue && this.renderer.placeholderNode) {
this.renderer.off("afterRender", this.$updatePlaceholder);
dom.removeCssClass(this.container, "ace_hasPlaceholder");
this.renderer.placeholderNode.remove();
this.renderer.placeholderNode = null;
} else if (!hasValue && !this.renderer.placeholderNode) {
this.renderer.on("afterRender", this.$updatePlaceholder);
dom.addCssClass(this.container, "ace_hasPlaceholder");
var el = dom.createElement("div");
el.className = "ace_placeholder";
el.textContent = this.$placeholder || "";
this.renderer.placeholderNode = el;
this.renderer.content.appendChild(this.renderer.placeholderNode);
} else if (!hasValue && this.renderer.placeholderNode) {
this.renderer.placeholderNode.textContent = this.$placeholder || "";
}
}.bind(this);
// @ts-ignore
this.on("input", this.$updatePlaceholder);
}
this.$updatePlaceholder();
}
},
enableKeyboardAccessibility: {
set: function(value) {
var blurCommand = {
name: "blurTextInput",
description: "Set focus to the editor content div to allow tabbing through the page",
bindKey: "Esc",
exec: function(editor) {
editor.blur();
editor.renderer.scroller.focus();
},
readOnly: true
};
var focusOnEnterKeyup = function (e) {
if (e.target == this.renderer.scroller && e.keyCode === keys['enter']){
e.preventDefault();
var row = this.getCursorPosition().row;
if (!this.isRowVisible(row))
this.scrollToLine(row, true, true);
this.focus();
}
};
/**@type {GutterKeyboardHandler}*/
var gutterKeyboardHandler;
// If keyboard a11y mode is enabled we:
// - Enable keyboard operability gutter.
// - Prevent tab-trapping.
// - Hide irrelevant elements from assistive technology.
// - On Windows, set more lines to the textarea.
// - set aria-label to the text input.
if (value){
this.renderer.enableKeyboardAccessibility = true;
this.renderer.keyboardFocusClassName = "ace_keyboard-focus";
this.textInput.getElement().setAttribute("tabindex", -1);
// VoiceOver on Mac OS works best with single line in the textarea, the screen readers on
// Windows work best with multiple lines in the textarea.
this.textInput.setNumberOfExtraLines(useragent.isWin ? 3 : 0);
this.renderer.scroller.setAttribute("tabindex", 0);
this.renderer.scroller.setAttribute("role", "group");
this.renderer.scroller.setAttribute("aria-roledescription", nls("editor.scroller.aria-roledescription", "editor"));
this.renderer.scroller.classList.add(this.renderer.keyboardFocusClassName);
this.renderer.scroller.setAttribute("aria-label",
nls("editor.scroller.aria-label", "Editor content, press Enter to start editing, press Escape to exit")
);
this.renderer.scroller.addEventListener("keyup", focusOnEnterKeyup.bind(this));
this.commands.addCommand(blurCommand);
this.renderer.$gutter.setAttribute("tabindex", 0);
this.renderer.$gutter.setAttribute("aria-hidden", false);
this.renderer.$gutter.setAttribute("role", "group");
this.renderer.$gutter.setAttribute("aria-roledescription", nls("editor.gutter.aria-roledescription", "editor gutter"));
this.renderer.$gutter.setAttribute("aria-label",
nls("editor.gutter.aria-label", "Editor gutter, press Enter to interact with controls using arrow keys, press Escape to exit")
);
this.renderer.$gutter.classList.add(this.renderer.keyboardFocusClassName);
this.renderer.content.setAttribute("aria-hidden", true);
if (!gutterKeyboardHandler)
gutterKeyboardHandler = new GutterKeyboardHandler(this);
gutterKeyboardHandler.addListener();
this.textInput.setAriaOptions({
setLabel: true
});
} else {
this.renderer.enableKeyboardAccessibility = false;
this.textInput.getElement().setAttribute("tabindex", 0);
this.textInput.setNumberOfExtraLines(0);
this.renderer.scroller.setAttribute("tabindex", -1);
this.renderer.scroller.removeAttribute("role");
this.renderer.scroller.removeAttribute("aria-roledescription");
this.renderer.scroller.classList.remove(this.renderer.keyboardFocusClassName);
this.renderer.scroller.removeAttribute("aria-label");
this.renderer.scroller.removeEventListener("keyup", focusOnEnterKeyup.bind(this));
this.commands.removeCommand(blurCommand);
this.renderer.content.removeAttribute("aria-hidden");
this.renderer.$gutter.setAttribute("tabindex", -1);
this.renderer.$gutter.setAttribute("aria-hidden", true);
this.renderer.$gutter.removeAttribute("role");
this.renderer.$gutter.removeAttribute("aria-roledescription");
this.renderer.$gutter.removeAttribute("aria-label");
this.renderer.$gutter.classList.remove(this.renderer.keyboardFocusClassName);
if (gutterKeyboardHandler)
gutterKeyboardHandler.removeListener();
}
},
initialValue: false
},
textInputAriaLabel: {
set: function(val) { this.$textInputAriaLabel = val; },
initialValue: ""
},
enableMobileMenu: {
/**
* @param {boolean} val
*/
set: function(val) { this.$enableMobileMenu = val; },
initialValue: true
},
customScrollbar: "renderer",
hScrollBarAlwaysVisible: "renderer",
vScrollBarAlwaysVisible: "renderer",
highlightGutterLine: "renderer",
animatedScroll: "renderer",
showInvisibles: "renderer",
showPrintMargin: "renderer",
printMarginColumn: "renderer",
printMargin: "renderer",
fadeFoldWidgets: "renderer",
showFoldWidgets: "renderer",
displayIndentGuides: "renderer",
highlightIndentGuides: "renderer",
showGutter: "renderer",
fontSize: "renderer",
fontFamily: "renderer",
maxLines: "renderer",
minLines: "renderer",
scrollPastEnd: "renderer",
fixedWidthGutter: "renderer",
theme: "renderer",
hasCssTransforms: "renderer",
maxPixelHeight: "renderer",
useTextareaForIME: "renderer",
useResizeObserver: "renderer",
useSvgGutterIcons: "renderer",
showFoldedAnnotations: "renderer",
scrollSpeed: "$mouseHandler",
dragDelay: "$mouseHandler",
dragEnabled: "$mouseHandler",
focusTimeout: "$mouseHandler",
tooltipFollowsMouse: "$mouseHandler",
firstLineNumber: "session",
overwrite: "session",
newLineMode: "session",
useWorker: "session",
useSoftTabs: "session",
navigateWithinSoftTabs: "session",
tabSize: "session",
wrap: "session",
indentedSoftWrap: "session",
foldStyle: "session",
mode: "session"
});
var relativeNumberRenderer = {
getText: function(/**@type{EditSession}*/session, /**@type{number}*/row) {
return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9 ? "\xb7" : ""))) + "";
},
getWidth: function(session, /**@type{number}*/lastLineNumber, config) {
return Math.max(
lastLineNumber.toString().length,
(config.lastRow + 1).toString().length,
2
) * config.characterWidth;
},
update: function(e, /**@type{Editor}*/editor) {
editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER);
},
attach: function(/**@type{Editor}*/editor) {
editor.renderer.$gutterLayer.$renderer = this;
editor.on("changeSelection", this.update);
this.update(null, editor);
},
detach: function(/**@type{Editor}*/editor) {
if (editor.renderer.$gutterLayer.$renderer == this)
editor.renderer.$gutterLayer.$renderer = null;
editor.off("changeSelection", this.update);
this.update(null, editor);
}
};
exports.Editor = Editor;
================================================
FILE: demo/diff/index.html
================================================
Ace-diff - Simple Demo #1
================================================
FILE: demo/emmet.html
================================================
ACE Emmet demo
================================================
FILE: demo/i18n.html
================================================
ACE Editor StatusBar Demo
Russian
Armenian
English
Spanish
================================================
FILE: demo/inline_autocompletion.html
================================================
ACE Inline Autocompletion demo
================================================
FILE: demo/keyboard_shortcuts.html
================================================
Editor
================================================
FILE: demo/kitchen-sink/demo.js
================================================
"use strict";
require("ace/ext/rtl");
require("ace/multi_select");
require("./inline_editor");
var devUtil = require("./dev_util");
require("./file_drop");
var config = require("ace/config");
config.setLoader(function(moduleName, cb) {
require([moduleName], function(module) {
cb(null, module);
});
});
var env = {};
var dom = require("ace/lib/dom");
var net = require("ace/lib/net");
var lang = require("ace/lib/lang");
var event = require("ace/lib/event");
var theme = require("ace/theme/textmate");
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
var Editor = require("ace/editor").Editor;
var Range = require("ace/range").Range;
var whitespace = require("ace/ext/whitespace");
var createDiffView = require("ace/ext/diff").createDiffView;
var doclist = require("./doclist");
var layout = require("./layout");
var util = require("./util");
var saveOption = util.saveOption;
require("ace/ext/elastic_tabstops_lite");
require("ace/incremental_search");
require("ace/ext/whitespaces_in_selection");
var TokenTooltip = require("./token_tooltip").TokenTooltip;
require("ace/config").defineOptions(Editor.prototype, "editor", {
showTokenInfo: {
set: function(val) {
if (val) {
this.tokenTooltip = this.tokenTooltip || new TokenTooltip(this);
}
else if (this.tokenTooltip) {
this.tokenTooltip.destroy();
delete this.tokenTooltip;
}
},
get: function() {
return !!this.tokenTooltip;
},
handlesSet: true
}
});
require("ace/config").defineOptions(Editor.prototype, "editor", {
useAceLinters: {
set: function(val) {
var enabled = !!val;
if (enabled && !window.languageProvider) {
loadLanguageProvider(this);
}
else if (enabled) {
window.languageProvider.registerEditor(this);
} else {
if (window.languageProvider) {
window.languageProvider.unregisterEditor(this, true);
window.languageProvider = null;
}
if (this.getOption("useAceSpellCheck")) {
this.setOption("useAceSpellCheck", false);
saveOption("useAceSpellCheck", false);
if (env.optionsPanel) {
env.optionsPanel.editor = this;
env.optionsPanel.render();
}
}
}
}
}
});
require("ace/config").defineOptions(Editor.prototype, "editor", {
useAceSpellCheck: {
set: function(val) {
var nextValue = !!val;
if (window.useAceSpellCheck === nextValue) return;
window.useAceSpellCheck = nextValue;
if (nextValue && !this.getOption("useAceLinters")) {
this.setOption("useAceLinters", true);
saveOption("useAceLinters", true);
if (env.optionsPanel) {
env.optionsPanel.editor = this;
env.optionsPanel.render();
}
return;
}
if (window.languageProvider && this.getOption("useAceLinters")) {
window.languageProvider.unregisterEditor(this, true);
window.languageProvider = null;
loadLanguageProvider(this);
}
},
get: function() {
return window.useAceSpellCheck !== false;
},
handlesSet: true
}
});
var {HoverTooltip} = require("ace/tooltip");
var MarkerGroup = require("ace/marker_group").MarkerGroup;
var docTooltip = new HoverTooltip();
window.useAceSpellCheck = true;
function loadLanguageProvider(editor) {
function loadScript(cb) {
if (define.amd) {
require([
"https://mkslanc.github.io/ace-linters/build/ace-linters.js"
], function(m) {
cb(m.LanguageProvider);
});
} else {
net.loadScript([
"https://mkslanc.github.io/ace-linters/build/ace-linters.js"
], function() {
cb(window.LanguageProvider);
});
}
}
loadScript(function(LanguageProvider) {
var services = [];
if (window.useAceSpellCheck !== false) {
services.push({
name: "ace-spell-check",
className: "AceSpellCheck",
modes: "*",
script: "ace-spell-check.js",
cdnUrl: "https://unpkg.com/ace-spell-check@latest/build"
});
}
var languageProvider = LanguageProvider.fromCdn({
services: services,
serviceManagerCdn:"https://mkslanc.github.io/ace-linters/build",
includeDefaultLinters: true
}, {
functionality: {
hover: true,
completion: {
overwriteCompleters: true
},
completionResolve: true,
format: true,
documentHighlights: true,
signatureHelp: false
}
});
window.languageProvider = languageProvider;
languageProvider.registerEditor(editor);
});
}
var workerModule = require("ace/worker/worker_client");
if (location.href.indexOf("noworker") !== -1) {
workerModule.WorkerClient = workerModule.UIWorkerClient;
}
/*********** create editor ***************************/
var container = document.getElementById("editor-container");
// Splitting.
var Split = require("ace/split").Split;
var split = new Split(container, theme, 1);
env.editor = split.getEditor(0);
split.on("focus", function(editor) {
env.editor = editor;
updateUIEditorOptions();
});
env.split = split;
window.env = env;
var consoleEl = dom.createElement("div");
container.parentNode.appendChild(consoleEl);
consoleEl.style.cssText = "position:fixed; bottom:1px; right:0;\
border:1px solid #baf; z-index:100";
var cmdLine = new layout.singleLineEditor(consoleEl);
cmdLine.setOption("placeholder", "Enter a command...");
cmdLine.editor = env.editor;
env.editor.cmdLine = cmdLine;
env.editor.showCommandLine = function(val) {
this.cmdLine.focus();
if (typeof val == "string")
this.cmdLine.setValue(val, 1);
};
/**
* This demonstrates how you can define commands and bind shortcuts to them.
*/
env.editor.commands.addCommands([{
name: "snippet",
bindKey: {win: "Alt-C", mac: "Command-Alt-C"},
exec: function(editor, needle) {
if (typeof needle == "object") {
editor.cmdLine.setValue("snippet ", 1);
editor.cmdLine.focus();
return;
}
var s = snippetManager.getSnippetByName(needle, editor);
if (s)
snippetManager.insertSnippet(editor, s.content);
},
readOnly: true
}, {
name: "focusCommandLine",
bindKey: "shift-esc|ctrl-`",
exec: function(editor, needle) { editor.cmdLine.focus(); },
readOnly: true
}, {
name: "nextFile",
bindKey: "Ctrl-tab",
exec: function(editor) { doclist.cycleOpen(editor, 1); },
readOnly: true
}, {
name: "previousFile",
bindKey: "Ctrl-shift-tab",
exec: function(editor) { doclist.cycleOpen(editor, -1); },
readOnly: true
}, {
name: "execute",
bindKey: "ctrl+enter",
exec: function(editor) {
try {
var r = window.eval(editor.getCopyText() || editor.getValue());
} catch(e) {
r = e;
}
editor.cmdLine.setValue(r + "");
},
readOnly: true
}, {
name: "showKeyboardShortcuts",
bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
exec: function(editor) {
config.loadModule("ace/ext/keybinding_menu", function(module) {
module.init(editor);
editor.showKeyboardShortcuts();
});
}
}, {
name: "increaseFontSize",
bindKey: "Ctrl-=|Ctrl-+",
exec: function(editor) {
var size = parseInt(editor.getFontSize(), 10) || 12;
editor.setFontSize(size + 1);
}
}, {
name: "decreaseFontSize",
bindKey: "Ctrl+-|Ctrl-_",
exec: function(editor) {
var size = parseInt(editor.getFontSize(), 10) || 12;
editor.setFontSize(Math.max(size - 1 || 1));
}
}, {
name: "resetFontSize",
bindKey: "Ctrl+0|Ctrl-Numpad0",
exec: function(editor) {
editor.setFontSize(12);
}
}]);
env.editor.commands.addCommands(whitespace.commands);
cmdLine.commands.bindKeys({
"Shift-Return|Ctrl-Return|Alt-Return": function(cmdLine) { cmdLine.insert("\n"); },
"Esc|Shift-Esc": function(cmdLine){ cmdLine.editor.focus(); },
"Return": function(cmdLine){
var command = cmdLine.getValue().split(/\s+/);
var editor = cmdLine.editor;
editor.commands.exec(command[0], editor, command[1]);
editor.focus();
}
});
cmdLine.commands.removeCommands(["find", "gotoline", "findall", "replace", "replaceall"]);
var commands = env.editor.commands;
commands.addCommand({
name: "save",
bindKey: {win: "Ctrl-S", mac: "Command-S"},
exec: function(arg) {
var session = env.editor.session;
var name = session.name.match(/[^\/]+$/);
localStorage.setItem(
"saved_file:" + name,
session.getValue()
);
env.editor.cmdLine.setValue("saved "+ name);
}
});
commands.addCommand({
name: "load",
bindKey: {win: "Ctrl-O", mac: "Command-O"},
exec: function(arg) {
var session = env.editor.session;
var name = session.name.match(/[^\/]+$/);
var value = localStorage.getItem("saved_file:" + name);
if (typeof value == "string") {
session.setValue(value);
env.editor.cmdLine.setValue("loaded "+ name);
} else {
env.editor.cmdLine.setValue("no previuos value saved for "+ name);
}
}
});
/*********** manage layout ***************************/
function handleToggleActivate(target) {
if (dom.hasCssClass(sidePanelContainer, "closed"))
onResize(null, false);
else if (dom.hasCssClass(target, "toggleButton"))
onResize(null, true);
};
var sidePanelContainer = document.getElementById("sidePanel");
sidePanelContainer.onclick = function(e) {
handleToggleActivate(e.target);
};
var optionToggle = document.getElementById("optionToggle");
optionToggle.onkeydown = function(e) {
if (e.code === "Space" || e.code === "Enter") {
handleToggleActivate(e.target);
}
};
var consoleHeight = 20;
function onResize(e, closeSidePanel) {
var left = 280;
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
if (closeSidePanel == null)
closeSidePanel = width < 2 * left;
if (closeSidePanel) {
left = 20;
document.getElementById("optionToggle").setAttribute("aria-label", "Show Options");
} else
document.getElementById("optionToggle").setAttribute("aria-label", "Hide Options");
width -= left;
container.style.width = width + "px";
container.style.height = height - consoleHeight + "px";
container.style.left = left + "px";
env.split.resize();
consoleEl.style.width = width + "px";
consoleEl.style.left = left + "px";
cmdLine.resize();
sidePanel.style.width = left + "px";
sidePanel.style.height = height + "px";
dom.setCssClass(sidePanelContainer, "closed", closeSidePanel);
}
window.onresize = onResize;
onResize();
/*********** options panel ***************************/
var diffView;
doclist.history = doclist.docs.map(function(doc) {
return doc.name;
});
doclist.history.index = 0;
doclist.cycleOpen = function(editor, dir) {
var h = this.history;
h.index += dir;
if (h.index >= h.length)
h.index = 0;
else if (h.index <= 0)
h.index = h.length - 1;
var s = h[h.index];
doclist.pickDocument(s);
};
doclist.addToHistory = function(name) {
var h = this.history;
var i = h.indexOf(name);
if (i != h.index) {
if (i != -1)
h.splice(i, 1);
h.index = h.push(name);
}
};
var initDoc = (session) => {
if (!session)
return;
doclist.addToHistory(session.name);
session = env.split.setSession(session);
whitespace.detectIndentation(session);
optionsPanel.render();
env.editor.focus();
if (diffView) {
diffView.detach()
diffView = createDiffView({
inline: "b",
editorB: editor,
valueA: editor.getValue()
});
}
}
doclist.pickDocument = function(name) {
doclist.loadDoc(name, initDoc);
};
var OptionPanel = require("ace/ext/options").OptionPanel;
var optionsPanel = env.optionsPanel = new OptionPanel(env.editor);
var originalAutocompleteCommand = null;
optionsPanel.add({
Main: {
Document: {
type: "select",
path: "doc",
items: doclist.all,
position: -101,
onchange: doclist.pickDocument,
getValue: function() {
return env.editor.session.name || "javascript";
}
},
Split: {
type: "buttonBar",
path: "split",
values: ["None", "Below", "Beside"],
position: -100,
onchange: function(value) {
var sp = env.split;
if (value == "Below" || value == "Beside") {
var newEditor = (sp.getSplits() == 1);
sp.setOrientation(value == "Below" ? sp.BELOW : sp.BESIDE);
sp.setSplits(2);
if (newEditor) {
var session = sp.getEditor(0).session;
var newSession = sp.setSession(session, 1);
newSession.name = session.name;
}
} else {
sp.setSplits(1);
}
},
getValue: function() {
var sp = env.split;
return sp.getSplits() == 1
? "None"
: sp.getOrientation() == sp.BELOW
? "Below"
: "Beside";
}
},
"Show diffs": {
position: -102,
type: "buttonBar",
path: "diffView",
values: ["None", "Inline"],
onchange: function (value) {
if (value === "Inline" && !diffView) {
diffView = createDiffView({
inline: "b",
editorB: editor,
valueA: editor.getValue()
});
}
else if (value === "None") {
if (diffView) {
diffView.detach();
diffView = null;
}
}
},
getValue: function() {
return !diffView ? "None"
: "Inline";
}
}
},
More: {
"RTL": {
path: "rtl",
position: 900
},
"Line based RTL switching": {
path: "rtlText",
position: 900
},
"Show token info": {
path: "showTokenInfo",
position: 2000
},
"Inline preview for autocomplete": {
path: "inlineEnabledForAutocomplete",
position: 2000,
onchange: function(value) {
var Autocomplete = require("ace/autocomplete").Autocomplete;
if (value && !originalAutocompleteCommand) {
originalAutocompleteCommand = Autocomplete.startCommand.exec;
Autocomplete.startCommand.exec = function(editor) {
var autocomplete = Autocomplete.for(editor);
autocomplete.inlineEnabled = true;
originalAutocompleteCommand(...arguments);
}
} else if (!value) {
var autocomplete = Autocomplete.for(editor);
autocomplete.destroy();
if (originalAutocompleteCommand)
Autocomplete.startCommand.exec = originalAutocompleteCommand;
originalAutocompleteCommand = null;
}
},
getValue: function() {
return !!originalAutocompleteCommand;
}
},
"Use Ace Linters": {
position: 3000,
path: "useAceLinters"
},
"Use Spell Checker": {
position: 3001,
path: "useAceSpellCheck"
},
"Show whitespaces in selection": {
position: 3100,
path: "showWhitespacesInSelection"
},
"Show Textarea Position": devUtil.textPositionDebugger,
"Text Input Debugger": devUtil.textInputDebugger,
}
});
var optionsPanelContainer = document.getElementById("optionsPanel");
optionsPanel.render();
optionsPanelContainer.insertBefore(optionsPanel.container, optionsPanelContainer.firstChild);
optionsPanel.on("setOption", function(e) {
util.saveOption(e.name, e.value);
});
function updateUIEditorOptions() {
optionsPanel.editor = env.editor;
optionsPanel.render();
}
env.editor.on("changeSession", function() {
for (var i in env.editor.session.$options) {
if (i == "mode") continue;
var value = util.getOption(i);
if (value != undefined) {
env.editor.setOption(i, value);
}
}
});
if (localStorage.last_session) {
try {
var sessionObj = JSON.parse(localStorage.last_session);
var session = EditSession.fromJSON(localStorage.last_session);
session.name = sessionObj.name;
var cachedDoc = doclist.fileCache[session.name.toLowerCase()];
if (cachedDoc) {
cachedDoc.session = session;
}
initDoc(session);
} catch (e) {
console.error(e);
optionsPanel.setOption("doc", util.getOption("doc") || "JavaScript");
}
}
for (var i in optionsPanel.options) {
if (i === "doc") continue;
var value = util.getOption(i);
if (value != undefined) {
if ((i == "mode" || i == "theme") && !/[/]/.test(value))
value = "ace/" + i + "/" + value;
optionsPanel.setOption(i, value);
}
}
optionsPanel.render();
function synchroniseScrolling() {
var s1 = env.split.$editors[0].session;
var s2 = env.split.$editors[1].session;
s1.on('changeScrollTop', function(pos) {s2.setScrollTop(pos)});
s2.on('changeScrollTop', function(pos) {s1.setScrollTop(pos)});
s1.on('changeScrollLeft', function(pos) {s2.setScrollLeft(pos)});
s2.on('changeScrollLeft', function(pos) {s1.setScrollLeft(pos)});
}
var StatusBar = require("ace/ext/statusbar").StatusBar;
new StatusBar(env.editor, cmdLine.container);
require("ace/placeholder").PlaceHolder;
var snippetManager = require("ace/snippets").snippetManager;
env.editSnippets = function() {
var sp = env.split;
if (sp.getSplits() == 2) {
sp.setSplits(1);
return;
}
sp.setSplits(1);
sp.setSplits(2);
sp.setOrientation(sp.BESIDE);
var editor = sp.$editors[1];
var id = sp.$editors[0].session.$mode.$id || "";
var m = snippetManager.files[id];
if (!doclist["snippets/" + id]) {
var text = m.snippetText;
var s = doclist.initDoc(text, "", {});
s.setMode("ace/mode/snippets");
doclist["snippets/" + id] = s;
}
editor.on("blur", function() {
m.snippetText = editor.getValue();
snippetManager.unregister(m.snippets);
m.snippets = snippetManager.parseSnippetFile(m.snippetText, m.scope);
snippetManager.register(m.snippets);
});
sp.$editors[0].once("changeMode", function() {
sp.setSplits(1);
});
editor.setSession(doclist["snippets/" + id], 1);
editor.focus();
};
optionsPanelContainer.insertBefore(
dom.buildDom(["div", {style: "text-align:right;width: 80%"},
["div", {},
["button", {onclick: env.editSnippets}, "Edit Snippets"]],
["div", {},
["button", {onclick: function() {
var info = navigator.platform + "\n" + navigator.userAgent;
if (env.editor.getValue() == info)
return env.editor.undo();
env.editor.setValue(info, -1);
env.editor.setOption("wrap", 80);
}}, "Show Browser Info"]],
devUtil.getUI(),
["div", {},
"Open Dialog ",
["button", {onclick: openTestDialog.bind(null, false)}, "Scale"],
["button", {onclick: openTestDialog.bind(null, true)}, "Height"]
]
]),
optionsPanelContainer.children[1]
);
var resetSession = () => {
if (localStorage) {
localStorage.last_session = undefined;
}
try {
var session = env.editor.session;
if (session.name)
var cachedDoc = doclist.fileCache[session.name.toLowerCase()];
if (cachedDoc) {
cachedDoc.session = undefined;
}
optionsPanel.setOption("doc", util.getOption("doc") || "JavaScript");
} catch (e) {
console.error(e);
}
};
optionsPanelContainer.insertBefore(
dom.buildDom(["div", {style: "text-align:center;width: 100%"},
["div", {},
["button", {onclick: resetSession}, "Reset session"]],
]),
optionsPanelContainer.children[0]
);
function openTestDialog(animateHeight) {
if (window.dialogEditor)
window.dialogEditor.destroy();
var editor = ace.edit(null, {
value: "test editor",
mode: "ace/mode/javascript",
enableBasicAutocompletion: true
});
window.dialogEditor = editor;
editor.completer.parentNode = editor.container;
if (window.languageProvider)
window.languageProvider.registerEditor(editor);
var dialog = dom.buildDom(["div", {
style: "transition: all 1s; position: fixed; z-index: 100000;"
+ "background: darkblue; border: solid 1px black; display: flex; flex-direction: column"
},
["div", {}, "test dialog"],
editor.container
], document.body);
editor.container.style.flex = "1";
if (animateHeight) {
dialog.style.width = "0vw";
dialog.style.height = "0vh";
dialog.style.left = "20vw";
dialog.style.top = "20vh";
setTimeout(function() {
dialog.style.width = "80vw";
dialog.style.height = "80vh";
dialog.style.left = "10vw";
dialog.style.top = "10vh";
}, 0);
} else {
dialog.style.width = "80vw";
dialog.style.height = "80vh";
dialog.style.left = "10vw";
dialog.style.top = "10vh";
dialog.style.transform = "scale(0)";
setTimeout(function() {
dialog.style.transform = "scale(1)"
}, 0);
}
function close(e) {
if (!e || !dialog.contains(e.target)) {
if (animateHeight) {
dialog.style.width = "0vw";
dialog.style.height = "0vh";
dialog.style.left = "80vw";
dialog.style.top = "80vh";
} else {
dialog.style.transform = "scale(0)"
}
window.removeEventListener("mousedown", close);
dialog.addEventListener("transitionend", function() {
dialog.remove();
editor.destroy();
});
}
}
window.addEventListener("mousedown", close);
editor.focus()
editor.commands.bindKey("Esc", function() { close(); });
}
require("ace/ext/language_tools");
require("ace/ext/inline_autocomplete");
env.editor.setOptions({
enableBasicAutocompletion: true,
enableInlineAutocompletion: true,
enableSnippets: true
});
var beautify = require("ace/ext/beautify");
env.editor.commands.addCommands(beautify.commands);
// global keybindings
var KeyBinding = require("ace/keyboard/keybinding").KeyBinding;
var CommandManager = require("ace/commands/command_manager").CommandManager;
var commandManager = new CommandManager();
var kb = new KeyBinding({
commands: commandManager,
fake: true
});
event.addCommandKeyListener(document.documentElement, kb.onCommandKey.bind(kb));
event.addListener(document.documentElement, "keyup", function(e) {
if (e.keyCode === 18) // do not trigger browser menu on windows
e.preventDefault();
});
commandManager.addCommands([{
name: "window-left",
bindKey: {win: "cmd-alt-left", mac: "ctrl-cmd-left"},
exec: function() {
moveFocus();
}
}, {
name: "window-right",
bindKey: {win: "cmd-alt-right", mac: "ctrl-cmd-right"},
exec: function() {
moveFocus();
}
}, {
name: "window-up",
bindKey: {win: "cmd-alt-up", mac: "ctrl-cmd-up"},
exec: function() {
moveFocus();
}
}, {
name: "window-down",
bindKey: {win: "cmd-alt-down", mac: "ctrl-cmd-down"},
exec: function() {
moveFocus();
}
}]);
function moveFocus() {
var el = document.activeElement;
if (el == env.editor.textInput.getElement())
env.editor.cmdLine.focus();
else
env.editor.focus();
}
window.onbeforeunload = function () {
if (env.editor && localStorage) {
var sessionObj = env.editor.session.toJSON();
sessionObj.name = util.getOption("doc") || "JavaScript";
localStorage.last_session = JSON.stringify(sessionObj);
}
};
================================================
FILE: demo/kitchen-sink/dev_util.js
================================================
var ace = require("ace/ace");
var dom = require("ace/lib/dom");
var event = require("ace/lib/event");
var Range = require("ace/range").Range;
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
function def(o, key, get) {
try {
Object.defineProperty(o, key, {
configurable: true,
get: get,
set: function(val) {
delete o[key];
o[key] = val;
}
});
} catch(e) {
console.error(e);
}
}
def(window, "ace", function(){ return ace });
def(window, "editor", function(){ return window.env.editor == logEditor ? editor : window.env.editor });
def(window, "session", function(){ return window.editor.session });
def(window, "split", function(){ return window.env.split });
def(window, "devUtil", function(){ return exports });
exports.addGlobals = function() {
window.oop = require("ace/lib/oop");
window.dom = require("ace/lib/dom");
window.user = require("ace/test/user");
window.Range = require("ace/range").Range;
window.Editor = require("ace/editor").Editor;
window.assert = require("ace/test/asyncjs/assert");
window.asyncjs = require("ace/test/asyncjs/async");
window.UndoManager = require("ace/undomanager").UndoManager;
window.EditSession = require("ace/edit_session").EditSession;
window.MockRenderer = require("ace/test/mockrenderer").MockRenderer;
window.EventEmitter = require("ace/lib/event_emitter").EventEmitter;
window.getSelection = getSelection;
window.setSelection = setSelection;
window.testSelection = testSelection;
window.setValue = setValue;
window.testValue = testValue;
window.logToAce = exports.log;
};
function getSelection(editor) {
var data = editor.multiSelect.toJSON();
if (!data.length) data = [data];
data = data.map(function(x) {
var a, c;
if (x.isBackwards) {
a = x.end;
c = x.start;
} else {
c = x.end;
a = x.start;
}
return Range.comparePoints(a, c)
? [a.row, a.column, c.row, c.column]
: [a.row, a.column];
});
return data.length > 1 ? data : data[0];
}
function setSelection(editor, data) {
if (typeof data[0] == "number")
data = [data];
editor.selection.fromJSON(data.map(function(x) {
var start = {row: x[0], column: x[1]};
var end = x.length == 2 ? start : {row: x[2], column: x[3]};
var isBackwards = Range.comparePoints(start, end) > 0;
return isBackwards ? {
start: end,
end: start,
isBackwards: true
} : {
start: start,
end: end,
isBackwards: true
};
}));
}
function testSelection(editor, data) {
assert.equal(getSelection(editor) + "", data + "");
}
function setValue(editor, value) {
editor.setValue(value, 1);
}
function testValue(editor, value) {
assert.equal(editor.getValue(), value);
}
var editor;
var logEditor;
var logSession
exports.openLogView = function() {
exports.addGlobals();
var sp = window.env.split;
sp.setSplits(1);
sp.setSplits(2);
sp.setOrientation(sp.BESIDE);
editor = sp.$editors[0];
logEditor = sp.$editors[1];
if (!logSession) {
logSession = new EditSession(localStorage.lastTestCase || "", "ace/mode/javascript");
logSession.setUndoManager(new UndoManager)
}
logEditor.setSession(logSession);
logEditor.session.foldAll();
logEditor.on("input", save);
}
exports.record = function() {
exports.addGlobals();
exports.openLogView();
logEditor.setValue("var Range = require(\"ace/range\").Range;\n"
+ getSelection + "\n"
+ testSelection + "\n"
+ setSelection + "\n"
+ testValue + "\n"
+ setValue + "\n"
+ "\n//-------------------------------------\n", 1);
logEditor.session.foldAll();
addAction({
type: "setValue",
data: editor.getValue()
});
addAction({
type: "setSelection",
data: getSelection(editor)
});
editor.commands.on("afterExec", onAfterExec);
editor.on("mouseup", onMouseUp);
editor.selection.on("beforeEndOperation", onBeforeEndOperation);
editor.session.on("change", reportChange);
editor.selection.on("changeCursor", reportCursorChange);
editor.selection.on("changeSelection", reportSelectionChange);
}
exports.stop = function() {
save();
editor.commands.off("afterExec", onAfterExec);
editor.off("mouseup", onMouseUp);
editor.off("beforeEndOperation", onBeforeEndOperation);
editor.session.off("change", reportChange);
editor.selection.off("changeCursor", reportCursorChange);
editor.selection.off("changeSelection", reportSelectionChange);
logEditor.off("input", save);
}
exports.closeLogView = function() {
exports.stop();
var sp = window.env.split;
sp.setSplits(1);
}
exports.play = function() {
exports.openLogView();
exports.stop();
var code = logEditor ? logEditor.getValue() : localStorage.lastTestCase;
var fn = new Function("editor", "debugger;\n" + code);
fn(editor);
}
var reportChange = reportEvent.bind(null, "change");
var reportCursorChange = reportEvent.bind(null, "CursorChange");
var reportSelectionChange = reportEvent.bind(null, "SelectionChange");
function save() {
localStorage.lastTestCase = logEditor.getValue();
}
function reportEvent(name) {
addAction({
type: "event",
source: name
});
}
function onSelection() {
addAction({
type: "event",
data: "change",
source: "operationEnd"
});
}
function onBeforeEndOperation() {
addAction({
type: "setSelection",
data: getSelection(editor),
source: "operationEnd"
});
}
function onMouseUp() {
addAction({
type: "setSelection",
data: getSelection(editor),
source: "mouseup"
});
}
function onAfterExec(e) {
addAction({
type: "exec",
data: e
});
addAction({
type: "value",
data: editor.getValue()
});
addAction({
type: "selection",
data: getSelection(editor)
});
}
function addAction(a) {
var str = toString(a);
if (str) {
logEditor.insert(str + "\n");
logEditor.renderer.scrollCursorIntoView();
}
}
var lastValue = "";
function toString(x) {
var str = "";
var data = x.data;
switch (x.type) {
case "exec":
str = 'editor.execCommand("'
+ data.command.name
+ (data.args ? '", ' + JSON.stringify(data.args) : '"')
+ ')';
break;
case "setSelection":
str = 'setSelection(editor, ' + JSON.stringify(data) + ')';
break;
case "setValue":
if (lastValue != data) {
lastValue = data;
str = 'editor.setValue(' + JSON.stringify(data) + ', -1)';
}
else {
return;
}
break;
case "selection":
str = 'testSelection(editor, ' + JSON.stringify(data) + ')';
break;
case "value":
if (lastValue != data) {
lastValue = data;
str = 'testValue(editor, ' + JSON.stringify(data) + ')';
}
else {
return;
}
break;
}
return str + (x.source ? " // " + x.source : "");
}
exports.getUI = function(container) {
return ["div", {role: "group", "aria-label": "Test"},
" Test ",
["button", {"aria-label": "Open Log View", onclick: exports.openLogView}, "O"],
["button", {onclick: exports.record}, "Record"],
["button", {onclick: exports.stop}, "Stop"],
["button", {onclick: exports.play}, "Play"],
["button", {"aria-label": "Close Log View", onclick: exports.closeLogView}, "X"],
];
};
var ignoreEvents = false;
exports.textInputDebugger = {
position: 2000,
path: "textInputDebugger",
onchange: function(value) {
var sp = env.split;
if (sp.getSplits() == 2) {
sp.setSplits(1);
}
if (env.textarea) {
if (env.textarea.detach)
env.textarea.detach();
env.textarea.oldParent.appendChild(env.textarea);
env.textarea.className = env.textarea.oldClassName;
env.textarea = null;
}
if (value) {
this.showConsole();
}
},
showConsole: function() {
var editor = env.split.$editors[0];
var text = editor.textInput.getElement();
text.oldParent = text.parentNode;
text.oldClassName = text.className;
text.className = "text-input-debug";
document.body.appendChild(text);
env.textarea = text;
var addToLog = function(e) {
if (ignoreEvents) return;
var data = {
_: e.type,
data: e.data,
inputType: e.inputType,
range: [text.selectionStart, text.selectionEnd],
value: text.value,
key: e.key && {
code: e.code,
key: e.key,
keyCode: e.keyCode
},
modifier: event.getModifierString(e) || undefined
};
var str = JSON.stringify(data).replace(/"(\w+)":/g, " $1: ");
exports.log(str);
};
var events = ["select", "input", "keypress", "keydown", "keyup",
"compositionstart", "compositionupdate", "compositionend", "cut", "copy", "paste"
];
events.forEach(function(name) {
text.addEventListener(name, addToLog, true);
});
function onMousedown(ev) {
if (ev.domEvent.target == text)
ev.$pos = editor.getCursorPosition();
}
text.detach = function() {
delete text.value;
delete text.setSelectionRange;
events.forEach(function(name) {
text.removeEventListener(name, addToLog, true);
});
editor.off("mousedown", onMousedown);
};
editor.on("mousedown", onMousedown);
text.__defineSetter__("value", function(v) {
this.__proto__.__lookupSetter__("value").call(this, v);
console.log(v);
});
text.__defineGetter__("value", function(v) {
var v = this.__proto__.__lookupGetter__("value").call(this);
return v;
});
text.setSelectionRange = function(start, end) {
ignoreEvents = true;
this.__proto__.setSelectionRange.call(this, start, end)
ignoreEvents = false;
}
exports.openConsole();
editor.focus();
},
getValue: function() {
return !!env.textarea;
}
};
exports.textPositionDebugger = {
position: 2000,
path: "textPositionDebugger",
onchange: function(value) {
document.body.classList[value ? "add" : "remove"]("show-text-input")
},
getValue: function() {
return document.body.classList.contains("show-text-input");
}
};
exports.openConsole = function() {
var sp = env.split;
var logEditor = sp.$editors[1];
if (!logEditor) {
sp.setSplits(2);
sp.setOrientation(sp.BELOW);
logEditor = sp.$editors[1];
}
if (!exports.session)
exports.session = new EditSession("");
logEditor.setSession(exports.session);
return logEditor
};
exports.log = function(str) {
var logEditor = exports.openConsole();
logEditor.navigateFileEnd();
logEditor.insert(str + ",\n");
logEditor.renderer.scrollCursorIntoView();
};
exports.addGlobals();
================================================
FILE: demo/kitchen-sink/doclist.js
================================================
"use strict";
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var net = require("ace/lib/net");
var modelist = require("ace/ext/modelist");
/*********** demo documents ***************************/
var fileCache = {};
function initDoc(file, path, doc) {
if (doc.prepare)
file = doc.prepare(file);
var session = new EditSession(file);
session.setUndoManager(new UndoManager());
doc.session = session;
doc.path = path;
session.name = doc.name;
if (doc.wrapped) {
session.setUseWrapMode(true);
session.setWrapLimitRange(80, 80);
}
var mode = modelist.getModeForPath(path);
session.modeName = mode.name;
session.setMode(mode.mode);
return session;
}
function makeHuge(txt) {
for (var i = 0; i < 5; i++)
txt += txt;
return txt;
}
var docs = {
"docs/javascript.js": {order: 1, name: "JavaScript"},
"docs/latex.tex": {name: "LaTeX", wrapped: true},
"docs/markdown.md": {name: "Markdown", wrapped: true},
"docs/mushcode.mc": {name: "MUSHCode", wrapped: true},
"docs/pgsql.pgsql": {name: "pgSQL", wrapped: true},
"docs/plaintext.txt": {name: "Plain Text", prepare: makeHuge, wrapped: true},
"docs/sql.sql": {name: "SQL", wrapped: true},
"docs/textile.textile": {name: "Textile", wrapped: true},
"docs/c9search.c9search_results": "C9 Search Results",
"docs/mel.mel": "MEL",
};
var ownSource = {
/* filled from require*/
};
var hugeDocs = require.toUrl ? {
"build/src/ace.js": "",
"build/src-min/ace.js": ""
} : {
"src/ace.js": "",
"src-min/ace.js": ""
};
modelist.modes.forEach(function(m) {
var ext = m.extensions.split("|")[0];
if (ext[0] === "^") {
path = ext.substr(1);
} else {
var path = m.name + "." + ext;
}
path = "docs/" + path;
if (!docs[path]) {
docs[path] = {name: m.caption};
} else if (typeof docs[path] == "object" && !docs[path].name) {
docs[path].name = m.caption;
}
});
if (window.define && window.define.modules) try {
for (var path in window.define.modules) {
if (path.indexOf("!") != -1)
path = path.split("!").pop();
else
path = path + ".js";
ownSource[path] = "";
}
} catch(e) {}
function sort(list) {
return list.sort(function(a, b) {
var cmp = (b.order || 0) - (a.order || 0);
return cmp || a.name && a.name.localeCompare(b.name);
});
}
function prepareDocList(docs) {
var list = [];
for (var path in docs) {
var doc = docs[path];
if (typeof doc != "object")
doc = {name: doc || path};
doc.path = path;
doc.desc = doc.name.replace(/^(ace|docs|demo|build)\//, "");
if (doc.desc.length > 18)
doc.desc = doc.desc.slice(0, 7) + ".." + doc.desc.slice(-9);
fileCache[doc.name.toLowerCase()] = doc;
list.push(doc);
}
return list;
}
function loadDoc(name, callback) {
var doc = fileCache[name.toLowerCase()];
if (!doc)
return callback(null);
if (doc.session)
return callback(doc.session);
// TODO: show load screen while waiting
var path = doc.path;
var parts = path.split("/");
if (parts[0] == "docs")
path = "demo/kitchen-sink/" + path;
else if (parts[0] == "ace")
path = "src/" + parts.slice(1).join("/");
net.get(path, function(x) {
initDoc(x, path, doc);
callback(doc.session);
});
}
function saveDoc(name, callback) {
var doc = name;
if (typeof(name) === 'string') {
doc = fileCache[name.toLowerCase()];
}
if (!doc || !doc.session)
return callback("Unknown document: " + name);
var path = doc.path;
var parts = path.split("/");
if (parts[0] == "docs")
path = "demo/kitchen-sink/" + path;
else if (parts[0] == "ace")
path = "src/" + parts.slice(1).join("/");
upload(path, doc.session.getValue(), callback);
}
function upload(url, data, callback) {
var absUrl = net.qualifyURL(url);
if (/^file:/.test(absUrl))
absUrl = "http://localhost:8888/" + url;
url = absUrl;
if (!/^https?:/.test(url))
return callback(new Error("Unsupported url scheme"));
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(!/^2../.test(xhr.status));
}
};
xhr.send(data);
}
module.exports = {
fileCache: fileCache,
docs: sort(prepareDocList(docs)),
ownSource: prepareDocList(ownSource),
hugeDocs: prepareDocList(hugeDocs),
initDoc: initDoc,
loadDoc: loadDoc,
saveDoc: saveDoc
};
module.exports.all = {
"Mode Examples": module.exports.docs,
"Huge documents": module.exports.hugeDocs,
"own source": module.exports.ownSource
};
================================================
FILE: demo/kitchen-sink/docs/Dockerfile
================================================
#
# example Dockerfile for http://docs.docker.io/en/latest/examples/postgresql_service/
#
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
# Add the PostgreSQL PGP key to verify their Debian packages.
# It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
# Add PostgreSQL's repository. It contains the most recent stable release
# of PostgreSQL, ``9.3``.
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
# Update the Ubuntu and PostgreSQL repository indexes
RUN apt-get update
# Install ``python-software-properties``, ``software-properties-common`` and PostgreSQL 9.3
# There are some warnings (in red) that show up during the build. You can hide
# them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive
RUN apt-get -y -q install python-software-properties software-properties-common
RUN apt-get -y -q install postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
# Note: The official Debian and Ubuntu images automatically ``apt-get clean``
# after each ``apt-get``
# Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed``
USER postgres
# Create a PostgreSQL role named ``docker`` with ``docker`` as the password and
# then create a database `docker` owned by the ``docker`` role.
# Note: here we use ``&&\`` to run commands one after the other - the ``\``
# allows the RUN command to span multiple lines.
RUN /etc/init.d/postgresql start &&\
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\
createdb -O docker docker
# Adjust PostgreSQL configuration so that remote connections to the
# database are possible.
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf
# And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf``
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf
# Expose the PostgreSQL port
EXPOSE 5432
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
# Set the default command to run when starting the container
CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]
================================================
FILE: demo/kitchen-sink/docs/Makefile
================================================
.PHONY: apf ext worker mode theme package test
default: apf worker
update: worker
# packages apf
# This is the first line of a comment \
and this is still part of the comment \
as is this, since I keep ending each line \
with a backslash character
apf:
cd node_modules/packager; node package.js projects/apf_cloud9.apr
cd node_modules/packager; cat build/apf_release.js | sed 's/\(\/\*FILEHEAD(\).*//g' > ../../plugins-client/lib.apf/www/apf-packaged/apf_release.js
# package debug version of apf
apfdebug:
cd node_modules/packager/projects; cat apf_cloud9.apr | sed 's///g' > apf_cloud9_debug2.apr
cd node_modules/packager/projects; cat apf_cloud9_debug2.apr | sed 's/apf_release/apf_debug/g' > apf_cloud9_debug.apr; rm apf_cloud9_debug2.apr
cd node_modules/packager; node package.js projects/apf_cloud9_debug.apr
cd node_modules/packager; cat build/apf_debug.js | sed 's/\(\/\*FILEHEAD(\).*\/apf\/\(.*\)/\1\2/g' > ../../plugins-client/lib.apf/www/apf-packaged/apf_debug.js
# package_apf--temporary fix for non-workering infra
pack_apf:
mkdir -p build/src
mv plugins-client/lib.apf/www/apf-packaged/apf_release.js build/src/apf_release.js
node build/r.js -o name=./build/src/apf_release.js out=./plugins-client/lib.apf/www/apf-packaged/apf_release.js baseUrl=.
# makes ace; at the moment, requires dryice@0.4.2
ace:
cd node_modules/ace; make clean pre_build; ./Makefile.dryice.js minimal
# packages core
core: ace
mkdir -p build/src
node build/r.js -o build/core.build.js
# generates packed template
helper:
node build/packed_helper.js
helper_clean:
mkdir -p build/src
node build/packed_helper.js 1
# packages ext
ext:
node build/r.js -o build/app.build.js
# calls dryice on worker & packages it
worker: plugins-client/lib.ace/www/worker/worker-language.js
plugins-client/lib.ace/www/worker/worker-language.js plugins-client/lib.ace/www/worker/worker-javascript.js : \
$(wildcard node_modules/ace/*) $(wildcard node_modules/ace/*/*) $(wildcard node_modules/ace/*/*/mode/*) \
$(wildcard plugins-client/ext.language/*) \
$(wildcard plugins-client/ext.language/*/*) \
$(wildcard plugins-client/ext.linereport/*) \
$(wildcard plugins-client/ext.codecomplete/*) \
$(wildcard plugins-client/ext.codecomplete/*/*) \
$(wildcard plugins-client/ext.jslanguage/*) \
$(wildcard plugins-client/ext.jslanguage/*/*) \
$(wildcard plugins-client/ext.csslanguage/*) \
$(wildcard plugins-client/ext.csslanguage/*/*) \
$(wildcard plugins-client/ext.htmllanguage/*) \
$(wildcard plugins-client/ext.htmllanguage/*/*) \
$(wildcard plugins-client/ext.jsinfer/*) \
$(wildcard plugins-client/ext.jsinfer/*/*) \
$(wildcard node_modules/treehugger/lib/*) \
$(wildcard node_modules/treehugger/lib/*/*) \
$(wildcard node_modules/ace/lib/*) \
$(wildcard node_modules/ace/*/*) \
Makefile.dryice.js
mkdir -p plugins-client/lib.ace/www/worker
rm -rf /tmp/c9_worker_build
mkdir -p /tmp/c9_worker_build/ext
ln -s `pwd`/plugins-client/ext.language /tmp/c9_worker_build/ext/language
ln -s `pwd`/plugins-client/ext.codecomplete /tmp/c9_worker_build/ext/codecomplete
ln -s `pwd`/plugins-client/ext.jslanguage /tmp/c9_worker_build/ext/jslanguage
ln -s `pwd`/plugins-client/ext.csslanguage /tmp/c9_worker_build/ext/csslanguage
ln -s `pwd`/plugins-client/ext.htmllanguage /tmp/c9_worker_build/ext/htmllanguage
ln -s `pwd`/plugins-client/ext.linereport /tmp/c9_worker_build/ext/linereport
ln -s `pwd`/plugins-client/ext.linereport_php /tmp/c9_worker_build/ext/linereport_php
node Makefile.dryice.js worker
cp node_modules/ace/build/src/worker* plugins-client/lib.ace/www/worker
define
ifeq
override
# copies built ace modes
mode:
mkdir -p plugins-client/lib.ace/www/mode
cp `find node_modules/ace/build/src | grep -E "mode-[a-zA-Z_0-9]+.js"` plugins-client/lib.ace/www/mode
# copies built ace themes
theme:
mkdir -p plugins-client/lib.ace/www/theme
cp `find node_modules/ace/build/src | grep -E "theme-[a-zA-Z_0-9]+.js"` plugins-client/lib.ace/www/theme
gzip_safe:
for i in `ls ./plugins-client/lib.packed/www/*.js`; do \
gzip -9 -v -c -q -f $$i > $$i.gz ; \
done
gzip:
for i in `ls ./plugins-client/lib.packed/www/*.js`; do \
gzip -9 -v -q -f $$i ; \
done
c9core: apf ace core worker mode theme
package_clean: helper_clean c9core ext
package: helper c9core ext
test check:
test/run-tests.sh
================================================
FILE: demo/kitchen-sink/docs/abap.abap
================================================
***************************************
** Program: EXAMPLE **
** Author: Joe Byte, 07-Jul-2007 **
***************************************
REPORT BOOKINGS.
* Read flight bookings from the database
SELECT * FROM FLIGHTINFO
WHERE CLASS = 'Y' "Y = economy
OR CLASS = 'C'. "C = business
(...)
REPORT TEST.
WRITE 'Hello World'.
USERPROMPT = 'Please double-click on a line in the output list ' &
'to see the complete details of the transaction.'.
DATA LAST_EOM TYPE D. "last end-of-month date
* Start from today's date
LAST_EOM = SY-DATUM.
* Set characters 6 and 7 (0-relative) of the YYYYMMDD string to "01",
* giving the first day of the current month
LAST_EOM+6(2) = '01'.
* Subtract one day
LAST_EOM = LAST_EOM - 1.
WRITE: 'Last day of previous month was', LAST_EOM.
DATA : BEGIN OF I_VBRK OCCURS 0,
VBELN LIKE VBRK-VBELN,
ZUONR LIKE VBRK-ZUONR,
END OF I_VBRK.
SORT i_vbrk BY vbeln ASCENDING.
SORT i_vbrk BY vbeln DESCENDING.
RETURN.
================================================
FILE: demo/kitchen-sink/docs/abc.abc
================================================
%abc-2.1
H:This file contains some example English tunes
% note that the comments (like this one) are to highlight usages
% and would not normally be included in such detail
O:England % the origin of all tunes is England
X:1 % tune no 1
T:Dusty Miller, The % title
T:Binny's Jig % an alternative title
C:Trad. % traditional
R:DH % double hornpipe
M:3/4 % meter
K:G % key
B>cd BAG|FA Ac BA|B>cd BAG|DG GB AG:|
Bdd gfg|aA Ac BA|Bdd gfa|gG GB AG:|
BG G/2G/2G BG|FA Ac BA|BG G/2G/2G BG|DG GB AG:|
W:Hey, the dusty miller, and his dusty coat;
W:He will win a shilling, or he spend a groat.
W:Dusty was the coat, dusty was the colour;
W:Dusty was the kiss, that I got frae the miller.
X:2
T:Old Sir Simon the King
C:Trad.
S:Offord MSS % from Offord manuscript
N:see also Playford % reference note
M:9/8
R:SJ % slip jig
N:originally in C % transcription note
K:G
D|GFG GAG G2D|GFG GAG F2D|EFE EFE EFG|A2G F2E D2:|
D|GAG GAB d2D|GAG GAB c2D|[1 EFE EFE EFG|[A2G] F2E D2:|\ % no line-break in score
M:12/8 % change of meter
[2 E2E EFE E2E EFG|\ % no line-break in score
M:9/8 % change of meter
A2G F2E D2|]
X:3
T:William and Nancy
T:New Mown Hay
T:Legacy, The
C:Trad.
O:England; Gloucs; Bledington % place of origin
B:Sussex Tune Book % can be found in these books
B:Mally's Cotswold Morris vol.1 2
D:Morris On % can be heard on this record
P:(AB)2(AC)2A % play the parts in this order
M:6/8
K:G
[P:A] D|"G"G2G GBd|"C"e2e "G"dBG|"D7"A2d "G"BAG|"C"E2"D7"F "G"G2:|
[P:B] d|"G"e2d B2d|"C"gfe "G"d2d| "G"e2d B2d|"C"gfe "D7"d2c|
"G"B2B Bcd|"C"e2e "G"dBG|"D7"A2d "G"BAG|"C"E2"D7"F "G"G2:|
% changes of meter, using inline fields
[T:Slows][M:4/4][L:1/4][P:C]"G"d2|"C"e2 "G"d2|B2 d2|"Em"gf "A7"e2|"D7"d2 "G"d2|\
"C"e2 "G"d2|[M:3/8][L:1/8] "G"B2 d |[M:6/8] "C"gfe "D7"d2c|
"G"B2B Bcd|"C"e2e "G"dBG|"D7"A2d "G"BAG|"C"E2"D7"F "G"G2:|
X:4
T:South Downs Jig
R:jig
S:Robert Harbron
M:6/8
L:1/8
K:G
|: d | dcA G3 | EFG AFE | DEF GAB | cde d2d |
dcA G3 | EFG AFE | DEF GAB | cAF G2 :|
B | Bcd e2c | d2B c2A | Bcd e2c | [M:9/8]d2B c2B A3 |
[M:6/8]DGF E3 | cBA FED | DEF GAB |1 cAF G2 :|2 cAF G3 |]
X:5
T:Atholl Brose
% in this example, which reproduces Highland Bagpipe gracing,
% the large number of grace notes mean that it is more convenient to be specific about
% score line-breaks (using the $ symbol), rather than using code line breaks to indicate them
I:linebreak $
K:D
{gcd}c<{e}A {gAGAG}A2 {gef}e>A {gAGAG}Ad|
{gcd}c<{e}A {gAGAG}A>e {ag}a>f {gef}e>d|
{gcd}c<{e}A {gAGAG}A2 {gef}e>A {gAGAG}Ad|
{g}c/d/e {g}G>{d}B {gf}gG {dc}d>B:|$
{g}ce {ag}a>e {gf}g>e|
{g}ce {ag}a2 {GdG}a>d|
{g}ce {ag}a>e {gf}g>f|
{gef}e>d {gf}g>d {gBd}B<{e}G {dc}d>B|
{g}ce {ag}a>e {gf}g>e|
{g}ce {ag}a2 {GdG}ad|
{g}c<{GdG}e {gf}ga {f}g>e {g}f>d|
{g}e/f/g {Gdc}d>c {gBd}B<{e}G {dc}d2|]
X:6
T:Untitled Reel
C:Trad.
K:D
eg|a2ab ageg|agbg agef|g2g2 fgag|f2d2 d2:|\
ed|cecA B2ed|cAcA E2ed|cecA B2ed|c2A2 A2:|
K:G
AB|cdec BcdB|ABAF GFE2|cdec BcdB|c2A2 A2:|
X:7
T:Kitchen Girl
C:Trad.
K:D
[c4a4] [B4g4]|efed c2cd|e2f2 gaba|g2e2 e2fg|
a4 g4|efed cdef|g2d2 efed|c2A2 A4:|
K:G
ABcA BAGB|ABAG EDEG|A2AB c2d2|e3f edcB|ABcA BAGB|
ABAG EGAB|cBAc BAG2|A4 A4:|
%abc-2.1
%%pagewidth 21cm
%%pageheight 29.7cm
%%topspace 0.5cm
%%topmargin 1cm
%%botmargin 0cm
%%leftmargin 1cm
%%rightmargin 1cm
%%titlespace 0cm
%%titlefont Times-Bold 32
%%subtitlefont Times-Bold 24
%%composerfont Times 16
%%vocalfont Times-Roman 14
%%staffsep 60pt
%%sysstaffsep 20pt
%%musicspace 1cm
%%vocalspace 5pt
%%measurenb 0
%%barsperstaff 5
%%scale 0.7
X: 1
T: Canzonetta a tre voci
C: Claudio Monteverdi (1567-1643)
M: C
L: 1/4
Q: "Andante mosso" 1/4 = 110
%%score [1 2 3]
V: 1 clef=treble name="Soprano"sname="A"
V: 2 clef=treble name="Alto" sname="T"
V: 3 clef=bass middle=d name="Tenor" sname="B"
%%MIDI program 1 75 % recorder
%%MIDI program 2 75
%%MIDI program 3 75
K: Eb
% 1 - 4
[V: 1] |:z4 |z4 |f2ec |_ddcc |
w: Son que-sti~i cre-spi cri-ni~e
w: Que-sti son gli~oc-chi che mi-
[V: 2] |:c2BG|AAGc|(F/G/A/B/)c=A|B2AA |
w: Son que-sti~i cre-spi cri-ni~e que - - - - sto~il vi-so e
w: Que-sti son~gli oc-chi che mi-ran - - - - do fi-so mi-
[V: 3] |:z4 |f2ec|_ddcf |(B/c/_d/e/)ff|
w: Son que-sti~i cre-spi cri-ni~e que - - - - sto~il
w: Que-sti son~gli oc-chi che mi-ran - - - - do
% 5 - 9
[V: 1] cAB2 |cAAA |c3B|G2!fermata!Gz ::e4|
w: que-sto~il vi-so ond' io ri-man-go~uc-ci-so. Deh,
w: ran-do fi-so, tut-to re-stai con-qui-so.
[V: 2] AAG2 |AFFF |A3F|=E2!fermata!Ez::c4|
w: que-sto~il vi-so ond' io ri-man-go~uc-ci-so. Deh,
w: ran-do fi-so tut-to re-stai con-qui-so.
[V: 3] (ag/f/e2)|A_ddd|A3B|c2!fermata!cz ::A4|
w: vi - - - so ond' io ti-man-go~uc-ci-so. Deh,
w: fi - - - so tut-to re-stai con-qui-so.
% 10 - 15
[V: 1] f_dec |B2c2|zAGF |\
w: dim-me-lo ben mi-o, che que-sto\
=EFG2 |1F2z2:|2F8|] % more notes
w: sol de-si-o_. % more lyrics
[V: 2] ABGA |G2AA|GF=EF |(GF3/2=E//D//E)|1F2z2:|2F8|]
w: dim-me-lo ben mi-o, che que-sto sol de-si - - - - o_.
[V: 3] _dBc>d|e2AF|=EFc_d|c4 |1F2z2:|2F8|]
w: dim-me-lo ben mi-o, che que-sto sol de-si-o_.
================================================
FILE: demo/kitchen-sink/docs/actionscript.as
================================================
package code
{
/*****************************************
* based on textmate actionscript bundle
****************************************/
import fl.events.SliderEvent;
public class Foo extends MovieClip
{
//*************************
// Properties:
public var activeSwatch:MovieClip;
// Color offsets
public var c1:Number = 0; // R
//*************************
// Constructor:
public function Foo()
{
// Respond to mouse events
swatch1_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
previewBox_btn.addEventListener(MouseEvent.MOUSE_DOWN,dragPressHandler);
// Respond to drag events
red_slider.addEventListener(SliderEvent.THUMB_DRAG,sliderHandler);
// Draw a frame later
addEventListener(Event.ENTER_FRAME,draw);
}
protected function clickHandler(event:MouseEvent):void
{
car.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
}
protected function changeRGBHandler(event:Event):void
{
c1 = Number(c1_txt.text);
if(!(c1>=0)){
c1 = 0;
}
updateSliders();
}
}
}
================================================
FILE: demo/kitchen-sink/docs/ada.ada
================================================
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is
begin
Put_Line("Hello, world!");
end Hello;
================================================
FILE: demo/kitchen-sink/docs/alda.alda
================================================
# Example taken from https://github.com/alda-lang/alda-core/blob/master/examples/across_the_sea.alda
(tempo! 90)
(quant! 95)
piano:
o5 g- > g- g-/f > e- d-4. < b-8 d-2 | c-4 e- d- d- g-
flute:
r2 g-4 a- b-2. > d-32~ e-16.~8 < b-2 a- g-1
================================================
FILE: demo/kitchen-sink/docs/apex.apex
================================================
public class testBlockDuplicatesLeadTrigger {
static testMethod void testDuplicateTrigger(){
Lead[] l1 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
insert l1; // add a known lead
Lead[] l2 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
// try to add a matching lead
try { insert l2; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}
// test duplicates in the same batch
Lead[] l3 =new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' ),
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
try { insert l3; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Another new lead has the same email'),
e.getMessage());
}
// test update also
Lead[] lup = new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
insert lup;
Lead marge = [ select id,Email from lead where Email = 'marge@fox.tv' limit 1];
system.assert(marge!=null);
marge.Email = 'homer@fox.tv';
try { update marge; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('irst error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}
}
}
================================================
FILE: demo/kitchen-sink/docs/aql.aql
================================================
FOR user IN users
FILTER user.username == "olivier"
RETURN user
================================================
FILE: demo/kitchen-sink/docs/asciidoc.asciidoc
================================================
AsciiDoc User Guide
===================
Stuart Rackham
:Author Initials: SJR
:toc:
:icons:
:numbered:
:website: http://www.methods.co.nz/asciidoc/
AsciiDoc is a text document format for writing notes, documentation,
articles, books, ebooks, slideshows, web pages, blogs and UNIX man
pages. AsciiDoc files can be translated to many formats including
HTML, PDF, EPUB, man page. AsciiDoc is highly configurable: both the
AsciiDoc source file syntax and the backend output markups (which can
be almost any type of SGML/XML markup) can be customized and extended
by the user.
.This document
**********************************************************************
This is an overly large document, it probably needs to be refactored
into a Tutorial, Quick Reference and Formal Reference.
If you're new to AsciiDoc read this section and the <> section and take a look at the example AsciiDoc (`*.txt`)
source files in the distribution `doc` directory.
**********************************************************************
Introduction
------------
AsciiDoc is a plain text human readable/writable document format that
can be translated to DocBook or HTML using the asciidoc(1) command.
You can then either use asciidoc(1) generated HTML directly or run
asciidoc(1) DocBook output through your favorite DocBook toolchain or
use the AsciiDoc a2x(1) toolchain wrapper to produce PDF, EPUB, DVI,
LaTeX, PostScript, man page, HTML and text formats.
The AsciiDoc format is a useful presentation format in its own right:
AsciiDoc markup is simple, intuitive and as such is easily proofed and
edited.
AsciiDoc is light weight: it consists of a single Python script and a
bunch of configuration files. Apart from asciidoc(1) and a Python
interpreter, no other programs are required to convert AsciiDoc text
files to DocBook or HTML. See <>
below.
Text markup conventions tend to be a matter of (often strong) personal
preference: if the default syntax is not to your liking you can define
your own by editing the text based asciidoc(1) configuration files.
You can also create configuration files to translate AsciiDoc
documents to almost any SGML/XML markup.
asciidoc(1) comes with a set of configuration files to translate
AsciiDoc articles, books and man pages to HTML or DocBook backend
formats.
.My AsciiDoc Itch
**********************************************************************
DocBook has emerged as the de facto standard Open Source documentation
format. But DocBook is a complex language, the markup is difficult to
read and even more difficult to write directly -- I found I was
spending more time typing markup tags, consulting reference manuals
and fixing syntax errors, than I was writing the documentation.
**********************************************************************
[[X6]]
Getting Started
---------------
Installing AsciiDoc
~~~~~~~~~~~~~~~~~~~
See the `README` and `INSTALL` files for install prerequisites and
procedures. Packagers take a look at <>.
[[X11]]
Example AsciiDoc Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~
The best way to quickly get a feel for AsciiDoc is to view the
AsciiDoc web site and/or distributed examples:
- Take a look at the linked examples on the AsciiDoc web site home
page {website}. Press the 'Page Source' sidebar menu item to view
corresponding AsciiDoc source.
- Read the `*.txt` source files in the distribution `./doc` directory
along with the corresponding HTML and DocBook XML files.
AsciiDoc Document Types
-----------------------
There are three types of AsciiDoc documents: article, book and
manpage. All document types share the same AsciiDoc format with some
minor variations. If you are familiar with DocBook you will have
noticed that AsciiDoc document types correspond to the same-named
DocBook document types.
Use the asciidoc(1) `-d` (`--doctype`) option to specify the AsciiDoc
document type -- the default document type is 'article'.
By convention the `.txt` file extension is used for AsciiDoc document
source files.
article
~~~~~~~
Used for short documents, articles and general documentation. See the
AsciiDoc distribution `./doc/article.txt` example.
AsciiDoc defines standard DocBook article frontmatter and backmatter
<> (appendix, abstract, bibliography,
glossary, index).
book
~~~~
Books share the same format as articles, with the following
differences:
- The part titles in multi-part books are <>
(same level as book title).
- Some sections are book specific e.g. preface and colophon.
Book documents will normally be used to produce DocBook output since
DocBook processors can automatically generate footnotes, table of
contents, list of tables, list of figures, list of examples and
indexes.
AsciiDoc defines standard DocBook book frontmatter and backmatter
<> (appendix, dedication, preface,
bibliography, glossary, index, colophon).
.Example book documents
Book::
The `./doc/book.txt` file in the AsciiDoc distribution.
Multi-part book::
The `./doc/book-multi.txt` file in the AsciiDoc distribution.
manpage
~~~~~~~
Used to generate roff format UNIX manual pages. AsciiDoc manpage
documents observe special header title and section naming conventions
-- see the <> section for details.
AsciiDoc defines the 'synopsis' <> to
generate the DocBook `refsynopsisdiv` section.
See also the asciidoc(1) man page source (`./doc/asciidoc.1.txt`) from
the AsciiDoc distribution.
[[X5]]
AsciiDoc Backends
-----------------
The asciidoc(1) command translates an AsciiDoc formatted file to the
backend format specified by the `-b` (`--backend`) command-line
option. asciidoc(1) itself has little intrinsic knowledge of backend
formats, all translation rules are contained in customizable cascading
configuration files. Backend specific attributes are listed in the
<> section.
docbook45::
Outputs DocBook XML 4.5 markup.
html4::
This backend generates plain HTML 4.01 Transitional markup.
xhtml11::
This backend generates XHTML 1.1 markup styled with CSS2. Output
files have an `.html` extension.
html5::
This backend generates HTML 5 markup, apart from the inclusion of
<> it is functionally identical to
the 'xhtml11' backend.
slidy::
Use this backend to generate self-contained
http://www.w3.org/Talks/Tools/Slidy2/[Slidy] HTML slideshows for
your web browser from AsciiDoc documents. The Slidy backend is
documented in the distribution `doc/slidy.txt` file and
{website}slidy.html[online].
wordpress::
A minor variant of the 'html4' backend to support
http://srackham.wordpress.com/blogpost1/[blogpost].
latex::
Experimental LaTeX backend.
Backend Aliases
~~~~~~~~~~~~~~~
Backend aliases are alternative names for AsciiDoc backends. AsciiDoc
comes with two backend aliases: 'html' (aliased to 'xhtml11') and
'docbook' (aliased to 'docbook45').
You can assign (or reassign) backend aliases by setting an AsciiDoc
attribute named like `backend-alias-` to an AsciiDoc backend
name. For example, the following backend alias attribute definitions
appear in the `[attributes]` section of the global `asciidoc.conf`
configuration file:
backend-alias-html=xhtml11
backend-alias-docbook=docbook45
[[X100]]
Backend Plugins
~~~~~~~~~~~~~~~
The asciidoc(1) `--backend` option is also used to install and manage
backend <>.
- A backend plugin is used just like the built-in backends.
- Backend plugins <> over built-in backends with
the same name.
- You can use the `{asciidoc-confdir}` <> to
refer to the built-in backend configuration file location from
backend plugin configuration files.
- You can use the `{backend-confdir}` <> to
refer to the backend plugin configuration file location.
- By default backends plugins are installed in
`$HOME/.asciidoc/backends/` where `` is the
backend name.
DocBook
-------
AsciiDoc generates 'article', 'book' and 'refentry'
http://www.docbook.org/[DocBook] documents (corresponding to the
AsciiDoc 'article', 'book' and 'manpage' document types).
Most Linux distributions come with conversion tools (collectively
called a toolchain) for <> to
presentation formats such as Postscript, HTML, PDF, EPUB, DVI,
PostScript, LaTeX, roff (the native man page format), HTMLHelp,
JavaHelp and text. There are also programs that allow you to view
DocBook files directly, for example http://live.gnome.org/Yelp[Yelp]
(the GNOME help viewer).
[[X12]]
Converting DocBook to other file formats
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DocBook files are validated, parsed and translated various
presentation file formats using a combination of applications
collectively called a DocBook 'tool chain'. The function of a tool
chain is to read the DocBook markup (produced by AsciiDoc) and
transform it to a presentation format (for example HTML, PDF, HTML
Help, EPUB, DVI, PostScript, LaTeX).
A wide range of user output format requirements coupled with a choice
of available tools and stylesheets results in many valid tool chain
combinations.
[[X43]]
a2x Toolchain Wrapper
~~~~~~~~~~~~~~~~~~~~~
One of the biggest hurdles for new users is installing, configuring
and using a DocBook XML toolchain. `a2x(1)` can help -- it's a
toolchain wrapper command that will generate XHTML (chunked and
unchunked), PDF, EPUB, DVI, PS, LaTeX, man page, HTML Help and text
file outputs from an AsciiDoc text file. `a2x(1)` does all the grunt
work associated with generating and sequencing the toolchain commands
and managing intermediate and output files. `a2x(1)` also optionally
deploys admonition and navigation icons and a CSS stylesheet. See the
`a2x(1)` man page for more details. In addition to `asciidoc(1)` you
also need <>, <> and
optionally: <> or <> (to generate PDF);
`w3m(1)` or `lynx(1)` (to generate text).
The following examples generate `doc/source-highlight-filter.pdf` from
the AsciiDoc `doc/source-highlight-filter.txt` source file. The first
example uses `dblatex(1)` (the default PDF generator) the second
example forces FOP to be used:
$ a2x -f pdf doc/source-highlight-filter.txt
$ a2x -f pdf --fop doc/source-highlight-filter.txt
See the `a2x(1)` man page for details.
TIP: Use the `--verbose` command-line option to view executed
toolchain commands.
HTML generation
~~~~~~~~~~~~~~~
AsciiDoc produces nicely styled HTML directly without requiring a
DocBook toolchain but there are also advantages in going the DocBook
route:
- HTML from DocBook can optionally include automatically generated
indexes, tables of contents, footnotes, lists of figures and tables.
- DocBook toolchains can also (optionally) generate separate (chunked)
linked HTML pages for each document section.
- Toolchain processing performs link and document validity checks.
- If the DocBook 'lang' attribute is set then things like table of
contents, figure and table captions and admonition captions will be
output in the specified language (setting the AsciiDoc 'lang'
attribute sets the DocBook 'lang' attribute).
On the other hand, HTML output directly from AsciiDoc is much faster,
is easily customized and can be used in situations where there is no
suitable DocBook toolchain (for example, see the {website}[AsciiDoc
website]).
PDF generation
~~~~~~~~~~~~~~
There are two commonly used tools to generate PDFs from DocBook,
<> and <>.
.dblatex or FOP?
- 'dblatex' is easier to install, there's zero configuration
required and no Java VM to install -- it just works out of the box.
- 'dblatex' source code highlighting and numbering is superb.
- 'dblatex' is easier to use as it converts DocBook directly to PDF
whereas before using 'FOP' you have to convert DocBook to XML-FO
using <>.
- 'FOP' is more feature complete (for example, callouts are processed
inside literal layouts) and arguably produces nicer looking output.
HTML Help generation
~~~~~~~~~~~~~~~~~~~~
. Convert DocBook XML documents to HTML Help compiler source files
using <> and <>.
. Convert the HTML Help source (`.hhp` and `.html`) files to HTML Help
(`.chm`) files using the <>.
Toolchain components summary
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AsciiDoc::
Converts AsciiDoc (`.txt`) files to DocBook XML (`.xml`) files.
[[X13]]http://docbook.sourceforge.net/projects/xsl/[DocBook XSL Stylesheets]::
These are a set of XSL stylesheets containing rules for converting
DocBook XML documents to HTML, XSL-FO, manpage and HTML Help files.
The stylesheets are used in conjunction with an XML parser such as
<>.
[[X40]]http://www.xmlsoft.org[xsltproc]::
An XML parser for applying XSLT stylesheets (in our case the
<>) to XML documents.
[[X31]]http://dblatex.sourceforge.net/[dblatex]::
Generates PDF, DVI, PostScript and LaTeX formats directly from
DocBook source via the intermediate LaTeX typesetting language --
uses <>, <> and
`latex(1)`.
[[X14]]http://xml.apache.org/fop/[FOP]::
The Apache Formatting Objects Processor converts XSL-FO (`.fo`)
files to PDF files. The XSL-FO files are generated from DocBook
source files using <> and
<>.
[[X67]]Microsoft Help Compiler::
The Microsoft HTML Help Compiler (`hhc.exe`) is a command-line tool
that converts HTML Help source files to a single HTML Help (`.chm`)
file. It runs on MS Windows platforms and can be downloaded from
http://www.microsoft.com.
AsciiDoc dblatex configuration files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The AsciiDoc distribution `./dblatex` directory contains
`asciidoc-dblatex.xsl` (customized XSL parameter settings) and
`asciidoc-dblatex.sty` (customized LaTeX settings). These are examples
of optional <> output customization and are used by
<>.
AsciiDoc DocBook XSL Stylesheets drivers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You will have noticed that the distributed HTML and HTML Help
documentation files (for example `./doc/asciidoc.html`) are not the
plain outputs produced using the default 'DocBook XSL Stylesheets'
configuration. This is because they have been processed using
customized DocBook XSL Stylesheets along with (in the case of HTML
outputs) the custom `./stylesheets/docbook-xsl.css` CSS stylesheet.
You'll find the customized DocBook XSL drivers along with additional
documentation in the distribution `./docbook-xsl` directory. The
examples that follow are executed from the distribution documentation
(`./doc`) directory. These drivers are also used by <>.
`common.xsl`::
Shared driver parameters. This file is not used directly but is
included in all the following drivers.
`chunked.xsl`::
Generate chunked XHTML (separate HTML pages for each document
section) in the `./doc/chunked` directory. For example:
$ python ../asciidoc.py -b docbook asciidoc.txt
$ xsltproc --nonet ../docbook-xsl/chunked.xsl asciidoc.xml
`epub.xsl`::
Used by <> to generate EPUB formatted documents.
`fo.xsl`::
Generate XSL Formatting Object (`.fo`) files for subsequent PDF
file generation using FOP. For example:
$ python ../asciidoc.py -b docbook article.txt
$ xsltproc --nonet ../docbook-xsl/fo.xsl article.xml > article.fo
$ fop article.fo article.pdf
`htmlhelp.xsl`::
Generate Microsoft HTML Help source files for the MS HTML Help
Compiler in the `./doc/htmlhelp` directory. This example is run on
MS Windows from a Cygwin shell prompt:
$ python ../asciidoc.py -b docbook asciidoc.txt
$ xsltproc --nonet ../docbook-xsl/htmlhelp.xsl asciidoc.xml
$ c:/Program\ Files/HTML\ Help\ Workshop/hhc.exe htmlhelp.hhp
`manpage.xsl`::
Generate a `roff(1)` format UNIX man page from a DocBook XML
'refentry' document. This example generates an `asciidoc.1` man
page file:
$ python ../asciidoc.py -d manpage -b docbook asciidoc.1.txt
$ xsltproc --nonet ../docbook-xsl/manpage.xsl asciidoc.1.xml
`xhtml.xsl`::
Convert a DocBook XML file to a single XHTML file. For example:
$ python ../asciidoc.py -b docbook asciidoc.txt
$ xsltproc --nonet ../docbook-xsl/xhtml.xsl asciidoc.xml > asciidoc.html
If you want to see how the complete documentation set is processed
take a look at the A-A-P script `./doc/main.aap`.
Generating Plain Text Files
---------------------------
AsciiDoc does not have a text backend (for most purposes AsciiDoc
source text is fine), however you can convert AsciiDoc text files to
formatted text using the AsciiDoc <> toolchain wrapper
utility.
[[X35]]
HTML5 and XHTML 1.1
-------------------
The 'xhtml11' and 'html5' backends embed or link CSS and JavaScript
files in their outputs, there is also a <> plugin
framework.
- If the AsciiDoc 'linkcss' attribute is defined then CSS and
JavaScript files are linked to the output document, otherwise they
are embedded (the default behavior).
- The default locations for CSS and JavaScript files can be changed by
setting the AsciiDoc 'stylesdir' and 'scriptsdir' attributes
respectively.
- The default locations for embedded and linked files differ and are
calculated at different times -- embedded files are loaded when
asciidoc(1) generates the output document, linked files are loaded
by the browser when the user views the output document.
- Embedded files are automatically inserted in the output files but
you need to manually copy linked CSS and Javascript files from
AsciiDoc <> to the correct location
relative to the output document.
.Stylesheet file locations
[cols="3*",frame="topbot",options="header"]
|====================================================================
|'stylesdir' attribute
|Linked location ('linkcss' attribute defined)
|Embedded location ('linkcss' attribute undefined)
|Undefined (default).
|Same directory as the output document.
|`stylesheets` subdirectory in the AsciiDoc configuration directory
(the directory containing the backend conf file).
|Absolute or relative directory name.
|Absolute or relative to the output document.
|Absolute or relative to the AsciiDoc configuration directory (the
directory containing the backend conf file).
|====================================================================
.JavaScript file locations
[cols="3*",frame="topbot",options="header"]
|====================================================================
|'scriptsdir' attribute
|Linked location ('linkcss' attribute defined)
|Embedded location ('linkcss' attribute undefined)
|Undefined (default).
|Same directory as the output document.
|`javascripts` subdirectory in the AsciiDoc configuration directory
(the directory containing the backend conf file).
|Absolute or relative directory name.
|Absolute or relative to the output document.
|Absolute or relative to the AsciiDoc configuration directory (the
directory containing the backend conf file).
|====================================================================
[[X99]]
Themes
~~~~~~
The AsciiDoc 'theme' attribute is used to select an alternative CSS
stylesheet and to optionally include additional JavaScript code.
- Theme files reside in an AsciiDoc <>
named `themes//` (where `` is the the theme name set
by the 'theme' attribute). asciidoc(1) sets the 'themedir' attribute
to the theme directory path name.
- The 'theme' attribute can also be set using the asciidoc(1)
`--theme` option, the `--theme` option can also be used to manage
theme <>.
- AsciiDoc ships with two themes: 'flask' and 'volnitsky'.
- The `.css` file replaces the default `asciidoc.css` CSS file.
- The `.js` file is included in addition to the default
`asciidoc.js` JavaScript file.
- If the <> attribute is defined then icons are loaded
from the theme `icons` sub-directory if it exists (i.e. the
'iconsdir' attribute is set to theme `icons` sub-directory path).
- Embedded theme files are automatically inserted in the output files
but you need to manually copy linked CSS and Javascript files to the
location of the output documents.
- Linked CSS and JavaScript theme files are linked to the same linked
locations as <>.
For example, the command-line option `--theme foo` (or `--attribute
theme=foo`) will cause asciidoc(1) to search <<"X27","configuration
file locations 1, 2 and 3">> for a sub-directory called `themes/foo`
containing the stylesheet `foo.css` and optionally a JavaScript file
name `foo.js`.
Document Structure
------------------
An AsciiDoc document consists of a series of <>
starting with an optional document Header, followed by an optional
Preamble, followed by zero or more document Sections.
Almost any combination of zero or more elements constitutes a valid
AsciiDoc document: documents can range from a single sentence to a
multi-part book.
Block Elements
~~~~~~~~~~~~~~
Block elements consist of one or more lines of text and may contain
other block elements.
The AsciiDoc block structure can be informally summarized as follows
footnote:[This is a rough structural guide, not a rigorous syntax
definition]:
Document ::= (Header?,Preamble?,Section*)
Header ::= (Title,(AuthorInfo,RevisionInfo?)?)
AuthorInfo ::= (FirstName,(MiddleName?,LastName)?,EmailAddress?)
RevisionInfo ::= (RevisionNumber?,RevisionDate,RevisionRemark?)
Preamble ::= (SectionBody)
Section ::= (Title,SectionBody?,(Section)*)
SectionBody ::= ((BlockTitle?,Block)|BlockMacro)+
Block ::= (Paragraph|DelimitedBlock|List|Table)
List ::= (BulletedList|NumberedList|LabeledList|CalloutList)
BulletedList ::= (ListItem)+
NumberedList ::= (ListItem)+
CalloutList ::= (ListItem)+
LabeledList ::= (ListEntry)+
ListEntry ::= (ListLabel,ListItem)
ListLabel ::= (ListTerm+)
ListItem ::= (ItemText,(List|ListParagraph|ListContinuation)*)
Where:
- '?' implies zero or one occurrence, '+' implies one or more
occurrences, '*' implies zero or more occurrences.
- All block elements are separated by line boundaries.
- `BlockId`, `AttributeEntry` and `AttributeList` block elements (not
shown) can occur almost anywhere.
- There are a number of document type and backend specific
restrictions imposed on the block syntax.
- The following elements cannot contain blank lines: Header, Title,
Paragraph, ItemText.
- A ListParagraph is a Paragraph with its 'listelement' option set.
- A ListContinuation is a <>.
[[X95]]
Header
~~~~~~
The Header contains document meta-data, typically title plus optional
authorship and revision information:
- The Header is optional, but if it is used it must start with a
document <>.
- Optional Author and Revision information immediately follows the
header title.
- The document header must be separated from the remainder of the
document by one or more blank lines and cannot contain blank lines.
- The header can include comments.
- The header can include <>, typically
'doctype', 'lang', 'encoding', 'icons', 'data-uri', 'toc',
'numbered'.
- Header attributes are overridden by command-line attributes.
- If the header contains non-UTF-8 characters then the 'encoding' must
precede the header (either in the document or on the command-line).
Here's an example AsciiDoc document header:
Writing Documentation using AsciiDoc
====================================
Joe Bloggs
v2.0, February 2003:
Rewritten for version 2 release.
The author information line contains the author's name optionally
followed by the author's email address. The author's name is formatted
like:
firstname[ [middlename ]lastname][ ]]
i.e. a first name followed by optional middle and last names followed
by an email address in that order. Multi-word first, middle and last
names can be entered using the underscore as a word separator. The
email address comes last and must be enclosed in angle <> brackets.
Here a some examples of author information lines:
Joe Bloggs
Joe Bloggs
Vincent Willem van_Gogh
If the author line does not match the above specification then the
entire author line is treated as the first name.
The optional revision information line follows the author information
line. The revision information can be one of two formats:
. An optional document revision number followed by an optional
revision date followed by an optional revision remark:
+
--
* If the revision number is specified it must be followed by a
comma.
* The revision number must contain at least one numeric character.
* Any non-numeric characters preceding the first numeric character
will be dropped.
* If a revision remark is specified it must be preceded by a colon.
The revision remark extends from the colon up to the next blank
line, attribute entry or comment and is subject to normal text
substitutions.
* If a revision number or remark has been set but the revision date
has not been set then the revision date is set to the value of the
'docdate' attribute.
Examples:
v2.0, February 2003
February 2003
v2.0,
v2.0, February 2003: Rewritten for version 2 release.
February 2003: Rewritten for version 2 release.
v2.0,: Rewritten for version 2 release.
:Rewritten for version 2 release.
--
. The revision information line can also be an RCS/CVS/SVN $Id$
marker:
+
--
* AsciiDoc extracts the 'revnumber', 'revdate', and 'author'
attributes from the $Id$ revision marker and displays them in the
document header.
* If an $Id$ revision marker is used the header author line can be
omitted.
Example:
$Id: mydoc.txt,v 1.5 2009/05/17 17:58:44 jbloggs Exp $
--
You can override or set header parameters by passing 'revnumber',
'revremark', 'revdate', 'email', 'author', 'authorinitials',
'firstname' and 'lastname' attributes using the asciidoc(1) `-a`
(`--attribute`) command-line option. For example:
$ asciidoc -a revdate=2004/07/27 article.txt
Attribute entries can also be added to the header for substitution in
the header template with <> elements.
The 'title' element in HTML outputs is set to the AsciiDoc document
title, you can set it to a different value by including a 'title'
attribute entry in the document header.
[[X87]]
Additional document header information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AsciiDoc has two mechanisms for optionally including additional
meta-data in the header of the output document:
'docinfo' configuration file sections::
If a <> section named 'docinfo' has been loaded
then it will be included in the document header. Typically the
'docinfo' section name will be prefixed with a '+' character so that it
is appended to (rather than replace) other 'docinfo' sections.
'docinfo' files::
Two docinfo files are recognized: one named `docinfo` and a second
named like the AsciiDoc source file with a `-docinfo` suffix. For
example, if the source document is called `mydoc.txt` then the
document information files would be `docinfo.xml` and
`mydoc-docinfo.xml` (for DocBook outputs) and `docinfo.html` and
`mydoc-docinfo.html` (for HTML outputs). The <> attributes control which docinfo files are included in
the output files.
The contents docinfo templates and files is dependent on the type of
output:
HTML::
Valid 'head' child elements. Typically 'style' and 'script' elements
for CSS and JavaScript inclusion.
DocBook::
Valid 'articleinfo' or 'bookinfo' child elements. DocBook defines
numerous elements for document meta-data, for example: copyrights,
document history and authorship information. See the DocBook
`./doc/article-docinfo.xml` example that comes with the AsciiDoc
distribution. The rendering of meta-data elements (or not) is
DocBook processor dependent.
[[X86]]
Preamble
~~~~~~~~
The Preamble is an optional untitled section body between the document
Header and the first Section title.
Sections
~~~~~~~~
In addition to the document title (level 0), AsciiDoc supports four
section levels: 1 (top) to 4 (bottom). Section levels are delimited
by section <>. Sections are translated using
configuration file <>. AsciiDoc
generates the following <> specifically for
use in section markup templates:
level::
The `level` attribute is the section level number, it is normally just
the <> level number (1..4). However, if the `leveloffset`
attribute is defined it will be added to the `level` attribute. The
`leveloffset` attribute is useful for <>.
sectnum::
The `-n` (`--section-numbers`) command-line option generates the
`sectnum` (section number) attribute. The `sectnum` attribute is used
for section numbers in HTML outputs (DocBook section numbering are
handled automatically by the DocBook toolchain commands).
[[X93]]
Section markup templates
^^^^^^^^^^^^^^^^^^^^^^^^
Section markup templates specify output markup and are defined in
AsciiDoc configuration files. Section markup template names are
derived as follows (in order of precedence):
1. From the title's first positional attribute or 'template'
attribute. For example, the following three section titles are
functionally equivalent:
+
.....................................................................
[[terms]]
[glossary]
List of Terms
-------------
["glossary",id="terms"]
List of Terms
-------------
[template="glossary",id="terms"]
List of Terms
-------------
.....................................................................
2. When the title text matches a configuration file
<> entry.
3. If neither of the above the default `sect` template is used
(where `` is a number from 1 to 4).
In addition to the normal section template names ('sect1', 'sect2',
'sect3', 'sect4') AsciiDoc has the following templates for
frontmatter, backmatter and other special sections: 'abstract',
'preface', 'colophon', 'dedication', 'glossary', 'bibliography',
'synopsis', 'appendix', 'index'. These special section templates
generate the corresponding Docbook elements; for HTML outputs they
default to the 'sect1' section template.
Section IDs
^^^^^^^^^^^
If no explicit section ID is specified an ID will be synthesised from
the section title. The primary purpose of this feature is to ensure
persistence of table of contents links (permalinks): the missing
section IDs are generated dynamically by the JavaScript TOC generator
*after* the page is loaded. If you link to a dynamically generated TOC
address the page will load but the browser will ignore the (as yet
ungenerated) section ID.
The IDs are generated by the following algorithm:
- Replace all non-alphanumeric title characters with underscores.
- Strip leading or trailing underscores.
- Convert to lowercase.
- Prepend the `idprefix` attribute (so there's no possibility of name
clashes with existing document IDs). Prepend an underscore if the
`idprefix` attribute is not defined.
- A numbered suffix (`_2`, `_3` ...) is added if a same named
auto-generated section ID exists.
- If the `ascii-ids` attribute is defined then non-ASCII characters
are replaced with ASCII equivalents. This attribute may be
deprecated in future releases and *should be avoided*, it's sole
purpose is to accommodate deficient downstream applications that
cannot process non-ASCII ID attributes.
Example: the title 'Jim's House' would generate the ID `_jim_s_house`.
Section ID synthesis can be disabled by undefining the `sectids`
attribute.
[[X16]]
Special Section Titles
^^^^^^^^^^^^^^^^^^^^^^
AsciiDoc has a mechanism for mapping predefined section titles
auto-magically to specific markup templates. For example a title
'Appendix A: Code Reference' will automatically use the 'appendix'
<>. The mappings from title to template
name are specified in `[specialsections]` sections in the Asciidoc
language configuration files (`lang-*.conf`). Section entries are
formatted like:
=
`` is a Python regular expression and `` is the name
of a configuration file markup template section. If the ``
matches an AsciiDoc document section title then the backend output is
marked up using the `` markup template (instead of the
default `sect` section template). The `{title}` attribute value
is set to the value of the matched regular expression group named
'title', if there is no 'title' group `{title}` defaults to the whole
of the AsciiDoc section title. If `` is blank then any
existing entry with the same `` will be deleted.
.Special section titles vs. explicit template names
*********************************************************************
AsciiDoc has two mechanisms for specifying non-default section markup
templates: you can specify the template name explicitly (using the
'template' attribute) or indirectly (using 'special section titles').
Specifying a <> attribute explicitly is
preferred. Auto-magical 'special section titles' have the following
drawbacks:
- They are non-obvious, you have to know the exact matching
title for each special section on a language by language basis.
- Section titles are predefined and can only be customised with a
configuration change.
- The implementation is complicated by multiple languages: every
special section title has to be defined for each language (in each
of the `lang-*.conf` files).
Specifying special section template names explicitly does add more
noise to the source document (the 'template' attribute declaration),
but the intention is obvious and the syntax is consistent with other
AsciiDoc elements c.f. bibliographic, Q&A and glossary lists.
Special section titles have been deprecated but are retained for
backward compatibility.
*********************************************************************
Inline Elements
~~~~~~~~~~~~~~~
<> are used to format text and to
perform various types of text substitution. Inline elements and inline
element syntax is defined in the asciidoc(1) configuration files.
Here is a list of AsciiDoc inline elements in the (default) order in
which they are processed:
Special characters::
These character sequences escape special characters used by
the backend markup (typically `<`, `>`, and `&` characters).
See `[specialcharacters]` configuration file sections.
Quotes::
Elements that markup words and phrases; usually for character
formatting. See `[quotes]` configuration file sections.
Special Words::
Word or word phrase patterns singled out for markup without
the need for further annotation. See `[specialwords]`
configuration file sections.
Replacements::
Each replacement defines a word or word phrase pattern to
search for along with corresponding replacement text. See
`[replacements]` configuration file sections.
Attribute references::
Document attribute names enclosed in braces are replaced by
the corresponding attribute value.
Inline Macros::
Inline macros are replaced by the contents of parametrized
configuration file sections.
Document Processing
-------------------
The AsciiDoc source document is read and processed as follows:
1. The document 'Header' is parsed, header parameter values are
substituted into the configuration file `[header]` template section
which is then written to the output file.
2. Each document 'Section' is processed and its constituent elements
translated to the output file.
3. The configuration file `[footer]` template section is substituted
and written to the output file.
When a block element is encountered asciidoc(1) determines the type of
block by checking in the following order (first to last): (section)
Titles, BlockMacros, Lists, DelimitedBlocks, Tables, AttributeEntrys,
AttributeLists, BlockTitles, Paragraphs.
The default paragraph definition `[paradef-default]` is last element
to be checked.
Knowing the parsing order will help you devise unambiguous macro, list
and block syntax rules.
Inline substitutions within block elements are performed in the
following default order:
1. Special characters
2. Quotes
3. Special words
4. Replacements
5. Attributes
6. Inline Macros
7. Replacements2
The substitutions and substitution order performed on
Title, Paragraph and DelimitedBlock elements is determined by
configuration file parameters.
Text Formatting
---------------
[[X51]]
Quoted Text
~~~~~~~~~~~
Words and phrases can be formatted by enclosing inline text with
quote characters:
_Emphasized text_::
Word phrases \'enclosed in single quote characters' (acute
accents) or \_underline characters_ are emphasized.
*Strong text*::
Word phrases \*enclosed in asterisk characters* are rendered
in a strong font (usually bold).
[[X81]]+Monospaced text+::
Word phrases \+enclosed in plus characters+ are rendered in a
monospaced font. Word phrases \`enclosed in backtick
characters` (grave accents) are also rendered in a monospaced
font but in this case the enclosed text is rendered literally
and is not subject to further expansion (see <>).
`Single quoted text'::
Phrases enclosed with a \`single grave accent to the left and
a single acute accent to the right' are rendered in single
quotation marks.
``Double quoted text''::
Phrases enclosed with \\``two grave accents to the left and
two acute accents to the right'' are rendered in quotation
marks.
#Unquoted text#::
Placing \#hashes around text# does nothing, it is a mechanism
to allow inline attributes to be applied to otherwise
unformatted text.
New quote types can be defined by editing asciidoc(1) configuration
files. See the <> section for details.
.Quoted text behavior
- Quoting cannot be overlapped.
- Different quoting types can be nested.
- To suppress quoted text formatting place a backslash character
immediately in front of the leading quote character(s). In the case
of ambiguity between escaped and non-escaped text you will need to
escape both leading and trailing quotes, in the case of
multi-character quotes you may even need to escape individual
characters.
[[X96]]
Quoted text attributes
^^^^^^^^^^^^^^^^^^^^^^
Quoted text can be prefixed with an <>. The first
positional attribute ('role' attribute) is translated by AsciiDoc to
an HTML 'span' element 'class' attribute or a DocBook 'phrase' element
'role' attribute.
DocBook XSL Stylesheets translate DocBook 'phrase' elements with
'role' attributes to corresponding HTML 'span' elements with the same
'class' attributes; CSS can then be used
http://www.sagehill.net/docbookxsl/UsingCSS.html[to style the
generated HTML]. Thus CSS styling can be applied to both DocBook and
AsciiDoc generated HTML outputs. You can also specify multiple class
names separated by spaces.
CSS rules for text color, text background color, text size and text
decorators are included in the distributed AsciiDoc CSS files and are
used in conjunction with AsciiDoc 'xhtml11', 'html5' and 'docbook'
outputs. The CSS class names are:
- '' (text foreground color).
- '-background' (text background color).
- 'big' and 'small' (text size).
- 'underline', 'overline' and 'line-through' (strike through) text
decorators.
Where '' can be any of the
http://en.wikipedia.org/wiki/Web_colors#HTML_color_names[sixteen HTML
color names]. Examples:
[red]#Obvious# and [big red yellow-background]*very obvious*.
[underline]#Underline text#, [overline]#overline text# and
[blue line-through]*bold blue and line-through*.
is rendered as:
[red]#Obvious# and [big red yellow-background]*very obvious*.
[underline]#Underline text#, [overline]#overline text# and
[bold blue line-through]*bold blue and line-through*.
NOTE: Color and text decorator attributes are rendered for XHTML and
HTML 5 outputs using CSS stylesheets. The mechanism to implement
color and text decorator attributes is provided for DocBook toolchains
via the DocBook 'phrase' element 'role' attribute, but the actual
rendering is toolchain specific and is not part of the AsciiDoc
distribution.
[[X52]]
Constrained and Unconstrained Quotes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are actually two types of quotes:
Constrained quotes
++++++++++++++++++
Quoted must be bounded by white space or commonly adjoining
punctuation characters. These are the most commonly used type of
quote.
Unconstrained quotes
++++++++++++++++++++
Unconstrained quotes have no boundary constraints and can be placed
anywhere within inline text. For consistency and to make them easier
to remember unconstrained quotes are double-ups of the `_`, `*`, `+`
and `#` constrained quotes:
__unconstrained emphasized text__
**unconstrained strong text**
++unconstrained monospaced text++
##unconstrained unquoted text##
The following example emboldens the letter F:
**F**ile Open...
Superscripts and Subscripts
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Put \^carets on either^ side of the text to be superscripted, put
\~tildes on either side~ of text to be subscripted. For example, the
following line:
e^πi^+1 = 0. H~2~O and x^10^. Some ^super text^
and ~some sub text~
Is rendered like:
e^πi^+1 = 0. H~2~O and x^10^. Some ^super text^
and ~some sub text~
Superscripts and subscripts are implemented as <> and they can be escaped with a leading backslash and prefixed
with with an attribute list.
Line Breaks
~~~~~~~~~~~
A plus character preceded by at least one space character at the end
of a non-blank line forces a line break. It generates a line break
(`br`) tag for HTML outputs and a custom XML `asciidoc-br` processing
instruction for DocBook outputs. The `asciidoc-br` processing
instruction is handled by <>.
Page Breaks
~~~~~~~~~~~
A line of three or more less-than (`<<<`) characters will generate a
hard page break in DocBook and printed HTML outputs. It uses the CSS
`page-break-after` property for HTML outputs and a custom XML
`asciidoc-pagebreak` processing instruction for DocBook outputs. The
`asciidoc-pagebreak` processing instruction is handled by
<>. Hard page breaks are sometimes handy but as a general
rule you should let your page processor generate page breaks for you.
Rulers
~~~~~~
A line of three or more apostrophe characters will generate a ruler
line. It generates a ruler (`hr`) tag for HTML outputs and a custom
XML `asciidoc-hr` processing instruction for DocBook outputs. The
`asciidoc-hr` processing instruction is handled by <>.
Tabs
~~~~
By default tab characters input files will translated to 8 spaces. Tab
expansion is set with the 'tabsize' entry in the configuration file
`[miscellaneous]` section and can be overridden in included files by
setting a 'tabsize' attribute in the `include` macro's attribute list.
For example:
include::addendum.txt[tabsize=2]
The tab size can also be set using the attribute command-line option,
for example `--attribute tabsize=4`
Replacements
~~~~~~~~~~~~
The following replacements are defined in the default AsciiDoc
configuration:
(C) copyright, (TM) trademark, (R) registered trademark,
-- em dash, ... ellipsis, -> right arrow, <- left arrow, => right
double arrow, <= left double arrow.
Which are rendered as:
(C) copyright, (TM) trademark, (R) registered trademark,
-- em dash, ... ellipsis, -> right arrow, <- left arrow, => right
double arrow, <= left double arrow.
You can also include arbitrary entity references in the AsciiDoc
source. Examples:
➊ ¶
renders:
➊ ¶
To render a replacement literally escape it with a leading back-slash.
The <> section explains how to configure your
own replacements.
Special Words
~~~~~~~~~~~~~
Words defined in `[specialwords]` configuration file sections are
automatically marked up without having to be explicitly notated.
The <> section explains how to add and replace
special words.
[[X17]]
Titles
------
Document and section titles can be in either of two formats:
Two line titles
~~~~~~~~~~~~~~~
A two line title consists of a title line, starting hard against the
left margin, and an underline. Section underlines consist a repeated
character pairs spanning the width of the preceding title (give or
take up to two characters):
The default title underlines for each of the document levels are:
Level 0 (top level): ======================
Level 1: ----------------------
Level 2: ~~~~~~~~~~~~~~~~~~~~~~
Level 3: ^^^^^^^^^^^^^^^^^^^^^^
Level 4 (bottom level): ++++++++++++++++++++++
Examples:
Level One Section Title
-----------------------
Level 2 Subsection Title
~~~~~~~~~~~~~~~~~~~~~~~~
[[X46]]
One line titles
~~~~~~~~~~~~~~~
One line titles consist of a single line delimited on either side by
one or more equals characters (the number of equals characters
corresponds to the section level minus one). Here are some examples:
= Document Title (level 0) =
== Section title (level 1) ==
=== Section title (level 2) ===
==== Section title (level 3) ====
===== Section title (level 4) =====
[NOTE]
=====================================================================
- One or more spaces must fall between the title and the delimiters.
- The trailing title delimiter is optional.
- The one-line title syntax can be changed by editing the
configuration file `[titles]` section `sect0`...`sect4` entries.
=====================================================================
Floating titles
~~~~~~~~~~~~~~~
Setting the title's first positional attribute or 'style' attribute to
'float' generates a free-floating title. A free-floating title is
rendered just like a normal section title but is not formally
associated with a text body and is not part of the regular section
hierarchy so the normal ordering rules do not apply. Floating titles
can also be used in contexts where section titles are illegal: for
example sidebar and admonition blocks. Example:
[float]
The second day
~~~~~~~~~~~~~~
Floating titles do not appear in a document's table of contents.
[[X42]]
Block Titles
------------
A 'BlockTitle' element is a single line beginning with a period
followed by the title text. A BlockTitle is applied to the immediately
following Paragraph, DelimitedBlock, List, Table or BlockMacro. For
example:
........................
.Notes
- Note 1.
- Note 2.
........................
is rendered as:
.Notes
- Note 1.
- Note 2.
[[X41]]
BlockId Element
---------------
A 'BlockId' is a single line block element containing a unique
identifier enclosed in double square brackets. It is used to assign an
identifier to the ensuing block element. For example:
[[chapter-titles]]
Chapter titles can be ...
The preceding example identifies the ensuing paragraph so it can be
referenced from other locations, for example with
`<>`.
'BlockId' elements can be applied to Title, Paragraph, List,
DelimitedBlock, Table and BlockMacro elements. The BlockId element
sets the `{id}` attribute for substitution in the subsequent block's
markup template. If a second positional argument is supplied it sets
the `{reftext}` attribute which is used to set the DocBook `xreflabel`
attribute.
The 'BlockId' element has the same syntax and serves the same function
to the <>.
[[X79]]
AttributeList Element
---------------------
An 'AttributeList' block element is an <> on a
line by itself:
- 'AttributeList' attributes are only applied to the immediately
following block element -- the attributes are made available to the
block's markup template.
- Multiple contiguous 'AttributeList' elements are additively combined
in the order they appear..
- The first positional attribute in the list is often used to specify
the ensuing element's <>.
Attribute value substitution
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default, only substitutions that take place inside attribute list
values are attribute references, this is because not all attributes
are destined to be marked up and rendered as text (for example the
table 'cols' attribute). To perform normal inline text substitutions
(special characters, quotes, macros, replacements) on an attribute
value you need to enclose it in single quotes. In the following quote
block the second attribute value in the AttributeList is quoted to
ensure the 'http' macro is expanded to a hyperlink.
---------------------------------------------------------------------
[quote,'http://en.wikipedia.org/wiki/Samuel_Johnson[Samuel Johnson]']
_____________________________________________________________________
Sir, a woman's preaching is like a dog's walking on his hind legs. It
is not done well; but you are surprised to find it done at all.
_____________________________________________________________________
---------------------------------------------------------------------
Common attributes
~~~~~~~~~~~~~~~~~
Most block elements support the following attributes:
[cols="1e,1,5a",frame="topbot",options="header"]
|====================================================================
|Name |Backends |Description
|id |html4, html5, xhtml11, docbook |
Unique identifier typically serve as link targets.
Can also be set by the 'BlockId' element.
|role |html4, html5, xhtml11, docbook |
Role contains a string used to classify or subclassify an element and
can be applied to AsciiDoc block elements. The AsciiDoc 'role'
attribute is translated to the 'role' attribute in DocBook outputs and
is included in the 'class' attribute in HTML outputs, in this respect
it behaves like the <>.
DocBook XSL Stylesheets translate DocBook 'role' attributes to HTML
'class' attributes; CSS can then be used
http://www.sagehill.net/docbookxsl/UsingCSS.html[to style the
generated HTML].
|reftext |docbook |
'reftext' is used to set the DocBook 'xreflabel' attribute.
The 'reftext' attribute can an also be set by the 'BlockId' element.
|====================================================================
Paragraphs
----------
Paragraphs are blocks of text terminated by a blank line, the end of
file, or the start of a delimited block or a list. There are three
paragraph syntaxes: normal, indented (literal) and admonition which
are rendered, by default, with the corresponding paragraph style.
Each syntax has a default style, but you can explicitly apply any
paragraph style to any paragraph syntax. You can also apply
<> styles to single paragraphs.
The built-in paragraph styles are: 'normal', 'literal', 'verse',
'quote', 'listing', 'TIP', 'NOTE', 'IMPORTANT', 'WARNING', 'CAUTION',
'abstract', 'partintro', 'comment', 'example', 'sidebar', 'source',
'music', 'latex', 'graphviz'.
normal paragraph syntax
~~~~~~~~~~~~~~~~~~~~~~~
Normal paragraph syntax consists of one or more non-blank lines of
text. The first line must start hard against the left margin (no
intervening white space). The default processing expectation is that
of a normal paragraph of text.
[[X85]]
literal paragraph syntax
~~~~~~~~~~~~~~~~~~~~~~~~
Literal paragraphs are rendered verbatim in a monospaced font without
any distinguishing background or border. By default there is no text
formatting or substitutions within Literal paragraphs apart from
Special Characters and Callouts.
The 'literal' style is applied implicitly to indented paragraphs i.e.
where the first line of the paragraph is indented by one or more space
or tab characters. For example:
---------------------------------------------------------------------
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
---------------------------------------------------------------------
Renders:
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
NOTE: Because <> can be indented it's possible for your
indented paragraph to be misinterpreted as a list -- in situations
like this apply the 'literal' style to a normal paragraph.
Instead of using a paragraph indent you could apply the 'literal'
style explicitly, for example:
---------------------------------------------------------------------
[literal]
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
---------------------------------------------------------------------
Renders:
[literal]
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
[[X94]]
quote and verse paragraph styles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The optional 'attribution' and 'citetitle' attributes (positional
attributes 2 and 3) specify the author and source respectively.
The 'verse' style retains the line breaks, for example:
---------------------------------------------------------------------
[verse, William Blake, from Auguries of Innocence]
To see a world in a grain of sand,
And a heaven in a wild flower,
Hold infinity in the palm of your hand,
And eternity in an hour.
---------------------------------------------------------------------
Which is rendered as:
[verse, William Blake, from Auguries of Innocence]
To see a world in a grain of sand,
And a heaven in a wild flower,
Hold infinity in the palm of your hand,
And eternity in an hour.
The 'quote' style flows the text at left and right margins, for
example:
---------------------------------------------------------------------
[quote, Bertrand Russell, The World of Mathematics (1956)]
A good notation has subtlety and suggestiveness which at times makes
it almost seem like a live teacher.
---------------------------------------------------------------------
Which is rendered as:
[quote, Bertrand Russell, The World of Mathematics (1956)]
A good notation has subtlety and suggestiveness which at times makes
it almost seem like a live teacher.
[[X28]]
Admonition Paragraphs
~~~~~~~~~~~~~~~~~~~~~
'TIP', 'NOTE', 'IMPORTANT', 'WARNING' and 'CAUTION' admonishment
paragraph styles are generated by placing `NOTE:`, `TIP:`,
`IMPORTANT:`, `WARNING:` or `CAUTION:` as the first word of the
paragraph. For example:
NOTE: This is an example note.
Alternatively, you can specify the paragraph admonition style
explicitly using an <>. For example:
[NOTE]
This is an example note.
Renders:
NOTE: This is an example note.
TIP: If your admonition requires more than a single paragraph use an
<> instead.
[[X47]]
Admonition Icons and Captions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
NOTE: Admonition customization with `icons`, `iconsdir`, `icon` and
`caption` attributes does not apply when generating DocBook output. If
you are going the DocBook route then the <> `--no-icons`
and `--icons-dir` options can be used to set the appropriate XSL
Stylesheets parameters.
By default the asciidoc(1) HTML backends generate text captions
instead of admonition icon image links. To generate links to icon
images define the <> attribute, for example using the `-a
icons` command-line option.
The <> attribute sets the location of linked icon
images.
You can override the default icon image using the `icon` attribute to
specify the path of the linked image. For example:
[icon="./images/icons/wink.png"]
NOTE: What lovely war.
Use the `caption` attribute to customize the admonition captions (not
applicable to `docbook` backend). The following example suppresses the
icon image and customizes the caption of a 'NOTE' admonition
(undefining the `icons` attribute with `icons=None` is only necessary
if <> have been enabled):
[icons=None, caption="My Special Note"]
NOTE: This is my special note.
This subsection also applies to <>.
[[X104]]
Delimited Blocks
----------------
Delimited blocks are blocks of text enveloped by leading and trailing
delimiter lines (normally a series of four or more repeated
characters). The behavior of Delimited Blocks is specified by entries
in configuration file `[blockdef-*]` sections.
Predefined Delimited Blocks
~~~~~~~~~~~~~~~~~~~~~~~~~~~
AsciiDoc ships with a number of predefined DelimitedBlocks (see the
`asciidoc.conf` configuration file in the asciidoc(1) program
directory):
Predefined delimited block underlines:
CommentBlock: //////////////////////////
PassthroughBlock: ++++++++++++++++++++++++++
ListingBlock: --------------------------
LiteralBlock: ..........................
SidebarBlock: **************************
QuoteBlock: __________________________
ExampleBlock: ==========================
OpenBlock: --
.Default DelimitedBlock substitutions
[cols="2e,7*^",frame="topbot",options="header,autowidth"]
|=====================================================
| |Attributes |Callouts |Macros | Quotes |Replacements
|Special chars |Special words
|PassthroughBlock |Yes |No |Yes |No |No |No |No
|ListingBlock |No |Yes |No |No |No |Yes |No
|LiteralBlock |No |Yes |No |No |No |Yes |No
|SidebarBlock |Yes |No |Yes |Yes |Yes |Yes |Yes
|QuoteBlock |Yes |No |Yes |Yes |Yes |Yes |Yes
|ExampleBlock |Yes |No |Yes |Yes |Yes |Yes |Yes
|OpenBlock |Yes |No |Yes |Yes |Yes |Yes |Yes
|=====================================================
Listing Blocks
~~~~~~~~~~~~~~
'ListingBlocks' are rendered verbatim in a monospaced font, they
retain line and whitespace formatting and are often distinguished by a
background or border. There is no text formatting or substitutions
within Listing blocks apart from Special Characters and Callouts.
Listing blocks are often used for computer output and file listings.
Here's an example:
[listing]
......................................
--------------------------------------
#include
int main() {
printf("Hello World!\n");
exit(0);
}
--------------------------------------
......................................
Which will be rendered like:
--------------------------------------
#include
int main() {
printf("Hello World!\n");
exit(0);
}
--------------------------------------
By convention <> use the listing block syntax and
are implemented as distinct listing block styles.
[[X65]]
Literal Blocks
~~~~~~~~~~~~~~
'LiteralBlocks' are rendered just like <>.
Example:
---------------------------------------------------------------------
...................................
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
...................................
---------------------------------------------------------------------
Renders:
...................................
Consul *necessitatibus* per id,
consetetur, eu pro everti postulant
homero verear ea mea, qui.
...................................
If the 'listing' style is applied to a LiteralBlock it will be
rendered as a ListingBlock (this is handy if you have a listing
containing a ListingBlock).
Sidebar Blocks
~~~~~~~~~~~~~~
A sidebar is a short piece of text presented outside the narrative
flow of the main text. The sidebar is normally presented inside a
bordered box to set it apart from the main text.
The sidebar body is treated like a normal section body.
Here's an example:
---------------------------------------------------------------------
.An Example Sidebar
************************************************
Any AsciiDoc SectionBody element (apart from
SidebarBlocks) can be placed inside a sidebar.
************************************************
---------------------------------------------------------------------
Which will be rendered like:
.An Example Sidebar
************************************************
Any AsciiDoc SectionBody element (apart from
SidebarBlocks) can be placed inside a sidebar.
************************************************
[[X26]]
Comment Blocks
~~~~~~~~~~~~~~
The contents of 'CommentBlocks' are not processed; they are useful for
annotations and for excluding new or outdated content that you don't
want displayed. CommentBlocks are never written to output files.
Example:
---------------------------------------------------------------------
//////////////////////////////////////////
CommentBlock contents are not processed by
asciidoc(1).
//////////////////////////////////////////
---------------------------------------------------------------------
See also <>.
NOTE: System macros are executed inside comment blocks.
[[X76]]
Passthrough Blocks
~~~~~~~~~~~~~~~~~~
By default the block contents is subject only to 'attributes' and
'macros' substitutions (use an explicit 'subs' attribute to apply
different substitutions). PassthroughBlock content will often be
backend specific. Here's an example:
---------------------------------------------------------------------
[subs="quotes"]
++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++
---------------------------------------------------------------------
The following styles can be applied to passthrough blocks:
pass::
No substitutions are performed. This is equivalent to `subs="none"`.
asciimath, latexmath::
By default no substitutions are performed, the contents are rendered
as <>.
Quote Blocks
~~~~~~~~~~~~
'QuoteBlocks' are used for quoted passages of text. There are two
styles: 'quote' and 'verse'. The style behavior is identical to
<> except that blocks can contain
multiple paragraphs and, in the case of the 'quote' style, other
section elements. The first positional attribute sets the style, if
no attributes are specified the 'quote' style is used. The optional
'attribution' and 'citetitle' attributes (positional attributes 2 and
3) specify the quote's author and source. For example:
---------------------------------------------------------------------
[quote, Sir Arthur Conan Doyle, The Adventures of Sherlock Holmes]
____________________________________________________________________
As he spoke there was the sharp sound of horses' hoofs and
grating wheels against the curb, followed by a sharp pull at the
bell. Holmes whistled.
"A pair, by the sound," said he. "Yes," he continued, glancing
out of the window. "A nice little brougham and a pair of
beauties. A hundred and fifty guineas apiece. There's money in
this case, Watson, if there is nothing else."
____________________________________________________________________
---------------------------------------------------------------------
Which is rendered as:
[quote, Sir Arthur Conan Doyle, The Adventures of Sherlock Holmes]
____________________________________________________________________
As he spoke there was the sharp sound of horses' hoofs and
grating wheels against the curb, followed by a sharp pull at the
bell. Holmes whistled.
"A pair, by the sound," said he. "Yes," he continued, glancing
out of the window. "A nice little brougham and a pair of
beauties. A hundred and fifty guineas apiece. There's money in
this case, Watson, if there is nothing else."
____________________________________________________________________
[[X48]]
Example Blocks
~~~~~~~~~~~~~~
'ExampleBlocks' encapsulate the DocBook Example element and are used
for, well, examples. Example blocks can be titled by preceding them
with a 'BlockTitle'. DocBook toolchains will normally automatically
number examples and generate a 'List of Examples' backmatter section.
Example blocks are delimited by lines of equals characters and can
contain any block elements apart from Titles, BlockTitles and
Sidebars) inside an example block. For example:
---------------------------------------------------------------------
.An example
=====================================================================
Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens.
=====================================================================
---------------------------------------------------------------------
Renders:
.An example
=====================================================================
Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens.
=====================================================================
A title prefix that can be inserted with the `caption` attribute
(HTML backends). For example:
---------------------------------------------------------------------
[caption="Example 1: "]
.An example with a custom caption
=====================================================================
Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens.
=====================================================================
---------------------------------------------------------------------
[[X22]]
Admonition Blocks
~~~~~~~~~~~~~~~~~
The 'ExampleBlock' definition includes a set of admonition
<> ('NOTE', 'TIP', 'IMPORTANT', 'WARNING', 'CAUTION') for
generating admonition blocks (admonitions containing more than a
<>). Just precede the 'ExampleBlock' with an
attribute list specifying the admonition style name. For example:
---------------------------------------------------------------------
[NOTE]
.A NOTE admonition block
=====================================================================
Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens.
. Fusce euismod commodo velit.
. Vivamus fringilla mi eu lacus.
.. Fusce euismod commodo velit.
.. Vivamus fringilla mi eu lacus.
. Donec eget arcu bibendum
nunc consequat lobortis.
=====================================================================
---------------------------------------------------------------------
Renders:
[NOTE]
.A NOTE admonition block
=====================================================================
Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens.
. Fusce euismod commodo velit.
. Vivamus fringilla mi eu lacus.
.. Fusce euismod commodo velit.
.. Vivamus fringilla mi eu lacus.
. Donec eget arcu bibendum
nunc consequat lobortis.
=====================================================================
See also <>.
[[X29]]
Open Blocks
~~~~~~~~~~~
Open blocks are special:
- The open block delimiter is line containing two hyphen characters
(instead of four or more repeated characters).
- They can be used to group block elements for <>.
- Open blocks can be styled to behave like any other type of delimited
block. The following built-in styles can be applied to open
blocks: 'literal', 'verse', 'quote', 'listing', 'TIP', 'NOTE',
'IMPORTANT', 'WARNING', 'CAUTION', 'abstract', 'partintro',
'comment', 'example', 'sidebar', 'source', 'music', 'latex',
'graphviz'. For example, the following open block and listing block
are functionally identical:
[listing]
--
Lorum ipsum ...
--
---------------
Lorum ipsum ...
---------------
- An unstyled open block groups section elements but otherwise does
nothing.
Open blocks are used to generate document abstracts and book part
introductions:
- Apply the 'abstract' style to generate an abstract, for example:
[abstract]
--
In this paper we will ...
--
. Apply the 'partintro' style to generate a book part introduction for
a multi-part book, for example:
[partintro]
.Optional part introduction title
--
Optional part introduction goes here.
--
[[X64]]
Lists
-----
.List types
- Bulleted lists. Also known as itemized or unordered lists.
- Numbered lists. Also called ordered lists.
- Labeled lists. Sometimes called variable or definition lists.
- Callout lists (a list of callout annotations).
.List behavior
- List item indentation is optional and does not determine nesting,
indentation does however make the source more readable.
- Another list or a literal paragraph immediately following a list
item will be implicitly included in the list item; use <> to explicitly append other block elements to a
list item.
- A comment block or a comment line block macro element will terminate
a list -- use inline comment lines to put comments inside lists.
- The `listindex` <> is the current list item
index (1..). If this attribute is used outside a list then it's value
is the number of items in the most recently closed list. Useful for
displaying the number of items in a list.
Bulleted Lists
~~~~~~~~~~~~~~
Bulleted list items start with a single dash or one to five asterisks
followed by some white space then some text. Bulleted list syntaxes
are:
...................
- List item.
* List item.
** List item.
*** List item.
**** List item.
***** List item.
...................
Numbered Lists
~~~~~~~~~~~~~~
List item numbers are explicit or implicit.
.Explicit numbering
List items begin with a number followed by some white space then the
item text. The numbers can be decimal (arabic), roman (upper or lower
case) or alpha (upper or lower case). Decimal and alpha numbers are
terminated with a period, roman numbers are terminated with a closing
parenthesis. The different terminators are necessary to ensure 'i',
'v' and 'x' roman numbers are are distinguishable from 'x', 'v' and
'x' alpha numbers. Examples:
.....................................................................
1. Arabic (decimal) numbered list item.
a. Lower case alpha (letter) numbered list item.
F. Upper case alpha (letter) numbered list item.
iii) Lower case roman numbered list item.
IX) Upper case roman numbered list item.
.....................................................................
.Implicit numbering
List items begin one to five period characters, followed by some white
space then the item text. Examples:
.....................................................................
. Arabic (decimal) numbered list item.
.. Lower case alpha (letter) numbered list item.
... Lower case roman numbered list item.
.... Upper case alpha (letter) numbered list item.
..... Upper case roman numbered list item.
.....................................................................
You can use the 'style' attribute (also the first positional
attribute) to specify an alternative numbering style. The numbered
list style can be one of the following values: 'arabic', 'loweralpha',
'upperalpha', 'lowerroman', 'upperroman'.
Here are some examples of bulleted and numbered lists:
---------------------------------------------------------------------
- Praesent eget purus quis magna eleifend eleifend.
1. Fusce euismod commodo velit.
a. Fusce euismod commodo velit.
b. Vivamus fringilla mi eu lacus.
c. Donec eget arcu bibendum nunc consequat lobortis.
2. Vivamus fringilla mi eu lacus.
i) Fusce euismod commodo velit.
ii) Vivamus fringilla mi eu lacus.
3. Donec eget arcu bibendum nunc consequat lobortis.
4. Nam fermentum mattis ante.
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
* Fusce euismod commodo velit.
** Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens. Sit munere ponderum dignissim et. Minim luptatum et
vel.
** Vivamus fringilla mi eu lacus.
* Donec eget arcu bibendum nunc consequat lobortis.
- Nulla porttitor vulputate libero.
. Fusce euismod commodo velit.
. Vivamus fringilla mi eu lacus.
[upperroman]
.. Fusce euismod commodo velit.
.. Vivamus fringilla mi eu lacus.
. Donec eget arcu bibendum nunc consequat lobortis.
---------------------------------------------------------------------
Which render as:
- Praesent eget purus quis magna eleifend eleifend.
1. Fusce euismod commodo velit.
a. Fusce euismod commodo velit.
b. Vivamus fringilla mi eu lacus.
c. Donec eget arcu bibendum nunc consequat lobortis.
2. Vivamus fringilla mi eu lacus.
i) Fusce euismod commodo velit.
ii) Vivamus fringilla mi eu lacus.
3. Donec eget arcu bibendum nunc consequat lobortis.
4. Nam fermentum mattis ante.
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
* Fusce euismod commodo velit.
** Qui in magna commodo, est labitur dolorum an. Est ne magna primis
adolescens. Sit munere ponderum dignissim et. Minim luptatum et
vel.
** Vivamus fringilla mi eu lacus.
* Donec eget arcu bibendum nunc consequat lobortis.
- Nulla porttitor vulputate libero.
. Fusce euismod commodo velit.
. Vivamus fringilla mi eu lacus.
[upperroman]
.. Fusce euismod commodo velit.
.. Vivamus fringilla mi eu lacus.
. Donec eget arcu bibendum nunc consequat lobortis.
A predefined 'compact' option is available to bulleted and numbered
lists -- this translates to the DocBook 'spacing="compact"' lists
attribute which may or may not be processed by the DocBook toolchain.
Example:
[options="compact"]
- Compact list item.
- Another compact list item.
TIP: To apply the 'compact' option globally define a document-wide
'compact-option' attribute, e.g. using the `-a compact-option`
command-line option.
You can set the list start number using the 'start' attribute (works
for HTML outputs and DocBook outputs processed by DocBook XSL
Stylesheets). Example:
[start=7]
. List item 7.
. List item 8.
Labeled Lists
~~~~~~~~~~~~~
Labeled list items consist of one or more text labels followed by the
text of the list item.
An item label begins a line with an alphanumeric character hard
against the left margin and ends with two, three or four colons or two
semi-colons. A list item can have multiple labels, one per line.
The list item text consists of one or more lines of text starting
after the last label (either on the same line or a new line) and can
be followed by nested List or ListParagraph elements. Item text can be
optionally indented.
Here are some examples:
---------------------------------------------------------------------
In::
Lorem::
Fusce euismod commodo velit.
Fusce euismod commodo velit.
Ipsum:: Vivamus fringilla mi eu lacus.
* Vivamus fringilla mi eu lacus.
* Donec eget arcu bibendum nunc consequat lobortis.
Dolor::
Donec eget arcu bibendum nunc consequat lobortis.
Suspendisse;;
A massa id sem aliquam auctor.
Morbi;;
Pretium nulla vel lorem.
In;;
Dictum mauris in urna.
Vivamus::: Fringilla mi eu lacus.
Donec::: Eget arcu bibendum nunc consequat lobortis.
---------------------------------------------------------------------
Which render as:
In::
Lorem::
Fusce euismod commodo velit.
Fusce euismod commodo velit.
Ipsum:: Vivamus fringilla mi eu lacus.
* Vivamus fringilla mi eu lacus.
* Donec eget arcu bibendum nunc consequat lobortis.
Dolor::
Donec eget arcu bibendum nunc consequat lobortis.
Suspendisse;;
A massa id sem aliquam auctor.
Morbi;;
Pretium nulla vel lorem.
In;;
Dictum mauris in urna.
Vivamus::: Fringilla mi eu lacus.
Donec::: Eget arcu bibendum nunc consequat lobortis.
Horizontal labeled list style
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The 'horizontal' labeled list style (also the first positional
attribute) places the list text side-by-side with the label instead of
under the label. Here is an example:
---------------------------------------------------------------------
[horizontal]
*Lorem*:: Fusce euismod commodo velit. Qui in magna commodo, est
labitur dolorum an. Est ne magna primis adolescens.
Fusce euismod commodo velit.
*Ipsum*:: Vivamus fringilla mi eu lacus.
- Vivamus fringilla mi eu lacus.
- Donec eget arcu bibendum nunc consequat lobortis.
*Dolor*::
- Vivamus fringilla mi eu lacus.
- Donec eget arcu bibendum nunc consequat lobortis.
---------------------------------------------------------------------
Which render as:
[horizontal]
*Lorem*:: Fusce euismod commodo velit. Qui in magna commodo, est
labitur dolorum an. Est ne magna primis adolescens.
Fusce euismod commodo velit.
*Ipsum*:: Vivamus fringilla mi eu lacus.
- Vivamus fringilla mi eu lacus.
- Donec eget arcu bibendum nunc consequat lobortis.
*Dolor*::
- Vivamus fringilla mi eu lacus.
- Donec eget arcu bibendum nunc consequat lobortis.
[NOTE]
=====================================================================
- Current PDF toolchains do not make a good job of determining
the relative column widths for horizontal labeled lists.
- Nested horizontal labeled lists will generate DocBook validation
errors because the 'DocBook XML V4.2' DTD does not permit nested
informal tables (although <> and
<> process them correctly).
- The label width can be set as a percentage of the total width by
setting the 'width' attribute e.g. `width="10%"`
=====================================================================
Question and Answer Lists
~~~~~~~~~~~~~~~~~~~~~~~~~
AsciiDoc comes pre-configured with a 'qanda' style labeled list for generating
DocBook question and answer (Q&A) lists. Example:
---------------------------------------------------------------------
[qanda]
Question one::
Answer one.
Question two::
Answer two.
---------------------------------------------------------------------
Renders:
[qanda]
Question one::
Answer one.
Question two::
Answer two.
Glossary Lists
~~~~~~~~~~~~~~
AsciiDoc comes pre-configured with a 'glossary' style labeled list for
generating DocBook glossary lists. Example:
---------------------------------------------------------------------
[glossary]
A glossary term::
The corresponding definition.
A second glossary term::
The corresponding definition.
---------------------------------------------------------------------
For working examples see the `article.txt` and `book.txt` documents in
the AsciiDoc `./doc` distribution directory.
NOTE: To generate valid DocBook output glossary lists must be located
in a section that uses the 'glossary' <>.
Bibliography Lists
~~~~~~~~~~~~~~~~~~
AsciiDoc comes with a predefined 'bibliography' bulleted list style
generating DocBook bibliography entries. Example:
---------------------------------------------------------------------
[bibliography]
.Optional list title
- [[[taoup]]] Eric Steven Raymond. 'The Art of UNIX
Programming'. Addison-Wesley. ISBN 0-13-142901-9.
- [[[walsh-muellner]]] Norman Walsh & Leonard Muellner.
'DocBook - The Definitive Guide'. O'Reilly & Associates.
1999. ISBN 1-56592-580-7.
---------------------------------------------------------------------
The `[[[]]]` syntax is a bibliography entry anchor, it
generates an anchor named `` and additionally displays
`[]` at the anchor position. For example `[[[taoup]]]`
generates an anchor named `taoup` that displays `[taoup]` at the
anchor position. Cite the reference from elsewhere your document using
`<