7
$\begingroup$

Let's say I select 2 different cells and then attempt to replace their content using NotebookWrite inside a button. How might I replace each cell's content individually instead of the current functionality I am getting.

Button["Write", NotebookWrite[EvaluationNotebook[], "Write"]]
Dynamic[Refresh[NotebookRead[SelectedNotebook[]],UpdateInterval -> 1]]

enter image description here

When I click on the Write button, only the last selected Cell gets replaced.

enter image description here

Is there a safe technique to replace each cell with unique content?

$\endgroup$

1 Answer 1

11
$\begingroup$

This is very straightforward in v9 using Cells and CellObject. Let's start with a notebook with a disjoint selection of the type you're describing:

nb = NotebookPut[
  Notebook[{
    Cell["a", CellTags -> "x"],
    Cell["b"], 
    Cell["c", CellTags -> "x"]}]];
NotebookFind[nb, "x", All, CellTags]

Now, we can get CellObjects for the selected cells by using Cells.

cells = Cells[NotebookSelection[nb]]

NotebookWrite allows you to overwrite any given CellObject.

NotebookWrite[First[cells], Cell["d"]]
NotebookWrite[Last[cells], Cell["e"]]

And this NotebookWrite operation can be done regardless of where the selection is at the time. If you want to manipulate a notebook without having to fiddle with selections, CellObject is a very powerful tool and worth further exploration.

$\endgroup$
0

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.