Is there a straightforward way to reference and modify a cell from within itself?

This is a little outside the ordinary use case and certainly not good practice, but I would like to execute an input cell in a notebook causing the kernel to perform some action and output results and then replace or delete the current input cell and it's output.

I currently use some trivial cleanup code at the end of a routine to process data and after it has run once it isn't useful to have around and I end up deleting it manually. This got me thinking, how can I get Mathematica to do this automatically? Maybe it's possible to build it into the notebook style? Something like:

Format --> Style --> RunOnceAndDeleteInput

  • $\begingroup$ is this relevant/useful? $\endgroup$ – kglr Nov 11 '14 at 15:19
  • $\begingroup$ @kguler Yes, NotebookDelete seems to be useful for clobbering cells and output, but it's not clear to me how to reference an input cell from within itself. $\endgroup$ – dionys Nov 11 '14 at 15:28
  • 1
    $\begingroup$ You can use EvaluationCell to reference an input cell from within itself . So a cell with the lines SelectionMove[EvaluationNotebook[], All, EvaluationCell];NotebookDelete[] finds and deletes itself. $\endgroup$ – kglr Nov 11 '14 at 15:32
  • $\begingroup$ @kguler Cool. This: SelectionMove[EvaluationNotebook[],All,EvaluationCell];NotebookDelete[]; works great for clobbering a cell. $\endgroup$ – dionys Nov 11 '14 at 15:37
  • $\begingroup$ @kguler looks like NotebookWrite can be used with the cell selector code and you've got everything you need for arbitrary self-modifying cells. $\endgroup$ – dionys Nov 11 '14 at 15:42

From Mathematica version 9 onward, the following expressions are possible...

To delete the current cell:


To replace the current cell with a text cell:

NotebookWrite[EvaluationCell[], Cell["New Content", "Text"]]

To replace the current cell with an input cell containing an arbitrary expression:

NotebookWrite[EvaluationCell[], Cell[BoxData@ToBoxes[a + b/c], "Input"]]

Self-deleting cell with output:

Print@"arbitrary output";
SelectionMove[EvaluationNotebook[], All, EvaluationCell];
SelectionMove[EvaluationNotebook[], All, CellGroup];

Modifying an input cell:

Print@"arbitrary text";
SelectionMove[EvaluationNotebook[], All, EvaluationCell];
SelectionMove[EvaluationNotebook[], Before, CellContents];
Do[SelectionMove[EvaluationNotebook[], After, Word], {i, 7}];
Paste[Defer[Print@"... bonus text!";]];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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