How to delete unnecessary options from Notebook[]? - wolfram-mathematica

By default Notebook[] has a small set of Options:
In[4]:= Options[EvaluationNotebook[]]
Out[4]= {FrontEndVersion ->
"7.0 for Microsoft Windows (32-bit) (February 18, 2009)",
StyleDefinitions -> "Default.nb",
WindowMargins -> {{0, Automatic}, {Automatic, 0}},
WindowSize -> {616, 537}}
Sometimes I wish to modify Notebook appearance and set additional Options. For example I like to have comments to be Plain rather than Bold:
SetOptions[EvaluationNotebook[],
AutoStyleOptions -> {"CommentStyle" -> {FontWeight -> Plain,
FontColor -> GrayLevel[0.6`], ShowAutoStyles -> False,
ShowSyntaxStyles -> False, AutoNumberFormatting -> False}}]
Now Options[EvaluationNotebook[]] will return also new option I have set.
But sometimes I wish to restore default behavior and delete additional Options. How can I do that?

Igor's answer is almost right. To remove the options set by
SetOptions[EvaluationNotebook[],
AutoStyleOptions -> {"CommentStyle" -> {FontWeight -> Plain,
FontColor -> GrayLevel[0.6`], ShowAutoStyles -> False,
ShowSyntaxStyles -> False, AutoNumberFormatting -> False}}]
You need to run
SetOptions[EvaluationNotebook[],
AutoStyleOptions -> {"CommentStyle" -> Inherited}]
But this only works for options that are standard and have a default to inherit (if it's a cell then from the enclosing section or notebook, if it's a notebook then from the stylesheet). What if you make up your own option, e.g.
Protect[HiddenData];
SetOptions[EvaluationNotebook[], HiddenData -> {"here's a string"}]
I don't know how to programmatically remove this option.
Edit:
Actually, to remove the HiddenData option created above, I can use something like
NotebookPut[DeleteCases[NotebookGet[EvaluationNotebook[]],
$CellContext`HiddenData -> _],
EvaluationNotebook[]]
Edit 2:
Mr Wizard asked how to remove all user-set notebook options. Assuming that this means all options that can't be inherited, then I believe that the following should work:
NotebookPut[
With[{nb = NotebookGet[EvaluationNotebook[]], opts = Options[Notebook][[All, 1]]},
Prepend[Select[Rest#nb, MemberQ[opts, First[#]] &], First#nb]],
EvaluationNotebook[]]
But maybe there are options associated with the StyleSheet that I've ignored...
If he meant how do you get back to your system's default notebook options - then you can just delete all notebook options:
NotebookPut[Notebook[First#NotebookGet[EvaluationNotebook[]]],
EvaluationNotebook[]]

(1) Select Format -> Options Inspector (or Shift+Ctrl+O on Windows)
(2) For the two fields next to "Show option values" select Notebook and as text
(3) Select and delete all text in the box below
(4) Click Apply
After understanding NotebookGet, I believe this works for full options reset.
NotebookPut[
Notebook#First#NotebookGet[EvaluationNotebook[]],
EvaluationNotebook[]]

Use:
SetOptions[EvaluationNotebook[], Background -> Inherited]
Igor

Related

how to apply AccountingForm to TableView without affecting the row/column labels?

I am using M 8.0.4.
I am use TableView in demo Manipulate[] to display final solution data, which is a matrix of numerical data.
TableView is very nice to use, since it comes with an automatic scroll bars to move down the rows and to the right over the columns, so that one can see the whole matrix, while keeping the overall display area fixed. (I have an image at the bottom)
The problem that I am not able to find a solution for, is that I need to format the matrix data, so that it looks nice. Otherwise, if the a data element is too large to fit in a cell, it will wrap around, making the TableView misaligned. I also need to adjust decimal point an such other formatting.
I can't apply NumberForm nor AccountForm to the data, and then apply TableView on the result, because TableView does not like to see those wrappers, it needs the numbers.
But if apply the AccountingForm to the TableView, then the numbers that represent the row numbers and column numbers, which are added by TableView automatically, get formatted as well. And I do not want those formatted as well. A row number should remain an integer, not floating point. I just want the data itself formatted.
I could not figure how to format the data from inside Table view. When I use FullForm to see how the data is kept inside TableView, I could not figure how to format it without breaking TableView.
I'll show the problem, then show what I tried.
(* make up some data, and make a TableView of it *)
data = {{-1234.8, 0.123}, {0.12345678, 0.1234}}
tbl = TableView[data, ItemSize -> {{3, {8}}}, DefaultBaseStyle -> 11,
Spacings -> {.2, .1}, FrameStyle -> Gray]
Notice the row numbers and columns number (marked) are positive integers.
Now, I wanted to format the data itself, (the exact formatting options used below is just an example)
AccountingForm[tbl, {6, 3}, NumberSigns -> {"-", "+"},
NumberPadding -> {"", ""}, SignPadding -> True]
But now the Table rows and columns are also formatted:
The FullForm of TableView is:
In[156]:= FullForm[tbl]
TableView[List[List[-1234.8`,0.123`],List[0.12345678`,0.1234`]],
Rule[ItemSize,List[List[3,List[8]]]],
Rule[DefaultBaseStyle,11],Rule[Spacings,List[0.2`,0.1`]],
Rule[FrameStyle,GrayLevel[0.5`]]]
So the data in TableView can be pulled out using
In[166]:= tbl[[1]]
Out[166]= {{-1234.8,0.123},{0.12345678,0.1234}}
But when I change tbl[[1]], using ReplacePart[], with an AccountingForm version of the data, TableView no longer works:
formattedData =
AccountingForm[data, {6, 3}, NumberSigns -> {"-", "+"},
NumberPadding -> {"", "0"}, SignPadding -> True];
In[245]:= tbl=ReplacePart[tbl,1->formatted]
Out[245]= TableView[{{-1234.8,+0.123},{+0.123,+0.123}},
ItemSize->{{3,{8}}},DefaultBaseStyle->11,Spacings->{0.2,0.1},
FrameStyle->GrayLevel[0.5]]
So, I broke TableView. Since it does not display any more.
Question is: How to format numeric data that goes into TableView without affecting the row/column index values?
Fyi, this is how the TableView looks inside one Manipulate demo I have. Notice the automatics scroll-bars. (In this one, I am not using NumberForm and its friends to do the formatting. But what I did is not very efficient, I'd rather use NumberForm if I can, hence my question)
thanks
update 12/22/11 1:30 AM
Here is a complete code example for Mike to follow up on his answer below
data = {{-1234.8, 0.123}, {0.12345678, 0.1234}};
newData =
Map[AccountingForm[#, {6, 3}, NumberSigns -> {"-", "+"},
NumberPadding -> {"", ""}, SignPadding -> True] &, data, {2}];
tbl = TableView[newData, ItemSize -> {{3, {8}}}, Spacings -> {.2, .1},
FrameStyle -> Gray]
Now how exactly do I use the Cell command for the above? (This is in Manipulate, not a notebook session, Manipulate runs all in one cell. I can't make separate cells and such in this code. But for trying it, I can in a new notebook, but the actual code that will use this solution, has to run in a Manipulate with no Cells.
Update 12/22/11 5 am
I am noticing some not good performance of TableView. Consider this code
Remove["Global`*"];
ClearSystemCache[]
m1 = MemoryInUse[$FrontEnd];
N[m1/10^6]
n = 256;
data = Table[RandomReal[], {n}, {n}];
TableView[data, ContentSize -> {300, 300}]
m2 = MemoryInUse[$FrontEnd] - m1;
N[m2/10^6]
The data itself, assuming double for the reals, is about half MB only. ByteCount says
2 MB due to other bookkeeping data struct.
In[114]:= ByteCount[data]/10^6//N
Out[114]= 2.10948
But Front end seems to use much more RAM (for the whole TableView I mean not just the data), sometimes I get 20 MB and sometimes much more (got 100 MB at one time). But if you try the above on your computer, you'll notice M is having hard time with this. I think it might be the rendering of the table part that causes M to take so much time.
I do not think 256 by 256 is such a large matrix. Even with 128 by 128, it was having hard time to render it on the screen. Once it is up, then it is fast and no problem using it.
It looks like TableView is not yet optimized well. I think I will only use it to display small part of the solution Matrix as the performance is not good to use it in a demo to display the whole solution, it will make the demo look bad.
The problem is that my solution matrix can be large, and I wanted a away to display the data in limited amount of GUI space. TableView is all what I can find that comes with scrollbars build-in. Nothing else in the Manipulate controls has something like this to use, so I have to use TableView.
Update 12/22/11 4 PM
Thanks for the hint by Mike below, I am now looking at using Pane with Scollbars, and it is working better than TableView. (still little slow with large data, but not as bad as TableView)
Here is a code example of doing that:
n = 32;
data = Table[RandomReal[], {n}, {n}];
grid = Grid[data, Spacings -> {.4, .4}, Alignment -> Left, Frame -> All];
grid = Style[NumberForm[grid, {6, 5}], LineBreakWithin -> False];
pane = Pane[grid, ImageSize -> {200}, Scrollbars -> True]
Only problem I noticed so far is that when n gets large, Pane generates this outer frame saying very large output was generated. But I am sure there is a programmatic way (option somewhere) to turn that effect off, I just started looking at this and should be able to find a way around this once I have my coffee. (fingers crossed)
good news
The "Very large output was generated" ONLY showed up when in notebook interface. When I put the code in a Manipulate and and run it, it did not show this output frame. So, I am happy now and this issue is closed. I'll use Pane from now on. (Thanks again to Mike)
btw, to remove the message in question, here is a useful link I found:
http://forums.wolfram.com/mathgroup/archive/2009/Apr/msg00935.html
but I did not need to do anything for what I am doing.
I guess this is a different enough method to post as another answer, though it clearly borrows from Mike's answer.
f = ToString #
AccountingForm[#, {6, 3}, NumberSigns -> {"-", "+"},
NumberPadding -> {"", ""}, SignPadding -> True] &;
data = {{-1234.8, 0.123}, {0.12345678, 0.1234}};
TableView[Map[f, data, {2}], ItemSize -> {{3, {8}}},
DefaultBaseStyle -> 11, Spacings -> {.2, .1}, FrameStyle -> Gray]
Since using ToString was non-intuitive, I decided to explore it a bit more. It seems that TableView suppresses quotation marks in strings, but only bare strings. e.g.:
string = "\"\"\"test\"";
TableView[{{ string }}]
TableView[{{ {string} }}]
Other interesting behavior can be seen with 2D formatted strings:
string = "\!\(\*SuperscriptBox[SqrtBox[\"5\"], \"2\"]\)";
TableView[{{ string }}]
TableView[{{ {string} }}]
One suggestion:
Firstly make each element in your data into AccountingForm, or whatever Form you want:
f = AccountingForm[#, {6, 3}, NumberSigns -> {"-", "+"},
NumberPadding -> {"", ""}, SignPadding -> True] &
newdata = {f[#[[1]]], f[#[[2]]]} & /# data
Note that I've had a bit of a brain fade doing this. I'm sure there is an easier way than Mapping (Edit: the brain fade made me forget levelspec). This will give you output like this:
The problem of course is that you now have string characters showing and "conventional" attempts to switch this off failed ("conventional" == options inspector, Style[] etc.). But you can fix this by modifying two styles that exist in the Core.nb stylesheet. So you will need to edit the private styles in your current notebook -- and also remove DefaultBaseStyle from your code because it will cause conflicts with the stylesheet style. So Format > Edit Stylesheet and add this style:
Cell[StyleData["TableViewItemExpression"],
ShowStringCharacters->False,
TemplateBoxOptions->{DisplayFunction->(StyleBox[#, Deployed -> False]& )}]
Actually that is really all you need to do but if you subsequently wanted to do some additional styling of the numbers then you need to modify a different style. Here is an example making the numbers red:
Cell[StyleData["TableViewGrid"],
ContextMenu->FEPrivate`FrontEndResource["ContextMenus", "TableView"],
ShowAutoStyles->False,
AutoSpacing->False,
ShowStringCharacters->False,
AutoNumberFormatting->True,
LineIndent->0,
FontWeight->"Plain",
FontColor->RGBColor[1, 0, 0]]
And this is what it looks like:

How to modify OUTPUT font type?

Is it possible to change the OUTPUT font type instead of the default one? How?
This is my default stylesheet: http://filefactory.com/file/cfc2cb0/n/blueOutput.nb
Thanks!
The problem lies in StandardForm not respecting the FontFamily option, although it does seem to respect most other font options. Sjoerd's answer used TraditionalForm output and thus worked. You can see this problem if you run
SetOptions[EvaluationNotebook[], StyleDefinitions -> Notebook[{
Cell[StyleData[StyleDefinitions -> "Default.nb"]],
Cell[StyleData["Output"],
FontColor -> RGBColor[0, 0, .5], FontSize -> 14,
FontFamily -> "Symbol", FontWeight -> "Bold"]}]]
Then compare
{1 + 1, "abc", Sin[x]} (* This is by default in StandardForm *)
{1 + 1, "abc", Sin[x]} // StandardForm
{1 + 1, "abc", Sin[x]} // OutputForm
{1 + 1, "abc", Sin[x]} // TraditionalForm
You can also look at
Dynamic[CurrentValue/#{FontFamily, FontWeight, FontSize}]
Dynamic[CurrentValue/#{FontFamily, FontWeight, FontSize}] // TraditionalForm
which shows that the CurrentValue of FontFamily "seen" in the output depends on the output format.
Unfortunately, I don't see how to get around this issue...
Just go to the Format > Edit Stylesheet... menu. Then in the private style definitions sheet that pops-up choose 'Output' from the pull-down menu and change the looks of the resulting Output cell. This stylesheet will be stored with your open notebook.
In light of Simon's answer, you could force output printing in a certain style using $PrePrint.
$PrePrint = Style[#, FontFamily -> "Symbol"] &;
{1 + 1, "abc", Sin[x]}
You can do this by redefining the StandardForm style which is used for Output style by default (see the DefaultFormatType option in the Output style):
SetOptions[EvaluationNotebook[],
StyleDefinitions ->
Notebook[{Cell[StyleData[StyleDefinitions -> "Default.nb"]],
Cell[StyleData["StandardForm"],
FontFamily -> "Palatino Linotype"]},
StyleDefinitions -> "PrivateStylesheetFormatting.nb"]]
But Input style in this case is also affected because it is based on the StandardForm style too...
You could try wrapping your inputs using the Style[] command. For example:
test="This is a test string.";
Style[test,{Red,"Title"}]
This generates the string in my style sheet's 'title' settings in the colour red. The solution of changing your Stylesheets is obviously preferable to this, but this might be a quick and dirty temporary workaround.

Getting CellDingbat to remember its state between Mathematica sessions

I have modified my notebook's stylesheet to include a StyleData["Todo"] that inherits from StyleData["Item"]. It changes the cell dingbat to a checkbox. In the stylesheet editor:
Cell[StyleData["ToDo", StyleDefinitions -> StyleData["Item"]],
CellDingbat->DynamicModuleBox[{$CellContext`color$$},
CheckboxBox[
Dynamic[$CellContext`color$$], {RGBColor[1, 0.5, 0],RGBColor[0,Rational[2, 3], 0]},
Background -> Dynamic[$CellContext`color$$]],
DynamicModuleValues :> {}
],
]
The problem is that the state of the checkbox, when used in a notebook, is not saved between Mathematica sessions. I thought the DynamicModule[] would do the trick. How do I get the checkbox to remember its state?
EDIT
Simon's solution does save the state of the checkbox, but the checkbox is clipped when used as a CellDingbat (MacOS X). Putting Simon's code in a CellFrameLabels options does the trick, and also keeps the default "Item" CellDingbat. Here is what I've gone with:
Cell[StyleData["ToDo", StyleDefinitions -> StyleData["Item"]],
CellFrameLabels->{{
ButtonBox[
CheckboxBox[False], ButtonFunction :> (SelectionMove[
ButtonNotebook[], All, ButtonCell];
With[{$CellContext`new = ReplaceAll[
Options[
NotebookSelection[
ButtonNotebook[]], CellFrameLabels], CheckboxBox[
Pattern[$CellContext`x,
Alternatives[True, False]]] :> CheckboxBox[
Not[$CellContext`x]]]},
SetOptions[
NotebookSelection[
ButtonNotebook[]], $CellContext`new]]; SelectionMove[
ButtonNotebook[], After, CellContents]), Appearance -> None,
Method -> "Preemptive", Evaluator -> Automatic], None}, {
None, None}},
MenuSortingValue->1621]
The problem with your code (I think) is that a new DynamicModule does not get created each time you create a new "ToDo" cell. So there is nowhere that the state of each Checkbox can get saved.
The simplest solution I could think of for storing the state of the Checkbox for each "ToDo" cell is to overwrite the CellDingbat the first time that the Checkbox is activated.
(Other options I played with were using TaggingRules,
toggling between "ToDo" and "ToDone" styles, etc...)
However, even a plain Checkbox in a CellDingbat does not store its state - try running the following then cycle the output through a Show Expression cycle.
CellPrint[Cell["test", "Text", CellDingbat -> ToBoxes[Checkbox[]]]]
To get around this, I used Checkbox with the definite argument True or False wrapped up in a button that changes the state. This is stupid and inefficient, but it works!
So, my code for the cell style
Cell[StyleData["ToDo", StyleDefinitions -> StyleData["Item"]],
CellDingbat -> ButtonBox[CheckboxBox[False],
ButtonFunction :> (SelectionMove[ButtonNotebook[], All, ButtonCell];
With[{$CellContext`new = ReplaceAll[
Options[NotebookSelection[ButtonNotebook[]], CellDingbat],
CheckboxBox[Pattern[$CellContext`x, Alternatives[True, False]]] :> CheckboxBox[Not[$CellContext`x]]]},
SetOptions[NotebookSelection[ButtonNotebook[]], $CellContext`new]];
SelectionMove[ButtonNotebook[], After, CellContents]),
Appearance -> None, Method -> "Preemptive", Evaluator -> Automatic]]
I'm not happy with this solution, but it's the best I've come up with. An improvement would be to move the button function code out of the cell so that it is not repeated for every checked ToDo cell. Also to make it run without a ReplaceAll so that the kernel is not needed and the function can be run using just the frontend.

Dialog manipulation

I want to create a dialog window, where the user can perform various tasks, and would like him to return from the dialog by clicking on the Cancel button with the mouse (i.e. not by hitting Enter). Therefore I do not want to use CreateDialog. However, by creating a less-specific dialog window via CreateWindow, all strings appear unformatted.
expr = Column[{
Row#{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not #1.",
CancelButton[]
}];
CreateWindow[DialogNotebook[expr], WindowSize -> All, WindowMargins -> {{100, Automatic}, {Automatic, Automatic}}, WindowTitle -> "1. CreateWindow & DialogNotebook"];
CreateDialog[expr, WindowTitle -> "2. CreateDialog"];
Is there any clever way to have the looks of the second dialog window, but the button-behaviour of the first one? Of course, expr here is a simple example, but it can be quite complex in reality, thus it is no option to wrap every string into Cell[string, "Text"], and every other expression into some obscure boxform.
This will stop your dialog window closing when Enter is pressed:
CreateDialog[expr, WindowTitle -> "2. CreateDialog", NotebookEventActions -> {}];
It overwrites the default dialog NotebookEventActions.
Another option:
expr = Style[
Column[{Row#{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not \
#1.", CancelButton[]}], ShowStringCharacters -> False];
Perhaps using TextCell:
expr = Column[{Row#{TextCell#"set variable to: ",
InputField["value", String]},
TextCell#"Try to hit Enter in any of the dialogs: \
it closes #2 but not #1.",
CancelButton[]}];
CreateWindow[
DialogNotebook[expr], WindowSize -> All,
WindowMargins -> {{100, Automatic}, {Automatic, Automatic}},
WindowTitle -> "1. CreateWindow & DialogNotebook"]
Edit
Use
TextCell#Style[" ... blah blah ...", style_opt ]
for formatting.
There are a number of ways to do this, and other folks have posted two good ones, but in my opinion the easiest approach is to set the BaseStyle of the Column expression to match the base style of the dialog, and then use CreateWindow. The style in question is "Panel", so this gets you the result you want:
expr = Column[{Row#{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not #1.",
CancelButton[]}, BaseStyle -> "Panel"];
CreateWindow[DialogNotebook[expr], WindowSize -> All,
WindowMargins -> {{100, Automatic}, {Automatic, Automatic}},
WindowTitle -> "1. CreateWindow & DialogNotebook"];

How to control Trigger state (Pause, Play) using code (not just buttons)

A trigger is useful to use for animation, but I am not able to find a way to change the state of the trigger in the code (i.e. without having to hit the Pause or Play button myself).
For example, suppose I want to do a simulation where when some event happen, I want to make the currently active trigger go to a PAUSE state, and when another event happen, I want the trigger to go to PLAY state.
The buttons to do that will still be there, but I want to also be able to change these from the code without having to physically do it.
The reason is, I am doing some action, and having the trigger being in PLAY mode while I am doing this other action is making things not working.
So I need to make it go to PAUSE state, and when I am done, I can set it back to PLAY state.
Here is a small example of what I mean:
Manipulate[
EventHandler[
Dynamic#Graphics[
{Circle[{0,0},1], Text[n,pt] },
PlotRange->All,ImageSize->200,ImagePadding->10],
{
"MouseDown":>
(
(* What to do here to cause the trigger to become Paused?"*)
pt=MousePosition["Graphics"]
),
"MouseDragged":>
(
(* while dragging, the trigger remains in PAUSED state "*)
Print["mouse dragged"];
pt=MousePosition["Graphics"]
),
"MouseUp":>
(
Print["MouseUp"]
(* What to do here to cause the trigger to Play again?"*)
)
}
],
Control[{{n,0,"Run"},0,100,0.01,
ControlType->Trigger, DisplayAllSteps->True, AnimationRate->1,
AppearanceElements->{"PlayPauseButton","ResetButton"}}
],
{{pt,{0,0}},ControlType->None}
]
In above, when I drag the mouse on the display, I want the trigger to become PAUSED so that the number shown is not changing while being dragged. When done with dragging, I can then make the trigger PLAY again if needed.
So, my question: Is there a way to change trigger state like the above in the code?
I can ofcourse not use trigger at all, and code everything myself in other ways, but thought to ask before I give up, as trigger is convenient to use.
Here is a link to more documentation of trigger and the buttons.
The closest thing I found is the Enabled-> option to trigger, but this just makes the trigger itself enabled to not, and does not affect the trigger state. i.e. if trigger is firing, it will remain firing even if I make disabled.
http://reference.wolfram.com/mathematica/ref/Manipulator.html
http://reference.wolfram.com/mathematica/ref/Trigger.html
thanks
There is probably an easier way to do this, but this seems to work. It's basically mimicking a Trigger by creating a scheduled task and stopping and starting it when a mouse button is pressed or released or when the Play/Pause button is clicked.
DynamicModule[{start = 0, finish = 100, dt = 0.01, running = False, task, n},
n = start;
Manipulate[
EventHandler[
Dynamic#
Graphics[{Circle[{0, 0}, 1], Text[n, pt]}, PlotRange -> All,
ImageSize -> 200, ImagePadding -> 10],
{
"MouseDown" :>
(StopScheduledTask[task]; pt = MousePosition["Graphics"]),
"MouseDragged" :>
(Print["mouse dragged"]; pt = MousePosition["Graphics"]),
"MouseUp" :>
(If[running, StartScheduledTask[task]]; Print["MouseUp"])
}],
Control[Labeled[
Row[{
Button[
Dynamic#If[running, Magnify["\[DoubleVerticalBar]", 1.5],
Magnify["\[RightPointer]", 1.5]],
(If[running, running = False; StopScheduledTask[task],
running = True; StartScheduledTask[task]]),
Appearance -> "Palette", ImageSize -> 15, ContentPadding -> False],
Button[
Magnify["\[FirstPage]", 1.5],
(n = start; ResetScheduledTask[task]),
Appearance -> "Palette", ImageSize -> 15, ContentPadding -> False]
}], "Run", Left]
],
{{pt, {0, 0}}, ControlType -> None}
],
Initialization :> (task =
CreateScheduledTask[n += dt, {dt, Floor[(finish - start)/dt]}]),
Deinitialization :> RemoveScheduledTask[task]
]
Edit: Changed the appearance of the controls to make them look more like traditional play/pause/reset buttons.

Resources