Sublime Forum

Different colour for variables in loops

#1

I’d like to highlight my variables that are only valid inside the scope of a loop. In the following example it would be “i” and “pntr” respectively.

for( int i = 0; i < 10; i++ ){
    double some_value = i - i*i/2. + i*i*i/6.;
    std::cout << i << ": " << some_value << std::endl;
}

for( std::vector<MyClass>::const_iterator pntr = myVector.begin(); pntr != myVector.end(); pntr++ ){
  someFunction(*pntr);
}

while( int i = getValue(n) ){
    std::cout << i << " ";
    if( i > 10 ) break;
    
}

Is this possible? If yes, how?

0 Likes

#2

This is not possible via syntax highlighting. Highlighting a variable differently depending on how it was declared in a previous statement would require a context-sensitive parser. Sublime’s parser is context-free, with only very narrow exceptions that would not be useful here.

0 Likes

#3

I see the problem. That is unfortunate. I guess an ugly workaround would be to create a fixed set of loop variables which will get highlighted throughout the entire scope.

0 Likes