2

Is there a way to export Input Cells in my current notebook(.nb) as a .m file while including indents?

For example if my notebook contains

Print[
  23
]

The .m should ideally contain

Print[
  23
]

with formatting. This and this are related but not exactly the same.

William
  • 7,595
  • 2
  • 22
  • 70

2 Answers2

3

Does it fit your needs?

Print[
  23
]

cell break

cell = NotebookRead @ Experimental`PreviousCell[];
DumpSave["test", cell]

You don't have to use PreviousCell, it is just handy here.

ClearAll[cell]
<< test
CellPrint @ cell
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • +1. But I really would like the file to be human readable and indented similar to if you manually indented the file on the Wolfram WorkBench or another text editor. To me this although is nice, it doesn't really have any advantages over saving something as a notebook only to copy the notebook cells out of the notebook to restore formatting. – William Oct 18 '14 at 18:10
3

The following creates a duplicate notebook before temporarily exporting the text. It removes all output cells.

CleanNotebook[nb_: SelectedNotebook[], 
   styles_: {"Output", 
     "Print"}] := (NotebookFind[nb, #, All, CellStyle];
     NotebookDelete[nb];) & /@ styles;
nbExport[n_, new_: ""] := 
  Module[{loc, nb}, 
   loc = FileNameJoin[{$TemporaryDirectory, "output.txt"}];
   nb = CreateDocument[n, Visible -> False];
   CleanNotebook[nb];
   FrontEndExecute[FrontEndToken[nb, "Save", {loc, "Text"}]];
   NotebookClose[nb];
   (*ret=StringReplace["\n"<>Import[loc,"Text"],"\nIn["~~
   ShortestMatch[___]~~"]:= "\[Rule]""];*)NotebookClose[nb];
   If[new != "", CopyFile[loc, new];];
   Return[Import[loc]]];

Convert current nb to text.

nbExport[NotebookGet[InputNotebook[]][[1]]];

Or convert BoxData to text.

nbExport[{Cell[
   BoxData[RowBox[{"1", "\[IndentingNewLine]", RowBox[{"+", "1"}]}]], 
   "Input"]}]
William
  • 7,595
  • 2
  • 22
  • 70