# How to set the current Directory as the default?

Everytime, before my code, I always write

SetDirectory[NotebookDirectory[]];


So, how to make this as the default?

• I wonder if it's safe to do globally: wouldn't that fail in notebooks that have not been saved yet? – MarcoB Mar 14 '16 at 5:45
• 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. – Szabolcs Mar 14 '16 at 7:51

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