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.

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?

share|improve this question
    
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. –  kguler Dec 1 at 15:39

2 Answers 2

up vote 7 down vote accepted

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.

share|improve this answer

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.

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.