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 (not (= (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 (string-match "^\\([^=]+\\)=\\(.*\\)" (car sets
))
297 (setenv (match-string 1 (car sets
))
298 (match-string 2 (car sets
))))
299 (setq sets
(cdr sets
))))
301 (defun pcomplete/eshell-mode
/export
()
302 "Completion function for Eshell's `export'."
303 (while (pcomplete-here
304 (if eshell-complete-export-definition
306 (eshell-envvar-names)))))
308 (defun eshell/setq
(&rest args
)
309 "Allow command-ish use of `setq'."
312 (let ((sym (intern (car args
)))
314 (setq last-value
(set sym val
)
318 (defun pcomplete/eshell-mode
/setq
()
319 "Completion function for Eshell's `setq'."
320 (while (and (pcomplete-here (all-completions pcomplete-stub
324 (defun eshell/env
(&rest args
)
325 "Implemention of `env' in Lisp."
326 (eshell-init-print-buffer)
327 (eshell-eval-using-options
329 '((?h
"help" nil nil
"show this usage screen")
331 :usage
"<no arguments>")
332 (eshell-for setting
(sort (eshell-environment-variables)
334 (eshell-buffered-print setting
"\n"))
337 (defun eshell-insert-envvar (envvar-name)
338 "Insert ENVVAR-NAME into the current buffer at point."
340 (list (read-envvar-name "Name of environment variable: " t
)))
341 (insert-and-inherit "$" envvar-name
))
343 (defun eshell-envvar-names (&optional environment
)
344 "Return a list of currently visible environment variable names."
347 (substring x
0 (string-match "=" x
))))
348 (or environment process-environment
)))
350 (defun eshell-environment-variables ()
351 "Return a `process-environment', fully updated.
352 This involves setting any variable aliases which affect the
353 environment, as specified in `eshell-variable-aliases-list'."
354 (let ((process-environment (eshell-copy-environment)))
355 (eshell-for var-alias eshell-variable-aliases-list
356 (if (nth 2 var-alias
)
357 (setenv (car var-alias
)
359 (or (eshell-get-variable (car var-alias
)) "")))))
360 process-environment
))
362 (defun eshell-parse-variable ()
363 "Parse the next variable reference at point.
364 The variable name could refer to either an environment variable, or a
365 Lisp variable. The priority order depends on the setting of
366 `eshell-prefer-lisp-variables'.
368 Its purpose is to call `eshell-parse-variable-ref', and then to
369 process any indices that come after the variable reference."
370 (let* ((get-len (when (eq (char-after) ?
#)
373 (setq value
(eshell-parse-variable-ref)
374 indices
(and (not (eobp))
375 (eq (char-after) ?\
[)
376 (eshell-parse-indices))
379 (list 'quote indices
)))
385 (defun eshell-parse-variable-ref ()
386 "Eval a variable reference.
387 Returns a Lisp form which, if evaluated, will return the value of the
390 Possible options are:
392 NAME an environment or Lisp variable value
393 <LONG-NAME> disambiguates the length of the name
394 {COMMAND} result of command is variable's value
395 (LISP-FORM) result of Lisp form is variable's value"
398 ((eq (char-after) ?
{)
399 (let ((end (eshell-find-delimiter ?\
{ ?\
})))
401 (throw 'eshell-incomplete ?\
{)
403 (list 'eshell-convert
404 (list 'eshell-command-to-value
405 (list 'eshell-as-subcommand
406 (eshell-parse-command
407 (cons (1+ (point)) end
)))))
408 (goto-char (1+ end
))))))
409 ((memq (char-after) '(?
\' ?
\"))
410 (let ((name (if (eq (char-after) ?
\')
411 (eshell-parse-literal-quote)
412 (eshell-parse-double-quote))))
414 (list 'eshell-get-variable
(eval name
) 'indices
))))
415 ((eq (char-after) ?
<)
416 (let ((end (eshell-find-delimiter ?\
< ?\
>)))
418 (throw 'eshell-incomplete ?\
<)
419 (let* ((temp (make-temp-name temporary-file-directory
))
420 (cmd (concat (buffer-substring (1+ (point)) end
)
424 'let
(list (list 'eshell-current-handles
425 (list 'eshell-create-handles temp
426 (list 'quote
'overwrite
))))
429 (list 'eshell-as-subcommand
430 (eshell-parse-command cmd
))
432 (list 'nconc
'eshell-this-command-hook
436 (list 'delete-file temp
))))))
438 (goto-char (1+ end
)))))))
439 ((eq (char-after) ?\
()
441 (list 'eshell-command-to-value
442 (list 'eshell-lisp-command
443 (list 'quote
(read (current-buffer)))))
445 (throw 'eshell-incomplete ?\
())))
446 ((assoc (char-to-string (char-after))
447 eshell-variable-aliases-list
)
449 (list 'eshell-get-variable
450 (char-to-string (char-before)) 'indices
))
451 ((looking-at eshell-variable-name-regexp
)
453 (list 'eshell-get-variable
(match-string 0) 'indices
)
454 (goto-char (match-end 0))))
456 (error "Invalid variable reference")))))
458 (eshell-deftest var interp-cmd
459 "Interpolate command result"
460 (eshell-command-result-p "+ ${+ 1 2} 3" "6\n"))
462 (eshell-deftest var interp-lisp
463 "Interpolate Lisp form evalution"
464 (eshell-command-result-p "+ $(+ 1 2) 3" "6\n"))
466 (eshell-deftest var interp-concat
467 "Interpolate and concat command"
468 (eshell-command-result-p "+ ${+ 1 2}3 3" "36\n"))
470 (eshell-deftest var interp-concat-lisp
471 "Interpolate and concat Lisp form"
472 (eshell-command-result-p "+ $(+ 1 2)3 3" "36\n"))
474 (eshell-deftest var interp-concat2
475 "Interpolate and concat two commands"
476 (eshell-command-result-p "+ ${+ 1 2}${+ 1 2} 3" "36\n"))
478 (eshell-deftest var interp-concat-lisp2
479 "Interpolate and concat two Lisp forms"
480 (eshell-command-result-p "+ $(+ 1 2)$(+ 1 2) 3" "36\n"))
482 (defun eshell-parse-indices ()
483 "Parse and return a list of list of indices."
485 (while (eq (char-after) ?\
[)
486 (let ((end (eshell-find-delimiter ?\
[ ?\
])))
488 (throw 'eshell-incomplete ?\
[)
490 (let (eshell-glob-function)
491 (setq indices
(cons (eshell-parse-arguments (point) end
)
493 (goto-char (1+ end
)))))
496 (defun eshell-get-variable (name &optional indices
)
497 "Get the value for the variable NAME."
498 (let* ((alias (assoc name eshell-variable-aliases-list
))
502 (if (and alias
(functionp var
))
503 (funcall var indices
)
504 (eshell-apply-indices
507 (let ((sym (intern-soft var
)))
508 (if (and sym
(boundp sym
)
509 (or eshell-prefer-lisp-variables
516 (error "Unknown variable `%s'" (eshell-stringify var
))))
519 (defun eshell-apply-indices (value indices
)
520 "Apply to VALUE all of the given INDICES, returning the sub-result.
521 The format of INDICES is:
523 ((INT-OR-NAME-OR-OTHER INT-OR-NAME INT-OR-NAME ...)
526 Each member of INDICES represents a level of nesting. If the first
527 member of a sublist is not an integer or name, and the value it's
528 reference is a string, that will be used as the regexp with which is
529 to divide the string into sub-parts. The default is whitespace.
530 Otherwise, each INT-OR-NAME refers to an element of the list value.
531 Integers imply a direct index, and names, an associate lookup using
534 For example, to retrieve the second element of a user's record in
535 '/etc/passwd', the variable reference would look like:
537 ${egrep johnw /etc/passwd}[: 2]"
539 (let ((refs (car indices
)))
540 (when (stringp value
)
542 (if (not (or (not (stringp (caar indices
)))
544 (concat "^" eshell-variable-name-regexp
"$")
546 (setq separator
(caar indices
)
549 (mapcar 'eshell-convert
550 (split-string value separator
)))))
553 (error "Illegal array variable index: %s"
554 (eshell-stringify refs
)))
556 (setq value
(eshell-index-value value
(car refs
))))
558 (let ((new-value (list t
)))
561 (list (eshell-index-value value
563 (setq refs
(cdr refs
)))
564 (setq value
(cdr new-value
))))))
565 (setq indices
(cdr indices
)))
568 (defun eshell-index-value (value index
)
569 "Reference VALUE using the given INDEX."
571 (cdr (assoc index value
))
574 (if (> index
(ring-length value
))
575 (error "Index exceeds length of ring")
576 (ring-ref value index
)))
578 (if (> index
(length value
))
579 (error "Index exceeds length of list")
582 (if (> index
(length value
))
583 (error "Index exceeds length of vector")
586 (error "Invalid data type for indexing")))))
588 ;;;_* Variable name completion
590 (defun eshell-complete-variable-reference ()
591 "If there is a variable reference, complete it."
592 (let ((arg (pcomplete-actual-arg)) index
)
595 (concat "\\$\\(" eshell-variable-name-regexp
597 (setq pcomplete-stub
(substring arg
(1+ index
)))
598 (throw 'pcomplete-completions
(eshell-variables-list)))))
600 (defun eshell-variables-list ()
601 "Generate list of applicable variables."
602 (let ((argname pcomplete-stub
)
604 (eshell-for alias eshell-variable-aliases-list
605 (if (string-match (concat "^" argname
) (car alias
))
606 (setq completions
(cons (car alias
) completions
))))
612 (let ((value (eshell-get-variable varname
)))
615 (file-directory-p value
))
616 (concat varname
(char-to-string directory-sep-char
))
618 (eshell-envvar-names (eshell-environment-variables)))
619 (all-completions argname obarray
'boundp
)
623 (defun eshell-complete-variable-assignment ()
624 "If there is a variable assignment, allow completion of entries."
625 (let ((arg (pcomplete-actual-arg)) pos
)
626 (when (string-match (concat "\\`" eshell-variable-name-regexp
"=") arg
)
627 (setq pos
(match-end 0))
628 (if (string-match "\\(:\\)[^:]*\\'" arg
)
629 (setq pos
(match-end 1)))
630 (setq pcomplete-stub
(substring arg pos
))
631 (throw 'pcomplete-completions
(pcomplete-entries)))))
635 ;;; esh-var.el ends here