Sectional PHP Highlighting in VSCode

2019-07-16 

So, my eyes were glazing over some WordPress PHP in my editor of choice, VSCode.

The weaving in and out of <?php, <?= and ?> tags, bouncing between PHP and HTML contexts was making my head spin.

I kept having fantasies of a time when I could highlight the PHP (or HTML) context using a different background color… but there didn’t seem to be anything like that for VSCode, at least. It’s possible I was thinking of PHPStorm, but that was a lifetime ago.

So I powered through, cleaning up the twisty templates, trying to make them as readable as possible. But I finally hit my breaking point and started looking around… and I think I found a good solution. Whether it’s a good long term solution, well, that remains to be seen.

The Highlighter extension for VSCode is where the magic happens.

This extension allows you to define custom highlighting rules to regex matches in your code.

You can probably see where this is going.

After some futzing around, I wound up with these rules in my VSCode settings config:

"highlight.regexes": {
&lt;a href="https://clips.twitch.tv/JoyousEnthusiasticSpaghettiVoHiYo"&gt;https://clips.twitch.tv/JoyousEnthusiasticSpaghettiVoHiYo&lt;/a&gt;    "(&lt;\?php)((.|r|n)+?)(\?&gt;)": [
        { "color": "#FF00FF", "backgroundColor": "#FF00FF40" },
        { "backgroundColor": "#FF00FF40" },
        { "color": "#FF00FF", "backgroundColor": "#FF00FF40" }
    ],
    "(&lt;\?=)((.|r|n)+?)(\?&gt;)": [
        { "color": "#FF00FF", "backgroundColor": "#FF00FF40" },
        { "backgroundColor": "#FF00FF40" },
        { "color": "#FF00FF", "backgroundColor": "#FF00FF40" }
    ]
}

Your color preferences will vary, of course, but do at least note that I’m using the extended alpha value in the hex (the final octet), so you can blend your background color into your theme’s existing color!

(And yes, you can combine that down into one regex. Go ahead and do that.)

(IMAGE MISSING; SORRY…)

(The rainbow colored indents are part of the terrific indent-rainbow extension!)

I haven’t bounced on this very hard, so you might find some quirks here and there.

For instance, if you don’t include the closing PHP tag, ?>, it won’t match the regex. You could make the closing tag optional, but that might be undesirable…

But in any event, this seems to get me 9/10th of the way to the functionality I want, so I’m pretty happy. 😏