How can I determine (from within Emacs) the current directory as it was when the Shell launched
emacs from the command line?
AFAICT, Emacs does not save this info in a standard place. Håkon's solution might work for you, but that completely depends on the program that launches Emacs: some will put the directory in $PWD, but others won't (so you may get a valid $PWD, or no $PWD, or a $PWD that's not truthful). Other solutions would be:
If it's for your own personal use, just add
(setq my-saved-launch-directory default-directory)
somewhere at the beginning of your
~/.emacs, after which you can use that variable.
Otherwise, you can use
(with-current-buffer "*scratch*" default-directory)
which will usually work as long as nothing has deleted
*scratch*nor changed its default directory. As pointed out by Gilles, you can also use the
*Messages*buffer, which might even work better.
According to the Section 38.3 "Operating System Environment" in the GNU Emacs Lisp Reference Manual:
Variable: initial-environment This variable holds the list of environment variables Emacs inherited from its parent process when Emacs started.
So you can scan the list and check for any item starting with
PWD=. For example:
(require 'cl-lib) (defun my--get-initial-pwd () (let ((var) (value)) (cl-dolist (str initial-environment) (when (string-match "^\\(.*?\\)=\\(.*\\)" str) (setq var (match-string 1 str)) (setq value (match-string 2 str)) (when (string= var "PWD") (cl-return)))) value))