I have a useful snippet of code that I use for anything in my Notebooknotebook that takes a while to execute and doesn't need to be executed for subsequent cells:
buttonEvaluate[expr_] :=
Module[{cell},
Button["Evaluate", cell
= Cell[BoxData[ToBoxes[
expr
cell = Cell[BoxData[ToBoxes[ expr ]], "Output"];
SelectionMove[ButtonNotebook[], All, ButtonCell];
NotebookWrite[ButtonNotebook[], cell]
,
Method -> "Queued"
]] ]
];
SetAttributes[buttonEvaluate, HoldFirst];
buttonEvaluate::usage = "Returns a button, that when pressed, replaces itself with the evaluation of the passed in expression. Useful for things you don't necessarily care to recalculate when the notebook is evaluated.";
I usually use it like this:
some[expression,that,takes] + a * long / time // buttonEvaluate
...and when that cell is executed, the output is a button labelled 'Evaluate'Evaluate
, which, when pressed, replaces the output cell with the result. This means I can use Evaluation->Evaluate NotebookEvaluation->Evaluate Notebook
, and it effectively skips over some cells until I explicitly choose to evaluate them.
However, I've run into an issue when I try to use it inside an expression, because the perfectionist in me wants to be able to do something like:
Row[{slowThing[] // buttonEvaluate, fastThing[]}]
However, the Button'sButton's
action is to replace the ButtonCellButtonCell
with the results, which inadvertently replaces everything, not just the Button'sButton's
Box. So, two questions:
- Is there any way to select the Box
Box
of the ButtonButton
? - Will replacing that selection using NotebookWrite
NotebookWrite
work how I want it to? I can imagine it might play havoc with Mathematica'sMathematica's formatting.