7

Recently code.google.com added the feature to edit a file and syntax highlight it!

like this

From what I can understand they added a textarea along with at iframe, where the textarea is where you type in content and the iframe displays the formatting. The textarea is moved up ( like -10000 px or something ) so it is invisible.

What I don't get is how they manage to have the iframe content behaving like a textarea. For instance if you copy and paste a bunch of code they format it immediately.

This is very interesting. Can anyone explain a bit on how does this works?

2 Answers 2

6

Google Code uses CodeMirror for editing.

Here are documents about its internals written by the author:

1

Lot's and lot's of javascript and custom event handling. It's not so easy to answer since it's a complex piece of software.

They are probably using an <iframe> with contentEditable="true" to make the text editable, the textarea might be there to capture input on browsers that do not support it (or even for some other reason, I can't tell without more analysis).

They also need a lexer for each supported language. This can be done client or server side, to identify which style to apply to each token, plus some heavy DOM manipulation (probably using a library like jQuery for example, to simplify updates to the tree).

2
  • +1 Thanks, as for the actual formatting @Gostoy is right about the library which have been used for a long while now. What is amazing form me is the fact both may be used at the same time, editing and formatting. It would be amazing if you get to know how to do this ( I don't have that much of javascript power )
    – OscarRyz
    Commented Jul 19, 2011 at 4:03
  • I haven't done it in Javascript, but I have some experience writing syntax highlighting editors with code completion, syntax checking, etc. It's a lot of work with many corner cases, I've played a bit trying to make a Javascript implementation, and even it's trickier due to the different runtime environments (there are some subtleties in event handling, and corner case behaviors). It probably has gotten better in the last few years.
    – juancn
    Commented Jul 19, 2011 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.