Reputation: 2532
I have different environmental variables in different files, and usually use source
to load/unload these. Now I want to change my environmental variables while using emacs. Is there any way to source
from within emacs?
Upvotes: 0
Views: 816
Reputation: 20258
In order to change the environment of Emacs itself (which will be inherited by all commands run by it, like compilation commands or shells), I use the following setup:
in the emacs init file, the following snippets defines (and calls) a function which starts the server and exports its name in the EMACS_SERVER
environment variable.
(defun my/server-start ()
"Start an emacs server using an automatically generated name.
If an emacs server is already running, it is restarted.
The EMACS_SERVER environment variable is set, so that child processes
can know which emacs server to contact."
(if (and (boundp 'server-process)
server-process
(memq (process-status server-process) '(connect listen open run)))
;; There is already an instance running; just restart it
(server-start)
;; Start a new server
(let ((i 0)
(max-try 100)
(ok nil))
(while (and (< i max-try)
(not ok))
(setq server-name (format "server%d" i))
(setq i (1+ i))
(unless (server-running-p server-name)
(setq ok t)))
(if (>= i max-try)
(display-warning 'my/server-start
"Could not find any unused server name."
:warning)
(message "Starting server with name %s." server-name)
(server-start))))
(setenv "EMACS_SERVER" server-name))
(my/server-start)
in my ~/.bashrc
file, the following function allows sourcing a shell script and exporting the resulting environment to the emacs server referenced by $EMACS_SERVER
:
E-source ()
{
( if [ -n "$1" ]; then
source "$1";
fi;
export | perl -pn -e 's/^declare -x //;' -e 's/([^=]+)=(.*)$/(setenv "$1" $2)/' | while read line; do
emacsclient -s ${EMACS_SERVER} -e "$line";
done )
}
all this being set up, when I want to develop in a project, I open a shell/term/multi-term buffer and while in it, I run
E-source my-env.sh
before running the compilation commands I need for developping in this particular project.
All this is somewhat complex, but I found it less error-prone than endlessly prefixing all compilation commands with source my-env.sh
, and also sourcing the environment in all shell/term/multi-term buffers.
Upvotes: 1