5

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

dionys
  • 4,321
  • 1
  • 19
  • 46
  • is this relevant/useful? – kglr Nov 11 '14 at 15:19
  • @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. – dionys Nov 11 '14 at 15:28
  • 1
    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. – kglr Nov 11 '14 at 15:32
  • @kguler Cool. This: SelectionMove[EvaluationNotebook[],All,EvaluationCell];NotebookDelete[]; works great for clobbering a cell. – dionys Nov 11 '14 at 15:37
  • @kguler looks like NotebookWrite can be used with the cell selector code and you've got everything you need for arbitrary self-modifying cells. – dionys Nov 11 '14 at 15:42
  • dyonis, you might consider self-answering your question along those lines. – kglr Nov 11 '14 at 15:45
  • Closely related: http://mathematica.stackexchange.com/questions/6211/how-to-create-a-notebook-element-that-can-replace-itself – Szabolcs Nov 11 '14 at 19:00

2 Answers2

2

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

To delete the current cell:

NotebookDelete[EvaluationCell[]]

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"]]
WReach
  • 68,832
  • 4
  • 164
  • 269
1

Self-deleting cell with output:

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

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!";]];
dionys
  • 4,321
  • 1
  • 19
  • 46