1 ;;; esh-var --- handling of variables
3 ;; Copyright (C) 1999, 2000 Free Software Foundation
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING. If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
24 (eval-when-compile (require 'esh-maint
))
26 (defgroup eshell-var nil
27 "Variable interpolation is introduced whenever the '$' character
28 appears unquoted in any argument (except when that argument is
29 surrounded by single quotes) . It may be used to interpolate a
30 variable value, a subcommand, or even the result of a Lisp form."
31 :tag
"Variable handling"
36 ;; These are the possible variable interpolation syntaxes. Also keep
37 ;; in mind that if an argument looks like a number, it will be
38 ;; converted to a number. This is not significant when invoking
39 ;; external commands, but it's important when calling Lisp functions.
43 ;; Interval the value of an environment variable, or a Lisp variable
47 ;; "-" is a legal part of a variable name.
51 ;; Only "MYVAR" is part of the variable name in this case.
55 ;; Returns the length of the value of VARIABLE. This could also be
56 ;; done using the `length' Lisp function.
60 ;; Returns result of lisp evaluation. Note: Used alone like this, it
61 ;; is identical to just saying (lisp); but with the variable expansion
62 ;; form, the result may be interpolated a larger string, such as
67 ;; Returns the value of an eshell subcommand. See the note above
68 ;; regarding Lisp evaluations.
72 ;; Return the 10th element of ANYVAR. If ANYVAR's value is a string,
73 ;; it will be split in order to make it a list. The splitting will
74 ;; occur at whitespace.
78 ;; As above, except that splitting occurs at the colon now.
82 ;; As above, but instead of returning just a string, it now returns a
83 ;; list of two strings. If the result is being interpolated into a
84 ;; larger string, this list will be flattened into one big string,
85 ;; with each element separated by a space.
89 ;; Separate on backslash characters. Actually, the first argument --
90 ;; if it doesn't have the form of a number, or a plain variable name
91 ;; -- can be any regular expression. So to split on numbers, use
92 ;; '$ANYVAR["[0-9]+" 10 20]'.
96 ;; Calls `assoc' on ANYVAR with 'hello', expecting it to be an alist.
100 ;; Returns the length of the cdr of the element of ANYVAR who car is
103 ;; There are also a few special variables defined by Eshell. '$$' is
104 ;; the value of the last command (t or nil, in the case of an external
105 ;; command). This makes it possible to chain results:
107 ;; /tmp $ echo /var/spool/mail/johnw
108 ;; /var/spool/mail/johnw
114 ;; '$_' refers to the last argument of the last command. And $?
115 ;; contains the exit code of the last command (0 or 1 for Lisp
116 ;; functions, based on successful completion).
123 (defcustom eshell-var-load-hook
'(eshell-var-initialize)
124 "*A list of functions to call when loading `eshell-var'."
128 (defcustom eshell-prefer-lisp-variables nil
129 "*If non-nil, prefer Lisp variables to environment variables."
133 (defcustom eshell-complete-export-definition t
134 "*If non-nil, completing names for `export' shows current definition."
138 (defcustom eshell-variable-name-regexp
"[A-Za-z0-9_-]+"
139 "*A regexp identifying what constitutes a variable name reference.
140 Note that this only applies for '$NAME'. If the syntax '$<NAME>' is
141 used, then NAME can contain any character, including angle brackets,
142 if they are quoted with a backslash."
146 (defcustom eshell-variable-aliases-list
148 ("COLUMNS" (lambda (indices) (window-width)) t
)
149 ("LINES" (lambda (indices) (window-height)) t
)
152 ("_" (lambda (indices)
154 (car (last eshell-last-arguments
))
155 (eshell-apply-indices eshell-last-arguments
157 ("?" eshell-last-command-status
)
158 ("$" eshell-last-command-result
)
159 ("0" eshell-command-name
)
160 ("1" (lambda (indices) (nth 0 eshell-command-arguments
)))
161 ("2" (lambda (indices) (nth 1 eshell-command-arguments
)))
162 ("3" (lambda (indices) (nth 2 eshell-command-arguments
)))
163 ("4" (lambda (indices) (nth 3 eshell-command-arguments
)))
164 ("5" (lambda (indices) (nth 4 eshell-command-arguments
)))
165 ("6" (lambda (indices) (nth 5 eshell-command-arguments
)))
166 ("7" (lambda (indices) (nth 6 eshell-command-arguments
)))
167 ("8" (lambda (indices) (nth 7 eshell-command-arguments
)))
168 ("9" (lambda (indices) (nth 8 eshell-command-arguments
)))
169 ("*" (lambda (indices)
171 eshell-command-arguments
172 (eshell-apply-indices eshell-command-arguments
174 "*This list provides aliasing for variable references.
175 It is very similar in concept to what `eshell-user-aliases-list' does
176 for commands. Each member of this defines defines the name of a
177 command, and the Lisp value to return for that variable if it is
178 accessed via the syntax '$NAME'.
180 If the value is a function, that function will be called with two
181 arguments: the list of the indices that was used in the reference, and
182 whether the user is requesting the length of the ultimate element.
183 For example, a reference of '$NAME[10][20]' would result in the
184 function for alias `NAME' being called (assuming it were aliased to a
185 function), and the arguments passed to this function would be the list
187 :type
'(repeat (list string sexp
188 (choice (const :tag
"Copy to environment" t
)
189 (const :tag
"Use only in Eshell" nil
))))
192 (put 'eshell-variable-aliases-list
'risky-local-variable t
)
196 (defun eshell-var-initialize ()
197 "Initialize the variable handle code."
198 ;; Break the association with our parent's environment. Otherwise,
199 ;; changing a variable will affect all of Emacs.
200 (set (make-local-variable 'process-environment
) (eshell-copy-environment))
202 (define-key eshell-command-map
[(meta ?v
)] 'eshell-insert-envvar
)
204 (set (make-local-variable 'eshell-special-chars-inside-quoting
)
205 (append eshell-special-chars-inside-quoting
'(?$
)))
206 (set (make-local-variable 'eshell-special-chars-outside-quoting
)
207 (append eshell-special-chars-outside-quoting
'(?$
)))
209 (make-local-hook 'eshell-parse-argument-hook
)
210 (add-hook 'eshell-parse-argument-hook
'eshell-interpolate-variable t t
)
212 (make-local-hook 'eshell-prepare-command-hook
)
213 (add-hook 'eshell-prepare-command-hook
214 'eshell-handle-local-variables nil t
)
216 (when (eshell-using-module 'eshell-cmpl
)
217 (make-local-hook 'pcomplete-try-first-hook
)
218 (add-hook 'pcomplete-try-first-hook
219 'eshell-complete-variable-reference nil t
)
220 (add-hook 'pcomplete-try-first-hook
221 'eshell-complete-variable-assignment nil t
)))
223 (defun eshell-handle-local-variables ()
224 "Allow for the syntax 'VAR=val <command> <args>'."
225 ;; strip off any null commands, which can only happen if a variable
226 ;; evaluates to nil, such as "$var x", where `var' is nil. The
227 ;; command name in that case becomes `x', for compatibility with
228 ;; most regular shells (the difference is that they do an
229 ;; interpolation pass before the argument parsing pass, but Eshell
230 ;; does both at the same time).
231 (while (and (not eshell-last-command-name
)
232 eshell-last-arguments
)
233 (setq eshell-last-command-name
(car eshell-last-arguments
)
234 eshell-last-arguments
(cdr eshell-last-arguments
)))
235 (let ((setvar "\\`\\([A-Za-z_][A-Za-z0-9_]*\\)=\\(.*\\)\\'")
236 (command (eshell-stringify eshell-last-command-name
))
237 (args eshell-last-arguments
))
238 ;; local variable settings (such as 'CFLAGS=-O2 make') are handled
239 ;; by making the whole command into a subcommand, and calling
240 ;; setenv immediately before the command is invoked. This means
241 ;; that 'BLAH=x cd blah' won't work exactly as expected, but that
242 ;; is by no means a typical use of local environment variables.
243 (if (and command
(string-match setvar command
))
245 'eshell-replace-command
247 'eshell-as-subcommand
251 (while (string-match setvar command
)
254 (list 'setenv
(match-string 1 command
)
255 (match-string 2 command
)
256 (= (length (match-string 2 command
)) 0))))
257 (setq command
(eshell-stringify (car args
))
260 (list (list 'eshell-named-command
261 command
(list 'quote args
)))))))))
263 (defun eshell-interpolate-variable ()
264 "Parse a variable interpolation.
265 This function is explicit for adding to `eshell-parse-argument-hook'."
266 (when (and (eq (char-after) ?$
)
267 (/= (1+ (point)) (point-max)))
269 (list 'eshell-escape-arg
270 (eshell-parse-variable))))
272 (defun eshell/define
(var-alias definition
)
273 "Define an VAR-ALIAS using DEFINITION."
275 (setq eshell-variable-aliases-list
276 (delq (assoc var-alias eshell-variable-aliases-list
)
277 eshell-variable-aliases-list
))
278 (let ((def (assoc var-alias eshell-variable-aliases-list
))
281 (list 'quote
(if (= (length definition
) 1)
285 (setq eshell-variable-aliases-list
286 (delq (assoc var-alias eshell-variable-aliases-list
)
287 eshell-variable-aliases-list
)))
288 (setq eshell-variable-aliases-list
290 eshell-variable-aliases-list
))))
293 (defun eshell/export
(&rest sets
)
294 "This alias allows the 'export' command to act as bash users expect."
296 (if (and (stringp (car sets
))
297 (string-match "^\\([^=]+\\)=\\(.*\\)" (car sets
)))
298 (setenv (match-string 1 (car sets
))
299 (match-string 2 (car sets
))))
300 (setq sets
(cdr sets
))))
302 (defun pcomplete/eshell-mode
/export
()
303 "Completion function for Eshell's `export'."
304 (while (pcomplete-here
305 (if eshell-complete-export-definition
307 (eshell-envvar-names)))))
309 (defun eshell/unset
(&rest args
)
310 "Unset an environment variable."
312 (if (stringp (car args
))
313 (setenv (car args
) nil t
))
314 (setq args
(cdr args
))))
316 (defun pcomplete/eshell-mode
/unset
()
317 "Completion function for Eshell's `unset'."
318 (while (pcomplete-here (eshell-envvar-names))))
320 (defun eshell/setq
(&rest args
)
321 "Allow command-ish use of `setq'."
324 (let ((sym (intern (car args
)))
326 (setq last-value
(set sym val
)
330 (defun pcomplete/eshell-mode
/setq
()
331 "Completion function for Eshell's `setq'."
332 (while (and (pcomplete-here (all-completions pcomplete-stub
336 (defun eshell/env
(&rest args
)
337 "Implemention of `env' in Lisp."
338 (eshell-init-print-buffer)
339 (eshell-eval-using-options
341 '((?h
"help" nil nil
"show this usage screen")
343 :usage
"<no arguments>")
344 (eshell-for setting
(sort (eshell-environment-variables)
346 (eshell-buffered-print setting
"\n"))
349 (defun eshell-insert-envvar (envvar-name)
350 "Insert ENVVAR-NAME into the current buffer at point."
352 (list (read-envvar-name "Name of environment variable: " t
)))
353 (insert-and-inherit "$" envvar-name
))
355 (defun eshell-envvar-names (&optional environment
)
356 "Return a list of currently visible environment variable names."
359 (substring x
0 (string-match "=" x
))))
360 (or environment process-environment
)))
362 (defun eshell-environment-variables ()
363 "Return a `process-environment', fully updated.
364 This involves setting any variable aliases which affect the
365 environment, as specified in `eshell-variable-aliases-list'."
366 (let ((process-environment (eshell-copy-environment)))
367 (eshell-for var-alias eshell-variable-aliases-list
368 (if (nth 2 var-alias
)
369 (setenv (car var-alias
)
371 (or (eshell-get-variable (car var-alias
)) "")))))
372 process-environment
))
374 (defun eshell-parse-variable ()
375 "Parse the next variable reference at point.
376 The variable name could refer to either an environment variable, or a
377 Lisp variable. The priority order depends on the setting of
378 `eshell-prefer-lisp-variables'.
380 Its purpose is to call `eshell-parse-variable-ref', and then to
381 process any indices that come after the variable reference."
382 (let* ((get-len (when (eq (char-after) ?
#)
385 (setq value
(eshell-parse-variable-ref)
386 indices
(and (not (eobp))
387 (eq (char-after) ?\
[)
388 (eshell-parse-indices))
391 (list 'quote indices
)))
397 (defun eshell-parse-variable-ref ()
398 "Eval a variable reference.
399 Returns a Lisp form which, if evaluated, will return the value of the
402 Possible options are:
404 NAME an environment or Lisp variable value
405 <LONG-NAME> disambiguates the length of the name
406 {COMMAND} result of command is variable's value
407 (LISP-FORM) result of Lisp form is variable's value"
410 ((eq (char-after) ?
{)
411 (let ((end (eshell-find-delimiter ?\
{ ?\
})))
413 (throw 'eshell-incomplete ?\
{)
415 (list 'eshell-convert
416 (list 'eshell-command-to-value
417 (list 'eshell-as-subcommand
418 (eshell-parse-command
419 (cons (1+ (point)) end
)))))
420 (goto-char (1+ end
))))))
421 ((memq (char-after) '(?
\' ?
\"))
422 (let ((name (if (eq (char-after) ?
\')
423 (eshell-parse-literal-quote)
424 (eshell-parse-double-quote))))
426 (list 'eshell-get-variable
(eval name
) 'indices
))))
427 ((eq (char-after) ?
<)
428 (let ((end (eshell-find-delimiter ?\
< ?\
>)))
430 (throw 'eshell-incomplete ?\
<)
431 (let* ((temp (make-temp-name temporary-file-directory
))
432 (cmd (concat (buffer-substring (1+ (point)) end
)
436 'let
(list (list 'eshell-current-handles
437 (list 'eshell-create-handles temp
438 (list 'quote
'overwrite
))))
441 (list 'eshell-as-subcommand
442 (eshell-parse-command cmd
))
444 (list 'nconc
'eshell-this-command-hook
448 (list 'delete-file temp
))))))
450 (goto-char (1+ end
)))))))
451 ((eq (char-after) ?\
()
453 (list 'eshell-command-to-value
454 (list 'eshell-lisp-command
455 (list 'quote
(read (current-buffer)))))
457 (throw 'eshell-incomplete ?\
())))
458 ((assoc (char-to-string (char-after))
459 eshell-variable-aliases-list
)
461 (list 'eshell-get-variable
462 (char-to-string (char-before)) 'indices
))
463 ((looking-at eshell-variable-name-regexp
)
465 (list 'eshell-get-variable
(match-string 0) 'indices
)
466 (goto-char (match-end 0))))
468 (error "Invalid variable reference")))))
470 (eshell-deftest var interp-cmd
471 "Interpolate command result"
472 (eshell-command-result-p "+ ${+ 1 2} 3" "6\n"))
474 (eshell-deftest var interp-lisp
475 "Interpolate Lisp form evalution"
476 (eshell-command-result-p "+ $(+ 1 2) 3" "6\n"))
478 (eshell-deftest var interp-concat
479 "Interpolate and concat command"
480 (eshell-command-result-p "+ ${+ 1 2}3 3" "36\n"))
482 (eshell-deftest var interp-concat-lisp
483 "Interpolate and concat Lisp form"
484 (eshell-command-result-p "+ $(+ 1 2)3 3" "36\n"))
486 (eshell-deftest var interp-concat2
487 "Interpolate and concat two commands"
488 (eshell-command-result-p "+ ${+ 1 2}${+ 1 2} 3" "36\n"))
490 (eshell-deftest var interp-concat-lisp2
491 "Interpolate and concat two Lisp forms"
492 (eshell-command-result-p "+ $(+ 1 2)$(+ 1 2) 3" "36\n"))
494 (defun eshell-parse-indices ()
495 "Parse and return a list of list of indices."
497 (while (eq (char-after) ?\
[)
498 (let ((end (eshell-find-delimiter ?\
[ ?\
])))
500 (throw 'eshell-incomplete ?\
[)
502 (let (eshell-glob-function)
503 (setq indices
(cons (eshell-parse-arguments (point) end
)
505 (goto-char (1+ end
)))))
508 (defun eshell-get-variable (name &optional indices
)
509 "Get the value for the variable NAME."
510 (let* ((alias (assoc name eshell-variable-aliases-list
))
514 (if (and alias
(functionp var
))
515 (funcall var indices
)
516 (eshell-apply-indices
519 (let ((sym (intern-soft var
)))
520 (if (and sym
(boundp sym
)
521 (or eshell-prefer-lisp-variables
528 (error "Unknown variable `%s'" (eshell-stringify var
))))
531 (defun eshell-apply-indices (value indices
)
532 "Apply to VALUE all of the given INDICES, returning the sub-result.
533 The format of INDICES is:
535 ((INT-OR-NAME-OR-OTHER INT-OR-NAME INT-OR-NAME ...)
538 Each member of INDICES represents a level of nesting. If the first
539 member of a sublist is not an integer or name, and the value it's
540 reference is a string, that will be used as the regexp with which is
541 to divide the string into sub-parts. The default is whitespace.
542 Otherwise, each INT-OR-NAME refers to an element of the list value.
543 Integers imply a direct index, and names, an associate lookup using
546 For example, to retrieve the second element of a user's record in
547 '/etc/passwd', the variable reference would look like:
549 ${egrep johnw /etc/passwd}[: 2]"
551 (let ((refs (car indices
)))
552 (when (stringp value
)
554 (if (not (or (not (stringp (caar indices
)))
556 (concat "^" eshell-variable-name-regexp
"$")
558 (setq separator
(caar indices
)
561 (mapcar 'eshell-convert
562 (split-string value separator
)))))
565 (error "Illegal array variable index: %s"
566 (eshell-stringify refs
)))
568 (setq value
(eshell-index-value value
(car refs
))))
570 (let ((new-value (list t
)))
573 (list (eshell-index-value value
575 (setq refs
(cdr refs
)))
576 (setq value
(cdr new-value
))))))
577 (setq indices
(cdr indices
)))
580 (defun eshell-index-value (value index
)
581 "Reference VALUE using the given INDEX."
583 (cdr (assoc index value
))
586 (if (> index
(ring-length value
))
587 (error "Index exceeds length of ring")
588 (ring-ref value index
)))
590 (if (> index
(length value
))
591 (error "Index exceeds length of list")
594 (if (> index
(length value
))
595 (error "Index exceeds length of vector")
598 (error "Invalid data type for indexing")))))
600 ;;;_* Variable name completion
602 (defun eshell-complete-variable-reference ()
603 "If there is a variable reference, complete it."
604 (let ((arg (pcomplete-actual-arg)) index
)
607 (concat "\\$\\(" eshell-variable-name-regexp
609 (setq pcomplete-stub
(substring arg
(1+ index
)))
610 (throw 'pcomplete-completions
(eshell-variables-list)))))
612 (defun eshell-variables-list ()
613 "Generate list of applicable variables."
614 (let ((argname pcomplete-stub
)
616 (eshell-for alias eshell-variable-aliases-list
617 (if (string-match (concat "^" argname
) (car alias
))
618 (setq completions
(cons (car alias
) completions
))))
624 (let ((value (eshell-get-variable varname
)))
627 (file-directory-p value
))
628 (concat varname
(char-to-string directory-sep-char
))
630 (eshell-envvar-names (eshell-environment-variables)))
631 (all-completions argname obarray
'boundp
)
635 (defun eshell-complete-variable-assignment ()
636 "If there is a variable assignment, allow completion of entries."
637 (let ((arg (pcomplete-actual-arg)) pos
)
638 (when (string-match (concat "\\`" eshell-variable-name-regexp
"=") arg
)
639 (setq pos
(match-end 0))
640 (if (string-match "\\(:\\)[^:]*\\'" arg
)
641 (setq pos
(match-end 1)))
642 (setq pcomplete-stub
(substring arg pos
))
643 (throw 'pcomplete-completions
(pcomplete-entries)))))
647 ;;; esh-var.el ends here