# Is there a way to track the current context without updating at regular time intervals?

I would like to create a dynamically updated value of the current $Context. The problem I have encountered is that the expression Dynamic[$Context]

produces an output that updates only when Begin expression is evaluated but not End. For example, if I evaluate the above expression in a fresh Kernel, I obtain

Global

as expected. Then, after evaluation of

Begin["lalala"]

the dynamic output correctly switches to

lalala

but after evaluation of

End[]

the dynamic output remains

lalala

Of course, I could just use manual update at regular times intervals via Refresh:

Dynamic[Refresh[$Context, UpdateInterval -> 0.1]] but it would cause the kernel to check$Context every 100 milliseconds while the output is visible, which I find inefficient.

I have tried introducing an auxiliary symbol:

x := $Context; Dynamic[x] but to no avail. Is there a way to make Dynamic catch this change of$Context?

P.S.

Just in case:

$Version (*Returns: 11.2.0 for Microsoft Windows (64-bit) (September 11, 2017)*) EDIT1 Just in case someone is interested in the question, here is my "research rabbit": Cell 1: ClearAll[x]; x /;$Context === "Global" := 1;
x /; $Context === "a" := 2; x /;$Context === "b" := 3

Cell 2:

Row[
{
Dynamic[Refresh[$Context, UpdateInterval -> 0.01]], Dynamic[$Context],
Dynamic[x]
},
"|"
]

Cell 3:

Pause[1]; Begin["a"];
Pause[1]; Begin["b"]
Pause[1]; End[];
Pause[1]; End[];

EDIT2

Funny, but calling Documentation Center (directly or via F1) refreshes the dynamic. I really love Mathematica! There is so much to investigate.

EDIT3

@Jason B. proposed brutal force as a solution:

Unprotect[End, EndPackage];

End[] := Block[{$inMsg = True, new, result}, result = End[]; new =$Context;
$Context = "";$Context = new;
result
] /; ! TrueQ[$inMsg] EndPackage[] := Block[{$inMsg = True, new, result},
result = EndPackage[];
new = $Context;$Context = "`";
$Context = new; result ] /; ! TrueQ[$inMsg]

Protect[End, EndPackage];

the essence of which is to hack End and the friend to manually and explicitly assign a value to \$Context.

• It seems entirely too hacky a solution for me to put in an answer, but if you evaluate this code then your Dynamic works as expected. – Jason B. Aug 31 '18 at 17:31
• I would report that issue first. – Kuba Aug 31 '18 at 22:01