Syntax Coloring In Mathematica - wolfram-mathematica

How could user-defined function symbol such as f in
f[x_] = 2 x
or variable symbols such as lotto in
lotto = Table[2, {10}];
be colored automatically ?
In Syntax coloring on M8 no option is offered for this.
Only Local Variables or Global symbols that have no values assigned.

This is not exactly what you asked for, but it may be useful to you.
You can highlight symbols by context, using this method:
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" -> {"highlight`" -> Green}}
]
AppendTo[$ContextPath, "highlight`"];
Now, when you create a symbol in the context highlight` it will automatically be colored green:
highlight`lotto ;
and since highlight` was appended to $ContextPath, after that the symbol can be used plainly:
lotto
Highlighting all symbols (variables)
If you want all the symbols you create to automatically be highlighted, then set:
$Context = "highlight`"
After that, all new symbols you create will belong to the context highlight` and will receive the color.
New means ones that have not been previously used in the session, or have been Removed.
It occurs to me that a better way to accomplish this, that avoids a possible "shadowing" problem, may be to set highlighting for the Global` context itself. I have not considered the ramifications of this, but it can be done with this alone:
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" -> {"Global`" -> Green}}
]
Tips on usage
The context highlight` is completely arbitrary, and you can have multiple contexts highlighted with different colors.
You can color the contexts of packages such as Units` to distinguish which symbols belong to that package.

Such variables are automatically colored after you assign a value to them. Under the default Mathematica settings, lotto changes color from blue to black as soon as you assign the value. Strictly speaking, it is the unassigned variables that get colored according to the setting you will find under Preferences / Appearance / Syntax Coloring / Other / Global symbols that have no value assigned.
If what you are looking for is a way to assign a distinct color to global symbols whose only definitions are own-values, then I believe that you are out of luck. As far as I know, the syntax coloring machinery does not distinguish between own-values ("variable assignments"), down-values ("function definitions") and up-values ("expression part definitions").

As I said in my comment above, I think that this would be hard to completely automate. You'd have to wrap Set and SetDelayed to automatically move variables into the right context depending on whether they're creating an OwnValue or a DownValue.
To do this manually just requires a simple edit of Mr.Wizard's previous work...
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" ->
{"functions`" -> Green, "variables`" -> Pink}}]
$ContextPath = Join[$ContextPath, {"functions`", "variables`"}]//DeleteDuplicates;
variables`x;
functions`f;
Is this what you want?

Related

Code Fragment mode in Pycharm 3 debugging returns None always

When in debug mode in Pycharm, the Evaluate Expression -> Code Fragment tool doesn't seem to be able to assign and display a variable in one go. The only case that seems to be evaluated correctly is when the first line is a constant value.
eg.
10
results as expected in
result = {int} 10
but when trying to obtain the same result with:
c = 10
c
the output is
result = {NoneType} None
However, if I hover over each variable in fragment window, the values are shown as a popup.
Edits to sum up the comments (thanks Vaibhav Mishra):
Unfortunately, this seems to be the default behavior: (won't fix bug)
My understanding of this feature:
Although Pycharm will display a None result when evaluating multiple lines, they are all executed in the context of the currently selected stack frame. One of the consequences being the update of the namespace. Subsequently using single-line evaluations in the same context (or mouse hover) will display the expected values.
Two potential usages:
The Evaluate Code Fragment dialog is automatically prompted when evaluating multiple lines from the editor: Select a block | Evaluate Expression (Alt+F8). May be useful to tweak a couple of lines and run evaluation in one go.
As an alternative to the Debug Command Line, the code fragment mode supports loops and if/else. Although the inspection seems a bit tipsy (mistakenly unresolved variables), it can be ignored, and the editing assistance provided there can be put to good use.

ANTLRWorks debugging - the meaning of the different colors?

I'm using the debugging mode of ANTLRWorks to test my c-grammar. Debugging in ANTLRWorks is really great for better understanding but I have a problem in understanding the different colors of the output tree. I'm using backtrack=true in my grammar. I thought that the red color means that the debugger goes the wrong way while green tells me that it is has gone the right way. But what about dark red and dark green?
I added a picture of a "small tree" which only match the following input:
int test;
If it's necessary to answer the question, here are the 4 most important rules which are used.
start
: declaration*
;
declaration
: functionDefinition
| dataDeclaration //also used for Function Declaration
| assemblerDefinition
;
functionDefinition
: declarationSpecifier* declarator Equals Default Semi
| declarationSpecifier* declarator Equals Delete Semi
| declarationSpecifier* declarator functionBody
;
dataDeclaration
:declarationSpecifier* declarator initializer? (Comma declarator initializer?)* Semi
;
It's not so much about "right" and "wrong" as it as about the parser trying to figure out which rule will match the input. When ANTLR has to backtrack, ANTLRWorks uses red for branches of the parse tree that it considered as possible matches. Green is used for branches the parser actually explored and black for the branch that successfully matched the input. The darker and lighter colors is ANTLRWorks providing visual feedback for nested levels of backtracking - the deeper the level the darker the color.
The primary source of this answer is from ANTLRWorks: An ANTLR Grammar Development Environment Unpublished Draft written by Bovet (created ANTLRWorks) and Parr (created ANTLR).
From page 8:
the path taken by the parser is shown in green
From page 15:
When ANTLR must backtrack to distinguish between alternative productions, it is usually difficult
to debug the parser because developers must track when the parser is speculating and when it is
not. ANTLRWorks clearly distinguishes between the two modes by showing all speculative parsing branches in the parse tree in red. ... The second subtree [shown in black] is the parse tree for the second alternative in rule s that matches successfully. In situations where ANTLR must nest the backtrack, ANTLRWorks changes the color through a series of gradations, one for each backtracking nesting level.

Mathematica output formatting

How does Mathematica decide when to round numbers in its output? For example,
giving the input
250000.5
gives the output
2500001
While
25000.5
is indeed printed as
25000.5
N[] isn't helpful here either, I need to use NumberForm[] to get it to actually print 250000.5 as 250000.5
I'm a Mathematica newbie, and I'm sure its ridiculously easy to control this threshold for when it starts ignoring decimals in its output, but could somebody please point me in the right direction?
another option for you to try, you can go to options and change the default PrintPrecision from 6 to say 16, and now you will see that it will print what you typed above
after I changed that to 16 (click on the field itself, and type 16 into the field to replace the 6, and hit return), then
Nasser is correct that PrintPrecision is the right setting.
You have a number of options for its use. You can set it Globally or for the specific Notebook using the Options Inspector. You can also use it directly with Style:
Style[250000.5, PrintPrecision -> 10]
250000.5
You can set it temporarily for one session like this:
SetOptions[$FrontEndSession, PrintPrecision -> 10]
Finally you can set it using Style Sheets (select cell type Output).
In the default TraditionalForm and StandardForm output modes Mathematica only shows a certain number of most significant digits. You can use InputForm to get the full precision number.

How to run initialization code for a palette?

Occasionally it would be preferable to have some initialization code for palettes (of buttons). For example, it could define some functions that are used by palette buttons.
What is the easiest and preferable way to define/run initialization code for a palette?
The initialization can run either when the palette is loaded or when any button is pressed for the first time (possible issue: what if the kernel is restarted after the palette was loaded?)
The definitions should be somehow localized (i.e. in their own context -- do unique notebook contexts help here?)
If possible, I'd prefer a minimal effort solution (i.e. extra code at the fewest possible places, self contained palette file with no extra package files, palette creation using the existing convenience tools of palettes menu or CreatePalette, etc.)
(You can assume that the initialization code runs fast, e.g. it consists of definitions only)
You're right to be concerned about the visibility of the Dynamic being an issue. The way to absolutely guarantee a Dynamic expression to be evaluated regardless of the visibility of any of the individual cells is to use NotebookDynamicExpression. Here's an example that illustrates NotebookDynamicExpression working while a Dynamic fails because it's hidden within a closed cell group:
cell1 = First # MakeBoxes[
TextCell["Click to open", "Title",
CellMargins -> 0, System`WholeCellGroupOpener -> True],
StandardForm];
cell2 = First # MakeBoxes[
ExpressionCell[DynamicWrapper["hidden cell", Print["DynamicWrapper"]]],
StandardForm];
CreatePalette[
Notebook[{Cell[CellGroupData[{cell1, cell2}, Closed]]},
NotebookDynamicExpression :>
Dynamic[Refresh[Print["NotebookDynamicExpression"], None]]]]
When you evaluate this, note that the Dynamic in NotebookDynamicExpression evaluates immediately. The DynamicWrapper never evaluates until you open the cell group, which you can do by clicking on the "Click to open" text.
In this example, incidentally, notice that I wrapped the NotebookDynamicExpression with Refresh. The function Refresh[#, None]& will make sure that the code evaluates only once -- when the notebook is first opened. Otherwise, the code would obey the standard properties of Dynamic and evaluate whenever any of the dependencies change.
NotebookDynamicExpression has been around since v6, but was only documented in v8. Also documented are its related cousins, CellDynamicExpression and FrontEndDynamicExpression.
A DynamicBox with Initialization is capable of the basic function. You can size the palette such that the object is not visible, and it will still operate.
Here is code for a small sample palette. It sets a value for var. The active code is offset with whitespace.
(* Beginning of Notebook Content *)
Notebook[{
Cell[BoxData[{
TagBox[GridBox[{
{
ButtonBox["\<\"TSV\"\>",
Appearance->Automatic,
ButtonFunction:>None,
Evaluator->Automatic,
Method->"Preemptive"]},
{
ButtonBox["\<\"CSV\"\>",
Appearance->Automatic,
ButtonFunction:>None,
Evaluator->Automatic,
Method->"Preemptive"]},
{
ButtonBox["\<\"Table\"\>",
Appearance->Automatic,
ButtonFunction:>None,
Evaluator->Automatic,
Method->"Preemptive"]}
},
GridBoxAlignment->{"Columns" -> {{Left}}},
GridBoxItemSize->{"Columns" -> {{Automatic}}, "Rows" -> {{Automatic}}}],
"Column"], "\[IndentingNewLine]",
DynamicBox[Null,
Initialization :> ($CellContext`var = "It is done, Master.")
]
}], NotebookDefault,
CellMargins->{{0, 0}, {0, 0}},
CellBracketOptions->{"Color"->RGBColor[0.269993, 0.308507, 0.6]},
CellHorizontalScrolling->True,
PageBreakAbove->True,
PageBreakWithin->False,
ShowAutoStyles->True,
LineSpacing->{1.25, 0},
AutoItalicWords->{},
ScriptMinSize->9,
ShowStringCharacters->False,
FontFamily:>CurrentValue["PanelFontFamily"],
FontSize:>CurrentValue["PanelFontSize"]]
},
WindowSize->{55, 105},
WindowMargins->{{Automatic, 583}, {Automatic, 292}},
WindowFrame->"Palette",
WindowElements->{},
WindowFrameElements->{"CloseBox", "MinimizeBox"},
StyleDefinitions->"Palette.nb"
]
(* End of Notebook Content *)

Dangerous symbol names that begin with a lowercase letter

I am looking for a full list of dangerous symbol names that begin with a lowercase letter in Mathematica.
At this moment I know three such names: min, max and lim. These names appear in the LimitsPositioningTokens list and are being treated as operators at least when they are entered in the FrontEnd with a superscript:
In[3]:= Options[$FrontEnd,LimitsPositioningTokens]
Out[3]= {LimitsPositioningTokens->{\[Sum],\[Product],\[Intersection],
\[Union],\[UnionPlus],\[Wedge],\[Vee],lim,max,min,\[CirclePlus],
\[CircleMinus],\[CircleTimes],\[CircleDot]}}
For example, type in the FrontEnd the following (use Ctrl+^ for making superscript - it is important!):
In[1]:= max^n+4
(max^n+4)//HoldComplete//FullForm
Out[1]= 4 max^n
Out[2]//FullForm= HoldComplete[Times[Power[max,n],Plus[4]]]
You see that max^n+4 is interpreted as 4*max^n in this case.
Can anyone explain what LimitsPositioningTokens option really does?
Are there other dangerous symbols that begin with a lowercase letter in Mathematica?
I cannot confirm the problem you report. Besides, the tokens you've found seem to be strings rather than symbols.
This is on win7-64/M8.0.1, my wife's mac lion/M8 doesn't show it either.
The fact that they are strings seems to be consistent with the description on the doc page of LimitsPositioning
LimitsPositioningTokens is a Cell option which can be set to a list of
forms for which LimitsPositioning->True should be used.
All examples given there use strings.
Update to illustrate the point made in the comments below
This is with the standard LimitsPositioningTokens setting in $FrontEnd:
and this is with SetOptions[$FrontEnd, LimitsPositioningTokens -> {}]:
Please note that the $FrontEnd setting with SetOptions is sticky. It is likely that yours isn't at default anymore. Use the option inspector to return LimitsPositioningTokens to its default value (search for LimitsPositioningTokens with Global Settings on and remove the cross next to the variable if there is any).

Resources