6
$\begingroup$

I usually use descriptive filenames for my notebooks, and then find myself manually copying that filename into a "Title" style top-level section in the notebook. I would like this to be automatic, or at least to happen when the notebook is evaluated. What is the best way to achieve this?

$\endgroup$
  • $\begingroup$ Do you want to update the first title cell multiple times? What if the first title cell isn't the first cell? $\endgroup$ – Kuba Mar 22 at 12:44
  • $\begingroup$ I want the title displayed in the notebook to match the filename. I could by convention always have the first title cell being the first cell, and I could also have only a single title cell in the notebook, if that were necessary to make a good solution work. Probably the most elegant solution wouldn't have these constraints, but I'm not too fussed about that. $\endgroup$ – Ian Hinder Mar 22 at 15:24
4
$\begingroup$

Put the following into a "Title" cell:

Dynamic[FileBaseName @ NotebookFileName[]]

An alternate version that will work even if the notebook has not been saved yet:

Dynamic["WindowTitle" /. NotebookInformation[]]

You can create the title cell with:

CellPrint @ ExpressionCell[
    Dynamic["WindowTitle" /. NotebookInformation[]], 
    "Title",
    ShowStringCharacters -> False
]
$\endgroup$
  • $\begingroup$ If I copy and paste the former into a title cell, it doesn't evaluate when I do shift-enter. Probably title cells don't evaluate? If I copy and paste the result of evaluating it, i.e. the actual dynamic object, it crashes the frontend (11.2, Mac OS). Did you try this solution? Maybe I am doing something wrong? $\endgroup$ – Ian Hinder Mar 22 at 15:11
1
$\begingroup$

My solution is the following:

NotebookPut[
  NotebookGet[InputNotebook[]] /. 
   Cell[x_, "Title", y__] :> 
    Cell[FileBaseName[FileNameTake[NotebookFileName[], -1]], "Title", 
     y], InputNotebook[]];

which seems to work, but has a few issues:

  1. It seems quite heavyweight to read and write the whole notebook for this. The notebook might be very large, containing graphics etc, and performance might suffer.
  2. When the NotebookPut cell is evaluated, the selection in the notebook moves to the end, which is a bit odd.
  3. Running "Evaluate notebook" causes "(Running...)" to remain in the notebook title bar even after evaluation has completed.

Does anyone have any better solution? For example, searching for the title cell and setting its text? I tried to do this, but I'm not familiar enough with how the various notebook functions work.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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