ACE Editor – Setup / Usage

Create syntax highlighter: https://ace.c9.io/#nav=higlighter

themes: https://github.com/ajaxorg/ace/tree/master/lib/ace/theme

Embedding Ace in Your Site

https://ace.c9.io/#nav=embedding

Ace can be easily embedded into a web page. Get prebuilt version of ace from ace-builds repository and use the code below:

<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
    #editor { 
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
</style>
</head>
<body>

<div id="editor">function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
}</div>
    
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/javascript");
</script>
</body>
</html>

Now check out the How-To Guide for instructions on common operations, such as setting a different language mode or getting the contents from the editor.

Loading Ace from a Local URL

If you want to clone and host Ace locally you can use one of the pre-packaged versions. Just copy one of src* subdirectories somewhere into your project, or use RequireJS to load the contents of lib/ace folder as ace:

Loading Ace from a CDN

The packaged version can also be loaded from CDN's such as PageCDN, jsDelivr or cdnjs.

https://ace.c9.io/#nav=howto

Working with Ace

In all of these examples Ace has been invoked as shown in the embedding guide.

Configuring the editor

there are several ways to pass configuration to Ace

// pass options to ace.edit

ace.edit(element, {

    mode: "ace/mode/javascript",

    selectionStyle: "text"

})

// use setOptions method to set several options at once

editor.setOptions({

    autoScrollEditorIntoView: true,

    copyWithEmptySelection: true,

});

// use setOptions method

editor.setOption("mergeUndoDeltas", "always");



// some options are also available as methods e.g. 

editor.setTheme(...)



// to get the value of the option use

editor.getOption("optionName");

See Configuring-Ace wiki page for a more detailed list of options.

Changing the size of the editor

Ace only checks for changes of the size of it's container when window is resized. If you resize the editor div in another manner, and need Ace to resize, use the following:

editor.resize()

if you want editor to change it's size based on contents, use maxLines option as shown in https://ace.c9.io/demo/autoresize.html

Setting Themes

Themes are loaded on demand; all you have to do is pass the string name:

editor.setTheme("ace/theme/twilight");

> See all themes

Setting the Programming Language Mode

By default, the editor supports plain text mode. All other language modes are available as separate modules, loaded on demand like this:

editor.session.setMode("ace/mode/javascript");

One Editor, Multiple Sessions

Ace keeps everything about the state of the editor (selection, scroll position, etc.) in “

editor.session 

. This means you can grab the session, store it in a var, and set the editor to another session (e.g. a tabbed editor).

You might accomplish this like so:

var EditSession = require("ace/edit_session").EditSession;

var js = new EditSession("some js code");

var css = new EditSession(["some", "css", "code here"]);

// and then to load document into editor, just call

editor.setSession(js);

Common Operations

Set and get content:

editor.setValue("the new text here");

editor.session.setValue("the new text here"); // set value and reset undo history

editor.getValue(); // or session.getValue

Get selected text:

editor.getSelectedText(); // or for a specific range

editor.session.getTextRange(editor.getSelectionRange()); 

Insert at cursor, emulating user input:

editor.insert("Something cool");

Replace text in range:

editor.session.replace(new ace.Range(0, 0, 1, 1), "new text");

Get the current cursor line and column:

editor.selection.getCursor();

Go to a line:

editor.gotoLine(lineNumber);

Get total number of lines:

editor.session.getLength();

Set the default tab size:

editor.session.setTabSize(4);

Use soft tabs:

editor.session.setUseSoftTabs(true);

Set the font size:

document.getElementById('editor').style.fontSize='12px';

Toggle word wrapping:

editor.session.setUseWrapMode(true);

Set line highlighting:

editor.setHighlightActiveLine(false);

Set the print margin visibility:

editor.setShowPrintMargin(false);

Set the editor to read-only:

editor.setReadOnly(true);  // false to make it editable

Using undo manager

To group undo delta of the next edit with the previous one set mergeUndoDeltas to true

editor.session.mergeUndoDeltas = true; 

editor.session.insert({row: 0, column:0}, Date()+"");

To start new undo group use markUndoGroup method

editor.insertSnippet("a$0b"); 

editor.session.markUndoGroup(); 

editor.insertSnippet("x$0y");

To disable undo of a an edit in a collaborative editor

var rev = session.$undoManager.startNewGroup(); // start new undo group

... // apply the edit 

session.$undoManager.markIgnored(rev); // mark the new group as ignored

To implement undo/redo buttons see https://ace.c9.io/demo/toolbar.html

Searching

editor.find('needle',{

    backwards: false,

    wrap: false,

    caseSensitive: false,

    wholeWord: false,

    regExp: false

});

editor.findNext();

editor.findPrevious();

The following options are available to you for your search parameters:

  • needle: The string or regular expression you're looking for
  • backwards: Whether to search backwards from where cursor currently is. Defaults to false.
  • wrap: Whether to wrap the search back to the beginning when it hits the end. Defaults to false.
  • caseSensitive: Whether the search ought to be case-sensitive. Defaults to false.
  • wholeWord: Whether the search matches only on whole words. Defaults to false.
  • range: The Range to search within. Set this to null for the whole document
  • regExp: Whether the search is a regular expression or not. Defaults to false.
  • start: The starting Range or cursor position to begin the search
  • skipCurrent: Whether or not to include the current line in the search. Default to false.
  • preventScroll: Whether or not to move the cursor to the next match. Default to false.

Here's how you can perform a replace:

editor.find('foo');

editor.replace('bar');

And here's a replace all:

editor.replaceAll('bar');

(editor.replaceAll uses the needle set earlier by editor.find('needle', ...)

Listening to Events

To listen for an onchange:

editor.session.on('change', function(delta) {

    // delta.start, delta.end, delta.lines, delta.action

});

To listen for an selection change:

editor.session.selection.on('changeSelection', function(e) {

});

To listen for a cursor change:

editor.session.selection.on('changeCursor', function(e) {

});

Adding New Commands and Keybindings

To assign key bindings to a custom function:

editor.commands.addCommand({

    name: 'myCommand',

    bindKey: {win: 'Ctrl-M',  mac: 'Command-M'},

    exec: function(editor) {

        //...

    },

    readOnly: true // false if this command should not apply in readOnly mode

});

Configure dynamic loading of modes and themes

By default ace detcts the url for dynamic loading by finding the script node for ace.js. This doesn't work if ace.js is not loaded with a separate script tag, and in this case it is required to set url explicitely

ace.config.set("basePath", "https://url.to.a/folder/that/contains-ace-modes");

Path for one module alone can be configured with:

ace.config.setModuleUrl("ace/theme/textmate", "url for textmate.js");

When using ace with webpack, it is possible to configure paths for all submodules using

require("ace-builds/webpack-resolver");

which depends on file-loader