4

I'm trying to read in all input cells in a notebook that are contained in (or outside of) a specific group.

NotebookImport[nb, "Input" -> "InputText"]

gives the input text of all the input cells in the notebook, but I don't know how to filter out the input cells in a CellGroup with a specific title.

A motivating application would be trying to import the input cells in a documentation notebook from only the Basic Examples and Possible Issues sections.

Kuba
  • 136,707
  • 13
  • 279
  • 740
M.R.
  • 31,425
  • 8
  • 90
  • 281

1 Answers1

3

NotebookImport doesn't support it directly but you could import "Input"|"ExampleSection" and just split by style. You could but you can't because somehow ExampleSection style in those cells is put there twice:

Cell[
  TextData[{"Basic Examples",... }], 
  "ExampleSection", "ExampleSection",...
]

Which is not a problem but NotebookImport doesn't support it (which is a bug imo).

So at the end we have to live with NotebookGet or Import and parse it:

Cases[
  NotebookGet[nb],
  {
     c : Cell[
       _?(! FreeQ[#, ("Basic Examples" | "Possible Issues")] &), 
       "ExampleSection", 
       ___
     ], 
     r___
  } :> (
    c[[1, 1, 1]] -> Cases[
      {r}, cell : Cell[_, "Input", ___] :> First @ FrontEndExecute[
         FrontEnd`ExportPacket[cell, "InputText"]], ∞]
  ),
  ∞
]
{"Basic Examples" -> {"nb = CreateDocument[{TextCell[\"project \
title\", \"Title\"],
  TextCell[\"first section\", \"Section\"], 

  TextCell[\"details\", \"Subsection\"], 

  ExpressionCell[Defer[2 + 2], \"Input\"], 

  TextCell[\"second section\", \"Section\"], 

  ExpressionCell[Defer[3 + 3], \"Input\"], 

  ExpressionCell[Defer[1/0], \"Input\"]}, 

 WindowMargins -> {{Automatic, 0}, {Automatic, 0}}, 

 WindowSize -> {500, 600}];

NotebookEvaluate[nb, InsertResults -> True];", "NotebookImport[nb, _]", "NotebookImport[nb, _ -> "Text"]", "NotebookImport[nb, "Input"]", "NotebookImport[nb, "Input" -> "InputText"]", "NotebookImport[nb, "Input" -> "InactiveExpression"]", "NotebookImport[nb, "Input" | "Output", "FlattenCellGroups" ->
False]", "NotebookImport[nb, "Input" | "Output" -> "InputText",

"FlattenCellGroups" -> False]"}, "Possible Issues" -> {"NotebookImport[Notebook[{Cell["2+", "Input
"]}],

"Input" -> "HeldExpression"]", "2+", "2+", "NotebookImport[Notebook[{Cell["Grid[{{1,2},{3,4}}]",
"Input"]}],

"Input" -> "HeldExpression"]", "InputForm[%]", "NotebookImport[Notebook[{Cell["Grid[{{1,2},{3,4}}]",
"Input"]}],

"Input" -> "InputText"]"}}

Kuba
  • 136,707
  • 13
  • 279
  • 740