9
$\begingroup$

Is it possible to programmatically highlight (eg, by change background color) an input cell conditional on the input expression's Head (or other attributes) upon evaluation?

For example, would like input cells with expressions whose Head is Set colored Blue, ones containing Import or Export colored Green.

$\endgroup$

2 Answers 2

11
$\begingroup$

There are several ways to do that. Perhaps, the simplest is to do something like this:

ClearAll[color];
SetAttributes[color, HoldAll];
color[_Export | _Import] := LightGreen;
color[_Set] := LightBlue;
color[_] := None;

and then

$Pre = 
  Function[
     code
     , 
     SetOptions[ EvaluationCell[], Background -> color[code]]; code
     , 
     HoldAll
  ];
$\endgroup$
9
  • $\begingroup$ Works as intended, but when I added another item, got a string of this msg: "The specified setting for the option Background cannot be used" $\endgroup$ Sep 15, 2014 at 21:12
  • $\begingroup$ @alancalvitti Can you provide the exact code you added? $\endgroup$ Sep 15, 2014 at 21:15
  • $\begingroup$ Actually I am getting these messages by clicking anywhere in a notebook not just in your code. $\endgroup$ Sep 15, 2014 at 21:38
  • $\begingroup$ @alancalvitti This is weird. My code should not affect click events, only the cells being evaluated (via SHIFT+RETURN). Anyway, thanks for the accept. $\endgroup$ Sep 15, 2014 at 21:42
  • $\begingroup$ after restarting M, no longer see warnings. However, existing input cells with Head = that I manually highlighted revert to no background color when evaluated, even if de-novo expressions turn blue as desired. $\endgroup$ Sep 16, 2014 at 17:09
2
$\begingroup$

An alternative to using $Pre as suggested by @LeonidShifrin is to use the Cell option CellProlog in a style sheet. Here is an example style sheet that does this:

ss = Notebook[
    {
    Cell[StyleData[StyleDefinitions->"Default.nb"]],
    Cell[StyleData["Input"],
        CellProlog :> Module[{cell = NotebookRead[EvaluationCell[]], held, color},
            held = Replace[cell, Cell[b_, __] :> ToExpression[b, StandardForm, Hold]];
            held = Replace[held, Hold[b_;] :> Hold[b]];
            color = Replace[held,
                {
                Hold[_Set] -> LightBlue,
                Hold[_Import | _Export] -> LightGreen, 
                _ -> None
                }
            ];
            CurrentValue[EvaluationCell[], Background] = color
        ]
    ]
    },
    StyleDefinitions->"PrivateStylesheetFormatting.nb"
];

To use, evaluate:

SetOptions[EvaluationNotebook[], StyleDefinitions -> ss];

and then any Input cells you evaluate should turn color if they match your criteria.

$\endgroup$

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.