# Building the $Context from a stack of Begin and BeginPackage Assume I'm reading a package file and want to know the current$Context while going serially through the file. I want to do this by inspecting the arguments of each Begin and BeginPackage, and by collecting all End and EndPackage to maintain a stack or list of contexts. This stack is then used to build the $Context. I'm mainly interested in whether my understanding of the situation is correct, how to build the current context and in the stability of the approach. Here are some examples, starting with the most trivial one p[] := Print[$Context]

BeginPackage["P"];
Globalp[];
Begin["Private"];
Globalp[];
End[];
Globalp[];
EndPackage[];

Here Begin is used to replace the context rather than appending a sub-context

BeginPackage["P"];
Globalp[];
Begin["New"];
Globalp[];
End[];
Globalp[];
EndPackage[];

See, that Begin and BeginPackage can be mixed up. That does influence $ContextPath but not how$Context is build up:

BeginPackage["P"];
Globalp[];
Begin["New"];
Globalp[];
EndPackage[];
Globalp[];
End[];

In the first example, in the most inner call to p[], I would have collected {"P","Private"}, in the second example {"P","New"}. Am I correct in the following assumptions

• A (sub-)context always needs to end in 
• Every element in my context list that does not start with a , like e.g. P starts a new context. Relative contexts like Rel are always appended
• every End or EndPackage drops the last element of my context-list

Finally, beside the ugly \[Alpha] are there any special characters allowed in a context? Would it be OK to assume the following regex for a relative context?

(([a-zA-Z$]+[0-9]*)+)+ • About the last one" Begin["123"] gives a tip: A context must consist of valid symbol names separated by and ending with  and valid symbol names are in documentation somewhere. – Kuba Dec 18 '16 at 12:35 • Related: Import package with correct symbol contexts. But I assume that the answer there doesn't apply because you are going to do this in Java eventually. – Szabolcs Dec 18 '16 at 12:46 •$ is also allowed in context names. – Szabolcs Dec 18 '16 at 12:50
• OK, so I probably can re-use my regex for Symbols which can have $as Szabolcs pointed out but nothing else. – halirutan Dec 18 '16 at 12:52 • I am not sure that there is such a thing as a relative context. I think that "foo" is immediately expanded to$Contextfoo . It would be better to collect PPrivate instead of "Private" because "Private`" can't even be interpreted without a current value of \$Context. (I had to use some " in this comment to make the markdown converter do what I wanted.) – Szabolcs Dec 18 '16 at 12:55