- Faades for Integration
- Walking the Tree
- Generating HTML
- Syntax Highlighting
- Autoreleasing Performance
- Final Thoughts
Syntax Highlighting
Any programming book is going to have a lot of source code examples. These days, most people read code in IDEs and expect syntax highlighting. I find this is a lot more important when it's a language that I've not used much. I can easily read code in a language I use every day as plain text, but it really helps understanding if code in a language I've only used intermittently is properly highlighted.
For the HTML edition of this book, the code is all highlighted using libclang. This uses the same parser that you will use if you compile Objective-C with clang (the default now on OS X and iOS).
One of the strengths of Objective-C is that it is effectively a dialect of C, and it can trivially interoperate with C code. Unlike the rest of the document, the structure of the code is flat. Well, technically, it's also a tree of nested scopes, but for the purpose of typesetting I only care about the keywords, macro definitions, and so on.
I talked a bit about how the syntax highlighting used libclang in a previous article. The first pass attached semantic metadata to an NSAttributedString and the second pass replaced this with presentation markup. In this case, I'm not using the second pass at allthe code just uses the same sort of loop I described in the previous article, but writes the type out as the class attribute to a span tag. This means that the keyword, macro, and type definitions (for example) are all highlighted uniformly from CSS.
This is a good example of using NSAttributedString to store semantic annotations, rather than just rich text. The class also supports generating HTML itself (via AppKit additions, so no on iOS), but this only translates presentation markup into HTML.