Short version: PasteButton
will paste its contents at the input cursor. I am looking to create a similar button that will paste something into a new cell and evaluate that cell immediately.
Requirements:
- Must paste content into a new cell (never inside an existing cell, regardless of the current selection).
- The new cell may be created either below the position of the button or at/below the position of the input cursor (both are acceptable, first is preferred).
- Must minimize dependency on dynamic evaluations. Ideally, it should use only the FE but not the kernel. (Think of evaluating the just created cell as adding it to the evaluation queue, i.e. an FE action, not a kernel action).
- The button will be styled as a hyperlink and inlined into running text. It will be labelled with some code. This is the code that will be pasted and evaluated. The design should not interfere with this use case.
"What have you tried?"
From the documentation of Button
,
Thus my first try was:
Button[Defer[1 + 1], None, BaseStyle -> "CopyEvaluateCell"]
There are two issues with this, one which I could solve and one which I could not.
The contents of the output cell will be selected. This I could solve (see below).
Evaluate the line above, press the button, evaluate the line again, press the button again. This creates an extra, unneeded, empty input cell (see red arrow below). This I could not solve.
I solve the first issue by looking up the ButtonFunction
in the default stylesheet and modifying it. The original ButtonFunction
was:
(FrontEndExecute[{
FrontEnd`SelectionCreateCell[
FrontEnd`InputNotebook[], All],
FrontEnd`NotebookApply[
FrontEnd`InputNotebook[], #, All],
FrontEnd`SelectionEvaluateCreateCell[
FrontEnd`InputNotebook[], All]}]& )
We can remove All
from SelectionEvaluate
to prevent the output from being selected. However, the second issue still remains.
Button[
Defer[1 + 1],
None,
ButtonFunction :> (FrontEndExecute[{
FrontEnd`SelectionCreateCell[FrontEnd`InputNotebook[], All],
FrontEnd`NotebookApply[FrontEnd`InputNotebook[], #, All],
FrontEnd`SelectionEvaluateCreateCell[FrontEnd`InputNotebook[]]
}] &)
]