7

I am using Mathematica 8.0.4.0 running under Windows 7. Is there a way to programmatically do a "save as " on an init.nb file to save it as init.m?

In the documentation center under tutorial/FrontEndTokens I found

FrontEndExecute[{FrontEndToken[FrontEnd`InputNotebook[],"SaveRenameSpecial", "Text"]}]

but it doesn't seem to work? I am looking for a working variation of this where "Text" is replaced by "Package" or somesuch.

Thanks for your help.

Robert Miller
  • 360
  • 1
  • 4
  • 9
  • 1
    To confirm, File > Save As... and Mathematica Package (*.m) manually does what you want, correct? – Mr.Wizard Jun 18 '12 at 16:54
  • @Mr.Wizard Yes, I should have made that more clear. Maual File>Save As... and Mathematica Package (*.m) works fine and is exactly what I would like to achieve programmatically. – Robert Miller Jun 18 '12 at 17:39

1 Answers1

8

The correct token syntax appears to be as follows:

FrontEndExecute[
 FrontEndToken[
   FrontEnd`InputNotebook[], 
   "SaveRename",
   {"C:\\Data\\TestFile.m", "Package"}
 ]
]

This more compact form also works:

FrontEndTokenExecute[
  FrontEnd`InputNotebook[],
  "SaveRename",
  {"C:\\Data\\TestFile.m", "Package"}
]

Please note that:

  • This is equivalent to doing File > Save As... select Mathematica Package (*.m) manually and will save only the Initialization cells of the Notebook. (The other cells are saved as (* comments *).)

  • If you do not provide a file path the file will end up in $HomeDirectory which is not usually where you want it.

  • No warning message is issued if the file cannot be saved.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Thank you! Exactly what I was looking for. – Robert Miller Jun 18 '12 at 18:12
  • @Robert I'm glad I could help. Finding these sometimes requires a bit of wizardry. ;-) – Mr.Wizard Jun 18 '12 at 18:15
  • 1
    It seems like this may no longer be functional. At least for Mathematica 11.0.1 on a Mac the command does nothing. Both "SaveRename" and "SaveRenameSpecial" bare will open the dialogs, but passing a file name seems to do nothing. – b3m2a1 Dec 09 '16 at 06:54
  • @MB1965 Thanks for the note. I am still using 10.1.0 and run Windows so I cannot attempt to find a solution. If this is important to you please post a new question with a link back to this one, and note the version specific problem. – Mr.Wizard Dec 09 '16 at 07:10
  • 3
    @Mr.Wizard it turns out it merely doesn't like the ~ shell escape that's the standard on Unix. If I give it an absolute path the package generates fine. No idea why I didn't check that earlier. – b3m2a1 Dec 09 '16 at 09:28