3

Please do not tag this question as already answered because the method described at Is there a way to programmatically do a “save as ” on an init.nb file to save it as init.m? is only for saving entire contents of notebooks. I wish to be able to save selected cells.

I often need to make edits to an init.m file which I have saved in two locations (FrontEnd,Kernel) in the $UserBaseDirectory. Doing this manually becomes quite cumbersome so I am looking for a quick and easy programmatic way of doing this.

I do all edits on init.nb and then manually do a Save As init.m to the two aforementioned locations. Ideally I only wish to save tagged cells from the currently open notebook (init.nb). Unfortunately I am very new to programmatic notebook operations so I am having great difficulty figuring this out.

As a proof of concept I wish to save the full contents of a list of tagged cells as a package file to a given temporary directory dir.

cells = Cells[CellTags -> {"paths", "packs", "tasks"}]
dir = FileNameJoin[{$Home, "tmp"}]
file = FileNameJoin[{dir, "tmp.m"}]

The following work but only for the entire contents of notebook...

FrontEndTokenExecute[
 FrontEnd`InputNotebook[], "SaveRename", {file, "Package"}]

I also tried this which again works only for entire contents of notebook...

FrontEndTokenExecute[
 FrontEnd`EvaluationNotebook[], "SaveRename", {file, "Package"}]

Please help. I tried many different things shown in official documentation and did learn a lot unfortunately nothing that addresses this problem.

Jules Manson
  • 2,457
  • 11
  • 19
  • 2
    Does FrontEndTokenExecute[Notebook@NotebookRead@cells, "SaveRename", {file, "Package"}] work? – Carl Woll Apr 14 '21 at 15:36
  • @CarlWoll Sorry i was too busy to respond sooner. yes thank you for this suggestion. it works almost perfectly except that every time i use it also pops up an Untitled (file with no extension). How do I suppress this ?behavior? – Jules Manson Apr 26 '21 at 05:50

0 Answers0