Why do syntax errors make a 8. run through $PreRead in a TagBox? Modified code from the help file on$Pre:

$PreRead =. SetAttributes[saveinputs, HoldAll]; inputs = {}; saveinputs[new_] := (inputs = {inputs, HoldForm[new]}; new);$PreRead = saveinputs;


Evaluating:

<>


then

Flatten[inputs]

{<>,8.,RowBox[{Flatten,[,inputs,]}]}


If you look at the Cell Expression for the 8. it is actually a TagBox

TagBox["8.", HoldForm]


Why does a syntax error cause this?

Example where this causes a problem in code:

$PreRead =. SetAttributes[saveinputs, HoldAll]; inputs = {}; saveinputs[new_] := (inputs = {inputs, HoldForm[new]}; If[Unevaluated[new], new, new);$PreRead = saveinputs;


When evaluating pretty much anything you get:

ToExpression::esntx: Could not parse 8. as Mathematica input.


If the test clause of the if statement in the above code does not depend on new then it runs fine.

$PreRead =. SetAttributes[saveinputs, HoldAll]; inputs = {}; saveinputs[new_] := (inputs = {inputs, HoldForm[new]}; If[True, new, new);$PreRead = saveinputs;


The above works fine.

How am I changing new in the test clause to cause this to fail?

-

"How am I changing new in the test clause to cause this to fail?"

With three arguments, If[condition,t,f], If remains unevaluated, i.e., it returns If[condition,t,f], if the condition is neither True nor False.

Using the four-arguments form, If[condition,t,f,u] gives u if condition evaluates to neither True nor False as in your case with Unevaluated[new] as the test clause.

So if you change your code to

$PreRead =. SetAttributes[saveinputs, HoldAll]; inputs = {}; saveinputs[new_] := (inputs = {inputs, HoldForm[new]};If[whatever, new, new, new]);$PreRead = saveinputs;
`

it works like the example in the docs.

-
Sure enough, just needed a TrueQ to make sure it turned out a boolean. –  Davorak Aug 24 '12 at 7:18