I have a useful snippet of code that I use for anything in my Notebook 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
]], "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', which, when pressed, replaces the output cell with the result. This means I can use Evaluation->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's action is to replace the ButtonCell with the results, which inadvertently replaces everything, not just the Button's Box. So, two questions:
- Is there any way to select the Box of the Button?
- Will replacing that selection using NotebookWrite work how I want it to? I can imagine it might play havoc with Mathematica's formatting.