Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

I am not looking for workarounds, unless the workaround is 100% safe. In my opinion it would make a lot of sense for Mathematica to have built in a technique for replacing multiple selected cells considering it allows selection of multiple cells.

share|improve this question

1 Answer 1

up vote 9 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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