Improved productivity coding html
by using CSS Selectors

Zen Coding

I’ve just discovered Zen Coding. This is a plugin for various editors that lets you write html using an abbreviation syntax that is based on CSS selectors.

I’m pretty keen on using this, not only because it will drastically reduce the number of keystrokes required for creating html once I become familiar with it, but it will also help me become more fluent at thinking in css-selector, which will make me more productive at writing functional tests & javascript.

I tried the TextMate plugin, since that is my editor of choice. Installation was simple; it is supplied as a bundle which you can install just by double-clicking it. Or you can copy it to ~/Library/Application\ Support/TextMate/Pristine\ Copy/Bundles.

The TextMate version of Zen Coding consists of a single command (written in python) that expands css-selector expressions when you type ⌘E. It supports a subset of CSS Selectors, and adds some operators specific to generating html:

Description example expands to:
E any html element div <div></div>
E#id an html element with an id div#bob <div id="bob"></div>
E.class an html element with class(es) div.bob.mary <div class="bob mary"></div>
E>N Child element div#bob>p>span.mary <div id="bob">
  <p><span class="mary"></span></p>
E+N multiple siblings h2+h3+p <h2></h2>
E*N multiply element ul>li*5>a <ul>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
E$*N item numbering ul>li.item-$*5 <ul>
  <li class="item-1"></li>
  <li class="item-2"></li>
  <li class="item-3"></li>
  <li class="item-4"></li>
  <li class="item-5"></li>

For example, I created the basic html for the above table by typing:



Currently Zen Coding has no provision for grouping expressions -- for example I was unable to do this:


Similarly, it does not have a way to move back up the hierarchy in an expression, so far as I could determine.


Zen Coding uses its own internal idea of snippets to do what it does. These live inside the bundle in Support/zencoding/ All the html tags are implemented as snippets in this file, so if you want to change something (for example, which default attributes get placed in an element), you can change it here. Along with snippets for all the html tags, it comes with a number of other snippets; details here. It also has approximately a bajillion snippets for writing CSS which I have not tried yet.


Hmmm, a quick google doesn't seem to show a HAML emitter. I guess I'll have to make one at some point. It should be fairly easy to do, though I'll have to learn a little python to switch between files depending on context.