How to improve on this Stylesheet Manipulation for Message Styling Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Programming scripts to create and modify stylesheets: problems with contextsChanging Color of error messagesAutomatically including custom stylesheet with notebookSharing styles between notebooks (Mathematica v9)Is it possible to create a styled cell with pre-defined content?How edit stylesheet to change automatic numbering of Reference type to numeric, not alphabetic?Where is the file Default.nb?Questions on applying a private Stylesheet to another NotebookHow can I Programmatically Delete Styles from a Notebook's Stylesheet?How to change the default Notebook stylesheetWhy does Mathematica ignore my stylesheet for DisplayFormulaNumbered cells?Merging list valued style options

What's called a person who works as someone who puts products on shelves in stores?

How do I deal with an erroneously large refund?

Why is water being consumed when my shutoff valve is closed?

Why do people think Winterfell crypts is the safest place for women, children & old people?

Will I lose my paid in full property

Writing a T-SQL stored procedure to receive 4 numbers and insert them into a table

Will I be more secure with my own router behind my ISP's router?

How was Lagrange appointed professor of mathematics so early?

Suing a Police Officer Instead of the Police Department

Is there an efficient way for synchronising audio events real-time with LEDs using an MCU?

What is the definining line between a helicopter and a drone a person can ride in?

Will temporary Dex penalties prevent you from getting the benefits of the "Two Weapon Fighting" feat if your Dex score falls below the prerequisite?

/bin/ls sorts differently than just ls

Stretch a Tikz tree

How did Elite on the NES work?

What is the purpose of the side handle on a hand ("eggbeater") drill?

TV series episode where humans nuke aliens before decrypting their message that states they come in peace

Is there a verb for listening stealthily?

Married in secret, can marital status in passport be changed at a later date?

Why did Israel vote against lifting the American embargo on Cuba?

Simulate round-robin tournament draw

What were wait-states, and why was it only an issue for PCs?

"Working on a knee"

Does a Draconic Bloodline sorcerer's doubled proficiency bonus for Charisma checks against dragons apply to all dragon types or only the chosen one?



How to improve on this Stylesheet Manipulation for Message Styling



Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Programming scripts to create and modify stylesheets: problems with contextsChanging Color of error messagesAutomatically including custom stylesheet with notebookSharing styles between notebooks (Mathematica v9)Is it possible to create a styled cell with pre-defined content?How edit stylesheet to change automatic numbering of Reference type to numeric, not alphabetic?Where is the file Default.nb?Questions on applying a private Stylesheet to another NotebookHow can I Programmatically Delete Styles from a Notebook's Stylesheet?How to change the default Notebook stylesheetWhy does Mathematica ignore my stylesheet for DisplayFormulaNumbered cells?Merging list valued style options










4












$begingroup$


The answer by @Kuba changing color of error messages did not seem to work for me (MMA 11.0.1 Win 10 64-bit).



I couldn't work out why and implemented something else that does work for me, but it seems very ugly and I'm sure I could learn much by seeing how others would improve on it.



I think @Kuba's answer should have worked because I created the Default.nb as proposed in $UserBaseDirectory and my stylesheets ultimately inherit from it (Default.nb -> JM Stylsheet -> JM Clearer for TeamViewer).



However, I also directly modified my own stylesheets by using the "enter a style name" box, entering MessageMenuLabel and MessageText and styling them appropriately. The new styles worked and I saved stylesheets but on restarting MMA these styles were gone again.



Finally I wrote this (my 1st attempt to programmatically manipulate style definitions) making further use of @Kuba's answer to this question as follows



(* To preserve the current stylesheet information it has to be
plucked out of the StyleDefinitions; 1st time this is OK as the
StyleDefinitions = just a notebook name, but after adding items it
gets messy and we need to extract the stylesheet notebook name to reapply it.
*)
sdef = CurrentValue[EvaluationNotebook[], StyleDefinitions];
If[! StringQ[sdef], (*
this is typically just the filename of a stylesheet notebook,
but if it isn't... *)
sdef = ToString[sdef];
sdef = StringCases[sdef, "StyleDefinitions -> " ~~ __ ~~ ".nb]]",
1];
sdef = StringReplace[
sdef[[1]], "StyleDefinitions -> " -> "", "]]" -> ""]
];
SetOptions[EvaluationNotebook[], StyleDefinitions -> Notebook[
Cell[StyleData[StyleDefinitions -> sdef]],
Cell[StyleData["MessageMenuLabel"], Bold,
FontColor -> RGBColor[N[174/255], 0.1, 0],
FontSize ->
CurrentValue[StyleDefinitions, "Output", "FontSize"]],
Cell[StyleData["MessageText"],
FontColor -> RGBColor[0.1, 0.1, 0.1]]

]
(* last line needed per Kuba's Programming scripts to create and modify stylesheets answer*)
/. s_Symbol /; Context[s] === "Global`" :>
Symbol["FrontEnd`" <> SymbolName[s]]]
(* Do something illegal to check the message appearance... *)
1/0


Questions Why might the straightforward approach not have worked, and - for educational purposes - how should it be done programmatically & idiomatically?










share|improve this question











$endgroup$
















    4












    $begingroup$


    The answer by @Kuba changing color of error messages did not seem to work for me (MMA 11.0.1 Win 10 64-bit).



    I couldn't work out why and implemented something else that does work for me, but it seems very ugly and I'm sure I could learn much by seeing how others would improve on it.



    I think @Kuba's answer should have worked because I created the Default.nb as proposed in $UserBaseDirectory and my stylesheets ultimately inherit from it (Default.nb -> JM Stylsheet -> JM Clearer for TeamViewer).



    However, I also directly modified my own stylesheets by using the "enter a style name" box, entering MessageMenuLabel and MessageText and styling them appropriately. The new styles worked and I saved stylesheets but on restarting MMA these styles were gone again.



    Finally I wrote this (my 1st attempt to programmatically manipulate style definitions) making further use of @Kuba's answer to this question as follows



    (* To preserve the current stylesheet information it has to be
    plucked out of the StyleDefinitions; 1st time this is OK as the
    StyleDefinitions = just a notebook name, but after adding items it
    gets messy and we need to extract the stylesheet notebook name to reapply it.
    *)
    sdef = CurrentValue[EvaluationNotebook[], StyleDefinitions];
    If[! StringQ[sdef], (*
    this is typically just the filename of a stylesheet notebook,
    but if it isn't... *)
    sdef = ToString[sdef];
    sdef = StringCases[sdef, "StyleDefinitions -> " ~~ __ ~~ ".nb]]",
    1];
    sdef = StringReplace[
    sdef[[1]], "StyleDefinitions -> " -> "", "]]" -> ""]
    ];
    SetOptions[EvaluationNotebook[], StyleDefinitions -> Notebook[
    Cell[StyleData[StyleDefinitions -> sdef]],
    Cell[StyleData["MessageMenuLabel"], Bold,
    FontColor -> RGBColor[N[174/255], 0.1, 0],
    FontSize ->
    CurrentValue[StyleDefinitions, "Output", "FontSize"]],
    Cell[StyleData["MessageText"],
    FontColor -> RGBColor[0.1, 0.1, 0.1]]

    ]
    (* last line needed per Kuba's Programming scripts to create and modify stylesheets answer*)
    /. s_Symbol /; Context[s] === "Global`" :>
    Symbol["FrontEnd`" <> SymbolName[s]]]
    (* Do something illegal to check the message appearance... *)
    1/0


    Questions Why might the straightforward approach not have worked, and - for educational purposes - how should it be done programmatically & idiomatically?










    share|improve this question











    $endgroup$














      4












      4








      4


      2



      $begingroup$


      The answer by @Kuba changing color of error messages did not seem to work for me (MMA 11.0.1 Win 10 64-bit).



      I couldn't work out why and implemented something else that does work for me, but it seems very ugly and I'm sure I could learn much by seeing how others would improve on it.



      I think @Kuba's answer should have worked because I created the Default.nb as proposed in $UserBaseDirectory and my stylesheets ultimately inherit from it (Default.nb -> JM Stylsheet -> JM Clearer for TeamViewer).



      However, I also directly modified my own stylesheets by using the "enter a style name" box, entering MessageMenuLabel and MessageText and styling them appropriately. The new styles worked and I saved stylesheets but on restarting MMA these styles were gone again.



      Finally I wrote this (my 1st attempt to programmatically manipulate style definitions) making further use of @Kuba's answer to this question as follows



      (* To preserve the current stylesheet information it has to be
      plucked out of the StyleDefinitions; 1st time this is OK as the
      StyleDefinitions = just a notebook name, but after adding items it
      gets messy and we need to extract the stylesheet notebook name to reapply it.
      *)
      sdef = CurrentValue[EvaluationNotebook[], StyleDefinitions];
      If[! StringQ[sdef], (*
      this is typically just the filename of a stylesheet notebook,
      but if it isn't... *)
      sdef = ToString[sdef];
      sdef = StringCases[sdef, "StyleDefinitions -> " ~~ __ ~~ ".nb]]",
      1];
      sdef = StringReplace[
      sdef[[1]], "StyleDefinitions -> " -> "", "]]" -> ""]
      ];
      SetOptions[EvaluationNotebook[], StyleDefinitions -> Notebook[
      Cell[StyleData[StyleDefinitions -> sdef]],
      Cell[StyleData["MessageMenuLabel"], Bold,
      FontColor -> RGBColor[N[174/255], 0.1, 0],
      FontSize ->
      CurrentValue[StyleDefinitions, "Output", "FontSize"]],
      Cell[StyleData["MessageText"],
      FontColor -> RGBColor[0.1, 0.1, 0.1]]

      ]
      (* last line needed per Kuba's Programming scripts to create and modify stylesheets answer*)
      /. s_Symbol /; Context[s] === "Global`" :>
      Symbol["FrontEnd`" <> SymbolName[s]]]
      (* Do something illegal to check the message appearance... *)
      1/0


      Questions Why might the straightforward approach not have worked, and - for educational purposes - how should it be done programmatically & idiomatically?










      share|improve this question











      $endgroup$




      The answer by @Kuba changing color of error messages did not seem to work for me (MMA 11.0.1 Win 10 64-bit).



      I couldn't work out why and implemented something else that does work for me, but it seems very ugly and I'm sure I could learn much by seeing how others would improve on it.



      I think @Kuba's answer should have worked because I created the Default.nb as proposed in $UserBaseDirectory and my stylesheets ultimately inherit from it (Default.nb -> JM Stylsheet -> JM Clearer for TeamViewer).



      However, I also directly modified my own stylesheets by using the "enter a style name" box, entering MessageMenuLabel and MessageText and styling them appropriately. The new styles worked and I saved stylesheets but on restarting MMA these styles were gone again.



      Finally I wrote this (my 1st attempt to programmatically manipulate style definitions) making further use of @Kuba's answer to this question as follows



      (* To preserve the current stylesheet information it has to be
      plucked out of the StyleDefinitions; 1st time this is OK as the
      StyleDefinitions = just a notebook name, but after adding items it
      gets messy and we need to extract the stylesheet notebook name to reapply it.
      *)
      sdef = CurrentValue[EvaluationNotebook[], StyleDefinitions];
      If[! StringQ[sdef], (*
      this is typically just the filename of a stylesheet notebook,
      but if it isn't... *)
      sdef = ToString[sdef];
      sdef = StringCases[sdef, "StyleDefinitions -> " ~~ __ ~~ ".nb]]",
      1];
      sdef = StringReplace[
      sdef[[1]], "StyleDefinitions -> " -> "", "]]" -> ""]
      ];
      SetOptions[EvaluationNotebook[], StyleDefinitions -> Notebook[
      Cell[StyleData[StyleDefinitions -> sdef]],
      Cell[StyleData["MessageMenuLabel"], Bold,
      FontColor -> RGBColor[N[174/255], 0.1, 0],
      FontSize ->
      CurrentValue[StyleDefinitions, "Output", "FontSize"]],
      Cell[StyleData["MessageText"],
      FontColor -> RGBColor[0.1, 0.1, 0.1]]

      ]
      (* last line needed per Kuba's Programming scripts to create and modify stylesheets answer*)
      /. s_Symbol /; Context[s] === "Global`" :>
      Symbol["FrontEnd`" <> SymbolName[s]]]
      (* Do something illegal to check the message appearance... *)
      1/0


      Questions Why might the straightforward approach not have worked, and - for educational purposes - how should it be done programmatically & idiomatically?







      stylesheet coding-style






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 19 at 10:51









      mikado

      6,9171929




      6,9171929










      asked Apr 19 at 8:35









      Julian MooreJulian Moore

      9471515




      9471515




















          1 Answer
          1






          active

          oldest

          votes


















          3












          $begingroup$

          I worked on this a while back and found that it was just too messy to really work with the Notebook expression.



          Here's a better approach: 1) pull the NotebookObject's stylesheet 2) determine if the cell style you want to edit is in there 3) edit that style or make a new cell to edit



          Here's a quick imp for that:



          nbStyleSheet[nb_] :=

          With[cv = CurrentValue[nb, StyleDefinitions],
          If[! MatchQ[cv, _Notebook],
          SetOptions[nb,
          StyleDefinitions ->
          Notebook[Cell[StyleData[StyleDefinitions -> cv]],
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"
          ]]
          ];
          Lookup[NotebookInformation[nb], "StyleDefinitions"][[1]]
          ];

          findStyleData[nb_,
          stylePattern : _?StringPattern`StringPatternQ : "*"] :=

          Module[cells = Cells[nb],
          Association@
          MapThread[
          Replace[
          #,

          Cell[
          StyleData[
          name_String?(StringMatchQ[stylePattern]), ___], ___] :>
          (name -> #2),
          _ -> Nothing

          ] &,

          NotebookRead[cells],
          cells

          ]
          ];

          editStyleCell // Clear
          editStyleCell[nb_, styleCell_, styleEdits_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SetOptions[styleCell, styleEdits],
          (* this is a hack to make these edits apply immediately *)

          FrontEnd`SelectionMove[styleCell, All, Cell],
          FrontEndToken[nb, "ToggleShowExpression"],
          FrontEndToken[nb, "ToggleShowExpression"]


          makeMissingStyles[nb_, names_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SelectionMove[nb, After, Notebook],
          FrontEnd`NotebookWrite[nb, Map[Cell[StyleData[#]] &, names]]


          styleSheetEdit[notebook_, styleEdits_?AssociationQ] :=
          Module[

          names = Keys[styleEdits],
          nb = nbStyleSheet[notebook],
          cells,
          missing
          ,
          cells = findStyleData[nb, Alternatives @@ names];
          missing = Complement[names, Keys@cells];
          If[Length@missing > 0,
          makeMissingStyles[nb, names];
          cells = Join[cells, findStyleData[nb, Alternatives @@ missing]]
          ];
          MapThread[
          editStyleCell[nb, #, #2] &,

          cells,
          styleEdits

          ];
          ];
          styleSheetEdit[styleEdits_?AssociationQ] :=
          styleSheetEdit[EvaluationNotebook[], styleEdits];


          Let me know if you have questions. Meantime you can edit notebook stylesheets like this:



          styleSheetEdit[<|"Input" -> FontColor -> Pink|>]


          enter image description here



          CurrentValue[EvaluationNotebook[], StyleDefinitions]

          Notebook[Cell[StyleData[StyleDefinitions -> "Default.nb"]],
          Cell[StyleData["Input"], FontColor -> RGBColor[1, 0.5, 0.5]],
          Visible -> False,
          FrontEndVersion -> "12.0 for Mac OS X x86 (64-bit) (April 8, 2019)",
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"]


          You can revert changes by setting them to Inherited:



          styleSheetEdit[<|"Input" -> FontColor -> Inherited|>]





          share|improve this answer









          $endgroup$












          • $begingroup$
            Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
            $endgroup$
            – Julian Moore
            Apr 19 at 9:50










          • $begingroup$
            @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
            $endgroup$
            – b3m2a1
            Apr 19 at 9:52











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "387"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195584%2fhow-to-improve-on-this-stylesheet-manipulation-for-message-styling%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3












          $begingroup$

          I worked on this a while back and found that it was just too messy to really work with the Notebook expression.



          Here's a better approach: 1) pull the NotebookObject's stylesheet 2) determine if the cell style you want to edit is in there 3) edit that style or make a new cell to edit



          Here's a quick imp for that:



          nbStyleSheet[nb_] :=

          With[cv = CurrentValue[nb, StyleDefinitions],
          If[! MatchQ[cv, _Notebook],
          SetOptions[nb,
          StyleDefinitions ->
          Notebook[Cell[StyleData[StyleDefinitions -> cv]],
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"
          ]]
          ];
          Lookup[NotebookInformation[nb], "StyleDefinitions"][[1]]
          ];

          findStyleData[nb_,
          stylePattern : _?StringPattern`StringPatternQ : "*"] :=

          Module[cells = Cells[nb],
          Association@
          MapThread[
          Replace[
          #,

          Cell[
          StyleData[
          name_String?(StringMatchQ[stylePattern]), ___], ___] :>
          (name -> #2),
          _ -> Nothing

          ] &,

          NotebookRead[cells],
          cells

          ]
          ];

          editStyleCell // Clear
          editStyleCell[nb_, styleCell_, styleEdits_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SetOptions[styleCell, styleEdits],
          (* this is a hack to make these edits apply immediately *)

          FrontEnd`SelectionMove[styleCell, All, Cell],
          FrontEndToken[nb, "ToggleShowExpression"],
          FrontEndToken[nb, "ToggleShowExpression"]


          makeMissingStyles[nb_, names_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SelectionMove[nb, After, Notebook],
          FrontEnd`NotebookWrite[nb, Map[Cell[StyleData[#]] &, names]]


          styleSheetEdit[notebook_, styleEdits_?AssociationQ] :=
          Module[

          names = Keys[styleEdits],
          nb = nbStyleSheet[notebook],
          cells,
          missing
          ,
          cells = findStyleData[nb, Alternatives @@ names];
          missing = Complement[names, Keys@cells];
          If[Length@missing > 0,
          makeMissingStyles[nb, names];
          cells = Join[cells, findStyleData[nb, Alternatives @@ missing]]
          ];
          MapThread[
          editStyleCell[nb, #, #2] &,

          cells,
          styleEdits

          ];
          ];
          styleSheetEdit[styleEdits_?AssociationQ] :=
          styleSheetEdit[EvaluationNotebook[], styleEdits];


          Let me know if you have questions. Meantime you can edit notebook stylesheets like this:



          styleSheetEdit[<|"Input" -> FontColor -> Pink|>]


          enter image description here



          CurrentValue[EvaluationNotebook[], StyleDefinitions]

          Notebook[Cell[StyleData[StyleDefinitions -> "Default.nb"]],
          Cell[StyleData["Input"], FontColor -> RGBColor[1, 0.5, 0.5]],
          Visible -> False,
          FrontEndVersion -> "12.0 for Mac OS X x86 (64-bit) (April 8, 2019)",
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"]


          You can revert changes by setting them to Inherited:



          styleSheetEdit[<|"Input" -> FontColor -> Inherited|>]





          share|improve this answer









          $endgroup$












          • $begingroup$
            Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
            $endgroup$
            – Julian Moore
            Apr 19 at 9:50










          • $begingroup$
            @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
            $endgroup$
            – b3m2a1
            Apr 19 at 9:52















          3












          $begingroup$

          I worked on this a while back and found that it was just too messy to really work with the Notebook expression.



          Here's a better approach: 1) pull the NotebookObject's stylesheet 2) determine if the cell style you want to edit is in there 3) edit that style or make a new cell to edit



          Here's a quick imp for that:



          nbStyleSheet[nb_] :=

          With[cv = CurrentValue[nb, StyleDefinitions],
          If[! MatchQ[cv, _Notebook],
          SetOptions[nb,
          StyleDefinitions ->
          Notebook[Cell[StyleData[StyleDefinitions -> cv]],
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"
          ]]
          ];
          Lookup[NotebookInformation[nb], "StyleDefinitions"][[1]]
          ];

          findStyleData[nb_,
          stylePattern : _?StringPattern`StringPatternQ : "*"] :=

          Module[cells = Cells[nb],
          Association@
          MapThread[
          Replace[
          #,

          Cell[
          StyleData[
          name_String?(StringMatchQ[stylePattern]), ___], ___] :>
          (name -> #2),
          _ -> Nothing

          ] &,

          NotebookRead[cells],
          cells

          ]
          ];

          editStyleCell // Clear
          editStyleCell[nb_, styleCell_, styleEdits_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SetOptions[styleCell, styleEdits],
          (* this is a hack to make these edits apply immediately *)

          FrontEnd`SelectionMove[styleCell, All, Cell],
          FrontEndToken[nb, "ToggleShowExpression"],
          FrontEndToken[nb, "ToggleShowExpression"]


          makeMissingStyles[nb_, names_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SelectionMove[nb, After, Notebook],
          FrontEnd`NotebookWrite[nb, Map[Cell[StyleData[#]] &, names]]


          styleSheetEdit[notebook_, styleEdits_?AssociationQ] :=
          Module[

          names = Keys[styleEdits],
          nb = nbStyleSheet[notebook],
          cells,
          missing
          ,
          cells = findStyleData[nb, Alternatives @@ names];
          missing = Complement[names, Keys@cells];
          If[Length@missing > 0,
          makeMissingStyles[nb, names];
          cells = Join[cells, findStyleData[nb, Alternatives @@ missing]]
          ];
          MapThread[
          editStyleCell[nb, #, #2] &,

          cells,
          styleEdits

          ];
          ];
          styleSheetEdit[styleEdits_?AssociationQ] :=
          styleSheetEdit[EvaluationNotebook[], styleEdits];


          Let me know if you have questions. Meantime you can edit notebook stylesheets like this:



          styleSheetEdit[<|"Input" -> FontColor -> Pink|>]


          enter image description here



          CurrentValue[EvaluationNotebook[], StyleDefinitions]

          Notebook[Cell[StyleData[StyleDefinitions -> "Default.nb"]],
          Cell[StyleData["Input"], FontColor -> RGBColor[1, 0.5, 0.5]],
          Visible -> False,
          FrontEndVersion -> "12.0 for Mac OS X x86 (64-bit) (April 8, 2019)",
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"]


          You can revert changes by setting them to Inherited:



          styleSheetEdit[<|"Input" -> FontColor -> Inherited|>]





          share|improve this answer









          $endgroup$












          • $begingroup$
            Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
            $endgroup$
            – Julian Moore
            Apr 19 at 9:50










          • $begingroup$
            @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
            $endgroup$
            – b3m2a1
            Apr 19 at 9:52













          3












          3








          3





          $begingroup$

          I worked on this a while back and found that it was just too messy to really work with the Notebook expression.



          Here's a better approach: 1) pull the NotebookObject's stylesheet 2) determine if the cell style you want to edit is in there 3) edit that style or make a new cell to edit



          Here's a quick imp for that:



          nbStyleSheet[nb_] :=

          With[cv = CurrentValue[nb, StyleDefinitions],
          If[! MatchQ[cv, _Notebook],
          SetOptions[nb,
          StyleDefinitions ->
          Notebook[Cell[StyleData[StyleDefinitions -> cv]],
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"
          ]]
          ];
          Lookup[NotebookInformation[nb], "StyleDefinitions"][[1]]
          ];

          findStyleData[nb_,
          stylePattern : _?StringPattern`StringPatternQ : "*"] :=

          Module[cells = Cells[nb],
          Association@
          MapThread[
          Replace[
          #,

          Cell[
          StyleData[
          name_String?(StringMatchQ[stylePattern]), ___], ___] :>
          (name -> #2),
          _ -> Nothing

          ] &,

          NotebookRead[cells],
          cells

          ]
          ];

          editStyleCell // Clear
          editStyleCell[nb_, styleCell_, styleEdits_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SetOptions[styleCell, styleEdits],
          (* this is a hack to make these edits apply immediately *)

          FrontEnd`SelectionMove[styleCell, All, Cell],
          FrontEndToken[nb, "ToggleShowExpression"],
          FrontEndToken[nb, "ToggleShowExpression"]


          makeMissingStyles[nb_, names_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SelectionMove[nb, After, Notebook],
          FrontEnd`NotebookWrite[nb, Map[Cell[StyleData[#]] &, names]]


          styleSheetEdit[notebook_, styleEdits_?AssociationQ] :=
          Module[

          names = Keys[styleEdits],
          nb = nbStyleSheet[notebook],
          cells,
          missing
          ,
          cells = findStyleData[nb, Alternatives @@ names];
          missing = Complement[names, Keys@cells];
          If[Length@missing > 0,
          makeMissingStyles[nb, names];
          cells = Join[cells, findStyleData[nb, Alternatives @@ missing]]
          ];
          MapThread[
          editStyleCell[nb, #, #2] &,

          cells,
          styleEdits

          ];
          ];
          styleSheetEdit[styleEdits_?AssociationQ] :=
          styleSheetEdit[EvaluationNotebook[], styleEdits];


          Let me know if you have questions. Meantime you can edit notebook stylesheets like this:



          styleSheetEdit[<|"Input" -> FontColor -> Pink|>]


          enter image description here



          CurrentValue[EvaluationNotebook[], StyleDefinitions]

          Notebook[Cell[StyleData[StyleDefinitions -> "Default.nb"]],
          Cell[StyleData["Input"], FontColor -> RGBColor[1, 0.5, 0.5]],
          Visible -> False,
          FrontEndVersion -> "12.0 for Mac OS X x86 (64-bit) (April 8, 2019)",
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"]


          You can revert changes by setting them to Inherited:



          styleSheetEdit[<|"Input" -> FontColor -> Inherited|>]





          share|improve this answer









          $endgroup$



          I worked on this a while back and found that it was just too messy to really work with the Notebook expression.



          Here's a better approach: 1) pull the NotebookObject's stylesheet 2) determine if the cell style you want to edit is in there 3) edit that style or make a new cell to edit



          Here's a quick imp for that:



          nbStyleSheet[nb_] :=

          With[cv = CurrentValue[nb, StyleDefinitions],
          If[! MatchQ[cv, _Notebook],
          SetOptions[nb,
          StyleDefinitions ->
          Notebook[Cell[StyleData[StyleDefinitions -> cv]],
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"
          ]]
          ];
          Lookup[NotebookInformation[nb], "StyleDefinitions"][[1]]
          ];

          findStyleData[nb_,
          stylePattern : _?StringPattern`StringPatternQ : "*"] :=

          Module[cells = Cells[nb],
          Association@
          MapThread[
          Replace[
          #,

          Cell[
          StyleData[
          name_String?(StringMatchQ[stylePattern]), ___], ___] :>
          (name -> #2),
          _ -> Nothing

          ] &,

          NotebookRead[cells],
          cells

          ]
          ];

          editStyleCell // Clear
          editStyleCell[nb_, styleCell_, styleEdits_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SetOptions[styleCell, styleEdits],
          (* this is a hack to make these edits apply immediately *)

          FrontEnd`SelectionMove[styleCell, All, Cell],
          FrontEndToken[nb, "ToggleShowExpression"],
          FrontEndToken[nb, "ToggleShowExpression"]


          makeMissingStyles[nb_, names_] :=
          MathLink`CallFrontEnd@
          FrontEnd`SelectionMove[nb, After, Notebook],
          FrontEnd`NotebookWrite[nb, Map[Cell[StyleData[#]] &, names]]


          styleSheetEdit[notebook_, styleEdits_?AssociationQ] :=
          Module[

          names = Keys[styleEdits],
          nb = nbStyleSheet[notebook],
          cells,
          missing
          ,
          cells = findStyleData[nb, Alternatives @@ names];
          missing = Complement[names, Keys@cells];
          If[Length@missing > 0,
          makeMissingStyles[nb, names];
          cells = Join[cells, findStyleData[nb, Alternatives @@ missing]]
          ];
          MapThread[
          editStyleCell[nb, #, #2] &,

          cells,
          styleEdits

          ];
          ];
          styleSheetEdit[styleEdits_?AssociationQ] :=
          styleSheetEdit[EvaluationNotebook[], styleEdits];


          Let me know if you have questions. Meantime you can edit notebook stylesheets like this:



          styleSheetEdit[<|"Input" -> FontColor -> Pink|>]


          enter image description here



          CurrentValue[EvaluationNotebook[], StyleDefinitions]

          Notebook[Cell[StyleData[StyleDefinitions -> "Default.nb"]],
          Cell[StyleData["Input"], FontColor -> RGBColor[1, 0.5, 0.5]],
          Visible -> False,
          FrontEndVersion -> "12.0 for Mac OS X x86 (64-bit) (April 8, 2019)",
          StyleDefinitions -> "PrivateStylesheetFormatting.nb"]


          You can revert changes by setting them to Inherited:



          styleSheetEdit[<|"Input" -> FontColor -> Inherited|>]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 19 at 9:45









          b3m2a1b3m2a1

          29.2k360167




          29.2k360167











          • $begingroup$
            Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
            $endgroup$
            – Julian Moore
            Apr 19 at 9:50










          • $begingroup$
            @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
            $endgroup$
            – b3m2a1
            Apr 19 at 9:52
















          • $begingroup$
            Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
            $endgroup$
            – Julian Moore
            Apr 19 at 9:50










          • $begingroup$
            @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
            $endgroup$
            – b3m2a1
            Apr 19 at 9:52















          $begingroup$
          Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
          $endgroup$
          – Julian Moore
          Apr 19 at 9:50




          $begingroup$
          Thanks; It'll take me a while to digest this but will get back when I have. Given your rep I guess this must be pretty optimal but it still seems like a lot of effort for something that I would have expected to be easier!
          $endgroup$
          – Julian Moore
          Apr 19 at 9:50












          $begingroup$
          @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
          $endgroup$
          – b3m2a1
          Apr 19 at 9:52




          $begingroup$
          @JulianMoore I just added a bunch of tweaks to make it work cleaner. It'd be doable in fewer lines if you wanted it to be less convenient I think.
          $endgroup$
          – b3m2a1
          Apr 19 at 9:52

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Mathematica Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195584%2fhow-to-improve-on-this-stylesheet-manipulation-for-message-styling%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Sum ergo cogito? 1 nng

          三茅街道4182Guuntc Dn precexpngmageondP