Objective-C – (Syntax) Highlighting with Regex & CoreText
by Kristian Kraljic, September 1, 2012
Long time no see. It took me nearly nine month to figure this one out! No…, just kidding. This one took me in fact one day, but I was very busy writing by bachelor thesis and finishing my final exams in university. Sorry for the long period of starving and be curious about what is going to happen in future.
Without further ado, let me tell you what I have been working on today. This time it is an Objective-C component. Very similar to my Wordfile Editor Plugin for Eclipse, it can be used to dynamically highlight and display any kind of text based programming language or other structured data. The goal was to create a simple, but yet powerfull component to make nice syntax editing possible on Cocoa and iOS.
Unlike my Eclipse plugin, the component is not based on a fullblown parser to make syntax highlighting possible, instead I decided to use a set of regular expressions, to get the highlighting to work. Using regular expressions is sufficient for most structured programming language and should be enough to provide at least a basic highlighting.
I have included eight predefined color schemes (themes) into the component. So the developer can freely pick one of these or define his own color scheme. For even simpler usage I have provided regular expression sets for these programming languages:
actionscript, actionscript3, active4d, ada, ampl, apache,
applescript, asm-mips, asm-x86, asp-js, asp-vb, aspdotnet-cs,
aspdotnet-vb, awk, batch, c, cobol, coldfusion, cpp, csharp,
csound, css, d, dylan, eiffel, erl, eztpl, fortran, freefem,
gedcom, gnuassembler, haskell, header, html, idl, java, javafx,
javascript, jsp, latex, lilypond, lisp, logtalk, lsl, lua,
matlab, mel, metapost, metaslang, mysql, nemerle, none, nrnhoc,
objectivec, objectivecaml, ox, pascal, pdf, perl, php, plist,
postscript, prolog, python, r, rhtml, ruby, scala, sgml, shell,
sml, sql, standard, stata, supercollider, tcltk, torquescript,
udo, vb, verilog, vhdl, xml
Further information on how to use the component and the source code of the project can be found on GitHub. I have created a public repository for the project, please check it out here:
https://github.com/KayK/RegexHighlightView
Hope you enjoy the component, feel free to leave suggestions in the comments below!
Great class! However, cursor goes out of sync (doesn’t line up) with text as you go further down the screen
any suggestions???
Thanks
Hey Rick, thanks for your comment. Unfortunately the class hasn’t received any updates since 2012 and still uses Core Text to render the highlighting. It still has a minimum iOS target version of 4.3 which is not contemporary any longer. The class would need to be reworked to use TextKit instead of Core Text. I’ll put this on my list, but no promises that I’ll make it anytime soon. Sorry!