1
$\begingroup$

I have created a button with a NotebookApply associated, something similar to the following

Button["Apply",
 Block[{in = InputNotebook[]},
  NotebookApply[in, "x + 1/\[SelectionPlaceholder]"]; 
  SelectionEvaluate[in]]]

This is used on expressions such as z + y + Expand[(1 + x)^4] + 1 where I select (highlight) Expand[(1 + x)^4], then press the "Apply" button to get z + y + x + 1/Expand[(1 + x)^4] + 1

I would like to modify the function so that I keep a copy of the original cell before the application of the button (i.e. the original z + y + Expand[(1 + x)^4] + 1) to keep track of the steps done (the copied cell could be above or below the original one).

Any ideas on how to implement this? I have tried to use SelectionMove but I haven't found a way with to select-and-copy the whole cell while keeping the initial selection.

$\endgroup$

1 Answer 1

0
$\begingroup$

Does it fit your needs?

Button["Apply", 
  Block[{in = InputNotebook[], oldCell, oldBoxes},
    oldBoxes = NotebookRead[oldCell = First@SelectedCells[]];

    NotebookApply[in, "x + 1/\[SelectionPlaceholder]"];
    SelectionEvaluate[in];

    SelectionMove[oldCell, Before, Cell];
    NotebookWrite[in, oldBoxes];
    SelectionMove[oldCell, After, CellContents];
  ]]

For the record: SelectionEvaluate does not do anything here or in your example.

$\endgroup$
1
  • $\begingroup$ That's great, thanks. You are right, SelectionEvaluate is not necessary in the example provided. $\endgroup$
    – Nicola
    Sep 29, 2022 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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