# NotebookEvaluate breaks notebook's context

Bug introduced in 10.4.1 or earlier and persists through 12.0

A support case with the identification [CASE:3813108] was created

[...] I have forwarded an incident report to our developers with the information you provided [...]

Here is an example of a notebook with local context:

nb = CreateDocument[{
ExpressionCell[Defer @ CurrentValue[EvaluationNotebook[], CellContext], "Input"],
ExpressionCell[Defer @ $Context, "Input"] }, CellContext -> Notebook ]  Let's NotebookEvaluate it twice: NotebookEvaluate[nb, InsertResults -> True]  "Notebook$$35971589"  NotebookEvaluate[nb, InsertResults -> True]  "Global"  We can see that the first evaluation was done with respect to the local context but left the notebook broken. It now works with Global  context despite CellContext->Notebook. According to NotebookEvaluate / Possible Issues one should expect "Notebook$$35$971589" each time. Ok, one could arguee here but everyone will probably agree that the result should at least be consistent each time.

Is this a bug or have I missed something?

Related:

[...] A possible fix to this had been suggested in the previous email. [...]

Which is to use CellContext->Notebook as an explicit option for each cell.

With

\$Version
(* 11.0.1 for Microsoft Windows (64-bit) (September 20, 2016) *)


The result depends on the context of the first notebook. If it is "Global", I obtain the result in the question. However, if the context is set by "Evaluation>Notebook's Default Context>Unique to this Notebook", the second notebook's context is unchanged for multiple calls to

NotebookEvaluate[nb, InsertResults -> True]


I also ran the first notebook with the context set to "Anything". The behavior was like that in the question but with the second call to

NotebookEvaluate[nb, InsertResults -> True]


returning "Anything`" as the context of the second notebook.

I believe that this is a bug.