? Coding in color (archive)

Source originale du contenu

How to make syntax highlighting more useful


This is what syntax highlighting looks like for most of us.

This is javascript for the Fisher-Yates shuffle, which I took from this StackOverflow question. Screenshot from Sublime Text 2 with the Dawn theme.

We think syntax highlighting makes the structure of code easier to understand. But as it stands, we highlight the obvious (like the word function) and leave most of the content in black. Rather than highlighting the differences between currentIndex and the keyword function, we could highlight the difference between currentIndex and randomIndex. Here’s what that might look like:

Notice that instead of the built-in keywords being highlighted, everything else is. Each variable has its own color, so I can see where it’s used at a glance. Even when skimming the code, I can see how data flows through the function.

By using only muted colors and bolder type for variable names, we can still reserve a brighter red to highlight strings and a lighter green for comments without causing confusion. Also, because any new or custom function will get a color, I’ll be able to catch the typo in querySelector below.

Variable names with similar prefixes will be assigned similar colors. We collect all the custom names and order them alphabetically, then distributing them evenly along a spectrum. This way we make sure we use as distinct colors as possible.

Across files, all variable that start with $ or _ will probably be in the red/orange spectrum.

Not sure if anyone has done work on this idea before, but I’m curious what it would be like to live with this implemented in a code editor. It might not scale to extremely large and/or complex files as is. But if you want to help, feel free to start with my code (or, even better, implement it in a smarter way!).

Updated June 12 2014

Update:

Thanks to r/programming for pointing out that semantic highlighting in KDevelop already does exactly this! I’ll have to give it a try.