LearnBuilding a Syntax-Highlighted Input Box with JavaScript

   
Avatar

Jake Rocheleau
writes on January 22, 2013

The textarea element has been commonly used for in-page web IDEs. Some great examples are in popular CMS’ like WordPress or Drupal. But inline web development is not the easiest solution to implement. And through other open source projects we have finally come to a point where textareas are not as much a necessity anymore.

In this article I want to present a JavaScript library called ACE. It is completely open source and free to download for use on any website project. This script allows developers to create input boxes which support syntax highlighting. Then you may pull this code to embed into other parts of your layout, or to process in the backend. The ACE library is my first choice to implement code highlighting and it is a breeze to install.

Download the Library

First we need to download a copy of the ACE code off of Github. Check out the ACE code page just to see how the files are put together. But instead of downloading off this repo, I want to grab the codes from this Github page. Just click the .zip to download from the master branch. This will include a lot of extra files we don’t need, plus some demos for running tests.

After the download completes just unzip the contents into a new folder anywhere on your computer. This will create a new folder named “ace-builds-master”. Inside are two almost mirror-identical directories which contain the basic source code we need. The directories src and src-min hold all the ACE codes and various stylesheets. For my demo examples I am using the src-min files which require less space on the drive.

Believe it or not we only need to include a single file out of the entire directory. This would be the ace.js script which contains all the other important settings. Then once we activate a live editor using JavaScript we can append some further customizations using property values and JS methods.

  <script src="src-min/ace.js" type="text/javascript" charset="utf-8"></script>

Adding the Code Editor

Now that we have the file included into our HTML page it’ll be easy to setup the codes. Basically you should include all the source code inside some type of element, in this case a div. Then calling the ace.edit() method we can apply all the styles and highlights onto a single ID name.

<div id="editor">function foo(items) {
  var x = "All this is syntax highlighted";
  return x;
}
</div>

This is the sample HTML demo code which you can download from ACE. I have put up a couple of demos using various styles and language formats. For this example the div element has an ID of #editor which we can access directly. Check out the single line of code we need to execute, which is added inside <script></script> tags at the bottom of the page.

  var editor = ace.edit("editor");
  editor.getSession().setMode("ace/mode/javascript");

Now keep in mind that you could rename the variable to anything you’d like. I am using var editor for the sake of convenience, and it’s the same in the ACE demo pages as well. The second line is declaring which type of syntax highlighting we should use. There is a huge collection of other syntax modes you may choose from which are located inside the src directory. Here are some of the more popular examples:

  • SQL
  • Ruby
  • SASS
  • PHP
  • Objectivec
  • Csharp
  • Java
  • JSON

Using Extra Features

What we have already put together should allow for a fully-functioning code editor. But there are some other additional parameters we can set using dot notation. So in reality these parameters behave more like properties, but they require a target editor object to work with.

  editor.setTheme("ace/theme/dawn");
  editor.getSession().setTabSize(2);
  editor.getSession().setUseWrapMode(true);

Consider the brief example I have included above. These 3 lines of code all perform varying tasks which are related to the text input. First we are changing the default code syntax colors and instead using the Dawn Theme. There are dozens of additional themes you can choose from which are all located inside the src directory. Each of the files is preceded with the text “theme-” so they are listed close together in alphabetical order.

The other two options are about user experience functionality. Typically the tab key will input 4 spaces, but I have reset this value as 2 spaces instead. I tend to enjoy the smaller tabs when coding documents. Additionally the text will not wrap by default, and will append a horizontal scrollbar after extending outside the boundaries. But using this method setUseWrapMode(true) we can quickly fix the issue of word wrap.

There are some other commands you may be interested in using which are listed on the ACE howto guide. The script references commands for changing the cursor position, adding in new content dynamically, or copying the entire contents of the text input block.

CSS Tips and Tricks

The #editor box will likely need some styling aside from the default syntax codes. However using positioning styles on the box can screw up your layout, or screw up the code inside. The best solution is to append a limited width/height on the element like I have done in my sample codes:

#editor { 
  margin-left: 15px;
  margin-top: 15px;
  width: 1000px;
  height: 400px;
}

Now you could use percents or ems to size the box instead of pixels. But the point is to have the editor contained inside a wrapper of some type, instead of spanning the entirety of the screen. This is how ACE’s initial demo page looks and it is difficult to navigate at times.

Also one final tip is to always use margins for resizing the box position. Or if you are using padding values, add these properties onto the container element and NOT the editor box itself. Padding will cause the box to shrink and overlay on top of the contents inside! It’s a small, almost unnoticeable trait unless you are looking for it. And it is definitely worthy of some advanced warning to developers.

live demo preview ACE syntax code editor

Live Demo #1Live Demo #2

Final Thoughts

I do hope this tutorial can provide a starting point for interested developers. Syntax highlighting has appeared as a difficult technique to build for the web, and has been almost exclusive to desktop software for years. It hasn’t been until recently that true dynamic code highlighting features have been possible for general HTML pages. If you have similar ideas or questions on the tutorial you may share with us in the post discussion area below.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started
man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop