5
$\begingroup$

This example is obviously not useful on its own, but it will cover everything I actually need to know for a more complicated function I'm making.

The example is to recreate the Do function, and call it Do2. My code is as follows:

Do2[function_, iterator_] := Do[function, Evaluate[iterator]]
SetAttributes[Do2, HoldAll]

This works correctly as expected, i.e. the functionality of Do2 is exactly the same as the functionality of Do (I think). However, the syntax highlighting is clearly different for the two functions: Do2's iterator is blue, but Do's iterator is cyan

Do2's iterator i is blue, but Do's iterator i is cyan.

Using the "Why the Coloring?" tool under Help, you can see that: the i of Do is under "Variables made special by use in arguments", but the i in my Do2 is under "Global symbols that have no value assigned".

the i of Do is under "Variables made special by use in arguments",

but the i in my Do2 is under "Global symbols that have no value assigned".

How do I get the i of Do2 to be under "Variables made special by use in arguments"? It seems like it should be under this category, and that the highlighting is wrong.

$\endgroup$

1 Answer 1

7
$\begingroup$

Welcome to MMA SE! (Note that I think you shouldn't be using Evaluate there: consider i=3; Do2[Print[i], {i,5}].) Syntax highlighting is done in terms of the syntax only, and the front end's processing of that syntax; the downvalue of Do2 (that is, the definition you gave it via :=) is not a syntactic property the front end can access.

But there is a way to achieve the syntax highlighting you want by informing Mathematica of the syntax information...

SyntaxInformation[Do2] = SyntaxInformation[Do]

Note, however, that your function is not quite like Do: Do can take multiple iterators, and will loop over all of them, whereas this definition only takes one iterator, in its 2nd argument. So (just as a way of illustrating it a bit further) the syntax information for your function should be:

SyntaxInformation[Do2] =
  {"ArgumentsPattern" -> {_, _}, "LocalVariables" -> {"Table", {2}}}

(See SyntaxInformation for more details.) Note that this will set the syntax highlighting regardless of the functionality. So, for example,

(* Nonsense definition: *)
Do3[x_] := 2

SyntaxInformation[Do3] = SyntaxInformation[Do]

will still make the syntax highlighting of Do3 like that of Do, even though it doesn't behave at all similarly.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.