This post is a continuation of an earlier Question, How to programmatically change CellStyle of all Cells from "Input" to "Code"? but with a different problem. The solution that works best was selected from the given link and set to a function ChangeCellStyle. It works fine when calling it with default values but when reversing the CellStyle so as to undo the changes it does nothing and I cannot figure out why.
Below are two helpers and the stage (top parent function). If you include backup it works fine so please ignore it. However I am not all that confident replace is bug free.
(* helpers *)
ClearAll[backup, replace]
backup[seq_ : "", app_ : "GCS_BACKUP", src_ : NotebookFileName[],
tar_ : True] := Module[{
sub = Evaluate["." <> FileExtension[src]],
new, dst
},
new = app <> Evaluate[ToString[seq]] <> sub;
dst = StringReplace[src, sub -> new];
CopyFile[src, dst, OverwriteTarget -> tar]];
replace[objs_, from_, to_] :=
NotebookWrite[#,
Block[{expr = NotebookRead[#]},
Join[expr[[1 ;; 1]], Replace[Rest[expr], from -> to, {1}]]]] & /@
objs;
(* stage *)
ClearAll[ChangeCellStyle]
Options[ChangeCellStyle] = {"From" -> "Input", "To" -> "Code",
Method -> Automatic, "MIMEType" -> Automatic,
OverwriteTarget -> True};
ChangeCellStyle[cells_ : Automatic, bak_ : True,
opts : OptionsPattern[]] := Module[{
bk = If[TrueQ[bak], backup[], None],
objs = Which[
MemberQ[cells, _CellObject], cells,
True, Evaluate[Cells[CellStyle -> OptionValue["From"]]]
]
},
Echo[bk, Row[{"backup", Style[" [Rule]", Orange, Bold]}]];
replace[objs, OptionValue["From"], OptionValue["To"]]
];
Both "forward" calling styles work.
nb = EvaluationNotebook[];
(* forward 1 *)
ChangeCellStyle[];
(* forward 2 *)
cells = Cells[nb, CellStyle -> OptionValue["Input"]];
ChangeCellStyle[cells, From -> "Input", To -> "Code"];
This is what I wish to fix. Attempting to reverse the style changes fails.
(* backwards 1 (undo) *)
cells = Cells[nb,
CellStyle -> OptionValue["Code"]]; ChangeCellStyle[cells,
From -> "Code", To -> "Input"]
ChangeCellStyle[cells_List : Automatic, bak : _True | False : True, opts : OptionsPattern[]]? – Jules Manson Jan 15 '23 at 09:40]that shouldn't have been there, should be fixed now (note that it really should bebak: True|False : Truewithout the_- the syntax isname:pattern:default, where the pattern isTrue|False, i.e. exactlyTrueorFalse) – Lukas Lang Jan 15 '23 at 10:42
– Jules Manson Feb 26 '23 at 05:47ChangeCellStyle[cells_List : Automatic, bak : True | False : True, opts : OptionsPattern[]]