Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISO Emacs [C]Perl-mode colorize hash references like hashes

I still use Perl, some new code, and maintaining old code. I use emacs and cperl-mode. I like syntax coloring.

At first (many years ago) I disliked cperl-mode's special coloring of arrays and hashes, but it has grown on me. To the point where I will sometimes prefer to use a hash rather than a hash reference, just to get the special coloring. That may not sound so bad - but if I admit to occasionally using a global %hash or $hash{key} rather than an object member $hashref->{key}, just to get the coloring, well, it is bad. I.e. syntax coloring is making me want to follow bad programming practices.

So, my question is: does anyone have emacs/elisp configuration code to get cperl-mode or perl-mode to colorize a hash reference like $hashref->{key} in the same or similar to $hash{key}?

Let me use bold to indicate the places that might be colored:

  • cperl-mode does now: $hash{key}
  • what I would like: $hash->{key}

I have done extensive customization of coloring (faces) in emacs - e.g. colorizing to distinguish DEBUG code from non-debug code, TEST from non-test, etc. - but I have not managed to get this syntax coloring in cperl-mode working. (FOLLOW-ON: I eventually got font-lock-add-keywords working, as shown in my answer to my own question below.)

In the example below, you can see that $hashref->{key} is not colored, while $hash{key} is.

example of cperl-mode syntax coloring

Similarly for array refs, and perhaps other refs.

I realize that coloring refs will only apply to derefs like $hashref->{key}, and not to other stuff like $hashref1 = $hashref2. I think that I can live with that.

like image 425
Krazy Glew Avatar asked Jan 03 '23 07:01

Krazy Glew


1 Answers

You can set cperl-highlight-variables-indiscriminately to t (via customizing it) to get scalar variables coloured not only when declared but always. enter image description here

Using the same colour for @ref and $ref is confusing, as they are different variable types (and different variables); similarly, it's confusing to use the scalar colour for $ref but array colour for $ref->[0] as they are the same variable.

Also, Perl being Perl, would you use all three colours here?

if (ref $ref eq 'ARRAY') {
    return $ref->[0]
} elsif (ref $ref eq 'HASH') {
    return $ref->{key}
}
like image 62
choroba Avatar answered Jan 13 '23 17:01

choroba