4
$\begingroup$

Recently I learned the hard way that there exists autosave functionality for notebooks. When a notebook is not saved yet, though, this feature doesn't work.

Question: Is there a way to tell Mathematica to autosave these 'Untitled' notebooks in the $TemporaryDirectory?

$\endgroup$

1 Answer 1

1
$\begingroup$

First you must get the notebooks that need saving:

nbs=Select[Notebooks[], (StringMatchQ[
    "WindowTitle" /. NotebookInformation[#], "Untitled*"]) &]

Further, we need the name of the notebook:

"WindowTitle" /.NotebookInformation[...];

Then we need to remember the current notebook:

cnb = SelectedNotebook[];

With these commands we can save all "Untitled" notebook to the $TemporaryDirectory:

cnb = SelectedNotebook[];
nbs = Select[
   Notebooks[], (StringMatchQ["WindowTitle" /. NotebookInformation[#],
       "Untitled*"]) &];
NotebookSave[#, 
    FileNameJoin[{$TemporaryDirectory, "WindowTitle"} /. 
      NotebookInformation[#]]] & /@ nbs;
SetSelectedNotebook[cnb];

To execute the above commands say every minute, we put them inside a Dynamic with an update interval of 60 sec:

Dynamic[
    cnb = SelectedNotebook[];
    nbs = Select[
       Notebooks[], (StringMatchQ["WindowTitle" /. NotebookInformation[#],
           "Untitled*"]) &];
    NotebookSave[#, 
        FileNameJoin[{$TemporaryDirectory, "WindowTitle"} /. 
          NotebookInformation[#]]] & /@ nbs;
    SetSelectedNotebook[cnb];
, UpdateInterval -> 60]
$\endgroup$
2
  • $\begingroup$ So basically if I add the code to Kernel/init.m I should have default autosave for Untitled notebooks. Is there any chance that problems may arise with computations that run for more than 60s? (not an expert on dynamic...) $\endgroup$
    – Gert
    Apr 13, 2022 at 14:18
  • $\begingroup$ The notebook will be saved as is at 60 seconds, eventually without the result of an ongoing evaluation. But you may easily increase the time interval. $\endgroup$ Apr 13, 2022 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.