1 ;;; esh-var.el --- handling of variables
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006 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).
126 (defcustom eshell-var-load-hook
'(eshell-var-initialize)
127 "*A list of functions to call when loading `eshell-var'."
131 (defcustom eshell-prefer-lisp-variables nil
132 "*If non-nil, prefer Lisp variables to environment variables."
136 (defcustom eshell-complete-export-definition t
137 "*If non-nil, completing names for `export' shows current definition."
141 (defcustom eshell-modify-global-environment nil
142 "*If non-nil, using `export' changes Emacs's global environment."
146 (defcustom eshell-variable-name-regexp
"[A-Za-z0-9_-]+"
147 "*A regexp identifying what constitutes a variable name reference.
148 Note that this only applies for '$NAME'. If the syntax '$<NAME>' is
149 used, then NAME can contain any character, including angle brackets,
150 if they are quoted with a backslash."
154 (defcustom eshell-variable-aliases-list
156 ("COLUMNS" (lambda (indices) (window-width)) t
)
157 ("LINES" (lambda (indices) (window-height)) t
)
160 ("_" (lambda (indices)
162 (car (last eshell-last-arguments
))
163 (eshell-apply-indices eshell-last-arguments
165 ("?" eshell-last-command-status
)
166 ("$" eshell-last-command-result
)
167 ("0" eshell-command-name
)
168 ("1" (lambda (indices) (nth 0 eshell-command-arguments
)))
169 ("2" (lambda (indices) (nth 1 eshell-command-arguments
)))
170 ("3" (lambda (indices) (nth 2 eshell-command-arguments
)))
171 ("4" (lambda (indices) (nth 3 eshell-command-arguments
)))
172 ("5" (lambda (indices) (nth 4 eshell-command-arguments
)))
173 ("6" (lambda (indices) (nth 5 eshell-command-arguments
)))
174 ("7" (lambda (indices) (nth 6 eshell-command-arguments
)))
175 ("8" (lambda (indices) (nth 7 eshell-command-arguments
)))
176 ("9" (lambda (indices) (nth 8 eshell-command-arguments
)))
177 ("*" (lambda (indices)
179 eshell-command-arguments
180 (eshell-apply-indices eshell-command-arguments
182 "*This list provides aliasing for variable references.
183 It is very similar in concept to what `eshell-user-aliases-list' does
184 for commands. Each member of this defines defines the name of a
185 command, and the Lisp value to return for that variable if it is
186 accessed via the syntax '$NAME'.
188 If the value is a function, that function will be called with two
189 arguments: the list of the indices that was used in the reference, and
190 whether the user is requesting the length of the ultimate element.
191 For example, a reference of '$NAME[10][20]' would result in the
192 function for alias `NAME' being called (assuming it were aliased to a
193 function), and the arguments passed to this function would be the list
195 :type
'(repeat (list string sexp
196 (choice (const :tag
"Copy to environment" t
)
197 (const :tag
"Use only in Eshell" nil
))))
200 (put 'eshell-variable-aliases-list
'risky-local-variable t
)
204 (defun eshell-var-initialize ()
205 "Initialize the variable handle code."
206 ;; Break the association with our parent's environment. Otherwise,
207 ;; changing a variable will affect all of Emacs.
208 (unless eshell-modify-global-environment
209 (set (make-local-variable 'process-environment
)
210 (eshell-copy-environment)))
212 (define-key eshell-command-map
[(meta ?v
)] 'eshell-insert-envvar
)
214 (set (make-local-variable 'eshell-special-chars-inside-quoting
)
215 (append eshell-special-chars-inside-quoting
'(?$
)))
216 (set (make-local-variable 'eshell-special-chars-outside-quoting
)
217 (append eshell-special-chars-outside-quoting
'(?$
)))
219 (add-hook 'eshell-parse-argument-hook
'eshell-interpolate-variable t t
)
221 (add-hook 'eshell-prepare-command-hook
222 'eshell-handle-local-variables nil t
)
224 (when (eshell-using-module 'eshell-cmpl
)
225 (add-hook 'pcomplete-try-first-hook
226 'eshell-complete-variable-reference nil t
)
227 (add-hook 'pcomplete-try-first-hook
228 'eshell-complete-variable-assignment nil t
)))
230 (defun eshell-handle-local-variables ()
231 "Allow for the syntax 'VAR=val <command> <args>'."
232 ;; strip off any null commands, which can only happen if a variable
233 ;; evaluates to nil, such as "$var x", where `var' is nil. The
234 ;; command name in that case becomes `x', for compatibility with
235 ;; most regular shells (the difference is that they do an
236 ;; interpolation pass before the argument parsing pass, but Eshell
237 ;; does both at the same time).
238 (while (and (not eshell-last-command-name
)
239 eshell-last-arguments
)
240 (setq eshell-last-command-name
(car eshell-last-arguments
)
241 eshell-last-arguments
(cdr eshell-last-arguments
)))
242 (let ((setvar "\\`\\([A-Za-z_][A-Za-z0-9_]*\\)=\\(.*\\)\\'")
243 (command (eshell-stringify eshell-last-command-name
))
244 (args eshell-last-arguments
))
245 ;; local variable settings (such as 'CFLAGS=-O2 make') are handled
246 ;; by making the whole command into a subcommand, and calling
247 ;; setenv immediately before the command is invoked. This means
248 ;; that 'BLAH=x cd blah' won't work exactly as expected, but that
249 ;; is by no means a typical use of local environment variables.
250 (if (and command
(string-match setvar command
))
252 'eshell-replace-command
254 'eshell-as-subcommand
258 (while (string-match setvar command
)
261 (list 'setenv
(match-string 1 command
)
262 (match-string 2 command
)
263 (= (length (match-string 2 command
)) 0))))
264 (setq command
(eshell-stringify (car args
))
267 (list (list 'eshell-named-command
268 command
(list 'quote args
)))))))))
270 (defun eshell-interpolate-variable ()
271 "Parse a variable interpolation.
272 This function is explicit for adding to `eshell-parse-argument-hook'."
273 (when (and (eq (char-after) ?$
)
274 (/= (1+ (point)) (point-max)))
276 (list 'eshell-escape-arg
277 (eshell-parse-variable))))
279 (defun eshell/define
(var-alias definition
)
280 "Define a VAR-ALIAS using DEFINITION."
282 (setq eshell-variable-aliases-list
283 (delq (assoc var-alias eshell-variable-aliases-list
)
284 eshell-variable-aliases-list
))
285 (let ((def (assoc var-alias eshell-variable-aliases-list
))
288 (list 'quote
(if (= (length definition
) 1)
292 (setq eshell-variable-aliases-list
293 (delq (assoc var-alias eshell-variable-aliases-list
)
294 eshell-variable-aliases-list
)))
295 (setq eshell-variable-aliases-list
297 eshell-variable-aliases-list
))))
300 (defun eshell/export
(&rest sets
)
301 "This alias allows the `export' command to act as bash users expect."
303 (if (and (stringp (car sets
))
304 (string-match "^\\([^=]+\\)=\\(.*\\)" (car sets
)))
305 (setenv (match-string 1 (car sets
))
306 (match-string 2 (car sets
))))
307 (setq sets
(cdr sets
))))
309 (defun pcomplete/eshell-mode
/export
()
310 "Completion function for Eshell's `export'."
311 (while (pcomplete-here
312 (if eshell-complete-export-definition
314 (eshell-envvar-names)))))
316 (defun eshell/unset
(&rest args
)
317 "Unset an environment variable."
319 (if (stringp (car args
))
320 (setenv (car args
) nil t
))
321 (setq args
(cdr args
))))
323 (defun pcomplete/eshell-mode
/unset
()
324 "Completion function for Eshell's `unset'."
325 (while (pcomplete-here (eshell-envvar-names))))
327 (defun eshell/setq
(&rest args
)
328 "Allow command-ish use of `setq'."
331 (let ((sym (intern (car args
)))
333 (setq last-value
(set sym val
)
337 (defun pcomplete/eshell-mode
/setq
()
338 "Completion function for Eshell's `setq'."
339 (while (and (pcomplete-here (all-completions pcomplete-stub
343 (defun eshell/env
(&rest args
)
344 "Implemention of `env' in Lisp."
345 (eshell-init-print-buffer)
346 (eshell-eval-using-options
348 '((?h
"help" nil nil
"show this usage screen")
350 :usage
"<no arguments>")
351 (eshell-for setting
(sort (eshell-environment-variables)
353 (eshell-buffered-print setting
"\n"))
356 (defun eshell-insert-envvar (envvar-name)
357 "Insert ENVVAR-NAME into the current buffer at point."
359 (list (read-envvar-name "Name of environment variable: " t
)))
360 (insert-and-inherit "$" envvar-name
))
362 (defun eshell-envvar-names (&optional environment
)
363 "Return a list of currently visible environment variable names."
366 (substring x
0 (string-match "=" x
))))
367 (or environment process-environment
)))
369 (defun eshell-environment-variables ()
370 "Return a `process-environment', fully updated.
371 This involves setting any variable aliases which affect the
372 environment, as specified in `eshell-variable-aliases-list'."
373 (let ((process-environment (eshell-copy-environment)))
374 (eshell-for var-alias eshell-variable-aliases-list
375 (if (nth 2 var-alias
)
376 (setenv (car var-alias
)
378 (or (eshell-get-variable (car var-alias
)) "")))))
379 process-environment
))
381 (defun eshell-parse-variable ()
382 "Parse the next variable reference at point.
383 The variable name could refer to either an environment variable, or a
384 Lisp variable. The priority order depends on the setting of
385 `eshell-prefer-lisp-variables'.
387 Its purpose is to call `eshell-parse-variable-ref', and then to
388 process any indices that come after the variable reference."
389 (let* ((get-len (when (eq (char-after) ?
#)
392 (setq value
(eshell-parse-variable-ref)
393 indices
(and (not (eobp))
394 (eq (char-after) ?\
[)
395 (eshell-parse-indices))
398 (list 'quote indices
)))
404 (defun eshell-parse-variable-ref ()
405 "Eval a variable reference.
406 Returns a Lisp form which, if evaluated, will return the value of the
409 Possible options are:
411 NAME an environment or Lisp variable value
412 <LONG-NAME> disambiguates the length of the name
413 {COMMAND} result of command is variable's value
414 (LISP-FORM) result of Lisp form is variable's value"
417 ((eq (char-after) ?
{)
418 (let ((end (eshell-find-delimiter ?\
{ ?\
})))
420 (throw 'eshell-incomplete ?\
{)
422 (list 'eshell-convert
423 (list 'eshell-command-to-value
424 (list 'eshell-as-subcommand
425 (eshell-parse-command
426 (cons (1+ (point)) end
)))))
427 (goto-char (1+ end
))))))
428 ((memq (char-after) '(?
\' ?
\"))
429 (let ((name (if (eq (char-after) ?
\')
430 (eshell-parse-literal-quote)
431 (eshell-parse-double-quote))))
433 (list 'eshell-get-variable
(eval name
) 'indices
))))
434 ((eq (char-after) ?\
<)
435 (let ((end (eshell-find-delimiter ?\
< ?\
>)))
437 (throw 'eshell-incomplete ?\
<)
438 (let* ((temp (make-temp-file temporary-file-directory
))
439 (cmd (concat (buffer-substring (1+ (point)) end
)
443 'let
(list (list 'eshell-current-handles
444 (list 'eshell-create-handles temp
445 (list 'quote
'overwrite
))))
448 (list 'eshell-as-subcommand
449 (eshell-parse-command cmd
))
451 (list 'nconc
'eshell-this-command-hook
455 (list 'delete-file temp
))))))
457 (goto-char (1+ end
)))))))
458 ((eq (char-after) ?\
()
460 (list 'eshell-command-to-value
461 (list 'eshell-lisp-command
462 (list 'quote
(read (current-buffer)))))
464 (throw 'eshell-incomplete ?\
())))
465 ((assoc (char-to-string (char-after))
466 eshell-variable-aliases-list
)
468 (list 'eshell-get-variable
469 (char-to-string (char-before)) 'indices
))
470 ((looking-at eshell-variable-name-regexp
)
472 (list 'eshell-get-variable
(match-string 0) 'indices
)
473 (goto-char (match-end 0))))
475 (error "Invalid variable reference")))))
477 (eshell-deftest var interp-cmd
478 "Interpolate command result"
479 (eshell-command-result-p "+ ${+ 1 2} 3" "6\n"))
481 (eshell-deftest var interp-lisp
482 "Interpolate Lisp form evalution"
483 (eshell-command-result-p "+ $(+ 1 2) 3" "6\n"))
485 (eshell-deftest var interp-concat
486 "Interpolate and concat command"
487 (eshell-command-result-p "+ ${+ 1 2}3 3" "36\n"))
489 (eshell-deftest var interp-concat-lisp
490 "Interpolate and concat Lisp form"
491 (eshell-command-result-p "+ $(+ 1 2)3 3" "36\n"))
493 (eshell-deftest var interp-concat2
494 "Interpolate and concat two commands"
495 (eshell-command-result-p "+ ${+ 1 2}${+ 1 2} 3" "36\n"))
497 (eshell-deftest var interp-concat-lisp2
498 "Interpolate and concat two Lisp forms"
499 (eshell-command-result-p "+ $(+ 1 2)$(+ 1 2) 3" "36\n"))
501 (defun eshell-parse-indices ()
502 "Parse and return a list of list of indices."
504 (while (eq (char-after) ?\
[)
505 (let ((end (eshell-find-delimiter ?\
[ ?\
])))
507 (throw 'eshell-incomplete ?\
[)
509 (let (eshell-glob-function)
510 (setq indices
(cons (eshell-parse-arguments (point) end
)
512 (goto-char (1+ end
)))))
515 (defun eshell-get-variable (name &optional indices
)
516 "Get the value for the variable NAME."
517 (let* ((alias (assoc name eshell-variable-aliases-list
))
521 (if (and alias
(functionp var
))
522 (funcall var indices
)
523 (eshell-apply-indices
526 (let ((sym (intern-soft var
)))
527 (if (and sym
(boundp sym
)
528 (or eshell-prefer-lisp-variables
535 (error "Unknown variable `%s'" (eshell-stringify var
))))
538 (defun eshell-apply-indices (value indices
)
539 "Apply to VALUE all of the given INDICES, returning the sub-result.
540 The format of INDICES is:
542 ((INT-OR-NAME-OR-OTHER INT-OR-NAME INT-OR-NAME ...)
545 Each member of INDICES represents a level of nesting. If the first
546 member of a sublist is not an integer or name, and the value it's
547 reference is a string, that will be used as the regexp with which is
548 to divide the string into sub-parts. The default is whitespace.
549 Otherwise, each INT-OR-NAME refers to an element of the list value.
550 Integers imply a direct index, and names, an associate lookup using
553 For example, to retrieve the second element of a user's record in
554 '/etc/passwd', the variable reference would look like:
556 ${egrep johnw /etc/passwd}[: 2]"
558 (let ((refs (car indices
)))
559 (when (stringp value
)
561 (if (not (or (not (stringp (caar indices
)))
563 (concat "^" eshell-variable-name-regexp
"$")
565 (setq separator
(caar indices
)
568 (mapcar 'eshell-convert
569 (split-string value separator
)))))
572 (error "Invalid array variable index: %s"
573 (eshell-stringify refs
)))
575 (setq value
(eshell-index-value value
(car refs
))))
577 (let ((new-value (list t
)))
580 (list (eshell-index-value value
582 (setq refs
(cdr refs
)))
583 (setq value
(cdr new-value
))))))
584 (setq indices
(cdr indices
)))
587 (defun eshell-index-value (value index
)
588 "Reference VALUE using the given INDEX."
590 (cdr (assoc index value
))
593 (if (> index
(ring-length value
))
594 (error "Index exceeds length of ring")
595 (ring-ref value index
)))
597 (if (> index
(length value
))
598 (error "Index exceeds length of list")
601 (if (> index
(length value
))
602 (error "Index exceeds length of vector")
605 (error "Invalid data type for indexing")))))
607 ;;;_* Variable name completion
609 (defun eshell-complete-variable-reference ()
610 "If there is a variable reference, complete it."
611 (let ((arg (pcomplete-actual-arg)) index
)
614 (concat "\\$\\(" eshell-variable-name-regexp
616 (setq pcomplete-stub
(substring arg
(1+ index
)))
617 (throw 'pcomplete-completions
(eshell-variables-list)))))
619 (defun eshell-variables-list ()
620 "Generate list of applicable variables."
621 (let ((argname pcomplete-stub
)
623 (eshell-for alias eshell-variable-aliases-list
624 (if (string-match (concat "^" argname
) (car alias
))
625 (setq completions
(cons (car alias
) completions
))))
631 (let ((value (eshell-get-variable varname
)))
634 (file-directory-p value
))
637 (eshell-envvar-names (eshell-environment-variables)))
638 (all-completions argname obarray
'boundp
)
642 (defun eshell-complete-variable-assignment ()
643 "If there is a variable assignment, allow completion of entries."
644 (let ((arg (pcomplete-actual-arg)) pos
)
645 (when (string-match (concat "\\`" eshell-variable-name-regexp
"=") arg
)
646 (setq pos
(match-end 0))
647 (if (string-match "\\(:\\)[^:]*\\'" arg
)
648 (setq pos
(match-end 1)))
649 (setq pcomplete-stub
(substring arg pos
))
650 (throw 'pcomplete-completions
(pcomplete-entries)))))
654 ;;; arch-tag: 393654fe-bdad-4f27-9a10-b1472ded14cf
655 ;;; esh-var.el ends here