4

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?

Gert
  • 1,530
  • 8
  • 22

1 Answers1

1

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]
Daniel Huber
  • 51,463
  • 1
  • 23
  • 57
  • 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...) – Gert Apr 13 '22 at 14:18
  • 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. – Daniel Huber Apr 13 '22 at 14:27