8
$\begingroup$

I would like a notebook to behave slightly differently depending on whether it is evaluated from another notebook; i.e.,

NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"]

How can the target notebook know when it has been called by another notebook?

$\endgroup$
1
  • 1
    $\begingroup$ If you put NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"] inside a Button, (i.e., Button["title", NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"] ]), then you can use ButtonNotebook[]=!= $Failed in the target notebook. $\endgroup$
    – kglr
    Commented Dec 1, 2014 at 15:39

2 Answers 2

8
$\begingroup$

Why not just set a symbol to have a value within the calling notebook? Something like...

$callingNotebook = EvaluationNotebook[];

Then in the called notebook see if $callingNotebook has a value.

$\endgroup$
4
$\begingroup$

I agree with @Ymareth that the simplest thing would be to have the calling notebook take explicit measures to communicate the context to the target notebook. However, if for some reason it is undesirable to alter the calling notebook, then here is another way.

When one notebook open in the front-end invokes another notebook, InputNotebook[] will normally return the calling notebook and EvaluationNotebook[] will return the target notebook. In contrast, if the target notebook is evaluated directly, then both expressions will return that single notebook. The target notebook could distinguish between the two cases by evaluating, for example:

If[InputNotebook[] === EvaluationNotebook[]
, (* action when invoked directly *)
, (* action when invoked from another notebook *)
]

This test is not 100% foolproof since one of the notebooks could contain code that expressly alters the InputNotebook[], or the calling notebook might be a palette (which is never the input notebook). But it is possible for this technique to be good enough for the circumstances that motivated the original post.

$\endgroup$

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.