4
$\begingroup$

Everytime, before my code, I always write

SetDirectory[NotebookDirectory[]];

So, how to make this as the default?

$\endgroup$
  • 3
    $\begingroup$ I wonder if it's safe to do globally: wouldn't that fail in notebooks that have not been saved yet? $\endgroup$ – MarcoB Mar 14 '16 at 5:45
  • 5
    $\begingroup$ How would this work? Would opening a notebook trigger a directory change? Would switching to notebook B trigger a directory change even if code is currently being run in notebook A? That might break the running code. Even if we forget about the feasibility of implementation, I don't see how to make this work in a predictable and user-friendly manner. But I can see how it could lead to a disaster. I recommend that you try to figure out how it should work exactly, and explain it in your question. Then we can think abut whether it can be implemented. $\endgroup$ – Szabolcs Mar 14 '16 at 7:51
  • 1
    $\begingroup$ There is a link for your reference. mathematica.stackexchange.com/questions/15552/… $\endgroup$ – madeinQuant Mar 14 '16 at 8:27
2
$\begingroup$

I'm not sure whether I would suggest to do something like that, but I think the following would basically provide the behavior that you might be after:

SetOptions[$FrontEndSession,
      CellProlog :> Replace[
        Quiet[NotebookDirectory[]],    
        {
          s_String?DirectoryQ :> SetDirectory[s], 
         _ :> $UserDocumentsDirectory
    }
  ]
]

it will globally set CellProlog for the current session. The CellProlog is evaluated before evaluation of any cell, and the corresponding code will set the directory if NotebookDirectory returns a valid directory, else it will set directory to $UserDocumentationsDirectory (of course you could adjust the behaviour to your needs).

Playing with that option might have several drawbacks, be it performance or subtle "unexpected" behavior, so no guarantees that this won't cause more problems than it helps. Another complication is that it might interfer with other functionality which makes use of the CellProlog option. If you don't see problems, you could make it a permanent setting by using SetOptions to $FrontEnd instead of just $FrontEndSession...

In case you want to switch back to the default, you just need to set CellProlog back to the default (usually None) for whatever object you have set it...

$\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.