### Install Ace Dependencies
Source: https://github.com/ajaxorg/ace/wiki/Building-Ace
Run this command in the Ace folder to install project dependencies.
```bash
npm install
```
--------------------------------
### Setup Ace Editor with Settings Menu
Source: https://github.com/ajaxorg/ace/blob/master/demo/settings_menu.html
Initializes the Ace editor, loads the settings menu extension, and sets the theme and mode. This is the primary setup for using the settings menu.
```javascript
Editor body { overflow: hidden; } #editor { margin: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
```
```javascript
// setup paths
require.config({paths: { "ace" : "../src"}});
// load ace and extensions
require(["ace/ace", "ace/ext/settings_menu"], function(ace) {
var editor = ace.edit("editor");
require('ace/ext/settings_menu').init(editor);
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/html");
editor.commands.addCommands([{
name: "showSettingsMenu",
bindKey: {win: "Ctrl-q", mac: "Ctrl-q"},
exec: function(editor) {
editor.showSettingsMenu();
},
readOnly: true
}]);
})
```
--------------------------------
### Install Dependencies and Package Ace
Source: https://github.com/ajaxorg/ace/blob/master/Readme.md
Run these commands in the ace folder to install dependencies and then package Ace using the dryice build tool.
```bash
npm install
node ./Makefile.dryice.js
```
--------------------------------
### Example .tmlanguage Conversion Command
Source: https://github.com/ajaxorg/ace/wiki/Importing-.tmtheme-and-.tmlanguage-Files-into-Ace
An example of how to run the tmlanguage conversion script with a specific language file.
```bash
node tmlanguage.js MyGreatLanguage.tmlanguage
```
--------------------------------
### Start Ace Development Server
Source: https://github.com/ajaxorg/ace/blob/master/demo/kitchen-sink/docs/markdown.md
Use this script to start a local HTTP server for development. This is necessary for running Ace in Google Chrome due to security restrictions with file:/// URLs.
```bash
./static.py
```
```bash
./static.js
```
--------------------------------
### Define Start and Cdata States
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Configure syntax highlighting states, transitioning from 'start' to 'cdata' upon encountering ''. The 'cdata' state applies the 'text' token by default.
```javascript
this.$rules = {
"start" : [ {
token : "text",
regex : "<\!\[CDATA\[",
next : "cdata"
} ],
"cdata" : [ {
token : "text",
regex : "\]\]>",
next : "start"
}, {
defaultToken : "text"
} ]
};
```
--------------------------------
### Build API Documentation (Build Directory)
Source: https://github.com/ajaxorg/ace/blob/master/doc/README.md
Execute these commands in the build directory to install dependencies and build API documentation.
```bash
npm install
node build.js
```
--------------------------------
### Start Ace Performance Test
Source: https://github.com/ajaxorg/ace/blob/master/tool/perf-test.html
Starts a performance test by setting up the editor, timeout, and profiling flags. It records the start time and initiates the first step of the test.
```javascript
function start(testName) { editor = env.editor timeout = parseInt(document.getElementById("timeout").value); shouldProfile = document.getElementById("profile").checked; startTime = Date.now() shouldProfile && console.profile() speed = 10; next = window[testName + "Next"]; window[testName + "Start"] && window[testName + "Start"]() setTimeout(next, 1); }
```
--------------------------------
### Setup Console Logging and Event Listeners
Source: https://github.com/ajaxorg/ace/blob/master/experiments/cut_copy.html
Initializes console logging and a helper function to add event listeners, ensuring compatibility with different browsers. This setup is crucial for debugging and event handling.
```javascript
if (!window.console) window.console = {}; if (!console.log) { var logger = document.getElementById("logger"); console.log = function() { logger.innerHTML += Array.prototype.join.call(arguments, ", ") + "
"; } }
function addListener(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
elem.attachEvent("on" + type, function() {
callback(window.event);
});
}
}
```
--------------------------------
### Run Ace HTTP Server
Source: https://github.com/ajaxorg/ace/blob/master/Readme.md
Start the bundled mini HTTP server using Node.js to test Ace locally.
```bash
node ./static.js
```
--------------------------------
### Run Ace Unit Tests with Node.js
Source: https://github.com/ajaxorg/ace/blob/master/Readme.md
After installing dependencies with 'npm install', you can run the Ace unit tests directly on Node.js.
```bash
npm run test
```
--------------------------------
### Example of Adding Namespaced Rules
Source: https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode
Demonstrates how to add new rules with a prefix, resulting in namespaced states like "new-start".
```javascript
this.$rules = {
start: [ /* ... */ ]
};
var newRules = {
start: [ /* ... */ ]
}
this.addRules(newRules, "new-");
/*
this.$rules == {
start: [ ... ],
"new-start": [ ... ]
};
*/
```
--------------------------------
### Setup Ace Editor and Toolbar
Source: https://github.com/ajaxorg/ace/blob/master/demo/toolbar.html
Initializes the Ace editor, configures its options, and builds a custom toolbar using `buildDom`. This snippet requires Ace editor and its language tools extension.
```javascript
require.config({
paths: {
"ace" : "../src"
}
});
require(["ace/ace", "ace/ext/language_tools"], function(ace) {
var buildDom = require("ace/lib/dom").buildDom;
var editor = ace.edit();
editor.setOptions({
theme: "ace/theme/tomorrow_night_eighties",
mode: "ace/mode/markdown",
maxLines: 30,
minLines: 30,
autoScrollEditorIntoView: true,
});
var refs = {};
function updateToolbar() {
refs.saveButton.disabled = editor.session.getUndoManager().isClean();
refs.undoButton.disabled = !editor.session.getUndoManager().hasUndo();
refs.redoButton.disabled = !editor.session.getUndoManager().hasRedo();
}
editor.on("input", updateToolbar);
editor.session.setValue(localStorage.savedValue || "Welcome to ace Toolbar demo!")
function save() {
localStorage.savedValue = editor.getValue();
editor.session.getUndoManager().markClean();
updateToolbar();
}
editor.commands.addCommand({
name: "save",
exec: save,
bindKey: {
win: "ctrl-s",
mac: "cmd-s"
}
});
buildDom([
"div", {
class: "toolbar"
},
["button", {
ref: "saveButton",
onclick: save
}, "save"],
["button", {
ref: "undoButton",
onclick: function() {
editor.undo();
}
}, "undo"],
["button", {
ref: "redoButton",
onclick: function() {
editor.redo();
}
}, "redo"],
["button", {
style: "font-weight: bold",
onclick: function() {
editor.insertSnippet("**${1:$SELECTION}**");
editor.renderer.scrollCursorIntoView()
}
}, "bold"],
["button", {
style: "font-style: italic",
onclick: function() {
editor.insertSnippet("*${1:$SELECTION}*");
editor.renderer.scrollCursorIntoView()
}
}, "Italic"],
], document.body, refs);
document.body.appendChild(editor.container)
window.editor = editor;
});
```
--------------------------------
### Get Existing HTML Highlight Rules
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Retrieve the syntax highlighting rules for HTML. This is often a starting point for extending existing highlighters.
```javascript
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
this.$rules = new HtmlHighlightRules().getRules();
/*
this.$rules == Same this.$rules as HTML highlighting
*/
```
--------------------------------
### Setup ACE Editor with Status Bar
Source: https://github.com/ajaxorg/ace/blob/master/demo/statusbar.html
Configure module paths and load ACE Editor along with the status bar extension. Instantiate the editor and the status bar, then set the theme and mode.
```javascript
require.config({
paths: {
"ace" : "../src"
}
});
require(["ace/ace", "ace/ext/statusbar"], function(ace) {
var editor = ace.edit("editor");
var StatusBar = require("ace/ext/statusbar").StatusBar;
var statusBar = new StatusBar(editor, document.getElementById("statusBar"));
editor.setTheme("ace/theme/dawn");
editor.session.setMode("ace/mode/html");
});
```
--------------------------------
### Setup and Initialize Code Lens in ACE Editor
Source: https://github.com/ajaxorg/ace/blob/master/demo/code_lens.html
Configures ACE editor paths, loads necessary extensions, and initializes Code Lens for HTML mode. Registers commands for Code Lens actions.
```javascript
// setup paths
require.config({paths: { "ace" : "../src"}}); // load ace and extensions
require(["ace/ace", "ace/ext/code_lens"], function(ace, codeLens) {
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/html");
var commandId = "describeCodeLens";
editor.commands.addCommand({
name: commandId,
exec: function(editor, args) {
// services available in `ctx`
alert('CodeLens command called with arguments ' + args);
}
});
editor.commands.addCommand({
name: "clearCodeLenses",
exec: function(editor, args) {
editor.setOption("enableCodeLens", false);
codeLens.clear(editor.session);
}
});
editor.setOption("enableCodeLens", true);
codeLens.registerCodeLensProvider(editor, {
provideCodeLenses: function(session, callback) {
var p = [{
start: {row: 0},
command: {
id: "clearCodeLenses",
title: "Clear all code lenses",
arguments: []
}
}];
var l = session.getLength()
for (var row = 2; row < l; row++) {
var line = session.getLine(row);
var endColumn = line.length;
var m = /\[{>]\s*\u0000$/.exec(line);
if (!m) continue;
p.push({
start: { row: row, column: m.index },
command: {
id: commandId,
title: "Line " + (row + 1),
arguments: ["line", row]
}
});
if (m.index < 10) continue;
p.push({
start: { row: row, column: m.index },
end: { row: row, column: m.index + 1 },
command: {
id: commandId,
title: "column " + endColumn,
arguments: ["column", endColumn]
}
});
if (m.index < 30) continue;
p.push({
start: { row: row, column: m.index },
command: {
id: commandId,
title: "Third Link",
arguments: ["3", row]
}
});
}
callback(null, p);
}
});
window.editor = editor;
window.codeLens = codeLens;
});
```
--------------------------------
### Define Token with RegExp
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Example of defining a token with a regular expression. Ensure the regex is correctly formatted.
```javascript
{
token : "constant.language.escape",
regex : /\$[\\\][\w\d]+/
}
```
--------------------------------
### Generate Fold Range for Starting Point
Source: https://github.com/ajaxorg/ace/blob/master/index.html
This code snippet demonstrates how to generate a folding range when a starting marker is found. It handles different types of opening brackets and comment blocks.
```javascript
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
```
--------------------------------
### Setup Ace Editor with CSS Transforms and Options
Source: https://github.com/ajaxorg/ace/blob/master/demo/transform.html
Initializes multiple Ace editor instances with various themes, modes, and enables basic autocompletion. The `hasCssTransforms` option is set to true for all editors.
```javascript
require.config({
paths: {
"ace" : "../src"
}
});
require(["ace/ace", "ace/ext/language_tools"], function(ace) {
var editor1 = ace.edit("editor1");
editor1.setOptions({
hasCssTransforms: true,
theme: "ace/theme/tomorrow_night_blue",
mode: "ace/mode/html"
});
var editor2 = ace.edit("editor2", {
hasCssTransforms: true,
theme: "ace/theme/kuroir",
mode: "ace/mode/html",
enableBasicAutocompletion: true,
});
var editor3 = ace.edit("editor3", {
hasCssTransforms: true,
theme: "ace/theme/tomorrow_night_eighties",
mode: "ace/mode/html",
enableBasicAutocompletion: true,
});
var editor4 = ace.edit("editor4", {
hasCssTransforms: true,
theme: "ace/theme/solarized_light",
mode: "ace/mode/html",
enableBasicAutocompletion: true,
});
var editor = ace.edit("editor", {
hasCssTransforms: true,
mode: "ace/mode/html",
value: "editor 4\n from a mirror",
enableBasicAutocompletion: true,
});
editor.renderer.setScrollMargin(10, 10, 10, 10);
var checkbox = document.getElementById("option");
checkbox.onchange = function() {
editor1.setOption("autoScrollEditorIntoView", checkbox.checked);
editor2.setOption("autoScrollEditorIntoView", checkbox.checked);
editor3.setOption("autoScrollEditorIntoView", checkbox.checked);
editor4.setOption("autoScrollEditorIntoView", checkbox.checked);
editor.setOption("autoScrollEditorIntoView", checkbox.checked);
};
checkbox.onchange();
window.editor = editor;
window.editor4 = editor4;
});
```
--------------------------------
### Setup Ace Editor and Add Keyboard Shortcut
Source: https://github.com/ajaxorg/ace/blob/master/demo/keyboard_shortcuts.html
Initializes the Ace editor, sets its theme and mode, and adds a custom command to display keyboard shortcuts. The command is bound to Ctrl-Alt-h (Windows) or Command-Alt-h (Mac) and lazily loads the 'keybinding_menu' extension.
```javascript
Editor body { overflow: hidden; }
#editor { margin: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
// setup paths
require.config({paths: { "ace" : "../src"}});
require(["ace/ace"], function(ace) {
var editor = ace.edit("editor")
editor.setTheme("ace/theme/twilight")
editor.session.setMode("ace/mode/html")
// add command to lazy-load keybinding_menu extension
editor.commands.addCommand({
name: "showKeyboardShortcuts",
bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
exec: function(editor) {
ace.config.loadModule("ace/ext/keybinding_menu", function(module) {
module.init(editor);
editor.showKeyboardShortcuts()
})
}
})
editor.execCommand("showKeyboardShortcuts")
})
```
--------------------------------
### Enable ACE Autocompletion and Snippets
Source: https://github.com/ajaxorg/ace/blob/master/demo/autocompletion.html
Load the language tools extension and configure the editor to enable basic and snippet autocompletion. Live autocompletion is disabled in this example.
```javascript
// trigger extension
ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/html");
editor.setTheme("ace/theme/tomorrow");
// enable autocompletion and snippets
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: false
});
```
--------------------------------
### Initialize and Load Diff Editors
Source: https://github.com/ajaxorg/ace/blob/master/demo/diff/index.html
Initializes two Ace editors for diffing. Loads initial content from localStorage or fetches example content. Sets the editor mode to JavaScript and updates the diff view.
```javascript
setValue(localStorage.valueA || v, -1); editorA.session.setMode("ace/mode/javascript"); diffView?.onInput(); }); require("ace/lib/net").get("./examples/editor.40.js", function (v) { initialValueB = v; editorB.setValue(localStorage.valueB || v, -1); editorB.session.setMode("ace/mode/javascript"); diffView?.onInput(); });
```
--------------------------------
### Setup ACE Editor with Modelist Extension
Source: https://github.com/ajaxorg/ace/blob/master/demo/modelist.html
Configures require.js paths for ACE, loads the editor and modelist extension, and initializes the editor. The modelist extension is then used to determine and set the session mode based on a file path.
```javascript
body { overflow: hidden; } #editor { margin: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
// setup paths
require.config({
paths: {
"ace" : "../src"
}
});
// load ace and extensions
require(["ace/ace", "ace/ext/modelist"], function(ace) {
var editor = ace.edit("editor");
editor.setTheme("ace/theme/twilight");
(function () {
var modelist = require("ace/ext/modelist");
// the file path could come from an xmlhttp request, a drop event,
// or any other scriptable file loading process.
// Extensions could consume the modelist and use it to dynamically
// set the editor mode. Webmasters could use it in their scripts
// for site specific purposes as well.
var filePath = "blahblah/weee/some.js";
var mode = modelist.getModeForPath(filePath).mode;
console.log(mode);
editor.session.setMode(mode);
}());
});
```
--------------------------------
### Tokenizing ES6 Built-in Methods
Source: https://github.com/ajaxorg/ace/blob/master/src/mode/_test/text_javascript.txt
Shows examples of tokenizing calls to new ES6 built-in methods like startsWith, endsWith, includes, find, findIndex, and repeat.
```javascript
"hello".startsWith("ello", 1) // true
```
```javascript
"hello".endsWith("hell", 4) // true
```
```javascript
"hello".includes("ell") // true
```
```javascript
[ 1, 3, 4, 2 ].find(x => x > 3) // 4
```
```javascript
[ 1, 3, 4, 2 ].findIndex(x => x > 3) // 2
```
```javascript
"foo".repeat(3)
```
```javascript
Number.isSafeInteger(42) === true
```
```javascript
let x = Number.MAX_SAFE_INTEGER;
```
```javascript
let x = Number.MIN_SAFE_INTEGER;
```
```javascript
let x = Number.EPSILON;
```
--------------------------------
### Define Folding Start and Stop Markers (C-Style)
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Define regular expressions for `foldingStartMarker` and `foldingStopMarker` to identify folding points. These are used by `getFoldWidgetRange`.
```javascript
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\ \[\{]*(\}|\])|^[\s\*]*(\*\/)/;
```
--------------------------------
### Get Ace Editor Instance
Source: https://github.com/ajaxorg/ace/wiki/Still-To-Work-Out
Initialize the Ace editor and store the instance in a global variable for later access. Ensure this code runs after the DOM is ready.
```javascript
window.onload = function() {
window.aceEditor = ace.edit("editor");
}
// Then elsewhere...
window.aceEditor.getSession().insert("Awesome!");
```
--------------------------------
### Initialize Tokenizer Test
Source: https://github.com/ajaxorg/ace/blob/master/tool/perf-test.html
Initializes the tokenizer test by getting the background tokenizer, resetting the state, and retrieving all lines from the document.
```javascript
var tokenizeStart = function() { var b = ace.session.bgTokenizer state = null tokenizer = b.tokenizer lines = b.doc.getAllLines() chunk = 1000 }
```
--------------------------------
### Setup Ace Editor with Autoresize Options
Source: https://github.com/ajaxorg/ace/blob/master/demo/autoresize.html
Configure Ace editor with options for themes, modes, and autoresizing behavior. Use `minLines` and `maxLines` to control height adjustments. `autoScrollEditorIntoView` ensures the editor is visible when focused.
```javascript
require.config({
paths: {
"ace" : "../src"
}
});
require(["ace/ace", "ace/ext/language_tools"], function(ace) {
var editor1 = ace.edit("editor1", {
theme: "ace/theme/tomorrow_night_eighties",
mode: "ace/mode/javascript",
maxLines: 30,
wrap: true,
autoScrollEditorIntoView: true
});
var editor2 = ace.edit("editor2", {
theme: "ace/theme/tomorrow_night_blue",
mode: "ace/mode/css",
autoScrollEditorIntoView: true,
maxLines: 30,
minLines: 2
});
var editor = ace.edit("editor3");
editor.setOptions({
autoScrollEditorIntoView: true,
maxLines: 8
});
editor.renderer.setScrollMargin(10, 10, 10, 10);
var editor = ace.edit("editor");
editor.setTheme("ace/theme/tomorrow");
editor.session.setMode("ace/mode/html");
editor.setAutoScrollEditorIntoView(true);
editor.setOption("maxLines", 100);
window.editor = editor;
var editor4 = ace.edit("editor4", {
theme: "ace/theme/tomorrow_night_blue",
mode: "ace/mode/javascript",
autoScrollEditorIntoView: true,
maxLines: 30,
minLines: 100,
hasCssTransforms: true,
value: "transformed editor" + "\n".repeat(100)
});
});
```
--------------------------------
### DOM Node Reuse Performance Test Setup
Source: https://github.com/ajaxorg/ace/blob/master/experiments/dom.html
Sets up and runs a performance test for DOM manipulation by rendering a large grid of text. It measures the time taken for rendering operations.
```javascript
tests.domdomReuseNodes_AllWrapped = function dom32() {
function elt(parent, name, className, content) {
var el = document.createElement(name);
if (content) {
el.appendChild(document.createTextNode(content))
}
parent && parent.appendChild(el)
el.className = className
return el;
}
function txtEl(parent, str) {
return parent.appendChild(document.createTextNode(str))
}
function clearEl(el, l) {
while (l --> 0) el.removeChild(el.lastChild);
}
function update(rootEl, lines) {
var ch = rootEl.childNodes
for (var i = 0; i < lines.length; i++) {
if (ch[i]) {
var el = ch[i]
el.className = "line"
} else var el = elt(rootEl, "div", "line")
renderLine(el, lines[i])
}
clearEl(rootEl, ch.length - i)
}
function renderLine(rootEl, tokens) {
var ch = rootEl.childNodes
for (var i = 0; i < tokens.length; i ++) {
if (ch[i]) {
var el = ch[i]
el.className = tokens[i]
el.firstChild.nodeValue = tokens[i]
} else elt(rootEl, "span", tokens[i], tokens[i])
}
clearEl(rootEl, ch.length - i)
}
return update;
}
function runTest(render, cb) {
var rootEl = document.getElementById("root")
rootEl.innerHTML = "";
var lines = []
for (var i = 0; i < LINES; i++) {
var line = []
lines.push(line)
for (var j = 0; j < COLS; j ++)
{
var ch = ((i + j) % COLS).toString(20)
var ch = " " + Array(5).join(ch) + " "
line.push(ch)
}
}
var now = performance.now()
var repeat = 100
function next() {
if (repeat-- < 0) {
var dt = now - performance.now()
console.log(dt)
return cb && cb(null, dt)
}
lines.push(lines.shift())
render(rootEl, lines);
requestAnimationFrame(next)
}
next()
}
var LINES = 100
var COLS = 50
var method = /test=(\w+)|$/.exec(location.search)[1]
window.clearResults = function() {
Object.keys(localStorage).forEach(function(x) {
if (/^m_/.test(x)) delete localStorage[x]
})
showResults()
}
function showResults() {
document.getElementById("root").innerHTML = Object.keys(tests).map(function(x) {
return "" + x + ": " + (localStorage["m_" + x] || "no results");
}).join("
") + "
clearResults";
}
if (method && tests[method]) {
var update = tests[method]()
runTest(update, function(e, a) {
var all = localStorage["m_" + method]
localStorage["m_" + method] = all ? all + "," + a : a;
showResults()
})
} else {
showResults();
}
```
--------------------------------
### Static Highlighter Extension for Ace (Node.js Server)
Source: https://github.com/ajaxorg/ace/wiki/Extensions
Provides static code highlighting capabilities, demonstrated here with a Node.js server-side implementation. Ensure the 'ace-builds' package is installed.
```javascript
var http = require('http');
var fs = require('fs');
var path = require('path');
var // Use the static highlighter
aceStaticHighlight = require('ace-builds/src-min-noconflict/ext-static_highlight').require("ace/ext/static_highlight");
var server = http.createServer(function(req, res) {
var filePath = path.join(__dirname, req.url);
fs.readFile(filePath, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found\n');
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
});
});
server.listen(8080);
console.log('Server running on port 8080');
// Example usage:
// var code = "function hello() { console.log('world!'); }\n";
// var html = aceStaticHighlight.render(code, 'javascript');
// console.log(html);
```
--------------------------------
### Paragraph Example
Source: https://github.com/ajaxorg/ace/blob/master/demo/kitchen-sink/docs/rst.rst
Demonstrates basic paragraph formatting and indented quote paragraphs in reStructuredText. Ensure paragraphs are separated by blank lines and maintain consistent indentation.
```rst
This is a paragraph. It's quite
short.
This paragraph will result in an indented block of
text, typically used for quoting other text.
This is another one.
```
--------------------------------
### Example Fold Range Object
Source: https://github.com/ajaxorg/ace/blob/master/index.html
An example of a `Range` object representing a foldable code block. This object specifies the start and end rows and columns for the collapsible section.
```json
{
"startRow": 0,
"endRow": 0,
"startColumn": 0,
"endColumn": 13
}
```
--------------------------------
### Build API Documentation (Root Directory)
Source: https://github.com/ajaxorg/ace/blob/master/doc/README.md
Run this command in the root directory to generate API documentation.
```bash
make doc
```
--------------------------------
### Setup ACE Editor with Inline Autocompletion
Source: https://github.com/ajaxorg/ace/blob/master/demo/inline_autocompletion.html
Configure ACE editor to use JavaScript mode and enable inline autocompletion. Ensure 'ace/ext/language_tools' and 'ace/ext/inline_autocomplete' are loaded.
```javascript
// setup paths
require.config({
paths: {
"ace" : "../src"
}
});
// load ace and extensions
require(["ace/ace", "ace/mode/javascript", "ace/ext/language_tools", "ace/ext/inline_autocomplete"], function(ace, codeLens) {
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/javascript");
editor.setTheme("ace/theme/tomorrow");
// enable inline autocompletion
editor.setOptions({
enableBasicAutocompletion: false,
enableInlineAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: false
});
window.editor = editor;
});
```
--------------------------------
### Get Cursor Position
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Gets the current line and column number of the cursor.
```APIDOC
## Get Cursor Position
### Description
Retrieves the current cursor's position, returning an object with line and column numbers.
### Method
```javascript
editor.selection.getCursor();
```
```
--------------------------------
### JavaScript Function Example
Source: https://github.com/ajaxorg/ace/blob/master/build_support/editor.html
A simple JavaScript function that iterates over an array and alerts a message for each item. This is a general JavaScript example.
```javascript
function foo(items) {
var i;
for (i = 0; i < items.length; i++) {
alert("Ace Rocks " + items[i]);
}
}
```
--------------------------------
### Get Selected Text in Ace Editor
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Retrieve the currently selected text. Can also get text within a specific range.
```javascript
editor.getSelectedText(); // or for a specific range
```
```javascript
editor.session.getTextRange(editor.getSelectionRange());
```
--------------------------------
### Basic JavaScript Function Example
Source: https://github.com/ajaxorg/ace/blob/master/index.html
A simple JavaScript function demonstrating string concatenation and arithmetic. This example is part of the introductory text.
```javascript
function add(x, y) {
var resultString = "Hello, ACE! The result of your math is: ";
var result = x + y;
return resultString + result;
}
var addResult = add(3, 2);
console.log(addResult);
```
--------------------------------
### Build Ace Bookmarklet
Source: https://github.com/ajaxorg/ace/wiki/Building-Ace
Run this command to generate the bookmarklet version of the Ace editor.
```bash
node Makefile.dryice.js bm
```
--------------------------------
### Initialize Ace Editor and Load Content
Source: https://github.com/ajaxorg/ace/blob/master/experiments/animate_folding.html
Sets up the Ace editor, loads JavaScript mode, and populates the editor with HTML content from a specific element. Requires the Ace editor library to be loaded.
```javascript
window.onload = function() {
var editor = ace.edit("editor");
var JavaScriptMode = require("ace/mode/javascript").Mode;
var EditSession = require("ace/edit_session").EditSession;
var lang = require("ace/lib/lang");
var Range = require("ace/range").Range;
editor.getSession().setMode(new JavaScriptMode());
editor.getSession().setValue(document.getElementById("main").innerHTML);
```
--------------------------------
### Initialize Ace Performance Test Environment
Source: https://github.com/ajaxorg/ace/blob/master/tool/perf-test.html
Sets up the require configuration for Ace and polyfills Date.now if not available. Initializes global variables for profiling and test parameters.
```javascript
var require = { baseUrl: window.location.protocol + "//" + window.location.host + window.location.pathname.split("/").slice(0, -1).join("/"), paths: { ace: "../lib/ace" } }; if (!Date.now) { Date.now = function() { return (new Date()).getTime() }; } var scrollTop, startTime; var timeout, speed, next var editor, shouldProfile;
```
--------------------------------
### Build Ace Editor with Options
Source: https://github.com/ajaxorg/ace/wiki/Building-Ace
The build script accepts options for minification, namespacing, and output path.
```bash
-m minify build files with uglify-js
-nc namespace require and define calls with "ace"
--target ./path specify relative path for output folder (default value is "./build")
```
--------------------------------
### Ace Mode Starter Template
Source: https://github.com/ajaxorg/ace/blob/master/index.html
A starter template for defining a new Ace mode. This includes setting up highlighting rules, indentation rules, and folding rules.
```javascript
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
// defines the parent mode
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
// defines the language specific highlighters and folding rules
var MyNewHighlightRules = require("./mynew_highlight_rules").MyNewHighlightRules;
var MyNewFoldMode = require("./folding/mynew").MyNewFoldMode;
var Mode = function() {
// set everything up
this.HighlightRules = MyNewHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new MyNewFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
// configure comment start/end characters
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
// special logic for indent/outdent.
// By default ace keeps indentation of previous line
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
// create worker for live syntax checking
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/mynew_worker", "NewWorker");
worker.attachToDocument(session.getDocument());
worker.on("errors", function(e) {
session.setAnnotations(e.data);
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
```
--------------------------------
### Get Highlighter Rules
Source: https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode
Retrieves the rules associated with a highlighter.
```javascript
getRules()
```
--------------------------------
### Getting Selected Text
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Retrieve the text that is currently selected by the user in the editor.
```APIDOC
## Getting Selected Text
### Description
Get the text currently highlighted by the user's selection.
### Methods
- `editor.getSelectedText()`: Gets the selected text.
- `editor.session.getTextRange(range)`: Gets the text within a specified range.
### Endpoint
N/A (JavaScript methods)
### Parameters
- `range` (Range object): A Range object defining the start and end of the text to retrieve.
### Request Example
```javascript
var selected = editor.getSelectedText();
var range = editor.getSelectionRange();
var textInRange = editor.session.getTextRange(range);
```
### Response
- `getSelectedText()`: Returns the selected text as a string.
- `getTextRange()`: Returns the text within the specified range as a string.
```
--------------------------------
### Inline Autocompletion
Source: https://context7.com/ajaxorg/ace/llms.txt
Demonstrates how to use the `ext/inline_autocomplete` module for a lightweight, ghost-text autocomplete feature. It shows how to attach an instance, provide completions, trigger the preview, navigate suggestions, insert matches, and detach the instance.
```APIDOC
## Inline Autocompletion — `ext/inline_autocomplete`
A lightweight, ghost-text autocomplete that shows a single inline completion preview without a dropdown popup. Activated on demand via `InlineAutocomplete.startCommand`.
```javascript
ace.require("ace/ext/inline_autocomplete");
var InlineAutocomplete = ace.require("ace/ext/inline_autocomplete").InlineAutocomplete;
var editor = ace.edit("editor", { mode: "ace/mode/javascript" });
// Attach inline autocomplete instance
var inlineAC = new InlineAutocomplete(editor);
// Provide completions via the same Completer interface
var langTools = ace.require("ace/ext/language_tools");
langTools.addCompleter({
id: "aiCompletion",
hideInlinePreview: false,
getCompletions: function(editor, session, pos, prefix, callback) {
// Simulate AI completions
setTimeout(function() {
callback(null, [
{ caption: "fetchUser", value: "fetchUser(id)", meta: "async fn", snippet: "fetchUser(${1:id})" }
]);
}, 50);
}
});
// Trigger inline completion programmatically (normally bound to Alt+/ or similar)
inlineAC.show({});
// Navigate suggestions
inlineAC.goTo("next");
inlineAC.goTo("prev");
// Insert the current suggestion
inlineAC.insertMatch();
// Detach / cleanup
inlineAC.detach();
```
```
--------------------------------
### Get Ace Editor Content
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Retrieve the current content of the editor or its session.
```javascript
editor.getValue(); // or session.getValue
```
--------------------------------
### Get Selected Text
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Retrieves the currently selected text within the editor.
```APIDOC
## Get Selected Text
### Description
Get the text that is currently selected by the user in the editor.
### Method
```javascript
editor.session.getTextRange(editor.getSelectionRange());
```
```
--------------------------------
### Configure Ace Editor Options
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Demonstrates various ways to configure Ace editor settings, including passing options during initialization, using setOptions, and setting individual options.
```javascript
ace.edit(element, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
```
```javascript
editor.setOptions({
autoScrollEditorIntoView: true,
copyWithEmptySelection: true,
});
```
```javascript
editor.setOption("mergeUndoDeltas", "always");
```
```javascript
editor.getOption("optionName");
```
--------------------------------
### Get Cursor Position
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Retrieves the current line and column number of the cursor.
```javascript
editor.selection.getCursor();
```
--------------------------------
### Client-Side Syntax Highlighting with Ace
Source: https://github.com/ajaxorg/ace/blob/master/demo/static-highlighter/client.html
Initializes Ace's static highlighter to render HTML content with JavaScript syntax highlighting using the twilight theme. Ensure Ace modules are correctly configured.
```javascript
var require = { paths: { demo: "..", ace: "../../lib/ace" } }; require(["ace/ext/static_highlight", "ace/mode/javascript", "ace/theme/twilight", "ace/lib/dom"], function() {
var highlighter = require("ace/ext/static_highlight");
var JavaScriptMode = require("ace/mode/javascript").Mode;
var theme = require("ace/theme/twilight");
var dom = require("ace/lib/dom");
var codeEl = document.getElementById("code");
var data = document.body.innerHTML;
var highlighted = highlighter.render(data, new JavaScriptMode(), theme);
dom.importCssString(highlighted.css, "ace_highlight");
codeEl.innerHTML = highlighted.html;
});
```
--------------------------------
### Get Selected Text
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Retrieves the currently selected text within the editor.
```javascript
editor.session.getTextRange(editor.getSelectionRange());
```
--------------------------------
### Getting Cursor Position
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Retrieve the current line and column number of the editor's cursor.
```APIDOC
## Getting Cursor Position
### Description
Get the current position of the cursor within the editor.
### Method
`editor.selection.getCursor()`
### Endpoint
N/A (JavaScript method)
### Parameters
None
### Request Example
```javascript
var cursorPosition = editor.selection.getCursor(); // Returns {row: number, column: number}
```
### Response
- Returns an object with `row` and `column` properties indicating the cursor's position.
```
--------------------------------
### Setting and Getting Content
Source: https://github.com/ajaxorg/ace/blob/master/index.html
Methods to set and retrieve the text content of the editor or a specific session.
```APIDOC
## Setting and Getting Content
### Description
Manipulate the text content of the Ace editor.
### Methods
- `editor.setValue(text, cursorPosition)`: Sets the entire editor content.
- `editor.session.setValue(text)`: Sets the session content and resets undo history.
- `editor.getValue()`: Gets the entire editor content.
- `editor.session.getValue()`: Gets the session content.
### Endpoint
N/A (JavaScript methods)
### Parameters
- `text` (string): The new text content.
- `cursorPosition` (number, optional): If -1, moves the cursor to the start.
### Request Example
```javascript
editor.setValue("New content");
var currentContent = editor.getValue();
editor.session.setValue("Session content");
```
### Response
- `getValue()`: Returns the current text content as a string.
```
--------------------------------
### Get Total Lines
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Returns the total number of lines in the editor's current session.
```APIDOC
## Get Total Lines
### Description
Gets the total number of lines currently present in the editor's session.
### Method
```javascript
editor.session.getLength();
```
```
--------------------------------
### Initialize Ace Editor with Options
Source: https://github.com/ajaxorg/ace/blob/master/demo/csp.html
Initialize an Ace editor instance with specified theme, mode, and display options. Ensure the target element ('editor') exists in the DOM before calling this.
```javascript
var editor = ace.edit("editor", { theme: "ace/theme/tomorrow_night_eighties", mode: "ace/mode/html", maxLines: 30, wrap: true, autoScrollEditorIntoView: true });
```
--------------------------------
### Get Total Lines
Source: https://github.com/ajaxorg/ace/wiki/Embedding---API
Returns the total number of lines in the editor's current session.
```javascript
editor.session.getLength();
```
--------------------------------
### Build Ace Editor
Source: https://github.com/ajaxorg/ace/wiki/Building-Ace
Execute the build script to compile Ace. Use options to customize the build process.
```bash
node Makefile.dryice.js
```
--------------------------------
### Initialize Ace Editor with Diff Functionality
Source: https://github.com/ajaxorg/ace/blob/master/demo/diff/index.html
Sets up two Ace editors and initializes the diff view. It configures the editor paths and loads necessary modules for diffing. The initial content is loaded from an external file.
```javascript
var debugInline = false
var diffView = null;
var editorA = null;
var editorB = null;
var paths = {
"ace": "../../src",
diff: ".",
demo: "..",
};
require.config({
paths: paths
});
require([
"ace/ext/diff/split_diff_view",
"ace/ext/diff/inline_diff_view",
"demo/kitchen-sink/util",
"demo/kitchen-sink/layout",
"ace/ext/diff/providers/default",
"ace/ext/options",
"ace/ext/menu_tools/overlay_page",
], function () {
var {InlineDiffView} = require("ace/ext/diff/inline_diff_view");
var {SplitDiffView} = require("ace/ext/diff/split_diff_view");
var {DiffProvider} = require("ace/ext/diff/providers/default");
var {OptionPanel, optionGroups} = require("ace/ext/options")
var {buildDom} = require("ace/lib/dom");
var tollbarButtons = {};
var initialValueA = "";
var initialValueB = "";
var updateButtonsState = () => {
if (!diffView) return;
tollbarButtons.prev.disabled = diffView.firstDiffSelected();
tollbarButtons.next.disabled = diffView.lastDiffSelected();
};
var goToNext = () => {
diffView.gotoNext(1);
updateButtonsState();
};
var goToPrevious = () => {
diffView.gotoNext(-1);
updateButtonsState();
};
function reset() {
editorA.setValue(initialValueA, -1);
editorB.setValue(initialValueB, -1);
localStorage.removeItem("valueA");
localStorage.removeItem("valueB");
}
var diffViewMode = "off";
var diffVewContainer = document.querySelector(".ace_diff-container");
var setMode = (mode) => {
if (diffViewMode == mode) return;
localStorage.diffViewMode = diffViewMode = mode;
if (diffView) {
diffView.detach();
}
switch (mode) {
case "inlineA":
diffView = new InlineDiffView({
editorA,
editorB,
});
if (!debugInline) editorB.container.style.display = "none";
editorA.container.style.display = "";
break;
case "inlineB":
diffView = new InlineDiffView({
editorA,
editorB,
inline: "b"
});
editorB.container.style.display = "";
if (!debugInline) editorA.container.style.display = "none";
break;
case "split":
diffView = new SplitDiffView({editorA, editorB});
editorA.container.style.display = "";
editorB.container.style.display = "";
break;
case "off":
diffView = undefined;
editorA.container.style.display = "";
editorB.container.style.display = "";
break;
}
if (diffView) {
diffView.setOptions(optionValues);
diffView.setProvider(new DiffProvider());
}
diffView?.onInput();
}
var optionValues = {
diffViewMode: localStorage.diffViewMode || "split",
ignoreTrimWhitespace: localStorage.ignoreTrimWhitespace == "true",
wrap: localStorage.wrap== "true",
syncSelections: localStorage.syncSelections != "false",
showOtherLineNumbers: localStorage.showOtherLineNumbers != "false",
folding: localStorage.folding != "false",
theme: localStorage.theme || "ace/theme/textmate",
}
function drawToolbar() {
var toolbar = document.createElement("div");
toolbar.className = "toolbar ace_optionsMenuEntry";
diffVewContainer.parentNode.insertBefore(toolbar, diffVewContainer);
optionBar = new OptionPanel({
getOption(path) {
return optionValues[path];
},
setOption(path, value) {
optionValues[path] = value;
if (path == "diffViewMode") {
setMode(value);
} else if (diffView) {
diffView.setOption(path, value);
}
localStorage.setItem(path, value);
}
});
var data = [
["button", {ref: "prev", onclick: goToPrevious}, "<"],
["button", {ref: "next", onclick: goToNext}, ">"],
optionBar.renderOptionControl("", {
path: "diffViewMode",
type: "buttonBar",
values: ["inlineA", "inlineB", "split", "off"],
}),
["label", {}, optionBar.renderOptionControl("", {
path: "ignoreTrimWhitespace",
type: "checkbox",
}), "Ignore Spaces"],
["label", {}, optionBar.renderOptionControl("", {
path: "syncSelections",
type: "checkbox",
}), "Sync Selections"],
["label", {}, optionBar.renderOptionControl("", {
path: "wrap",
type: "checkbox",
}), "Wrap"],
["label", {}, optionBar.renderOptionControl("", {
path: "folding",
type: "checkbox",
}), "Folding"],
["button", {onclick: function() {diffView.toggleFoldUnchanged()}}, "Fold Unchanged"],
["button", {id: "btn-reset", onclick: reset}, "Reset"],
["label", {}, optionBar.renderOptionControl("", optionGroups.Main.Theme), "Theme"],
]
buildDom(data, toolbar, tollbarButtons);
}
var config = require("ace/config");
config.setLoader(function (moduleName, cb) {
require([moduleName], function (module) {
cb(null, module);
});
});
var util = require("demo/kitchen-sink/util");
splitEditor = util.createSplitEditor(diffVewContainer);
editorA = splitEditor.editor0;
editorB = splitEditor.editor1;
require("ace/lib/net").get("./examples/editor.17.js", function (v) {
initialValueA = v;
editorA.setValue(initialValueA, -1);
require("ace/lib/net").get("./examples/editor.18.js", function (v) {
initialValueB = v;
editorB.setValue(initialValueB, -1);
drawToolbar();
setMode(optionValues.diffViewMode);
updateButtonsState();
});
});
});
```