7
$\begingroup$

On notebook edit, save, or opening I'd like to call SetDirectory[NotebookDirectory[]].

Using this excellent answer, I tried the obvious:

i = 0; SetOptions[$FrontEndSession, 
 FrontEndDynamicExpression :> Refresh[Notebooks[];
   If[CurrentValue[EvaluationNotebook[], {"NotebookFileName"}] != "", 
    SetDirectory[NotebookDirectory[]]; 
    Print["Switching to notebook's directory", ++i]], 
   TrackedSymbols :> {}]]

But this doesn't seem to work.

$\endgroup$
4
  • $\begingroup$ what happens if you have several open notebooks associated with the same kernel? $\endgroup$
    – george2079
    Commented Nov 14, 2016 at 12:39
  • $\begingroup$ @george2079 good question, I would like it to switch to the one you are currently editing $\endgroup$
    – M.R.
    Commented Nov 14, 2016 at 15:03
  • $\begingroup$ maybe define $Pre to check/set on every evaluation. I prefer to keep it simple and put SetDirectory[NotebookDirectory[]]; before any code that depends on the path being set. $\endgroup$
    – george2079
    Commented Nov 14, 2016 at 17:43
  • $\begingroup$ Does the solution below work for you? $\endgroup$
    – Stitch
    Commented Nov 18, 2016 at 23:12

1 Answer 1

2
$\begingroup$

This code works, but you have to confirm the dynamic content evaluation when you open a notebook first time or simply evaluate anything.

SetOptions[$FrontEndSession, 
 NotebookDynamicExpression :> Refresh[nb = InputNotebook[];
   If[EvaluationNotebook[] == nb && CurrentValue[nb, {"NotebookFileName"}] != "" && 
     Directory[] != NotebookDirectory[nb],
     SetDirectory[NotebookDirectory[nb]];
    ], TrackedSymbols :> {}]]
$\endgroup$

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.