Re: export to .m using a cell command
- To: mathgroup at smc.vnet.net
- Subject: [mg126598] Re: export to .m using a cell command
- From: Chris Degnen <degnen at cwgsy.net>
- Date: Wed, 23 May 2012 03:28:30 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <jp54pl$gpe$1@smc.vnet.net>
On Friday, May 18, 2012 10:29:25 AM UTC+1, Roberto wrote:
> Hello,
>
> I know how to make a .m file using the "Save As" menu. This forces every time to choose the folder where I want to put it and the file name.
>
> As I update frequently my .m I was wandering if there is a way to make this using a cell command.
>
> I tried something like
>
> Export["~/my.m", EvaluationNotebook[]]
>
> but the .m created does not contain the current notebook, but it's rather empty.
>
> What should I use to save all the cells in the current notebook into a .m?
>
> Thanks in advance for your replies.
> Cheers
> Roberto
Another way to write out the notebook as a package, (without using initialisation cells), is to run the following:-
FrontEndExecute[FrontEnd`AddMenuCommands["Save",
{MenuItem["Save As Pac&kage",
FrontEnd`KernelExecute[
nb = SelectedNotebook[];
SelectionMove[nb, All, Notebook];
str =
First[FrontEndExecute[
FrontEnd`ExportPacket[NotebookSelection[nb], "InputText"]]];
If[# =!= $Failed,
Module[{name},
name = StringDrop[#, -3];
Export[name <> ".txt", str];
Quiet[DeleteFile[name <> ".m"]];
RenameFile[name <> ".txt", name <> ".m"]
]
] &@Quiet[NotebookFileName[nb]]
],
MenuKey["G", Modifiers -> {"Control", "Shift"}],
System`MenuEvaluator -> Automatic]
}]]
It will place a command on the menu which can be run with Alt-F, K or Shift-Control-G. When run, it will write out the current notebook as a package, provided the notebook already exists as a saved file, ie has a filename.
You can read more about ExportPacket here:
http://mathematica.stackexchange.com/questions/1319/how-do-i-extract-the-contents-of-a-selected-cell-as-plain-text/1411#1411
The notebook text is first saved as a .txt file and then renamed because directly exporting as a .m file doesn't save the formatting so well.