I need to evaluate
Needs["GraphUtilities`"]
before I can use functions such as GraphPath[]
. When I do so, some functions get colored red, but still work.
Why does this happen and can I change this?
The red colouring indicates shadowing — i.e., when a symbol originally in a particular context, is exposed to the current context path, thereby clashing with another symbol of the same name in a different context, also on the context path.
Here is a short example that demonstrates this. Try it out in a fresh kernel (call Quit[]
before you try it).
(* Define f in the test` context *)
Begin["test`"]
f[x_] := x^2
End[]
(* Define f in the Global` context *)
f[y_] := y^3
So far, all's well and you see the symbols coloured the way you're used to. Now expose test`f
by adding it to the context path with:
$ContextPath = Prepend[$ContextPath, "test`"]
You'll now notice that both the f
turned red to indicate that it is being shadowed by a different definition.
For more information on this, you can read about shadowing in the documentation and also this article by David Wagner in the Mathematica journal.
The definition that is used first, in the case of shadowing, is the one belonging to the context that appears first in $ContextPath
. This is the same behaviour as in your unix shells, where directories in the $PATH
variable are searched in the order they appear.
In the above example, I used Prepend
, which would've placed test`
first in the list. So the definition of f
will be test`f
and you can easily test this:
f[x]
Out[1]= x^2
Now quit your kernel and do the same, except now you place the new context at the end. You can see that the definition used is that of Global`f
.
$ContextPath = Append[$ContextPath, "test`"]
f[x]
Out[2]= x^3
Incidentally, it is also possible to trigger this shadowing warning (red colour) even if there isn't a real conflict. This can occur if the same context appears at different positions in $ContextPath
. To test this, in a clean kernel, define test`f
as before, and Append
and Prepend
it to $ContextPath
.
To change the colour from red to your favourite, go to Preferences > Appearance > Syntax Coloring > Errors and Warnings
and change the colour in the very last option:
To do it programmatically, evaluate:
SetOptions[$FrontEndSession, AutoStyleOptions -> {"SymbolShadowingStyle" ->
{FontColor -> Orange}}]
Replace Orange
with the color of your choice and $FrontEndSession
with $FrontEnd
if you want the change to persist across future sessions (it essentially writes it to the FE's init.m
). See this answer for more on the various style tokens and what they control.
f[x_] := Module[{x}, x]
. You can actually change these colours inPreferences > Appearance > Syntax colouring > Errors and warnings
. By default they're all the same damn shade of red (I have different ones for each). CHM, to answer the last line of your question, the above is where you can change this colour. $\endgroup$