Remove old and crusty Sun pkg
[packages] / xemacs-packages / eshell / esh-var.el
1 ;;; esh-var.el --- handling of variables
2
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: John Wiegley <johnw@gnu.org>
7
8 ;; This file is part of GNU Emacs.
9
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)
13 ;; any later version.
14
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.
19
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.
24
25 (provide 'esh-var)
26
27 (eval-when-compile (require 'esh-maint))
28
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"
35   :group 'eshell)
36
37 ;;; Commentary:
38
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.
43 ;;
44 ;;   $VARIABLE
45 ;;
46 ;; Interval the value of an environment variable, or a Lisp variable
47 ;;
48 ;;   $ALSO-VAR
49 ;;
50 ;; "-" is a legal part of a variable name.
51 ;;
52 ;;   $<MYVAR>-TOO
53 ;;
54 ;; Only "MYVAR" is part of the variable name in this case.
55 ;;
56 ;;   $#VARIABLE
57 ;;
58 ;; Returns the length of the value of VARIABLE.  This could also be
59 ;; done using the `length' Lisp function.
60 ;;
61 ;;   $(lisp)
62 ;;
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
66 ;; '$(lisp)/other'.
67 ;;
68 ;;   ${command}
69 ;;
70 ;; Returns the value of an eshell subcommand.  See the note above
71 ;; regarding Lisp evaluations.
72 ;;
73 ;;   $ANYVAR[10]
74 ;;
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.
78 ;;
79 ;;   $ANYVAR[: 10]
80 ;;
81 ;; As above, except that splitting occurs at the colon now.
82 ;;
83 ;;   $ANYVAR[: 10 20]
84 ;;
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.
89 ;;
90 ;;   $ANYVAR["\\\\" 10]
91 ;;
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]'.
96 ;;
97 ;;   $ANYVAR[hello]
98 ;;
99 ;; Calls `assoc' on ANYVAR with 'hello', expecting it to be an alist.
100 ;;
101 ;;   $#ANYVAR[hello]
102 ;;
103 ;; Returns the length of the cdr of the element of ANYVAR who car is
104 ;; equal to "hello".
105 ;;
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:
109 ;;
110 ;;   /tmp $ echo /var/spool/mail/johnw
111 ;;   /var/spool/mail/johnw
112 ;;   /tmp $ dirname $$
113 ;;   /var/spool/mail/
114 ;;   /tmp $ cd $$
115 ;;   /var/spool/mail $
116 ;;
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).
120
121 (require 'env)
122 (require 'ring)
123
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.
131
132 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
133
134 If SUFFIX is non-nil, add that at the end of the file name."
135     (let ((umask (default-file-modes))
136           file)
137       (unwind-protect
138           (progn
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
144                        (progn
145                          (setq file
146                                (make-temp-name
147                                 (expand-file-name
148                                  prefix
149                                  (if (fboundp 'temp-directory)
150                                      ;; XEmacs
151                                      (temp-directory)
152                                    temporary-file-directory))))
153                          (if suffix
154                              (setq file (concat file suffix)))
155                          (if dir-flag
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
167                                            nil 'excl)))
168                          nil)
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.
178               nil)
179             file)
180         ;; Reset the umask.
181         (set-default-file-modes umask))))
182
183 (defalias 'esh-make-temp-file
184   (or (and (fboundp 'make-temp-file) 'make-temp-file)
185    'esh-make-temp-file-1))
186
187 ;;; User Variables:
188
189 (defcustom eshell-var-load-hook '(eshell-var-initialize)
190   "*A list of functions to call when loading `eshell-var'."
191   :type 'hook
192   :group 'eshell-var)
193
194 (defcustom eshell-prefer-lisp-variables nil
195   "*If non-nil, prefer Lisp variables to environment variables."
196   :type 'boolean
197   :group 'eshell-var)
198
199 (defcustom eshell-complete-export-definition t
200   "*If non-nil, completing names for `export' shows current definition."
201   :type 'boolean
202   :group 'eshell-var)
203
204 (defcustom eshell-modify-global-environment nil
205   "*If non-nil, using `export' changes Emacs's global environment."
206   :type 'boolean
207   :group 'eshell-var)
208
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."
214   :type 'regexp
215   :group 'eshell-var)
216
217 (defcustom eshell-variable-aliases-list
218   '(;; for eshell.el
219     ("COLUMNS" (lambda (indices) (window-width)) t)
220     ("LINES" (lambda (indices) (window-height)) t)
221
222     ;; for eshell-cmd.el
223     ("_" (lambda (indices)
224            (if (not indices)
225                (car (last eshell-last-arguments))
226              (eshell-apply-indices eshell-last-arguments
227                                    indices))))
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)
241            (if (not indices)
242                eshell-command-arguments
243              (eshell-apply-indices eshell-command-arguments
244                                    indices)))))
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'.
250
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
257 '(10 20)', and nil."
258   :type '(repeat (list string sexp
259                        (choice (const :tag "Copy to environment" t)
260                                (const :tag "Use only in Eshell" nil))))
261   :group 'eshell-var)
262
263 (put 'eshell-variable-aliases-list 'risky-local-variable t)
264
265 ;;; Functions:
266
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)))
274
275   (define-key eshell-command-map [(meta ?v)] 'eshell-insert-envvar)
276
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 '(?$)))
281
282   (make-local-hook 'eshell-parse-argument-hook)
283   (add-hook 'eshell-parse-argument-hook 'eshell-interpolate-variable t t)
284
285   (make-local-hook 'eshell-prepare-command-hook)
286   (add-hook 'eshell-prepare-command-hook
287             'eshell-handle-local-variables nil t)
288
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)))
295
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))
317         (throw
318          'eshell-replace-command
319          (list
320           'eshell-as-subcommand
321           (append
322            (list 'progn)
323            (let ((l (list t)))
324              (while (string-match setvar command)
325                (nconc
326                 l (list
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))
331                      args (cdr args)))
332              (cdr l))
333            (list (list 'eshell-named-command
334                        command (list 'quote args)))))))))
335
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)))
341     (forward-char)
342     (list 'eshell-escape-arg
343           (eshell-parse-variable))))
344
345 (defun eshell/define (var-alias definition)
346   "Define a VAR-ALIAS using DEFINITION."
347   (if (not 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))
352           (alias-def
353            (list var-alias
354                  (list 'quote (if (= (length definition) 1)
355                                   (car definition)
356                                 definition)))))
357       (if def
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
362             (cons alias-def
363                   eshell-variable-aliases-list))))
364   nil)
365
366 (defun eshell/export (&rest sets)
367   "This alias allows the `export' command to act as bash users expect."
368   (while sets
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))))
374
375 (defun pcomplete/eshell-mode/export ()
376   "Completion function for Eshell's `export'."
377   (while (pcomplete-here
378           (if eshell-complete-export-definition
379               process-environment
380             (eshell-envvar-names)))))
381
382 (defun eshell/unset (&rest args)
383   "Unset an environment variable."
384   (while args
385     (if (stringp (car args))
386         (setenv (car args) nil t))
387     (setq args (cdr args))))
388
389 (defun pcomplete/eshell-mode/unset ()
390   "Completion function for Eshell's `unset'."
391   (while (pcomplete-here (eshell-envvar-names))))
392
393 (defun eshell/setq (&rest args)
394   "Allow command-ish use of `setq'."
395   (let (last-value)
396     (while args
397       (let ((sym (intern (car args)))
398             (val (cadr args)))
399         (setq last-value (set sym val)
400               args (cddr args))))
401     last-value))
402
403 (defun pcomplete/eshell-mode/setq ()
404   "Completion function for Eshell's `setq'."
405   (while (and (pcomplete-here (all-completions pcomplete-stub
406                                                obarray 'boundp))
407               (pcomplete-here))))
408
409 (defun eshell/env (&rest args)
410   "Implemention of `env' in Lisp."
411   (eshell-init-print-buffer)
412   (eshell-eval-using-options
413    "env" args
414    '((?h "help" nil nil "show this usage screen")
415      :external "env"
416      :usage "<no arguments>")
417    (eshell-for setting (sort (eshell-environment-variables)
418                              'string-lessp)
419      (eshell-buffered-print setting "\n"))
420    (eshell-flush)))
421
422 (defun eshell-insert-envvar (envvar-name)
423   "Insert ENVVAR-NAME into the current buffer at point."
424   (interactive
425    (list (read-envvar-name "Name of environment variable: " t)))
426   (insert-and-inherit "$" envvar-name))
427
428 (defun eshell-envvar-names (&optional environment)
429   "Return a list of currently visible environment variable names."
430   (mapcar (function
431            (lambda (x)
432              (substring x 0 (string-match "=" x))))
433           (or environment process-environment)))
434
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)
443                   (eshell-stringify
444                    (or (eshell-get-variable (car var-alias)) "")))))
445     process-environment))
446
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'.
452
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) ?#)
456                     (forward-char) t))
457          value indices)
458     (setq value (eshell-parse-variable-ref)
459           indices (and (not (eobp))
460                        (eq (char-after) ?\[)
461                        (eshell-parse-indices))
462           value (list 'let
463                       (list (list 'indices
464                                   (list 'quote indices)))
465                       value))
466     (if get-len
467         (list 'length value)
468       value)))
469
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
473 variable.
474
475 Possible options are:
476
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"
481   (let (end)
482     (cond
483      ((eq (char-after) ?{)
484       (let ((end (eshell-find-delimiter ?\{ ?\})))
485         (if (not end)
486             (throw 'eshell-incomplete ?\{)
487           (prog1
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))))
498         (if name
499           (list 'eshell-get-variable (eval name) 'indices))))
500      ((eq (char-after) ?\<)
501       (let ((end (eshell-find-delimiter ?\< ?\>)))
502         (if (not end)
503             (throw 'eshell-incomplete ?\<)
504           ;; XEmacs change: 
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)
509                               " > " temp)))
510             (prog1
511                 (list
512                  'let (list (list 'eshell-current-handles
513                                   (list 'eshell-create-handles temp
514                                         (list 'quote 'overwrite))))
515                  (list
516                   'progn
517                   (list 'eshell-as-subcommand
518                         (eshell-parse-command cmd))
519                   (list 'ignore
520                         (list 'nconc 'eshell-this-command-hook
521                               (list 'list
522                                     (list 'function
523                                           (list 'lambda nil
524                                                 (list 'delete-file temp))))))
525                   (list 'quote temp)))
526               (goto-char (1+ end)))))))
527      ((eq (char-after) ?\()
528       (condition-case err
529           (list 'eshell-command-to-value
530                 (list 'eshell-lisp-command
531                       (list 'quote (read (current-buffer)))))
532         (end-of-file
533          (throw 'eshell-incomplete ?\())))
534      ((assoc (char-to-string (char-after))
535              eshell-variable-aliases-list)
536       (forward-char)
537       (list 'eshell-get-variable
538             (char-to-string (char-before)) 'indices))
539      ((looking-at eshell-variable-name-regexp)
540       (prog1
541           (list 'eshell-get-variable (match-string 0) 'indices)
542         (goto-char (match-end 0))))
543      (t
544       (error "Invalid variable reference")))))
545
546 (eshell-deftest var interp-cmd
547   "Interpolate command result"
548   (eshell-command-result-p "+ ${+ 1 2} 3" "6\n"))
549
550 (eshell-deftest var interp-lisp
551   "Interpolate Lisp form evalution"
552   (eshell-command-result-p "+ $(+ 1 2) 3" "6\n"))
553
554 (eshell-deftest var interp-concat
555   "Interpolate and concat command"
556   (eshell-command-result-p "+ ${+ 1 2}3 3" "36\n"))
557
558 (eshell-deftest var interp-concat-lisp
559   "Interpolate and concat Lisp form"
560   (eshell-command-result-p "+ $(+ 1 2)3 3" "36\n"))
561
562 (eshell-deftest var interp-concat2
563   "Interpolate and concat two commands"
564   (eshell-command-result-p "+ ${+ 1 2}${+ 1 2} 3" "36\n"))
565
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"))
569
570 (defun eshell-parse-indices ()
571   "Parse and return a list of list of indices."
572   (let (indices)
573     (while (eq (char-after) ?\[)
574       (let ((end (eshell-find-delimiter ?\[ ?\])))
575         (if (not end)
576             (throw 'eshell-incomplete ?\[)
577           (forward-char)
578           (let (eshell-glob-function)
579             (setq indices (cons (eshell-parse-arguments (point) end)
580                                 indices)))
581           (goto-char (1+ end)))))
582     (nreverse indices)))
583
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))
587          (var (if alias
588                   (cadr alias)
589                 name)))
590     (if (and alias (functionp var))
591         (funcall var indices)
592       (eshell-apply-indices
593        (cond
594         ((stringp var)
595          (let ((sym (intern-soft var)))
596            (if (and sym (boundp sym)
597                     (or eshell-prefer-lisp-variables
598                         (not (getenv var))))
599                (symbol-value sym)
600              (getenv var))))
601         ((symbolp var)
602          (symbol-value var))
603         (t
604          (error "Unknown variable `%s'" (eshell-stringify var))))
605        indices))))
606
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:
610
611   ((INT-OR-NAME-OR-OTHER INT-OR-NAME INT-OR-NAME ...)
612    ...)
613
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
620 `assoc'.
621
622 For example, to retrieve the second element of a user's record in
623 '/etc/passwd', the variable reference would look like:
624
625   ${egrep johnw /etc/passwd}[: 2]"
626   (while indices
627     (let ((refs (car indices)))
628       (when (stringp value)
629         (let (separator)
630           (if (not (or (not (stringp (caar indices)))
631                        (string-match
632                         (concat "^" eshell-variable-name-regexp "$")
633                         (caar indices))))
634               (setq separator (caar indices)
635                     refs (cdr refs)))
636           (setq value
637                 (mapcar 'eshell-convert
638                         (split-string value separator)))))
639       (cond
640        ((< (length refs) 0)
641         (error "Invalid array variable index: %s"
642                (eshell-stringify refs)))
643        ((= (length refs) 1)
644         (setq value (eshell-index-value value (car refs))))
645        (t
646         (let ((new-value (list t)))
647           (while refs
648             (nconc new-value
649                    (list (eshell-index-value value
650                                              (car refs))))
651             (setq refs (cdr refs)))
652           (setq value (cdr new-value))))))
653     (setq indices (cdr indices)))
654   value)
655
656 (defun eshell-index-value (value index)
657   "Reference VALUE using the given INDEX."
658   (if (stringp index)
659       (cdr (assoc index value))
660     (cond
661      ((ring-p value)
662       (if (> index (ring-length value))
663           (error "Index exceeds length of ring")
664         (ring-ref value index)))
665      ((listp value)
666       (if (> index (length value))
667           (error "Index exceeds length of list")
668         (nth index value)))
669      ((vectorp value)
670       (if (> index (length value))
671           (error "Index exceeds length of vector")
672         (aref value index)))
673      (t
674       (error "Invalid data type for indexing")))))
675
676 ;;;_* Variable name completion
677
678 (defun eshell-complete-variable-reference ()
679   "If there is a variable reference, complete it."
680   (let ((arg (pcomplete-actual-arg)) index)
681     (when (setq index
682                 (string-match
683                  (concat "\\$\\(" eshell-variable-name-regexp
684                          "\\)?\\'") arg))
685       (setq pcomplete-stub (substring arg (1+ index)))
686       (throw 'pcomplete-completions (eshell-variables-list)))))
687
688 (defun eshell-variables-list ()
689   "Generate list of applicable variables."
690   (let ((argname pcomplete-stub)
691         completions)
692     (eshell-for alias eshell-variable-aliases-list
693       (if (string-match (concat "^" argname) (car alias))
694           (setq completions (cons (car alias) completions))))
695     (sort
696      (append
697       (mapcar
698        (function
699         (lambda (varname)
700           (let ((value (eshell-get-variable varname)))
701             (if (and value
702                      (stringp value)
703                      (file-directory-p value))
704                 (concat varname (char-to-string directory-sep-char))
705               varname))))
706        (eshell-envvar-names (eshell-environment-variables)))
707       (all-completions argname obarray 'boundp)
708       completions)
709      'string-lessp)))
710
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)))))
720
721 ;;; Code:
722
723 ;;; esh-var.el ends here