Merged from
[bpt/emacs.git] / lisp / env.el
1 ;;; env.el --- functions to manipulate environment variables
2
3 ;; Copyright (C) 1991, 1994, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: processes, unix
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; UNIX processes inherit a list of name-to-string associations from their
29 ;; parents called their `environment'; these are commonly used to control
30 ;; program options. This package permits you to set environment variables
31 ;; to be passed to any sub-process run under Emacs.
32
33 ;; Note that the environment string `process-environment' is not
34 ;; decoded, but the args of `setenv' and `getenv' are normally
35 ;; multibyte text and get coding conversion.
36
37 ;;; Code:
38
39 (eval-when-compile (require 'cl))
40
41 ;; History list for environment variable names.
42 (defvar read-envvar-name-history nil)
43
44 (defun read-envvar-name (prompt &optional mustmatch)
45 "Read environment variable name, prompting with PROMPT.
46 Optional second arg MUSTMATCH, if non-nil, means require existing envvar name.
47 If it is also not t, RET does not exit if it does non-null completion."
48 (completing-read prompt
49 (mapcar (lambda (enventry)
50 (list (if enable-multibyte-characters
51 (decode-coding-string
52 (substring enventry 0
53 (string-match "=" enventry))
54 locale-coding-system t)
55 (substring enventry 0
56 (string-match "=" enventry)))))
57 (append process-environment
58 (frame-parameter (frame-with-environment) 'environment)
59 global-environment))
60 nil mustmatch nil 'read-envvar-name-history))
61
62 ;; History list for VALUE argument to setenv.
63 (defvar setenv-history nil)
64
65
66 (defun substitute-env-vars (string)
67 "Substitute environment variables referred to in STRING.
68 `$FOO' where FOO is an environment variable name means to substitute
69 the value of that variable. The variable name should be terminated
70 with a character not a letter, digit or underscore; otherwise, enclose
71 the entire variable name in braces. For instance, in `ab$cd-x',
72 `$cd' is treated as an environment variable.
73
74 Use `$$' to insert a single dollar sign."
75 (let ((start 0))
76 (while (string-match
77 (eval-when-compile
78 (rx (or (and "$" (submatch (1+ (regexp "[[:alnum:]_]"))))
79 (and "${" (submatch (minimal-match (0+ anything))) "}")
80 "$$")))
81 string start)
82 (cond ((match-beginning 1)
83 (let ((value (getenv (match-string 1 string))))
84 (setq string (replace-match (or value "") t t string)
85 start (+ (match-beginning 0) (length value)))))
86 ((match-beginning 2)
87 (let ((value (getenv (match-string 2 string))))
88 (setq string (replace-match (or value "") t t string)
89 start (+ (match-beginning 0) (length value)))))
90 (t
91 (setq string (replace-match "$" t t string)
92 start (+ (match-beginning 0) 1)))))
93 string))
94
95 ;; Fixme: Should the environment be recoded if LC_CTYPE &c is set?
96
97 (defun setenv (variable &optional value unset substitute-env-vars frame)
98 "Set the value of the environment variable named VARIABLE to VALUE.
99 VARIABLE should be a string. VALUE is optional; if not provided or
100 nil, the environment variable VARIABLE will be removed.
101 UNSET if non-nil means to remove VARIABLE from the environment.
102 SUBSTITUTE-ENV-VARS, if non-nil, means to substitute environment
103 variables in VALUE with `substitute-env-vars', where see.
104 Value is the new value if VARIABLE, or nil if removed from the
105 environment.
106
107 Interactively, a prefix argument means to unset the variable, and
108 otherwise the current value (if any) of the variable appears at
109 the front of the history list when you type in the new value.
110 This function always replaces environment variables in the new
111 value when called interactively.
112
113 If VARIABLE is set in `process-environment', then this function
114 modifies its value there. Otherwise, this function works by
115 modifying either `global-environment' or the environment
116 belonging to the selected frame, depending on the value of
117 `local-environment-variables'.
118
119 If optional parameter FRAME is non-nil, then it should be a a
120 frame. If the specified frame has its own set of environment
121 variables, this function will modify VARIABLE in it. Note that
122 frames on the same terminal device usually share their
123 environment, so calling `setenv' on one of them affects the
124 others as well.
125
126 As a special case, setting variable `TZ' calls `set-time-zone-rule' as
127 a side-effect."
128 (interactive
129 (if current-prefix-arg
130 (list (read-envvar-name "Clear environment variable: " 'exact) nil t)
131 (let* ((var (read-envvar-name "Set environment variable: " nil))
132 (value (getenv var)))
133 (when value
134 (push value setenv-history))
135 ;; Here finally we specify the args to give call setenv with.
136 (list var
137 (read-from-minibuffer (format "Set %s to value: " var)
138 nil nil nil 'setenv-history
139 value)
140 nil
141 t))))
142 (if (and (multibyte-string-p variable) locale-coding-system)
143 (let ((codings (find-coding-systems-string (concat variable value))))
144 (unless (or (eq 'undecided (car codings))
145 (memq (coding-system-base locale-coding-system) codings))
146 (error "Can't encode `%s=%s' with `locale-coding-system'"
147 variable (or value "")))))
148 (if unset
149 (setq value nil)
150 (if substitute-env-vars
151 (setq value (substitute-env-vars value))))
152 (if (multibyte-string-p variable)
153 (setq variable (encode-coding-string variable locale-coding-system)))
154 (if (and value (multibyte-string-p value))
155 (setq value (encode-coding-string value locale-coding-system)))
156 (if (string-match "=" variable)
157 (error "Environment variable name `%s' contains `='" variable))
158 (let ((pattern (concat "\\`" (regexp-quote variable) "\\(=\\|\\'\\)"))
159 (case-fold-search nil)
160 (frame-env (frame-parameter (frame-with-environment frame) 'environment))
161 (frame-forced (not frame))
162 (scan process-environment)
163 found)
164 (setq frame (frame-with-environment frame))
165 (if (string-equal "TZ" variable)
166 (set-time-zone-rule value))
167 (block nil
168 ;; Look for an existing entry for VARIABLE; try `process-environment' first.
169 (while (and scan (stringp (car scan)))
170 (when (string-match pattern (car scan))
171 (if value
172 (setcar scan (concat variable "=" value))
173 ;; Leave unset variables in `process-environment',
174 ;; otherwise the overridden value in `global-environment'
175 ;; or frame-env would become unmasked.
176 (setcar scan variable))
177 (return value))
178 (setq scan (cdr scan)))
179
180 ;; Look in the local or global environment, whichever is relevant.
181 (let ((local-var-p (and frame-env
182 (or frame-forced
183 (eq t local-environment-variables)
184 (member variable local-environment-variables)))))
185 (setq scan (if local-var-p
186 frame-env
187 global-environment))
188 (while scan
189 (when (string-match pattern (car scan))
190 (if value
191 (setcar scan (concat variable "=" value))
192 (if local-var-p
193 (set-frame-parameter frame 'environment
194 (delq (car scan) frame-env))
195 (setq global-environment (delq (car scan) global-environment))))
196 (return value))
197 (setq scan (cdr scan)))
198
199 ;; VARIABLE is not in any environment list.
200 (if value
201 (if local-var-p
202 (set-frame-parameter frame 'environment
203 (cons (concat variable "=" value)
204 frame-env))
205 (setq global-environment
206 (cons (concat variable "=" value)
207 global-environment))))
208 (return value)))))
209
210 (defun getenv (variable &optional frame)
211 "Get the value of environment variable VARIABLE.
212 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
213 the environment. Otherwise, value is a string.
214
215 If optional parameter FRAME is non-nil, then it should be a
216 frame. If that frame has its own set of environment variables,
217 this function will look up VARIABLE in there.
218
219 Otherwise, this function searches `process-environment' for
220 VARIABLE. If it is not found there, then it continues the
221 search in either `global-environment' or the environment list of
222 the selected frame, depending on the value of
223 `local-environment-variables'."
224 (interactive (list (read-envvar-name "Get environment variable: " t)))
225 (let ((value (getenv-internal (if (multibyte-string-p variable)
226 (encode-coding-string
227 variable locale-coding-system)
228 variable))))
229 (if (and enable-multibyte-characters value)
230 (setq value (decode-coding-string value locale-coding-system)))
231 (when (interactive-p)
232 (message "%s" (if value value "Not set")))
233 value))
234
235 (defun environment ()
236 "Return a list of environment variables with their values.
237 Each entry in the list is a string of the form NAME=VALUE.
238
239 The returned list can not be used to change environment
240 variables, only read them. See `setenv' to do that.
241
242 The list is constructed from elements of `process-environment',
243 `global-environment' and the local environment list of the
244 selected frame, as specified by `local-environment-variables'.
245
246 Non-ASCII characters are encoded according to the initial value of
247 `locale-coding-system', i.e. the elements must normally be decoded for use.
248 See `setenv' and `getenv'."
249 (let ((env (let ((local-env (frame-parameter (frame-with-environment)
250 'environment)))
251 (cond ((or (not local-environment-variables)
252 (not local-env))
253 (append process-environment global-environment nil))
254 ((consp local-environment-variables)
255 (let ((e (reverse process-environment)))
256 (dolist (entry local-environment-variables)
257 (setq e (cons (getenv entry) e)))
258 (append (nreverse e) global-environment nil)))
259 (t
260 (append process-environment local-env nil)))))
261 scan seen)
262 ;; Find the first valid entry in env.
263 (while (and env (stringp (car env))
264 (or (not (string-match "=" (car env)))
265 (member (substring (car env) 0 (string-match "=" (car env))) seen)))
266 (setq seen (cons (car env) seen)
267 env (cdr env)))
268 (setq scan env)
269 (while (and (cdr scan) (stringp (cadr scan)))
270 (let* ((match (string-match "=" (cadr scan)))
271 (name (substring (cadr scan) 0 match)))
272 (cond ((not match)
273 ;; Unset variable.
274 (setq seen (cons name seen))
275 (setcdr scan (cddr scan)))
276 ((member name seen)
277 ;; Duplicate variable.
278 (setcdr scan (cddr scan)))
279 (t
280 ;; New variable.
281 (setq seen (cons name seen)
282 scan (cdr scan))))))
283 env))
284
285 (defmacro let-environment (varlist &rest body)
286 "Evaluate BODY with environment variables set according to VARLIST.
287 The environment variables are then restored to their previous
288 values.
289 The value of the last form in BODY is returned.
290
291 Each element of VARLIST is either a string (which variable is
292 then removed from the environment), or a list (NAME
293 VALUEFORM) (which sets NAME to the value of VALUEFORM, a string).
294 All the VALUEFORMs are evaluated before any variables are set."
295 (declare (indent 2))
296 (let ((old-env (make-symbol "old-env"))
297 (name (make-symbol "name"))
298 (value (make-symbol "value"))
299 (entry (make-symbol "entry"))
300 (frame (make-symbol "frame")))
301 `(let ((,frame (selected-frame))
302 ,old-env)
303 ;; Evaluate VALUEFORMs and replace them in VARLIST with their values.
304 (dolist (,entry ,varlist)
305 (unless (stringp ,entry)
306 (if (cdr (cdr ,entry))
307 (error "`let-environment' bindings can have only one value-form"))
308 (setcdr ,entry (eval (cadr ,entry)))))
309 ;; Set the variables.
310 (dolist (,entry ,varlist)
311 (let ((,name (if (stringp ,entry) ,entry (car ,entry)))
312 (,value (if (consp ,entry) (cdr ,entry))))
313 (setq ,old-env (cons (cons ,name (getenv ,name)) ,old-env))
314 (setenv ,name ,value)))
315 (unwind-protect
316 (progn ,@body)
317 ;; Restore old values.
318 (with-selected-frame (if (frame-live-p ,frame)
319 ,frame
320 (selected-frame))
321 (dolist (,entry ,old-env)
322 (setenv (car ,entry) (cdr ,entry))))))))
323
324 (provide 'env)
325
326 ;;; arch-tag: b7d6a8f7-bc81-46db-8e39-8d721d4ed0b8
327 ;;; env.el ends here