5 ms·
This is my favorite syntax highlighting JS library, by far. The approach this library takes to building the highlighted DOM tree is very clever. It represents
by chromakode 12y ago
This is my favorite syntax highlighting JS library, by far.
The approach this library takes to building the highlighted DOM tree is very clever. It represents the original DOM and the highlighted code output as separate streams of tag open / close events and then merges them together. This allows the highlighter to maintain the pre-existing DOM structure of the highlighted code! The language auto-detection and sub-language handling are also very neat.
If you like interesting codebases, I'd recommend giving it a quick read. :)
- ioquatix 12y agoSounds exactly like what I implemented 4 years ago. Here is where you extract the existing HTML tags: https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d776713108ed392fe3e6701b9d2c8/source/jquery.syntax.core.js#L1118-L1119 https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d7... When you brush the code (extract highlighing information) you provide the set of initial matches which are converted into a tree: https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d776713108ed392fe3e6701b9d2c8/source/jquery.syntax.core.js#L1088 https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d7... - there is no merge step, they are merged in place in the tree which is then used to generate DOM (or whatever you like really) output. I never implemented language auto-detection but I'm sure I've seen that implemented before prism before, perhaps Google's Prettify might have been one of the first to do it. It basically highlights using all available brushes and looks at which one matches the most tokens - not sure if this is how it is currently implemented though. My feeling is that you usually know what language you are highlighting, the auto-highlighter wouldn't always get it right, and the cost of loading all brushes/languages is pretty high (imagine for example you have 100 different languages supported, you'd have to do all of them).. The sub-language handling in jQuery.Syntax is as precise as possible: https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d776713108ed392fe3e6701b9d2c8/source/jquery.syntax.brush.html.js#L14-L17 https://github.com/ioquatix/jquery-syntax/blob/97e38d08924d7... Basically, if you match some sub-portion of the code, you then highlight that using a different brush. Sometimes it's almost impossible to know though (e.g. diffs which may be incomplete).