Note: I put Simon's implementation on GitHub. Contributions welcome!

When trying to read the definition of already defined (package or built-in) symbols using Information or FullDefinition, the biggest inconvenience is that lots of distracting private context names appear in front of all symbol names.

Currently I am using a little function contextFreeDefinition[] to avoid this problem. It will attempt to hide the most frequently appearing context name in the definition. contextFreeDefinition[] is based on this answer.

Compare for example ClearAttributes[RunThrough, ReadProtected]; Information[RunThrough] and contextFreeDefinition[RunThrough]. The latter is a lot less cluttered because the System`Dump` context is hidden in the definition. (I usually paste the output of this function into Workbench and re-indent it using the Source -> Format context menu item for better readability)

Unfortunately contextFreeDefinition[] does not always successfully hide contexts, for example try the following:

ImportString["1", "List"]; (* force Stub symbols to be loaded *)

System`Convert`TableDump`ImportList // contextFreeDefinition

and notice that several symbols (especially patterns) still have System`Convert`TableDump` prepended. For example, I see the following in the FullDefinition it prints:

protectRegEx[System`Convert`TableDump`s_String] := 
     StringReplace[System`Convert`TableDump`s, $ProtectedCharacterRules]

The symbol System`Convert`TableDump`s still has the context name prepended even though the function tried to hide exactly this context.

Question: How can contextFreeDefinition[] be fixed so it always hides the context, or what other alternative approaches are there to read the definitions of in-memory symbols?

The code of contextFreeDefinition[].

Clear[commonestContexts, contextFreeDefinition]

commonestContexts[sym_Symbol, n_: 1] := Quiet[
   Cases[Level[DownValues[sym], {-1}, HoldComplete], 
    s_Symbol /; FreeQ[$ContextPath, Context[s]] :> Context[s]], n],

contextFreeDefinition::contexts = "Not showing the following contexts: `1`";

contextFreeDefinition[sym_Symbol, contexts_List] := 
 (If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]];
  Internal`InheritedBlock[{sym}, ClearAttributes[sym, ReadProtected];
   Block[{$ContextPath = Join[$ContextPath, contexts]}, 

contextFreeDefinition[sym_Symbol, context_String] := 
 contextFreeDefinition[sym, {context}]

contextFreeDefinition[sym_Symbol] := 
 contextFreeDefinition[sym, commonestContexts[sym]]

Understanding and using the function:

commonestContexts[sym, n] will find the n most frequently used contexts that are not in $ContextPath in the definition of symbol sym.

contextFreeDefinition[sym] will print the FullDefinition of sym, hiding the commonest context that would appear there. It will also issue a message with the name of the context being hidden.

contextFreeDefinition[sym, {"Context1`", "Context2`", ...}] will try to hide an explicitly given list of contexts.

  • $\begingroup$ When you write "always removes the context" do you mean extraneous context or all context? $\endgroup$
    – Mr.Wizard
    Commented Feb 14, 2012 at 16:02
  • $\begingroup$ Also, I get no output for System`Convert`TableDump`ImportList // contextFreeDefinition -- would you please try to provide an example that works in version 7? $\endgroup$
    – Mr.Wizard
    Commented Feb 14, 2012 at 16:07
  • $\begingroup$ @Mr.Wizard This function tries to find the commonest non-public context, then prints the definition with that context hidden. It is also possible to explicitly pass a number of contexts to be hidden (as the second argument). $\endgroup$
    – Szabolcs
    Commented Feb 14, 2012 at 16:27
  • $\begingroup$ I will accept either an answer that fixes contextFreeDefinition or one that will give a better suggestion on how to do this kind of system spelunking. $\endgroup$
    – Szabolcs
    Commented Feb 14, 2012 at 16:35
  • $\begingroup$ @Szabolcs do you think it's worth highlighting the second most popular answer to this question? For 10.0+ users it's probably the simplest way, don't you think? $\endgroup$
    – b3m2a1
    Commented Dec 28, 2016 at 0:58

7 Answers 7


Link to the code on GitHub

I have been using this. It's mostly Leonid's code from the stackoverflow question you linked to, but it uses Definition instead of DownValues. Symbol names are printed without any context, but the full symbol name is put into a Tooltip so you can always find out what context a symbol is in.


FullDefinition[symbol] claims to "print the definitions given for symbol, and all symbols on which these depend", but sometimes one wants to explore deeper than the first level of dependency. Here is a version of Spelunk which uses plain Definition instead of FullDefinition, but allows you to click on symbols in the definition to get their definition. So you can dig right down into the dependency chain.

Update 2

The code now copes with definitions containing strings with backticks in, and cases where Definition throws an error.

Also, it now works for symbols which have OwnValues, e.g. Internal`$VideoEncodings.


Spelunk::usage = "Spelunk[symbol]";


defboxes[symbol_Symbol] := Hold[symbol] /. _[sym_] :>
        If[MemberQ[Attributes[sym], Locked], "Locked",
            Unprotect[sym]; ClearAttributes[sym, ReadProtected];
            Quiet@Check[ToBoxes[Definition@sym], "DefError"] /. 
            InterpretationBox[a_, b___] :> a ]];

defboxes[s_String] := defboxes[#] &@ToExpression[s, InputForm, Unevaluated]

prettyboxes[boxes_] := 
  boxes /. {" "} -> {"\n-----------\n"} //. {RowBox[{left___, ";", 
       next : Except["\n"], right___}] :> 
     RowBox[{left, ";", "\n", "\t", next, right}], 
    RowBox[{sc : ("Block" | "Module" | "With"), "[", 
       RowBox[{vars_, ",", body_}], "]"}] :> 
     RowBox[{sc, "[", RowBox[{vars, ",", "\n\t", body}], "]"}]};

fancydefinition[symbol_Symbol] :=
     defboxes[symbol] /. 
      s_String?(StringMatchQ[#, __ ~~ "`" ~~ __] &) :> 
         a : (__ ~~ "`" ~~ b__) :> processsymbol[a, b]]]], "Output", 
   Background -> RGBColor[1, 0.95, 0.9],

processsymbol[a_, b_] := Module[{db},
   ! StringFreeQ[a, "\""], a,
   ! StringFreeQ[a, "_"] || (db = defboxes[a]) === "Null", 
   TooltipBox[b, a],
   db === "Locked", TooltipBox[b, a <> "\nLocked Symbol"],
   db === "DefError", TooltipBox[b, a <> "\nError getting Definition"],
   True, ButtonBox[TooltipBox[b, a], ButtonFunction :> Spelunk@a, 
    BaseStyle -> {}, Evaluator -> Automatic]]]

Spelunk[symbol_Symbol] := CellPrint[fancydefinition[symbol]];

Spelunk[s_String] := CellPrint[fancydefinition[#] &@ToExpression[s, InputForm, Unevaluated]];

SetAttributes[{defboxes, fancydefinition, Spelunk}, HoldFirst] 


  • 2
    $\begingroup$ This is very nice! What a surprise after such a long time :) $\endgroup$
    – Szabolcs
    Commented Dec 7, 2012 at 22:31
  • 1
    $\begingroup$ When you use BaseStyle->"Hyperlink" and maybe wrap it in a StyleBox to underline links, IMO the code is much better readable than with the buttons: i.sstatic.net/kNlOR.png Anyway, +1 for this nice work. $\endgroup$
    – halirutan
    Commented Jan 4, 2013 at 2:03
  • $\begingroup$ Would you mind if I put this on GitHub and start building on it? Or would you like to do that yourself? $\endgroup$
    – Szabolcs
    Commented Jan 21, 2013 at 19:21
  • $\begingroup$ @Szabolcs, please do! You'll probably find it's more a case of "rebuild" than "build on" - the code became a bit of a tangle as I patched bugs. I look forward to seeing what you create :-) $\endgroup$ Commented Jan 21, 2013 at 22:00
  • 1
    $\begingroup$ @Mr.Wizard, I've uploaded a new version of Spelunk to my fork of the GitHub. This uses the wonderful FrontEnd`UndocumentedTestFEParserPacket (which Kuba reminded me of) to extract boxes from the symbol definition. This seems to do a great job of stripping out the typesetting stuff which has been causing problems. It'll need some testing but so far it looks promising. $\endgroup$ Commented Feb 3, 2015 at 23:04

In version 10.1, I've built something like Spelunk into GeneralUtilities`.

To use it, run


This will pop up a window that shows all definitions of symbol. Here is a short summary of features:

  • The window shows code cells containing all DownValues, OwnValues, UpValues, SubValues, and Attributes of a symbol.
  • Most pathological kinds of StandardForm are avoided, so that Image, Graphics, Row, Column, SparseArray, etc. will show up as code, not UI elements. This is achieved via the PlainForm and CodeForm wrappers, which can also be found in GeneralUtilities`.
  • Hyperlinks are be injected as appropriate. Click on a hyperlinked symbol to print its definitions in a new window.
  • The CellContext of each code cell is set to reduce the amount of clutter from fully qualified private symbols. For symbols outside this context, the name is shown, the fully qualified name is tooltipped, and color coding is used: symbols in conventional private contexts like `Private` are brown/orange; system symbols are black; other symbols are dark gray if on the context path, otherwise light gray.

Here's a simple example of PrintDefinitions running on itself:

enter image description here

  • 3
    $\begingroup$ @RolfMertig more that before we had associations, people would use symbols as a key-value store via their downvalues... and there might be thousands of definitions on such symbols. $\endgroup$ Commented Apr 2, 2015 at 18:46
  • 1
    $\begingroup$ @RolfMertig Dataset is one of these functions, with 189 definitions. $\endgroup$
    – Murta
    Commented May 7, 2015 at 22:55
  • 1
    $\begingroup$ Is it by design that (Print)Definitions omits formatting definitions like MakeBoxes[...]^:=... (e.g. in case of PrintDefinitions@EvaluationObject)? Is it because some dynamic formatting box could lead to problems when evaluated for printing? @Rolf Try ChartElementData: it has 1853 definitions. $\endgroup$ Commented May 8, 2015 at 12:35
  • 4
    $\begingroup$ I've only just seen this - awesome! It's really good to have something like this built in, many thanks. $\endgroup$ Commented May 19, 2015 at 19:19
  • 1
    $\begingroup$ +1. Could it print something like 'there are 35000 DownValues and 1 Attributes for 'Temp'' instead of 'Temp has too many definitions (35001) to display.'? $\endgroup$ Commented Jan 12, 2019 at 23:34

I can now offer a solution which leverages the full power of the code formatter, in its new, more robust form.

Load the formatter:


Some examples:


enter image description here


enter image description here

In the last example, using MakeBoxes would produce a slightly better result:

CodeFormatterSpelunk[PacletManager`CreatePaclet, MakeBoxes]

enter image description here


enter image description here

  • $\begingroup$ Great stuff Leonid! would you happen to know how to use this on a Manipulate source code? When I do CodeFormatterSpelunk[ Manipulate[Plot[Sin[a x], {x, 0, 1}], {{a, 1, "a"}, 1, 10, 1}]] I just get !Mathematica graphics (I am trying to use your program to format my manipulate code, but not able to).... $\endgroup$
    – Nasser
    Commented Nov 3, 2013 at 2:14
  • $\begingroup$ @Nasser Thanks :). Re: manipulate - the CodeFormatterSpelunk function takes a symbol name, not code. You can do e.g. fn[] := Manipulate[Plot[Sin[a x], {x, 0, 1}], {{a, 1, "a"}, 1, 10, 1}], and then CodeFormatterPrint[fn], or you can do CellPrint[Cell[CodeFormatterMakeBoxes[Manipulate[Plot[Sin[a x], {x, 0, 1}], {{a, 1, "a"}, 1, 10, 1}]], "Input"]], but the latter for some reason does not format quite right...Perhaps a bug. Will look into this some time soon. $\endgroup$ Commented Nov 3, 2013 at 10:55

Since nobody has mentioned it yet...

V8 introduced the undocumented flag Debug`$ExamineCode. When it is set to true, the information functions will display the definitions of ReadProtected symbols:

Debug`$ExamineCode = True

It is sometimes useful to suppress some of the internal package names to make it easier to scan the definitions. Here is a quick-and-dirty way to do it:

  { $ContextPath = {"System`", "Internal`", "Statistics`BinningDump`"}
  , Debug`$ExamineCode = True
, RawBoxes @ ToBoxes @ Information[BinLists]

Here, the $ContextPath is carefully chosen to include package names I do not want to see. This, of course, can be automated but as that is the subject of other answers I will pass over it here.


I would just use strings, for all their fragility:

print[sym_, {conts_String}] :=
 With[{altptrn =  Alternatives @@ Reverse[SortBy[{conts}, StringLength]]},
         (x : (_ | "") ~~ altptrn ~~ y : (_ | "")) /; ! (x === "\"" && y === "\"") :> 
            StringJoin[x, y]]]

contextFreeDefinition[sym_Symbol, contexts_List] :=
    If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]];
    print[sym, contexts]

Note that my code to protect against modifications inside strings is not quite robust. But, if needed, it can be easily made more robust by preprocessing the string.


I have not tested this yet but here is one possible approach:

contextFreeDefinition[sym_Symbol, contexts_List] :=
  ClearAttributes[sym, ReadProtected];
  If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]];
  Block[{ipf = ToString @ InputForm @ FullDefinition @ sym},
   ipf = MakeExpression@StringSplit[ipf, "\n"] /. HoldComplete[Null] -> "";
   ipf /. x_Symbol /; MemberQ[contexts, Context[x]] :>
     With[{eval = StringDrop[ToString@Unevaluated@x, StringLength@Context@x]},
         eval /; True]
     /. HoldComplete -> HoldForm // Column

(sorry for the messy formatting)

Please point out all failings and I shall see if this is redeemable tomorrow.

  • $\begingroup$ Let me think hard and try to break this ;-) First attempt: contextFreeDefinition[someSymbol, "System`"]. Admittedly it's easy to put in a check if something from contexts is already in $ContextPath. $\endgroup$
    – Szabolcs
    Commented Feb 15, 2012 at 11:07

This answer addresses hiding the context marks only, not spelunking. You could use the following functions to view output without contexts marks:

SetAttributes[{ContextFreeForm, ContextFreeInformation}, HoldAll]

ContextFreeForm /: MakeBoxes[ContextFreeForm[expr_], form_] := Block[

    MakeBoxes[expr, form]

ContextFreeInformation[expr_] := With[
    {name = ToString[Unevaluated @ expr, InputForm]},

    Block[{Internal`$ContextMarks = False}, Information[name]]

First, here is the definition of System`Convert`TableDump`ImportList viewed using ContextFreeForm:

ContextFreeForm @ Definition @ System`Convert`TableDump`ImportList

ImportList[file_String,opts___]:=Block[{listsep},listsep=LineSeparators/. {opts}/. Options[ImportList];If[!ListQ[listsep],listsep={listsep}];Data->Flatten[Last[ImportTable[file,LineSeparators->listsep,FieldSeparators->listsep,RepeatedSeparators->False,opts]],1]]


, , , }}

For Information (i.e., ?symbol) there is no output, the definition is displayed as a side effect, so a different function is needed:

ContextFreeInformation @ System`Convert`TableDump`ImportList


ImportList[file_String,opts___]:=Block[{listsep},listsep=LineSeparators/. {opts}/. Options[ImportList];If[!ListQ[listsep],listsep={listsep}];Data->Flatten[Last[ImportTable[file,LineSeparators->listsep,FieldSeparators->listsep,RepeatedSeparators->False,opts]],1]]


, , , }}

It is also possible to just set Internal`$ContextMarks = False globally, but that can have issues (e.g., Information[System`Convert`TableDump`ImportList] will no longer work).


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.