Rework environment variable support. (Reported by Kalle Olavi Niemitalo and Noah...
[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, 2006 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 nil mustmatch nil 'read-envvar-name-history))
60
61 ;; History list for VALUE argument to setenv.
62 (defvar setenv-history nil)
63
64
65 (defun substitute-env-vars (string)
66 "Substitute environment variables referred to in STRING.
67 `$FOO' where FOO is an environment variable name means to substitute
68 the value of that variable. The variable name should be terminated
69 with a character not a letter, digit or underscore; otherwise, enclose
70 the entire variable name in braces. For instance, in `ab$cd-x',
71 `$cd' is treated as an environment variable.
72
73 Use `$$' to insert a single dollar sign."
74 (let ((start 0))
75 (while (string-match
76 (eval-when-compile
77 (rx (or (and "$" (submatch (1+ (regexp "[[:alnum:]_]"))))
78 (and "${" (submatch (minimal-match (0+ anything))) "}")
79 "$$")))
80 string start)
81 (cond ((match-beginning 1)
82 (let ((value (getenv (match-string 1 string))))
83 (setq string (replace-match (or value "") t t string)
84 start (+ (match-beginning 0) (length value)))))
85 ((match-beginning 2)
86 (let ((value (getenv (match-string 2 string))))
87 (setq string (replace-match (or value "") t t string)
88 start (+ (match-beginning 0) (length value)))))
89 (t
90 (setq string (replace-match "$" t t string)
91 start (+ (match-beginning 0) 1)))))
92 string))
93
94
95 (defun setenv-internal (env variable value keep-empty)
96 "Set VARIABLE to VALUE in ENV, adding empty entries if KEEP-EMPTY.
97 Changes ENV by side-effect, and returns its new value."
98 (let ((pattern (concat "\\`" (regexp-quote variable) "\\(=\\|\\'\\)"))
99 (case-fold-search nil)
100 (scan env)
101 prev found)
102 ;; Handle deletions from the beginning of the list specially.
103 (if (and (null value)
104 (not keep-empty)
105 env
106 (stringp (car env))
107 (string-match pattern (car env)))
108 (cdr env)
109 ;; Try to find existing entry for VARIABLE in ENV.
110 (while (and scan (stringp (car scan)))
111 (when (string-match pattern (car scan))
112 (if value
113 (setcar scan (concat variable "=" value))
114 (if keep-empty
115 (setcar scan variable)
116 (setcdr prev (cdr scan))))
117 (setq found t
118 scan nil))
119 (setq prev scan
120 scan (cdr scan)))
121 (if (and (not found) (or value keep-empty))
122 (cons (if value
123 (concat variable "=" value)
124 variable)
125 env)
126 env))))
127
128 ;; Fixme: Should the environment be recoded if LC_CTYPE &c is set?
129
130 (defun setenv (variable &optional value substitute-env-vars frame)
131 "Set the value of the environment variable named VARIABLE to VALUE.
132 VARIABLE should be a string. VALUE is optional; if not provided or
133 nil, the environment variable VARIABLE will be removed.
134
135 Interactively, a prefix argument means to unset the variable, and
136 otherwise the current value (if any) of the variable appears at
137 the front of the history list when you type in the new value.
138 This function always replaces environment variables in the new
139 value when called interactively.
140
141 SUBSTITUTE-ENV-VARS, if non-nil, means to substitute environment
142 variables in VALUE with `substitute-env-vars', which see.
143 This is normally used only for interactive calls.
144
145 If optional parameter FRAME is non-nil, this function modifies
146 only the frame-local value of VARIABLE on FRAME, ignoring
147 `process-environment'. Note that frames on the same terminal
148 device usually share their environment, so calling `setenv' on
149 one of them affects the others as well.
150
151 If FRAME is nil, `setenv' changes the global value of VARIABLE by
152 modifying `process-environment'. Note that the global value
153 overrides any frame-local values.
154
155 The return value is the new value of VARIABLE, or nil if
156 it was removed from the environment.
157
158 As a special case, setting variable `TZ' calls `set-time-zone-rule' as
159 a side-effect."
160 (interactive
161 (if current-prefix-arg
162 (list (read-envvar-name "Clear environment variable: " 'exact) nil)
163 (let* ((var (read-envvar-name "Set environment variable: " nil))
164 (value (getenv var)))
165 (when value
166 (add-to-history 'setenv-history value))
167 ;; Here finally we specify the args to give call setenv with.
168 (list var
169 (read-from-minibuffer (format "Set %s to value: " var)
170 nil nil nil 'setenv-history
171 value)
172 t))))
173 (if (and (multibyte-string-p variable) locale-coding-system)
174 (let ((codings (find-coding-systems-string (concat variable value))))
175 (unless (or (eq 'undecided (car codings))
176 (memq (coding-system-base locale-coding-system) codings))
177 (error "Can't encode `%s=%s' with `locale-coding-system'"
178 variable (or value "")))))
179 (and value
180 substitute-env-vars
181 (setq value (substitute-env-vars value)))
182 (if (multibyte-string-p variable)
183 (setq variable (encode-coding-string variable locale-coding-system)))
184 (if (and value (multibyte-string-p value))
185 (setq value (encode-coding-string value locale-coding-system)))
186 (if (string-match "=" variable)
187 (error "Environment variable name `%s' contains `='" variable))
188 (if (string-equal "TZ" variable)
189 (set-time-zone-rule value))
190 (if (null frame)
191 (setq process-environment (setenv-internal process-environment
192 variable value t))
193 (setq frame (frame-with-environment frame))
194 (set-frame-parameter frame 'environment
195 (setenv-internal (frame-parameter frame 'environment)
196 variable value nil)))
197 value)
198
199 (defun getenv (variable &optional frame)
200 "Get the value of environment variable VARIABLE.
201 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
202 the environment. Otherwise, value is a string.
203
204 If optional parameter FRAME is non-nil, then it should be a
205 frame. This function will look up VARIABLE in its 'environment
206 parameter.
207
208 Otherwise, this function searches `process-environment' for
209 VARIABLE. If it is not found there, then it continues the search
210 in the environment list of the selected frame."
211 (interactive (list (read-envvar-name "Get environment variable: " t)))
212 (let ((value (getenv-internal (if (multibyte-string-p variable)
213 (encode-coding-string
214 variable locale-coding-system)
215 variable))))
216 (if (and enable-multibyte-characters value)
217 (setq value (decode-coding-string value locale-coding-system)))
218 (when (interactive-p)
219 (message "%s" (if value value "Not set")))
220 value))
221
222 (defun environment ()
223 "Return a list of environment variables with their values.
224 Each entry in the list is a string of the form NAME=VALUE.
225
226 The returned list can not be used to change environment
227 variables, only read them. See `setenv' to do that.
228
229 The list is constructed by concatenating the elements of
230 `process-environment' and the 'environment parameter of the
231 selected frame, and removing duplicated and empty values.
232
233 Non-ASCII characters are encoded according to the initial value of
234 `locale-coding-system', i.e. the elements must normally be decoded for use.
235 See `setenv' and `getenv'."
236 (let* ((env (append process-environment
237 (frame-parameter (frame-with-environment)
238 'environment)
239 nil))
240 (scan env)
241 prev seen)
242 ;; Remove unset variables from the beginning of the list.
243 (while (and env
244 (or (not (stringp (car env)))
245 (not (string-match "=" (car env)))))
246 (or (member (car env) seen)
247 (setq seen (cons (car env) seen)))
248 (setq env (cdr env)
249 scan env))
250 (let (name)
251 (while scan
252 (cond ((or (not (stringp (car scan)))
253 (not (string-match "=" (car scan))))
254 ;; Unset variable.
255 (or (member (car scan) seen)
256 (setq seen (cons (car scan) seen)))
257 (setcdr prev (cdr scan)))
258 ((member (setq name (substring (car scan) 0 (string-match "=" (car scan)))) seen)
259 ;; Duplicated variable.
260 (setcdr prev (cdr scan)))
261 (t
262 ;; New variable.
263 (setq seen (cons name seen))))
264 (setq prev scan
265 scan (cdr scan))))
266 env))
267
268 (defmacro let-environment (varlist &rest body)
269 "Evaluate BODY with environment variables set according to VARLIST.
270 The environment variables are then restored to their previous
271 values.
272 The value of the last form in BODY is returned.
273
274 Each element of VARLIST is either a string (which variable is
275 then removed from the environment), or a list (NAME
276 VALUEFORM) (which sets NAME to the value of VALUEFORM, a string).
277 All the VALUEFORMs are evaluated before any variables are set."
278 (declare (indent 2))
279 (let ((old-env (make-symbol "old-env"))
280 (name (make-symbol "name"))
281 (value (make-symbol "value"))
282 (entry (make-symbol "entry"))
283 (frame (make-symbol "frame")))
284 `(let ((,frame (selected-frame))
285 ,old-env)
286 ;; Evaluate VALUEFORMs and replace them in VARLIST with their values.
287 (dolist (,entry ,varlist)
288 (unless (stringp ,entry)
289 (if (cdr (cdr ,entry))
290 (error "`let-environment' bindings can have only one value-form"))
291 (setcdr ,entry (eval (cadr ,entry)))))
292 ;; Set the variables.
293 (dolist (,entry ,varlist)
294 (let ((,name (if (stringp ,entry) ,entry (car ,entry)))
295 (,value (if (consp ,entry) (cdr ,entry))))
296 (setq ,old-env (cons (cons ,name (getenv ,name)) ,old-env))
297 (setenv ,name ,value)))
298 (unwind-protect
299 (progn ,@body)
300 ;; Restore old values.
301 (with-selected-frame (if (frame-live-p ,frame)
302 ,frame
303 (selected-frame))
304 (dolist (,entry ,old-env)
305 (setenv (car ,entry) (cdr ,entry))))))))
306
307 (provide 'env)
308
309 ;;; arch-tag: b7d6a8f7-bc81-46db-8e39-8d721d4ed0b8
310 ;;; env.el ends here