How to remove input box after evaluation?

I would like to accomplish the following: when evaluating an input cell, it must self-destruct (i.e. remove itself). I tried to hack something along with SelectionMoveand NotebookDelete, but did not get what I wanted.

Here are some potential use cases:

  • a command can be a shorthand for a number of other commands that will be generated dynamically and inserted into a laptop

  • the command can only be used for side effects (for example, to install a variant of a laptop or to open a new laptop); leaving the team in the notebook after the evaluation does not serve the purpose and creates a mess.

Edit: according to Mr. Magic, the answer SelectionMove[EvaluationNotebook[], Previous, Cell]; NotebookDelete[];. I do not know why this did not work for me before. Here is some code that uses this idiom.

writeAndEval[nb_, boxExpr_] := (NotebookWrite[nb, 
    CellGroupData[{Cell[BoxData[boxExpr], "Input"]}]];
   SelectionMove[nb, Previous, Cell];
   SelectionMove[nb, Next, Cell];
   SelectionEvaluate[nb]);

addTwoAndTwo[] := Module[{boxExpr},
  boxExpr = RowBox[{"2", "+", "2"}];
  SelectionMove[EvaluationNotebook[], Previous, Cell];
  NotebookDelete[];
  writeAndEval[EvaluationNotebook[], boxExpr];
  ]

addTwoAndTwo[] , "2 + 2". , .

2: . " ", , " ": Mathematica?

+5
2

, -. Wizard, SelfDestruct, , :

SetAttributes[SelfDestruct, HoldAllComplete];
SelfDestruct[e_] := (If[$FrontEnd =!= $Failed,
   SelectionMove[EvaluationNotebook[], All, EvaluationCell]; 
   NotebookDelete[]]; e)

2+3//SelfDestruct 5 . .

+8

, , :

SetOptions[EvaluationNotebook[], CellEvaluationFunction -> 
  ( (
    SelectionMove[EvaluationNotebook[], All, EvaluationCell]; NotebookDelete[];
    ToExpression@#
  )&)
]

, Inspector, CellEvaluationFunction, .

+9

All Articles