1 ;;; esh-var.el --- handling of variables
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: John Wiegley <johnw@gnu.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
27 (eval-when-compile (require 'esh-maint))
29 (defgroup eshell-var nil
30 "Variable interpolation is introduced whenever the '$' character
31 appears unquoted in any argument (except when that argument is
32 surrounded by single quotes). It may be used to interpolate a
33 variable value, a subcommand, or even the result of a Lisp form."
34 :tag "Variable handling"
39 ;; These are the possible variable interpolation syntaxes. Also keep
40 ;; in mind that if an argument looks like a number, it will be
41 ;; converted to a number. This is not significant when invoking
42 ;; external commands, but it's important when calling Lisp functions.
46 ;; Interval the value of an environment variable, or a Lisp variable
50 ;; "-" is a legal part of a variable name.
54 ;; Only "MYVAR" is part of the variable name in this case.
58 ;; Returns the length of the value of VARIABLE. This could also be
59 ;; done using the `length' Lisp function.
63 ;; Returns result of lisp evaluation. Note: Used alone like this, it
64 ;; is identical to just saying (lisp); but with the variable expansion
65 ;; form, the result may be interpolated a larger string, such as
70 ;; Returns the value of an eshell subcommand. See the note above
71 ;; regarding Lisp evaluations.
75 ;; Return the 10th element of ANYVAR. If ANYVAR's value is a string,
76 ;; it will be split in order to make it a list. The splitting will
77 ;; occur at whitespace.
81 ;; As above, except that splitting occurs at the colon now.
85 ;; As above, but instead of returning just a string, it now returns a
86 ;; list of two strings. If the result is being interpolated into a
87 ;; larger string, this list will be flattened into one big string,
88 ;; with each element separated by a space.
92 ;; Separate on backslash characters. Actually, the first argument --
93 ;; if it doesn't have the form of a number, or a plain variable name
94 ;; -- can be any regular expression. So to split on numbers, use
95 ;; '$ANYVAR["[0-9]+" 10 20]'.
99 ;; Calls `assoc' on ANYVAR with 'hello', expecting it to be an alist.
103 ;; Returns the length of the cdr of the element of ANYVAR who car is
106 ;; There are also a few special variables defined by Eshell. '$$' is
107 ;; the value of the last command (t or nil, in the case of an external
108 ;; command). This makes it possible to chain results:
110 ;; /tmp $ echo /var/spool/mail/johnw
111 ;; /var/spool/mail/johnw
117 ;; '$_' refers to the last argument of the last command. And $?
118 ;; contains the exit code of the last command (0 or 1 for Lisp
119 ;; functions, based on successful completion).
124 ;; XEmacs change; taken from Gnus. Remove once support for 21.4 is dropped.
125 (defun esh-make-temp-file-1 (prefix &optional dir-flag suffix)
126 "Create a temporary file.
127 The returned file name (created by appending some random characters at the end
128 of PREFIX, and expanding against `temporary-file-directory' if necessary),
129 is guaranteed to point to a newly created empty file.
130 You can then use `write-region' to write new data into the file.
132 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
134 If SUFFIX is non-nil, add that at the end of the file name."
135 (let ((umask (default-file-modes))
139 ;; Create temp files with strict access rights. It's easy to
140 ;; loosen them later, whereas it's impossible to close the
141 ;; time-window of loose permissions otherwise.
142 (set-default-file-modes 448)
143 (while (condition-case err
149 (if (fboundp 'temp-directory)
152 temporary-file-directory))))
154 (setq file (concat file suffix)))
156 (make-directory file)
157 (if (or (featurep 'xemacs)
158 (= emacs-major-version 20))
159 ;; NOTE: This is unsafe if Emacs 20
160 ;; users and XEmacs users don't use
161 ;; a secure temp directory.
162 (if (file-exists-p file)
163 (signal 'file-already-exists
164 (list "File exists" file))
165 (write-region "" nil file nil 'silent))
166 (write-region "" nil file nil 'silent
169 (file-already-exists t)
170 ;; The Emacs 20 and XEmacs versions of
171 ;; `make-directory' issue `file-error'.
172 (file-error (or (and (or (featurep 'xemacs)
173 (= emacs-major-version 20))
174 (file-exists-p file))
175 (signal (car err) (cdr err)))))
176 ;; the file was somehow created by someone else between
177 ;; `make-temp-name' and `write-region', let's try again.
181 (set-default-file-modes umask))))
183 (defalias 'esh-make-temp-file
184 (or (and (fboundp 'make-temp-file) 'make-temp-file)
185 'esh-make-temp-file-1))
189 (defcustom eshell-var-load-hook '(eshell-var-initialize)
190 "*A list of functions to call when loading `eshell-var'."
194 (defcustom eshell-prefer-lisp-variables nil
195 "*If non-nil, prefer Lisp variables to environment variables."
199 (defcustom eshell-complete-export-definition t
200 "*If non-nil, completing names for `export' shows current definition."
204 (defcustom eshell-modify-global-environment nil
205 "*If non-nil, using `export' changes Emacs's global environment."
209 (defcustom eshell-variable-name-regexp "[A-Za-z0-9_-]+"
210 "*A regexp identifying what constitutes a variable name reference.
211 Note that this only applies for '$NAME'. If the syntax '$<NAME>' is
212 used, then NAME can contain any character, including angle brackets,
213 if they are quoted with a backslash."
217 (defcustom eshell-variable-aliases-list
219 ("COLUMNS" (lambda (indices) (window-width)) t)
220 ("LINES" (lambda (indices) (window-height)) t)
223 ("_" (lambda (indices)
225 (car (last eshell-last-arguments))
226 (eshell-apply-indices eshell-last-arguments
228 ("?" eshell-last-command-status)
229 ("$" eshell-last-command-result)
230 ("0" eshell-command-name)
231 ("1" (lambda (indices) (nth 0 eshell-command-arguments)))
232 ("2" (lambda (indices) (nth 1 eshell-command-arguments)))
233 ("3" (lambda (indices) (nth 2 eshell-command-arguments)))
234 ("4" (lambda (indices) (nth 3 eshell-command-arguments)))
235 ("5" (lambda (indices) (nth 4 eshell-command-arguments)))
236 ("6" (lambda (indices) (nth 5 eshell-command-arguments)))
237 ("7" (lambda (indices) (nth 6 eshell-command-arguments)))
238 ("8" (lambda (indices) (nth 7 eshell-command-arguments)))
239 ("9" (lambda (indices) (nth 8 eshell-command-arguments)))
240 ("*" (lambda (indices)
242 eshell-command-arguments
243 (eshell-apply-indices eshell-command-arguments
245 "*This list provides aliasing for variable references.
246 It is very similar in concept to what `eshell-user-aliases-list' does
247 for commands. Each member of this defines defines the name of a
248 command, and the Lisp value to return for that variable if it is
249 accessed via the syntax '$NAME'.
251 If the value is a function, that function will be called with two
252 arguments: the list of the indices that was used in the reference, and
253 whether the user is requesting the length of the ultimate element.
254 For example, a reference of '$NAME[10][20]' would result in the
255 function for alias `NAME' being called (assuming it were aliased to a
256 function), and the arguments passed to this function would be the list
258 :type '(repeat (list string sexp
259 (choice (const :tag "Copy to environment" t)
260 (const :tag "Use only in Eshell" nil))))
263 (put 'eshell-variable-aliases-list 'risky-local-variable t)
267 (defun eshell-var-initialize ()
268 "Initialize the variable handle code."
269 ;; Break the association with our parent's environment. Otherwise,
270 ;; changing a variable will affect all of Emacs.
271 (unless eshell-modify-global-environment
272 (set (make-local-variable 'process-environment)
273 (eshell-copy-environment)))
275 (define-key eshell-command-map [(meta ?v)] 'eshell-insert-envvar)
277 (set (make-local-variable 'eshell-special-chars-inside-quoting)
278 (append eshell-special-chars-inside-quoting '(?$)))
279 (set (make-local-variable 'eshell-special-chars-outside-quoting)
280 (append eshell-special-chars-outside-quoting '(?$)))
282 (make-local-hook 'eshell-parse-argument-hook)
283 (add-hook 'eshell-parse-argument-hook 'eshell-interpolate-variable t t)
285 (make-local-hook 'eshell-prepare-command-hook)
286 (add-hook 'eshell-prepare-command-hook
287 'eshell-handle-local-variables nil t)
289 (when (eshell-using-module 'eshell-cmpl)
290 (make-local-hook 'pcomplete-try-first-hook)
291 (add-hook 'pcomplete-try-first-hook
292 'eshell-complete-variable-reference nil t)
293 (add-hook 'pcomplete-try-first-hook
294 'eshell-complete-variable-assignment nil t)))
296 (defun eshell-handle-local-variables ()
297 "Allow for the syntax 'VAR=val <command> <args>'."
298 ;; strip off any null commands, which can only happen if a variable
299 ;; evaluates to nil, such as "$var x", where `var' is nil. The
300 ;; command name in that case becomes `x', for compatibility with
301 ;; most regular shells (the difference is that they do an
302 ;; interpolation pass before the argument parsing pass, but Eshell
303 ;; does both at the same time).
304 (while (and (not eshell-last-command-name)
305 eshell-last-arguments)
306 (setq eshell-last-command-name (car eshell-last-arguments)
307 eshell-last-arguments (cdr eshell-last-arguments)))
308 (let ((setvar "\\`\\([A-Za-z_][A-Za-z0-9_]*\\)=\\(.*\\)\\'")
309 (command (eshell-stringify eshell-last-command-name))
310 (args eshell-last-arguments))
311 ;; local variable settings (such as 'CFLAGS=-O2 make') are handled
312 ;; by making the whole command into a subcommand, and calling
313 ;; setenv immediately before the command is invoked. This means
314 ;; that 'BLAH=x cd blah' won't work exactly as expected, but that
315 ;; is by no means a typical use of local environment variables.
316 (if (and command (string-match setvar command))
318 'eshell-replace-command
320 'eshell-as-subcommand
324 (while (string-match setvar command)
327 (list 'setenv (match-string 1 command)
328 (match-string 2 command)
329 (= (length (match-string 2 command)) 0))))
330 (setq command (eshell-stringify (car args))
333 (list (list 'eshell-named-command
334 command (list 'quote args)))))))))
336 (defun eshell-interpolate-variable ()
337 "Parse a variable interpolation.
338 This function is explicit for adding to `eshell-parse-argument-hook'."
339 (when (and (eq (char-after) ?$)
340 (/= (1+ (point)) (point-max)))
342 (list 'eshell-escape-arg
343 (eshell-parse-variable))))
345 (defun eshell/define (var-alias definition)
346 "Define a VAR-ALIAS using DEFINITION."
348 (setq eshell-variable-aliases-list
349 (delq (assoc var-alias eshell-variable-aliases-list)
350 eshell-variable-aliases-list))
351 (let ((def (assoc var-alias eshell-variable-aliases-list))
354 (list 'quote (if (= (length definition) 1)
358 (setq eshell-variable-aliases-list
359 (delq (assoc var-alias eshell-variable-aliases-list)
360 eshell-variable-aliases-list)))
361 (setq eshell-variable-aliases-list
363 eshell-variable-aliases-list))))
366 (defun eshell/export (&rest sets)
367 "This alias allows the `export' command to act as bash users expect."
369 (if (and (stringp (car sets))
370 (string-match "^\\([^=]+\\)=\\(.*\\)" (car sets)))
371 (setenv (match-string 1 (car sets))
372 (match-string 2 (car sets))))
373 (setq sets (cdr sets))))
375 (defun pcomplete/eshell-mode/export ()
376 "Completion function for Eshell's `export'."
377 (while (pcomplete-here
378 (if eshell-complete-export-definition
380 (eshell-envvar-names)))))
382 (defun eshell/unset (&rest args)
383 "Unset an environment variable."
385 (if (stringp (car args))
386 (setenv (car args) nil t))
387 (setq args (cdr args))))
389 (defun pcomplete/eshell-mode/unset ()
390 "Completion function for Eshell's `unset'."
391 (while (pcomplete-here (eshell-envvar-names))))
393 (defun eshell/setq (&rest args)
394 "Allow command-ish use of `setq'."
397 (let ((sym (intern (car args)))
399 (setq last-value (set sym val)
403 (defun pcomplete/eshell-mode/setq ()
404 "Completion function for Eshell's `setq'."
405 (while (and (pcomplete-here (all-completions pcomplete-stub
409 (defun eshell/env (&rest args)
410 "Implemention of `env' in Lisp."
411 (eshell-init-print-buffer)
412 (eshell-eval-using-options
414 '((?h "help" nil nil "show this usage screen")
416 :usage "<no arguments>")
417 (eshell-for setting (sort (eshell-environment-variables)
419 (eshell-buffered-print setting "\n"))
422 (defun eshell-insert-envvar (envvar-name)
423 "Insert ENVVAR-NAME into the current buffer at point."
425 (list (read-envvar-name "Name of environment variable: " t)))
426 (insert-and-inherit "$" envvar-name))
428 (defun eshell-envvar-names (&optional environment)
429 "Return a list of currently visible environment variable names."
432 (substring x 0 (string-match "=" x))))
433 (or environment process-environment)))
435 (defun eshell-environment-variables ()
436 "Return a `process-environment', fully updated.
437 This involves setting any variable aliases which affect the
438 environment, as specified in `eshell-variable-aliases-list'."
439 (let ((process-environment (eshell-copy-environment)))
440 (eshell-for var-alias eshell-variable-aliases-list
441 (if (nth 2 var-alias)
442 (setenv (car var-alias)
444 (or (eshell-get-variable (car var-alias)) "")))))
445 process-environment))
447 (defun eshell-parse-variable ()
448 "Parse the next variable reference at point.
449 The variable name could refer to either an environment variable, or a
450 Lisp variable. The priority order depends on the setting of
451 `eshell-prefer-lisp-variables'.
453 Its purpose is to call `eshell-parse-variable-ref', and then to
454 process any indices that come after the variable reference."
455 (let* ((get-len (when (eq (char-after) ?#)
458 (setq value (eshell-parse-variable-ref)
459 indices (and (not (eobp))
460 (eq (char-after) ?\[)
461 (eshell-parse-indices))
464 (list 'quote indices)))
470 (defun eshell-parse-variable-ref ()
471 "Eval a variable reference.
472 Returns a Lisp form which, if evaluated, will return the value of the
475 Possible options are:
477 NAME an environment or Lisp variable value
478 <LONG-NAME> disambiguates the length of the name
479 {COMMAND} result of command is variable's value
480 (LISP-FORM) result of Lisp form is variable's value"
483 ((eq (char-after) ?{)
484 (let ((end (eshell-find-delimiter ?\{ ?\})))
486 (throw 'eshell-incomplete ?\{)
488 (list 'eshell-convert
489 (list 'eshell-command-to-value
490 (list 'eshell-as-subcommand
491 (eshell-parse-command
492 (cons (1+ (point)) end)))))
493 (goto-char (1+ end))))))
494 ((memq (char-after) '(?\' ?\"))
495 (let ((name (if (eq (char-after) ?\')
496 (eshell-parse-literal-quote)
497 (eshell-parse-double-quote))))
499 (list 'eshell-get-variable (eval name) 'indices))))
500 ((eq (char-after) ?\<)
501 (let ((end (eshell-find-delimiter ?\< ?\>)))
503 (throw 'eshell-incomplete ?\<)
505 (let* ((temp (esh-make-temp-file
506 (if (fboundp 'temp-directory) (temp-directory)
507 temporary-file-directory)))
508 (cmd (concat (buffer-substring (1+ (point)) end)
512 'let (list (list 'eshell-current-handles
513 (list 'eshell-create-handles temp
514 (list 'quote 'overwrite))))
517 (list 'eshell-as-subcommand
518 (eshell-parse-command cmd))
520 (list 'nconc 'eshell-this-command-hook
524 (list 'delete-file temp))))))
526 (goto-char (1+ end)))))))
527 ((eq (char-after) ?\()
529 (list 'eshell-command-to-value
530 (list 'eshell-lisp-command
531 (list 'quote (read (current-buffer)))))
533 (throw 'eshell-incomplete ?\())))
534 ((assoc (char-to-string (char-after))
535 eshell-variable-aliases-list)
537 (list 'eshell-get-variable
538 (char-to-string (char-before)) 'indices))
539 ((looking-at eshell-variable-name-regexp)
541 (list 'eshell-get-variable (match-string 0) 'indices)
542 (goto-char (match-end 0))))
544 (error "Invalid variable reference")))))
546 (eshell-deftest var interp-cmd
547 "Interpolate command result"
548 (eshell-command-result-p "+ ${+ 1 2} 3" "6\n"))
550 (eshell-deftest var interp-lisp
551 "Interpolate Lisp form evalution"
552 (eshell-command-result-p "+ $(+ 1 2) 3" "6\n"))
554 (eshell-deftest var interp-concat
555 "Interpolate and concat command"
556 (eshell-command-result-p "+ ${+ 1 2}3 3" "36\n"))
558 (eshell-deftest var interp-concat-lisp
559 "Interpolate and concat Lisp form"
560 (eshell-command-result-p "+ $(+ 1 2)3 3" "36\n"))
562 (eshell-deftest var interp-concat2
563 "Interpolate and concat two commands"
564 (eshell-command-result-p "+ ${+ 1 2}${+ 1 2} 3" "36\n"))
566 (eshell-deftest var interp-concat-lisp2
567 "Interpolate and concat two Lisp forms"
568 (eshell-command-result-p "+ $(+ 1 2)$(+ 1 2) 3" "36\n"))
570 (defun eshell-parse-indices ()
571 "Parse and return a list of list of indices."
573 (while (eq (char-after) ?\[)
574 (let ((end (eshell-find-delimiter ?\[ ?\])))
576 (throw 'eshell-incomplete ?\[)
578 (let (eshell-glob-function)
579 (setq indices (cons (eshell-parse-arguments (point) end)
581 (goto-char (1+ end)))))
584 (defun eshell-get-variable (name &optional indices)
585 "Get the value for the variable NAME."
586 (let* ((alias (assoc name eshell-variable-aliases-list))
590 (if (and alias (functionp var))
591 (funcall var indices)
592 (eshell-apply-indices
595 (let ((sym (intern-soft var)))
596 (if (and sym (boundp sym)
597 (or eshell-prefer-lisp-variables
604 (error "Unknown variable `%s'" (eshell-stringify var))))
607 (defun eshell-apply-indices (value indices)
608 "Apply to VALUE all of the given INDICES, returning the sub-result.
609 The format of INDICES is:
611 ((INT-OR-NAME-OR-OTHER INT-OR-NAME INT-OR-NAME ...)
614 Each member of INDICES represents a level of nesting. If the first
615 member of a sublist is not an integer or name, and the value it's
616 reference is a string, that will be used as the regexp with which is
617 to divide the string into sub-parts. The default is whitespace.
618 Otherwise, each INT-OR-NAME refers to an element of the list value.
619 Integers imply a direct index, and names, an associate lookup using
622 For example, to retrieve the second element of a user's record in
623 '/etc/passwd', the variable reference would look like:
625 ${egrep johnw /etc/passwd}[: 2]"
627 (let ((refs (car indices)))
628 (when (stringp value)
630 (if (not (or (not (stringp (caar indices)))
632 (concat "^" eshell-variable-name-regexp "$")
634 (setq separator (caar indices)
637 (mapcar 'eshell-convert
638 (split-string value separator)))))
641 (error "Invalid array variable index: %s"
642 (eshell-stringify refs)))
644 (setq value (eshell-index-value value (car refs))))
646 (let ((new-value (list t)))
649 (list (eshell-index-value value
651 (setq refs (cdr refs)))
652 (setq value (cdr new-value))))))
653 (setq indices (cdr indices)))
656 (defun eshell-index-value (value index)
657 "Reference VALUE using the given INDEX."
659 (cdr (assoc index value))
662 (if (> index (ring-length value))
663 (error "Index exceeds length of ring")
664 (ring-ref value index)))
666 (if (> index (length value))
667 (error "Index exceeds length of list")
670 (if (> index (length value))
671 (error "Index exceeds length of vector")
674 (error "Invalid data type for indexing")))))
676 ;;;_* Variable name completion
678 (defun eshell-complete-variable-reference ()
679 "If there is a variable reference, complete it."
680 (let ((arg (pcomplete-actual-arg)) index)
683 (concat "\\$\\(" eshell-variable-name-regexp
685 (setq pcomplete-stub (substring arg (1+ index)))
686 (throw 'pcomplete-completions (eshell-variables-list)))))
688 (defun eshell-variables-list ()
689 "Generate list of applicable variables."
690 (let ((argname pcomplete-stub)
692 (eshell-for alias eshell-variable-aliases-list
693 (if (string-match (concat "^" argname) (car alias))
694 (setq completions (cons (car alias) completions))))
700 (let ((value (eshell-get-variable varname)))
703 (file-directory-p value))
704 (concat varname (char-to-string directory-sep-char))
706 (eshell-envvar-names (eshell-environment-variables)))
707 (all-completions argname obarray 'boundp)
711 (defun eshell-complete-variable-assignment ()
712 "If there is a variable assignment, allow completion of entries."
713 (let ((arg (pcomplete-actual-arg)) pos)
714 (when (string-match (concat "\\`" eshell-variable-name-regexp "=") arg)
715 (setq pos (match-end 0))
716 (if (string-match "\\(:\\)[^:]*\\'" arg)
717 (setq pos (match-end 1)))
718 (setq pcomplete-stub (substring arg pos))
719 (throw 'pcomplete-completions (pcomplete-entries)))))
723 ;;; esh-var.el ends here