Sublime Forum

Is there an functional variable highlighting package for C?

#1

I’m looking for a package that highlights instances of a variable within a scope with a particular color with different variables having different colors. ColorCoder seems to be the package that comes up when searching for this feature but that package has been broken for many months now on ST3. Are there any other packages that do the same?

0 Likes

#2

There is a built-in hash style syntax highlight that may be close to what you actually want.

Adding the following rule to rules in your color scheme.

        // hash style syntax highlight
        {
            "scope": "(source.c | source.c++) - comment - string - keyword - punctuation - storage - entity",
            "foreground": ["#f00", "#0f0", "#00f"],
        },

results in

The same same-name tokens (or other term, I am not sure) will be highlighted as the same color.

0 Likes

#3

Thanks for the suggestion! I’m playing around with this and am trying to get it to do what I want. Having a syntax highlighting package like C99, C11 or C Improved is resulting in different things being highlighted by the scope definition as suggested.

Either way, I’ll see if I can get this to work.

0 Likes

#4

I got this to work somewhat by updating the tmLanguage file in addition to the color scheme. The language file now contains:

	<dict>
		<key>match</key>
		<string>(([a-zA-Z_][a-zA-Z_0-9]*\b(?!\s*\()\->[a-zA-Z_][a-zA-Z_0-9]*\b(?!\s*\())|([a-zA-Z_][a-zA-Z_0-9]*\b(?!\s*\()\.[a-zA-Z_][a-zA-Z_0-9]*\b(?!\s*\()))</string>
		<key>name</key>
		<string>variable.other.readwrite.name</string>
	</dict>

This matches to patterns a->b and a.b

The color scheme contains

{
“scope”: “(variable.other.dot-access.c | variable.other.readwrite.name)”,
“foreground”: [“hsl(200, 10%, 60%)”, “hsl(270, 90%, 90%)”]
},

This gets me some of the way towards my goal. For example, a->b and a->c get highlighted but struct my_struct a does not have highlighting for a via this method.

0 Likes

#5

What you’re asking for is impossible in Sublime Text. It is also unreasonable to ask Sublime Text to parse languages in a semantic manner (“is this token an argument of the function I’m in?”, “Is this token a global variable or a global function?”, “Is this token a function, a struct defined earlier, or a local variable?”). There are ideas floating around to support semantic highlighting for the language server protocol, but nothing is standardized yet. Even if such a feature would be standardized, there is no way to “update” the scopes in an active view with the current API design of ST. The hash-style highlighting is the best course of action for now, or live with the fact that not every semantic detail will be colored differently in ST.

0 Likes