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.


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:

  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:

     c : Cell[
       _?(! FreeQ[#, ("Basic Examples" | "Possible Issues")] &), 
  } :> (
    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\" -> \"HeldExpression\"]", "InputForm[%]", 
   "NotebookImport[Notebook[{Cell[\"Grid[{{1,2},{3,4}}]\", \

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.