UPDATE 2.0
I just discovered this wonderful answer by Mr. Wizard on saving as a package via FrontEndTokenExecute
and so this is an even more trivial task now:
simply call
FrontEndTokenExecute[
FrontEnd`InputNotebook[], "SaveRename", {StringReplace[
NotebookFileName[], ".nb" -> ".wl"], "Package"}]
in your {"MenuCommand","Save"}
binding and use PassEventsDown->True
.
Note that this preserves constructs like "Input"
cells and whatnot so Karsten7's idea is the definite winner if you're looking for the direct AutoGeneratedPackage
analog. On the other hand, the ability to gather the data from the notebook in a more compressed package format is pretty useful.
UPDATE
Per Karsten7's comment, it suffices to copy a newly generated .m to a .wl so assuming AutoGeneratePackage
is set the code could be as simple as
SetOptions[
EvaluationNotebook[],
NotebookEventActions -> {
{"MenuCommand", "Save"} :>
(
NotebookSave[];
RenameFile[
StringReplace[NotebookFileName[],".nb"->".m"],
StringReplace[NotebookFileName[],".nb"->".wl"]
]
)
}
]
Note that we really do have to call NotebookSave[]
rather than just using PassEventsDown
because this event is called before the save event would have been called. This can lead to issues with Save As... but assuming one simply saves the thing normally, it is really this easy.
I'm keeping the original code below as it does give a mechanism to save things other than just IntializationCell
and InitializationGroup
constructs which is potentially useful.
ORIGINAL
Using the copy-as-plaintext scheme here one can write a custom save as package function and bind it to the {"MenuCommand","Save"}
event and have this do the exporting. The following will do this for all "Code"
cells. One could tweak it to work for all cells with InitializationCell
set. The real difficulty is getting it to work for InitializationGroup
cells, too, but that should really just be a matter of getting all the child cells of InitializationGroup
cells.
If all your code is in "Code"
cells, though, this should work for you:
getCodeString[cellStyles__] :=
First@
FrontEndExecute[
FrontEnd`ExportPacket[
Cases[
First@
NotebookTools`FlattenCellGroups@
NotebookGet@EvaluationNotebook[],
Cell[_, Alternatives@cellStyles, ___]
], "PlainText"]
];
SetOptions[
EvaluationNotebook[],
NotebookEventActions -> {
{"MenuCommand", "Save"} :>
With[{
file =
OpenWrite@FileNameJoin@{
NotebookDirectory[],
FileBaseName@NotebookFileName[] <> ".wl"
},
dnu =
DynamicUpdating /.
AbsoluteOptions[EvaluationNotebook[], DynamicUpdating]},
SetOptions[EvaluationNotebook[],
DynamicUpdating -> False
];
WriteString[
file,
getCodeString["Code"]
];
Close@file;
SetOptions[EvaluationNotebook[], DynamicUpdating -> dnu]
]
}
]
Interestingly enough ".wl"
seems not to be recognized as an export type in Export
.
.m
files. $\endgroup$ – Karsten 7. Dec 6 '16 at 5:54