Manipulating Mathematica Notebooks

A few examples of the power of notebook programming

Creating a Notebook

nb = NotebookCreate[];

NotebookWrite[nb, Cell["1000!", "Input"]]

SelectionMove[nb, All, Notebook]

SelectionEvaluateCreateCell[nb]

SelectionMove[nb, Before, Cell]

Do[NotebookFind[nb, "5"], {30}]

NotebookClose[nb]

Generating a Notebook of Usage Messages

UsageNotebook[cmds : {__String}]  := 
      NotebookPut[
        Notebook[
          Flatten[{Cell[#, "Section"], 
                  Cell[MessageName[#, "usage"]&[ToExpression[#]], 
                    "Text"]}&/@cmds], 
          StyleDefinitions -> "Report.nb"]]

UsageNotebook[Names["Li*"]]

UsageCells[cmds : {__String}]  := 
      Scan[(StylePrint[#, "Subsection"]; 
            StylePrint[MessageName[#, "usage"]&[ToExpression[#]], 
              "Text"])&, cmds]

UsageCells[Names["Abo*"]]

Creating Notebooks That Change Form

A Notebook That Changes Color

nb = 
      NotebookPut[
        Notebook[{Cell["Watch Me!", "Section"]}, 
          WindowTitle -> "A Changing Window", 
          WindowSize -> {160, 160}]];

Do[SetOptions[nb, Background -> Hue[Mod[t, 1], .5]], {t, 0., 
        4., .1}]

NotebookClose[nb]

A Notebook That Pulsates

nb = 
      NotebookCreate[WindowTitle -> "A Pulsating Window", 
        WindowSize -> {240, 240}, Background -> Hue[.3  .5]];

Do[SetOptions[nb, 
        WindowSize -> N[100 (2.4 + {Sin[(t/10)], Sin[(t/15)]})]], {t, 
        40}]

NotebookClose[nb]

A Notebook That Walks around the Screen

nb = 
      NotebookPut[
        Notebook[{Cell["Follow Me!", "Section"]}, 
          Background -> Hue[.3, .5], 
          WindowTitle -> "A Moving Window", 
          WindowSize -> {160, 75}]];

Do[SetOptions[nb, 
        First[Map[If[NumberQ[#], # + Random[Real, {-40, 40}], #]&, 
            Options[nb, WindowMargins], {-1}]]], {100}]

NotebookClose[nb]