4

consider the following list of Cell[]'s:

cells = {
         Cell[
              "foo=\"string1\";(*comment*)bar=\"string2\";"
            , "Input"
         ]
        ,Cell[
              "foo=\"string1\";(*comment*)bar=\"string2\";"
            , "Input"]
        };
nb = Notebook[{cells}];
SystemOpen@Export[$HomeDirectory <> "/notebook.nb", nb]

d

Using the Notebook function, I can create and export a notebook, but there is no syntax highlighting.

user64494
  • 26,149
  • 4
  • 27
  • 56
podge cassidy
  • 483
  • 2
  • 6

1 Answers1

5

You need to add BoxData to mark it StandardForm as opposed to a plain text content. Notice that as soon as the notebook is created or exported the text content will be automatically converted to a box expression.

cells = {
   Cell["foo=\"string1\";(*comment*)bar=\"string2\";", "Input"], 
   Cell["foo=\"string1\";(*comment*)bar=\"string2\";", "Input"]
   };
nb = Notebook[MapAt[BoxData, cells, {All, 1}]];

Export[FileNameJoin[{$TemporaryDirectory, "test.nb"}], nb]

NotebookOpen@%

enter image description here

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • 1
    Interesting. Is this usage of BoxData documented? – Gustavo Delfino Feb 07 '23 at 14:20
  • 2
    @GustavoDelfino I am not sure, I think I learned it from John Fultz's comments somewhere around here and I use it from time to time: https://mathematica.stackexchange.com/a/271092/5478 – Kuba Feb 07 '23 at 15:13