Skip to content
David Gonzalez edited this page Feb 6, 2016 · 27 revisions

Ace code editor

What is the Ace code editor, and where can I learn more about it?

Ace is web-based code editor that can be easily embedded in html pages as a JavaScript library. Out of the shelf it offers several features such as syntax highlighting, auto-format, drag and drop, code folding and more. Currently, it is capable of doing live syntax check in JS/CoffeeScript/CSS/Xquery. Also, it provides an API to extend its functionalities and add custom features. It is widely used in the industry, with the most notorious use being the code editor of the web-based IDE, Cloud9.

The following diagram provides an overview of Ace components. Please check other questions to learn how to add overlays via the Virtual Renderer, capture edit and user events with the Edit Session.

You can learn more about it here https://ace.c9.io/#api=&nav=about. For more details of its structure and API, check here https://ace.c9.io/#nav=api. For trouble-shooting and lore check the “ace-editor” tag in Stackoverflow http://stackoverflow.com/questions/tagged/ace-editor.

How do I embed it in my page?

  1. Add the library from CDNJS:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.3/ace.js" type="text/javascript" charset="utf-8"></script>
  2. Add your section on your web page:

    function foo(items) { var x = "All this is syntax highlighted"; return x; }
  3. and initiate the editor session:

    <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.getSession().setMode("ace/mode/javascript"); </script>

I want to build a visualization that overlays visual shapes on top of code and I want it to move smoothly when the code scrolls. What's the best way to do that?

The best way to add visualizations in the editor is by using the API to communicate the Virtual Renderer module via the Editor module( API’s entry class). First, the following snippet shows how to add an icon that move with the scroller: you should catch the scrolling events:

editor.getSession().on("changeScrollLeft", function(Number scrollLeft){
updateOverlay();
});

editor.getSession().on("changeScrollTop", function(Number scrollTop){
updateOverlay();
});

To make the scrolling transition smooth add the following line:

editor.renderer.setAnimatedScroll(true);

Information about Ace’s structure can be found here https://ace.c9.io/#nav=api.

I want to create a popup that comes up whenever the user hovers over a piece of code. What's the best way to do that?

Use the API for the event listener.

I want to get an event whenever the selection changes, either by mouse click or by keyboard input. Can I do that?

Not directly, you can get the selection event and then specify the type of input. These events are handled by the Edit Session object. You can get it by using the following command: editor.getSession().selection.on('changeSelection', function(e) { });

Clone this wiki locally