2
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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
$\endgroup$
  • $\begingroup$ +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. $\endgroup$ – William Oct 18 '14 at 18:10
3
$\begingroup$

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"]}]
$\endgroup$

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.