(prev_char_comstart_first): Remove.
[emacs.git] / lisp / eshell / esh-var.el
blobddbcf257d7e3bdc41159591f6e6bfe4eab4e6aa2
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)
10 ;; any later version.
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.
22 (provide 'esh-var)
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"
32 :group 'eshell)
34 ;;; Commentary:
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.
41 ;; $VARIABLE
43 ;; Interval the value of an environment variable, or a Lisp variable
45 ;; $ALSO-VAR
47 ;; "-" is a legal part of a variable name.
49 ;; $<MYVAR>-TOO
51 ;; Only "MYVAR" is part of the variable name in this case.
53 ;; $#VARIABLE
55 ;; Returns the length of the value of VARIABLE. This could also be
56 ;; done using the `length' Lisp function.
58 ;; $(lisp)
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
63 ;; '$(lisp)/other'.
65 ;; ${command}
67 ;; Returns the value of an eshell subcommand. See the note above
68 ;; regarding Lisp evaluations.
70 ;; $ANYVAR[10]
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.
76 ;; $ANYVAR[: 10]
78 ;; As above, except that splitting occurs at the colon now.
80 ;; $ANYVAR[: 10 20]
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.
87 ;; $ANYVAR["\\\\" 10]
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]'.
94 ;; $ANYVAR[hello]
96 ;; Calls `assoc' on ANYVAR with 'hello', expecting it to be an alist.
98 ;; $#ANYVAR[hello]
100 ;; Returns the length of the cdr of the element of ANYVAR who car is
101 ;; equal to "hello".
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
109 ;; /tmp $ dirname $$
110 ;; /var/spool/mail/
111 ;; /tmp $ cd $$
112 ;; /var/spool/mail $
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).
118 (require 'env)
119 (require 'ring)
121 ;;; User Variables:
123 (defcustom eshell-var-load-hook '(eshell-var-initialize)
124 "*A list of functions to call when loading `eshell-var'."
125 :type 'hook
126 :group 'eshell-var)
128 (defcustom eshell-prefer-lisp-variables nil
129 "*If non-nil, prefer Lisp variables to environment variables."
130 :type 'boolean
131 :group 'eshell-var)
133 (defcustom eshell-complete-export-definition t
134 "*If non-nil, completing names for `export' shows current definition."
135 :type 'boolean
136 :group 'eshell-var)
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."
143 :type 'regexp
144 :group 'eshell-var)
146 (defcustom eshell-variable-aliases-list
147 '(;; for eshell.el
148 ("COLUMNS" (lambda (indices) (window-width)) t)
149 ("LINES" (lambda (indices) (window-height)) t)
151 ;; for eshell-cmd.el
152 ("_" (lambda (indices)
153 (if (not indices)
154 (car (last eshell-last-arguments))
155 (eshell-apply-indices eshell-last-arguments
156 indices))))
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)
170 (if (not indices)
171 eshell-command-arguments
172 (eshell-apply-indices eshell-command-arguments
173 indices)))))
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
186 '(10 20)', and nil."
187 :type '(repeat (list string sexp
188 (choice (const :tag "Copy to environment" t)
189 (const :tag "Use only in Eshell" nil))))
190 :group 'eshell-var)
192 (put 'eshell-variable-aliases-list 'risky-local-variable t)
194 ;;; Functions:
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))
244 (throw
245 'eshell-replace-command
246 (list
247 'eshell-as-subcommand
248 (append
249 (list 'progn)
250 (let ((l (list t)))
251 (while (string-match setvar command)
252 (nconc
253 l (list
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))
258 args (cdr args)))
259 (cdr l))
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)))
268 (forward-char)
269 (list 'eshell-escape-arg
270 (eshell-parse-variable))))
272 (defun eshell/define (var-alias definition)
273 "Define an VAR-ALIAS using DEFINITION."
274 (if (not 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))
279 (alias-def
280 (list var-alias
281 (list 'quote (if (= (length definition) 1)
282 (car definition)
283 definition)))))
284 (if def
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
289 (cons alias-def
290 eshell-variable-aliases-list))))
291 nil)
293 (defun eshell/export (&rest sets)
294 "This alias allows the 'export' command to act as bash users expect."
295 (while sets
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
306 process-environment
307 (eshell-envvar-names)))))
309 (defun eshell/unset (&rest args)
310 "Unset an environment variable."
311 (while args
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'."
322 (let (last-value)
323 (while args
324 (let ((sym (intern (car args)))
325 (val (cadr args)))
326 (setq last-value (set sym val)
327 args (cddr args))))
328 last-value))
330 (defun pcomplete/eshell-mode/setq ()
331 "Completion function for Eshell's `setq'."
332 (while (and (pcomplete-here (all-completions pcomplete-stub
333 obarray 'boundp))
334 (pcomplete-here))))
336 (defun eshell/env (&rest args)
337 "Implemention of `env' in Lisp."
338 (eshell-init-print-buffer)
339 (eshell-eval-using-options
340 "env" args
341 '((?h "help" nil nil "show this usage screen")
342 :external "env"
343 :usage "<no arguments>")
344 (eshell-for setting (sort (eshell-environment-variables)
345 'string-lessp)
346 (eshell-buffered-print setting "\n"))
347 (eshell-flush)))
349 (defun eshell-insert-envvar (envvar-name)
350 "Insert ENVVAR-NAME into the current buffer at point."
351 (interactive
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."
357 (mapcar (function
358 (lambda (x)
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)
370 (eshell-stringify
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) ?#)
383 (forward-char) t))
384 value indices)
385 (setq value (eshell-parse-variable-ref)
386 indices (and (not (eobp))
387 (eq (char-after) ?\[)
388 (eshell-parse-indices))
389 value (list 'let
390 (list (list 'indices
391 (list 'quote indices)))
392 value))
393 (if get-len
394 (list 'length value)
395 value)))
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
400 variable.
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"
408 (let (end)
409 (cond
410 ((eq (char-after) ?{)
411 (let ((end (eshell-find-delimiter ?\{ ?\})))
412 (if (not end)
413 (throw 'eshell-incomplete ?\{)
414 (prog1
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))))
425 (if name
426 (list 'eshell-get-variable (eval name) 'indices))))
427 ((eq (char-after) ?<)
428 (let ((end (eshell-find-delimiter ?\< ?\>)))
429 (if (not end)
430 (throw 'eshell-incomplete ?\<)
431 (let* ((temp (make-temp-name temporary-file-directory))
432 (cmd (concat (buffer-substring (1+ (point)) end)
433 " > " temp)))
434 (prog1
435 (list
436 'let (list (list 'eshell-current-handles
437 (list 'eshell-create-handles temp
438 (list 'quote 'overwrite))))
439 (list
440 'progn
441 (list 'eshell-as-subcommand
442 (eshell-parse-command cmd))
443 (list 'ignore
444 (list 'nconc 'eshell-this-command-hook
445 (list 'list
446 (list 'function
447 (list 'lambda nil
448 (list 'delete-file temp))))))
449 (list 'quote temp)))
450 (goto-char (1+ end)))))))
451 ((eq (char-after) ?\()
452 (condition-case err
453 (list 'eshell-command-to-value
454 (list 'eshell-lisp-command
455 (list 'quote (read (current-buffer)))))
456 (end-of-file
457 (throw 'eshell-incomplete ?\())))
458 ((assoc (char-to-string (char-after))
459 eshell-variable-aliases-list)
460 (forward-char)
461 (list 'eshell-get-variable
462 (char-to-string (char-before)) 'indices))
463 ((looking-at eshell-variable-name-regexp)
464 (prog1
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."
496 (let (indices)
497 (while (eq (char-after) ?\[)
498 (let ((end (eshell-find-delimiter ?\[ ?\])))
499 (if (not end)
500 (throw 'eshell-incomplete ?\[)
501 (forward-char)
502 (let (eshell-glob-function)
503 (setq indices (cons (eshell-parse-arguments (point) end)
504 indices)))
505 (goto-char (1+ end)))))
506 (nreverse indices)))
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))
511 (var (if alias
512 (cadr alias)
513 name)))
514 (if (and alias (functionp var))
515 (funcall var indices)
516 (eshell-apply-indices
517 (cond
518 ((stringp var)
519 (let ((sym (intern-soft var)))
520 (if (and sym (boundp sym)
521 (or eshell-prefer-lisp-variables
522 (not (getenv var))))
523 (symbol-value sym)
524 (getenv var))))
525 ((symbolp var)
526 (symbol-value var))
528 (error "Unknown variable `%s'" (eshell-stringify var))))
529 indices))))
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 ...)
536 ...)
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
544 `assoc'.
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]"
550 (while indices
551 (let ((refs (car indices)))
552 (when (stringp value)
553 (let (separator)
554 (if (not (or (not (stringp (caar indices)))
555 (string-match
556 (concat "^" eshell-variable-name-regexp "$")
557 (caar indices))))
558 (setq separator (caar indices)
559 refs (cdr refs)))
560 (setq value
561 (mapcar 'eshell-convert
562 (split-string value separator)))))
563 (cond
564 ((< (length refs) 0)
565 (error "Illegal array variable index: %s"
566 (eshell-stringify refs)))
567 ((= (length refs) 1)
568 (setq value (eshell-index-value value (car refs))))
570 (let ((new-value (list t)))
571 (while refs
572 (nconc new-value
573 (list (eshell-index-value value
574 (car refs))))
575 (setq refs (cdr refs)))
576 (setq value (cdr new-value))))))
577 (setq indices (cdr indices)))
578 value)
580 (defun eshell-index-value (value index)
581 "Reference VALUE using the given INDEX."
582 (if (stringp index)
583 (cdr (assoc index value))
584 (cond
585 ((ring-p value)
586 (if (> index (ring-length value))
587 (error "Index exceeds length of ring")
588 (ring-ref value index)))
589 ((listp value)
590 (if (> index (length value))
591 (error "Index exceeds length of list")
592 (nth index value)))
593 ((vectorp value)
594 (if (> index (length value))
595 (error "Index exceeds length of vector")
596 (aref value index)))
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)
605 (when (setq index
606 (string-match
607 (concat "\\$\\(" eshell-variable-name-regexp
608 "\\)?\\'") arg))
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)
615 completions)
616 (eshell-for alias eshell-variable-aliases-list
617 (if (string-match (concat "^" argname) (car alias))
618 (setq completions (cons (car alias) completions))))
619 (sort
620 (append
621 (mapcar
622 (function
623 (lambda (varname)
624 (let ((value (eshell-get-variable varname)))
625 (if (and value
626 (stringp value)
627 (file-directory-p value))
628 (concat varname (char-to-string directory-sep-char))
629 varname))))
630 (eshell-envvar-names (eshell-environment-variables)))
631 (all-completions argname obarray 'boundp)
632 completions)
633 'string-lessp)))
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)))))
645 ;;; Code:
647 ;;; esh-var.el ends here