Move eshell's self-tests to the test/ directory.
[bpt/emacs.git] / lisp / eshell / esh-cmd.el
CommitLineData
60370d40 1;;; esh-cmd.el --- command invocation
25fffb31 2
73b0cd50 3;; Copyright (C) 1999-2011 Free Software Foundation, Inc.
25fffb31 4
7de5b421
GM
5;; Author: John Wiegley <johnw@gnu.org>
6
25fffb31
GM
7;; This file is part of GNU Emacs.
8
4ee57b2a 9;; GNU Emacs is free software: you can redistribute it and/or modify
25fffb31 10;; it under the terms of the GNU General Public License as published by
4ee57b2a
GM
11;; the Free Software Foundation, either version 3 of the License, or
12;; (at your option) any later version.
25fffb31
GM
13
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
4ee57b2a 20;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25fffb31 21
25fffb31
GM
22;;; Commentary:
23
24;;;_* Invoking external commands
25;;
26;; External commands cause processes to be created, by loading
27;; external executables into memory. This is what most normal shells
28;; do, most of the time. For more information, see [External commands].
29;;
30;;;_* Invoking Lisp functions
31;;
32;; A Lisp function can be invoked using Lisp syntax, or command shell
33;; syntax. For example, to run `dired' to edit the current directory:
34;;
35;; /tmp $ (dired ".")
36;;
37;; Or:
38;;
39;; /tmp $ dired .
40;;
41;; The latter form is preferable, but the former is more precise,
42;; since it involves no translations. See [Argument parsing], to
43;; learn more about how arguments are transformed before passing them
44;; to commands.
45;;
46;; Ordinarily, if 'dired' were also available as an external command,
47;; the external version would be called in preference to any Lisp
48;; function of the same name. To change this behavior so that Lisp
49;; functions always take precedence, set
50;; `eshell-prefer-lisp-functions' to t.
51
25fffb31
GM
52;;;_* Alias functions
53;;
54;; Whenever a command is specified using a simple name, such as 'ls',
55;; Eshell will first look for a Lisp function of the name `eshell/ls'.
56;; If it exists, it will be called in preference to any other command
57;; which might have matched the name 'ls' (such as command aliases,
58;; external commands, Lisp functions of that name, etc).
59;;
60;; This is the most flexible mechanism for creating new commands,
61;; since it does not pollute the global namespace, yet allows you to
62;; use all of Lisp's facilities to define that piece of functionality.
63;; Most of Eshell's "builtin" commands are defined as alias functions.
64;;
65;;;_* Lisp arguments
66;;
67;; It is possible to invoke a Lisp form as an argument. This can be
68;; done either by specifying the form as you might in Lisp, or by
69;; using the '$' character to introduce a value-interpolation:
70;;
71;; echo (+ 1 2)
72;;
73;; Or
74;;
75;; echo $(+ 1 2)
76;;
77;; The two forms are equivalent. The second is required only if the
78;; form being interpolated is within a string, or is a subexpression
79;; of a larger argument:
80;;
81;; echo x$(+ 1 2) "String $(+ 1 2)"
82;;
83;; To pass a Lisp symbol as a argument, use the alternate quoting
84;; syntax, since the single quote character is far too overused in
85;; shell syntax:
86;;
87;; echo #'lisp-symbol
88;;
89;; Backquote can also be used:
90;;
91;; echo `(list ,lisp-symbol)
92;;
93;; Lisp arguments are identified using the following regexp:
94
56590d2f
GM
95;;;_* Command hooks
96;;
97;; There are several hooks involved with command execution, which can
98;; be used either to change or augment Eshell's behavior.
99
100
101;;; Code:
102
103(require 'esh-util)
104(unless (featurep 'xemacs)
105 (require 'eldoc))
106(require 'esh-arg)
107(require 'esh-proc)
108(require 'esh-ext)
109
110(eval-when-compile
fc17acd1 111 (require 'cl)
56590d2f
GM
112 (require 'pcomplete))
113
114
115(defgroup eshell-cmd nil
116 "Executing an Eshell command is as simple as typing it in and
117pressing <RET>. There are several different kinds of commands,
118however."
119 :tag "Command invocation"
120 ;; :link '(info-link "(eshell)Command invocation")
121 :group 'eshell)
122
123(defcustom eshell-prefer-lisp-functions nil
ec60da52 124 "If non-nil, prefer Lisp functions to external commands."
56590d2f
GM
125 :type 'boolean
126 :group 'eshell-cmd)
127
25fffb31 128(defcustom eshell-lisp-regexp "\\([(`]\\|#'\\)"
ec60da52 129 "A regexp which, if matched at beginning of an argument, means Lisp.
25fffb31
GM
130Such arguments will be passed to `read', and then evaluated."
131 :type 'regexp
132 :group 'eshell-cmd)
133
25fffb31 134(defcustom eshell-pre-command-hook nil
ec60da52 135 "A hook run before each interactive command is invoked."
25fffb31
GM
136 :type 'hook
137 :group 'eshell-cmd)
138
139(defcustom eshell-post-command-hook nil
ec60da52 140 "A hook run after each interactive command is invoked."
25fffb31
GM
141 :type 'hook
142 :group 'eshell-cmd)
143
144(defcustom eshell-prepare-command-hook nil
ec60da52 145 "A set of functions called to prepare a named command.
25fffb31
GM
146The command name and its argument are in `eshell-last-command-name'
147and `eshell-last-arguments'. The functions on this hook can change
148the value of these symbols if necessary.
149
150To prevent a command from executing at all, set
151`eshell-last-command-name' to nil."
152 :type 'hook
153 :group 'eshell-cmd)
154
155(defcustom eshell-named-command-hook nil
ec60da52 156 "A set of functions called before a named command is invoked.
25fffb31
GM
157Each function will be passed the command name and arguments that were
158passed to `eshell-named-command'.
159
160If any of the functions returns a non-nil value, the named command
161will not be invoked, and that value will be returned from
162`eshell-named-command'.
163
164In order to substitute an alternate command form for execution, the
165hook function should throw it using the tag `eshell-replace-command'.
166For example:
167
168 (add-hook 'eshell-named-command-hook 'subst-with-cd)
169 (defun subst-with-cd (command args)
170 (throw 'eshell-replace-command
171 (eshell-parse-command \"cd\" args)))
172
173Although useless, the above code will cause any non-glob, non-Lisp
174command (i.e., 'ls' as opposed to '*ls' or '(ls)') to be replaced by a
175call to `cd' using the arguments that were passed to the function."
176 :type 'hook
177 :group 'eshell-cmd)
178
179(defcustom eshell-pre-rewrite-command-hook
180 '(eshell-no-command-conversion
181 eshell-subcommand-arg-values)
ec60da52 182 "A hook run before command rewriting begins.
25fffb31
GM
183The terms of the command to be rewritten is passed as arguments, and
184may be modified in place. Any return value is ignored."
185 :type 'hook
186 :group 'eshell-cmd)
187
188(defcustom eshell-rewrite-command-hook
189 '(eshell-rewrite-for-command
190 eshell-rewrite-while-command
191 eshell-rewrite-if-command
192 eshell-rewrite-sexp-command
193 eshell-rewrite-initial-subcommand
194 eshell-rewrite-named-command)
ec60da52 195 "A set of functions used to rewrite the command argument.
25fffb31
GM
196Once parsing of a command line is completed, the next step is to
197rewrite the initial argument into something runnable.
198
199A module may wish to associate special behavior with certain argument
200syntaxes at the beginning of a command line. They are welcome to do
201so by adding a function to this hook. The first function to return a
202substitute command form is the one used. Each function is passed the
203command's full argument list, which is a list of sexps (typically
204forms or strings)."
205 :type 'hook
206 :group 'eshell-cmd)
207
208(defcustom eshell-post-rewrite-command-hook nil
ec60da52 209 "A hook run after command rewriting is finished.
25fffb31
GM
210Each function is passed the symbol containing the rewritten command,
211which may be modified directly. Any return value is ignored."
212 :type 'hook
213 :group 'eshell-cmd)
214
820b9143 215(defcustom eshell-complex-commands '("ls")
ec60da52 216 "A list of commands names or functions, that determine complexity.
dace60cf
JW
217That is, if a command is defined by a function named eshell/NAME,
218and NAME is part of this list, it is invoked as a complex command.
219Complex commands are always correct, but run much slower. If a
220command works fine without being part of this list, then it doesn't
221need to be.
222
223If an entry is a function, it will be called with the name, and should
224return non-nil if the command is complex."
225 :type '(repeat :tag "Commands"
226 (choice (string :tag "Name")
227 (function :tag "Predicate")))
228 :group 'eshell-cmd)
229
25fffb31
GM
230;;; User Variables:
231
d783d303 232(defcustom eshell-cmd-load-hook nil
ec60da52 233 "A hook that gets run when `eshell-cmd' is loaded."
d783d303 234 :version "24.1" ; removed eshell-cmd-initialize
25fffb31
GM
235 :type 'hook
236 :group 'eshell-cmd)
237
238(defcustom eshell-debug-command nil
ec60da52 239 "If non-nil, enable debugging code. SSLLOOWW.
25fffb31
GM
240This option is only useful for reporting bugs. If you enable it, you
241will have to visit the file 'eshell-cmd.el' and run the command
242\\[eval-buffer]."
243 :type 'boolean
244 :group 'eshell-cmd)
245
246(defcustom eshell-deferrable-commands
247 '(eshell-named-command
248 eshell-lisp-command
249 eshell-process-identity)
ec60da52 250 "A list of functions which might return an ansychronous process.
25fffb31
GM
251If they return a process object, execution of the calling Eshell
252command will wait for completion (in the background) before finishing
253the command."
254 :type '(repeat function)
255 :group 'eshell-cmd)
256
257(defcustom eshell-subcommand-bindings
258 '((eshell-in-subcommand-p t)
259 (default-directory default-directory)
260 (process-environment (eshell-copy-environment)))
ec60da52 261 "A list of `let' bindings for subcommand environments."
25fffb31
GM
262 :type 'sexp
263 :group 'eshell-cmd)
264
265(put 'risky-local-variable 'eshell-subcommand-bindings t)
266
267(defvar eshell-ensure-newline-p nil
268 "If non-nil, ensure that a newline is emitted after a Lisp form.
269This can be changed by Lisp forms that are evaluated from the Eshell
270command line.")
271
272;;; Internal Variables:
273
274(defvar eshell-current-command nil)
275(defvar eshell-command-name nil)
276(defvar eshell-command-arguments nil)
5101a9dc
GM
277(defvar eshell-in-pipeline-p nil
278 "Internal Eshell variable, non-nil inside a pipeline.
279Has the value 'first, 'last for the first/last commands in the pipeline,
280otherwise t.")
25fffb31
GM
281(defvar eshell-in-subcommand-p nil)
282(defvar eshell-last-arguments nil)
283(defvar eshell-last-command-name nil)
284(defvar eshell-last-async-proc nil
285 "When this foreground process completes, resume command evaluation.")
286
287;;; Functions:
288
289(defsubst eshell-interactive-process ()
290 "Return currently running command process, if non-Lisp."
291 eshell-last-async-proc)
292
293(defun eshell-cmd-initialize ()
294 "Initialize the Eshell command processing module."
295 (set (make-local-variable 'eshell-current-command) nil)
296 (set (make-local-variable 'eshell-command-name) nil)
297 (set (make-local-variable 'eshell-command-arguments) nil)
298 (set (make-local-variable 'eshell-last-arguments) nil)
299 (set (make-local-variable 'eshell-last-command-name) nil)
300 (set (make-local-variable 'eshell-last-async-proc) nil)
301
25fffb31
GM
302 (add-hook 'eshell-kill-hook 'eshell-resume-command nil t)
303
304 ;; make sure that if a command is over, and no process is being
305 ;; waited for, that `eshell-current-command' is set to nil. This
306 ;; situation can occur, for example, if a Lisp function results in
307 ;; `debug' being called, and the user then types \\[top-level]
25fffb31
GM
308 (add-hook 'eshell-post-command-hook
309 (function
310 (lambda ()
311 (setq eshell-current-command nil
312 eshell-last-async-proc nil))) nil t)
313
25fffb31
GM
314 (add-hook 'eshell-parse-argument-hook
315 'eshell-parse-subcommand-argument nil t)
316 (add-hook 'eshell-parse-argument-hook
317 'eshell-parse-lisp-argument nil t)
318
319 (when (eshell-using-module 'eshell-cmpl)
25fffb31
GM
320 (add-hook 'pcomplete-try-first-hook
321 'eshell-complete-lisp-symbols nil t)))
322
25fffb31
GM
323(defun eshell-complete-lisp-symbols ()
324 "If there is a user reference, complete it."
325 (let ((arg (pcomplete-actual-arg)))
326 (when (string-match (concat "\\`" eshell-lisp-regexp) arg)
327 (setq pcomplete-stub (substring arg (match-end 0))
328 pcomplete-last-completion-raw t)
329 (throw 'pcomplete-completions
330 (all-completions pcomplete-stub obarray 'boundp)))))
331
332;; Command parsing
333
334(defun eshell-parse-command (command &optional args top-level)
335 "Parse the COMMAND, adding ARGS if given.
336COMMAND can either be a string, or a cons cell demarcating a buffer
337region. TOP-LEVEL, if non-nil, means that the outermost command (the
338user's input command) is being parsed, and that pre and post command
339hooks should be run before and after the command."
340 (let* (sep-terms
341 (terms
342 (append
343 (if (consp command)
344 (eshell-parse-arguments (car command) (cdr command))
345 (let ((here (point))
6e13206c
SM
346 (inhibit-point-motion-hooks t))
347 (with-silent-modifications
348 ;; FIXME: Why not use a temporary buffer and avoid this
349 ;; "insert&delete" business? --Stef
350 (insert command)
351 (prog1
352 (eshell-parse-arguments here (point))
353 (delete-region here (point))))))
25fffb31
GM
354 args))
355 (commands
356 (mapcar
357 (function
358 (lambda (cmd)
359 (if (or (not (car sep-terms))
360 (string= (car sep-terms) ";"))
361 (setq cmd
362 (eshell-parse-pipeline cmd (not (car sep-terms))))
363 (setq cmd
364 (list 'eshell-do-subjob
365 (list 'list (eshell-parse-pipeline cmd)))))
366 (setq sep-terms (cdr sep-terms))
367 (if eshell-in-pipeline-p
368 cmd
369 (list 'eshell-trap-errors cmd))))
370 (eshell-separate-commands terms "[&;]" nil 'sep-terms))))
371 (let ((cmd commands))
372 (while cmd
373 (if (cdr cmd)
374 (setcar cmd (list 'eshell-commands (car cmd))))
375 (setq cmd (cdr cmd))))
376 (setq commands
377 (append (list 'progn)
378 (if top-level
379 (list '(run-hooks 'eshell-pre-command-hook)))
380 (if (not top-level)
381 commands
382 (list
383 (list 'catch (quote 'top-level)
384 (append (list 'progn) commands))
385 '(run-hooks 'eshell-post-command-hook)))))
386 (if top-level
387 (list 'eshell-commands commands)
388 commands)))
389
56590d2f
GM
390(defun eshell-debug-command (tag subform)
391 "Output a debugging message to '*eshell last cmd*'."
392 (let ((buf (get-buffer-create "*eshell last cmd*"))
393 (text (eshell-stringify eshell-current-command)))
ee5b7365 394 (with-current-buffer buf
56590d2f
GM
395 (if (not tag)
396 (erase-buffer)
397 (insert "\n\C-l\n" tag "\n\n" text
398 (if subform
399 (concat "\n\n" (eshell-stringify subform)) ""))))))
400
25fffb31
GM
401(defun eshell-debug-show-parsed-args (terms)
402 "Display parsed arguments in the debug buffer."
403 (ignore
404 (if eshell-debug-command
405 (eshell-debug-command "parsed arguments" terms))))
406
407(defun eshell-no-command-conversion (terms)
408 "Don't convert the command argument."
409 (ignore
410 (if (and (listp (car terms))
411 (eq (caar terms) 'eshell-convert))
412 (setcar terms (cadr (car terms))))))
413
414(defun eshell-subcommand-arg-values (terms)
415 "Convert subcommand arguments {x} to ${x}, in order to take their values."
416 (setq terms (cdr terms)) ; skip command argument
417 (while terms
418 (if (and (listp (car terms))
419 (eq (caar terms) 'eshell-as-subcommand))
420 (setcar terms (list 'eshell-convert
421 (list 'eshell-command-to-value
422 (car terms)))))
423 (setq terms (cdr terms))))
424
425(defun eshell-rewrite-sexp-command (terms)
426 "Rewrite a sexp in initial position, such as '(+ 1 2)'."
427 ;; this occurs when a Lisp expression is in first position
428 (if (and (listp (car terms))
429 (eq (caar terms) 'eshell-command-to-value))
430 (car (cdar terms))))
431
25fffb31
GM
432(defun eshell-rewrite-initial-subcommand (terms)
433 "Rewrite a subcommand in initial position, such as '{+ 1 2}'."
434 (if (and (listp (car terms))
435 (eq (caar terms) 'eshell-as-subcommand))
436 (car terms)))
437
25fffb31
GM
438(defun eshell-rewrite-named-command (terms)
439 "If no other rewriting rule transforms TERMS, assume a named command."
f4dd1361
JW
440 (let ((sym (if eshell-in-pipeline-p
441 'eshell-named-command*
442 'eshell-named-command))
443 (cmd (car terms))
444 (args (cdr terms)))
445 (if args
446 (list sym cmd (append (list 'list) (cdr terms)))
447 (list sym cmd))))
25fffb31 448
1a32899d
GM
449(defvar eshell-command-body)
450(defvar eshell-test-body)
25fffb31
GM
451
452(defsubst eshell-invokify-arg (arg &optional share-output silent)
453 "Change ARG so it can be invoked from a structured command.
454
455SHARE-OUTPUT, if non-nil, means this invocation should share the
456current output stream, which is separately redirectable. SILENT
457means the user and/or any redirections shouldn't see any output
458from this command. If both SHARE-OUTPUT and SILENT are non-nil,
459the second is ignored."
460 ;; something that begins with `eshell-convert' means that it
461 ;; intends to return a Lisp value. We want to get past this,
462 ;; but if it's not _actually_ a value interpolation -- in which
463 ;; we leave it alone. In fact, the only time we muck with it
464 ;; is in the case of a {subcommand} that has been turned into
465 ;; the interpolation, ${subcommand}, by the parser because it
466 ;; didn't know better.
467 (if (and (listp arg)
468 (eq (car arg) 'eshell-convert)
469 (eq (car (cadr arg)) 'eshell-command-to-value))
470 (if share-output
471 (cadr (cadr arg))
472 (list 'eshell-commands (cadr (cadr arg))
473 silent))
474 arg))
475
476(defun eshell-rewrite-for-command (terms)
477 "Rewrite a `for' command into its equivalent Eshell command form.
478Because the implementation of `for' relies upon conditional evaluation
31096fe8 479of its argument (i.e., use of a Lisp special form), it must be
25fffb31
GM
480implemented via rewriting, rather than as a function."
481 (if (and (stringp (car terms))
482 (string= (car terms) "for")
483 (stringp (nth 2 terms))
484 (string= (nth 2 terms) "in"))
485 (let ((body (car (last terms))))
486 (setcdr (last terms 2) nil)
487 (list
488 'let (list (list 'for-items
489 (append
490 (list 'append)
491 (mapcar
492 (function
493 (lambda (elem)
494 (if (listp elem)
495 elem
496 (list 'list elem))))
022499fa 497 (cdr (cddr terms)))))
25fffb31
GM
498 (list 'eshell-command-body
499 (list 'quote (list nil)))
500 (list 'eshell-test-body
501 (list 'quote (list nil))))
502 (list
503 'progn
504 (list
505 'while (list 'car (list 'symbol-value
506 (list 'quote 'for-items)))
507 (list
508 'progn
509 (list 'let
510 (list (list (intern (cadr terms))
511 (list 'car
512 (list 'symbol-value
513 (list 'quote 'for-items)))))
dace60cf
JW
514 (list 'eshell-protect
515 (eshell-invokify-arg body t)))
25fffb31
GM
516 (list 'setcar 'for-items
517 (list 'cadr
518 (list 'symbol-value
519 (list 'quote 'for-items))))
520 (list 'setcdr 'for-items
521 (list 'cddr
522 (list 'symbol-value
523 (list 'quote 'for-items))))))
524 (list 'eshell-close-handles
525 'eshell-last-command-status
526 (list 'list (quote 'quote)
527 'eshell-last-command-result)))))))
528
529(defun eshell-structure-basic-command (func names keyword test body
530 &optional else vocal-test)
531 "With TERMS, KEYWORD, and two NAMES, structure a basic command.
532The first of NAMES should be the positive form, and the second the
533negative. It's not likely that users should ever need to call this
534function.
535
536If VOCAL-TEST is non-nil, it means output from the test should be
537shown, as well as output from the body."
538 ;; If the test form begins with `eshell-convert', it means
539 ;; something data-wise will be returned, and we should let
540 ;; that determine the truth of the statement.
541 (unless (eq (car test) 'eshell-convert)
542 (setq test
543 (list 'progn test
544 (list 'eshell-exit-success-p))))
545
546 ;; should we reverse the sense of the test? This depends
547 ;; on the `names' parameter. If it's the symbol nil, yes.
548 ;; Otherwise, it can be a pair of strings; if the keyword
549 ;; we're using matches the second member of that pair (a
550 ;; list), we should reverse it.
551 (if (or (eq names nil)
552 (and (listp names)
553 (string= keyword (cadr names))))
554 (setq test (list 'not test)))
555
556 ;; finally, create the form that represents this structured
557 ;; command
558 (list
559 'let (list (list 'eshell-command-body
560 (list 'quote (list nil)))
561 (list 'eshell-test-body
562 (list 'quote (list nil))))
563 (list func test body else)
564 (list 'eshell-close-handles
565 'eshell-last-command-status
566 (list 'list (quote 'quote)
567 'eshell-last-command-result))))
568
569(defun eshell-rewrite-while-command (terms)
570 "Rewrite a `while' command into its equivalent Eshell command form.
571Because the implementation of `while' relies upon conditional
572evaluation of its argument (i.e., use of a Lisp special form), it
573must be implemented via rewriting, rather than as a function."
574 (if (and (stringp (car terms))
575 (member (car terms) '("while" "until")))
576 (eshell-structure-basic-command
577 'while '("while" "until") (car terms)
578 (eshell-invokify-arg (cadr terms) nil t)
dace60cf 579 (list 'eshell-protect
25fffb31
GM
580 (eshell-invokify-arg (car (last terms)) t)))))
581
582(defun eshell-rewrite-if-command (terms)
583 "Rewrite an `if' command into its equivalent Eshell command form.
584Because the implementation of `if' relies upon conditional
585evaluation of its argument (i.e., use of a Lisp special form), it
586must be implemented via rewriting, rather than as a function."
587 (if (and (stringp (car terms))
588 (member (car terms) '("if" "unless")))
589 (eshell-structure-basic-command
590 'if '("if" "unless") (car terms)
591 (eshell-invokify-arg (cadr terms) nil t)
dace60cf
JW
592 (list 'eshell-protect
593 (eshell-invokify-arg
05a68572
JW
594 (if (= (length terms) 4)
595 (car (last terms 2))
dace60cf 596 (car (last terms))) t))
05a68572 597 (if (= (length terms) 4)
dace60cf
JW
598 (list 'eshell-protect
599 (eshell-invokify-arg
600 (car (last terms)))) t))))
25fffb31
GM
601
602(defun eshell-exit-success-p ()
603 "Return non-nil if the last command was \"successful\".
604For a bit of Lisp code, this means a return value of non-nil.
605For an external command, it means an exit code of 0."
05a68572
JW
606 (if (save-match-data
607 (string-match "#<\\(Lisp object\\|function .*\\)>"
608 eshell-last-command-name))
25fffb31
GM
609 eshell-last-command-result
610 (= eshell-last-command-status 0)))
611
612(defun eshell-parse-pipeline (terms &optional final-p)
613 "Parse a pipeline from TERMS, return the appropriate Lisp forms."
614 (let* (sep-terms
615 (bigpieces (eshell-separate-commands terms "\\(&&\\|||\\)"
616 nil 'sep-terms))
617 (bp bigpieces)
618 (results (list t))
619 final)
620 (while bp
621 (let ((subterms (car bp)))
622 (let* ((pieces (eshell-separate-commands subterms "|"))
623 (p pieces))
624 (while p
625 (let ((cmd (car p)))
626 (run-hook-with-args 'eshell-pre-rewrite-command-hook cmd)
627 (setq cmd (run-hook-with-args-until-success
628 'eshell-rewrite-command-hook cmd))
629 (run-hook-with-args 'eshell-post-rewrite-command-hook 'cmd)
630 (setcar p cmd))
631 (setq p (cdr p)))
632 (nconc results
633 (list
634 (if (<= (length pieces) 1)
635 (car pieces)
636 (assert (not eshell-in-pipeline-p))
637 (list 'eshell-execute-pipeline
638 (list 'quote pieces))))))
639 (setq bp (cdr bp))))
640 ;; `results' might be empty; this happens in the case of
641 ;; multi-line input
642 (setq results (cdr results)
643 results (nreverse results)
644 final (car results)
645 results (cdr results)
646 sep-terms (nreverse sep-terms))
647 (while results
648 (assert (car sep-terms))
649 (setq final (eshell-structure-basic-command
650 'if (string= (car sep-terms) "&&") "if"
dace60cf
JW
651 (list 'eshell-protect (car results))
652 (list 'eshell-protect final)
25fffb31
GM
653 nil t)
654 results (cdr results)
655 sep-terms (cdr sep-terms)))
656 final))
657
658(defun eshell-parse-subcommand-argument ()
659 "Parse a subcommand argument of the form '{command}'."
660 (if (and (not eshell-current-argument)
661 (not eshell-current-quoted)
662 (eq (char-after) ?\{)
663 (or (= (point-max) (1+ (point)))
664 (not (eq (char-after (1+ (point))) ?\}))))
665 (let ((end (eshell-find-delimiter ?\{ ?\})))
666 (if (not end)
667 (throw 'eshell-incomplete ?\{)
668 (when (eshell-arg-delimiter (1+ end))
669 (prog1
670 (list 'eshell-as-subcommand
671 (eshell-parse-command (cons (1+ (point)) end)))
672 (goto-char (1+ end))))))))
673
674(defun eshell-parse-lisp-argument ()
675 "Parse a Lisp expression which is specified as an argument."
676 (if (and (not eshell-current-argument)
677 (not eshell-current-quoted)
678 (looking-at eshell-lisp-regexp))
679 (let* ((here (point))
680 (obj
681 (condition-case err
682 (read (current-buffer))
683 (end-of-file
684 (throw 'eshell-incomplete ?\()))))
685 (if (eshell-arg-delimiter)
686 (list 'eshell-command-to-value
687 (list 'eshell-lisp-command (list 'quote obj)))
688 (ignore (goto-char here))))))
689
dace60cf
JW
690(defun eshell-separate-commands (terms separator &optional
691 reversed last-terms-sym)
25fffb31
GM
692 "Separate TERMS using SEPARATOR.
693If REVERSED is non-nil, the list of separated term groups will be
d4469517 694returned in reverse order. If LAST-TERMS-SYM is a symbol, its value
25fffb31
GM
695will be set to a list of all the separator operators found (or '(list
696nil)' if none)."
697 (let ((sub-terms (list t))
698 (eshell-sep-terms (list t))
699 subchains)
700 (while terms
701 (if (and (consp (car terms))
702 (eq (caar terms) 'eshell-operator)
703 (string-match (concat "^" separator "$")
704 (nth 1 (car terms))))
705 (progn
706 (nconc eshell-sep-terms (list (nth 1 (car terms))))
707 (setq subchains (cons (cdr sub-terms) subchains)
708 sub-terms (list t)))
709 (nconc sub-terms (list (car terms))))
710 (setq terms (cdr terms)))
711 (if (> (length sub-terms) 1)
712 (setq subchains (cons (cdr sub-terms) subchains)))
713 (if reversed
714 (progn
715 (if last-terms-sym
716 (set last-terms-sym (reverse (cdr eshell-sep-terms))))
717 subchains) ; already reversed
718 (if last-terms-sym
719 (set last-terms-sym (cdr eshell-sep-terms)))
720 (nreverse subchains))))
721
722;;_* Command evaluation macros
723;;
724;; The structure of the following macros is very important to
725;; `eshell-do-eval' [Iterative evaluation]:
726;;
727;; @ Don't use forms that conditionally evaluate their arguments, such
728;; as `setq', `if', `while', `let*', etc. The only special forms
729;; that can be used are `let', `condition-case' and
730;; `unwind-protect'.
731;;
732;; @ The main body of a `let' can contain only one form. Use `progn'
733;; if necessary.
734;;
735;; @ The two `special' variables are `eshell-current-handles' and
736;; `eshell-current-subjob-p'. Bind them locally with a `let' if you
737;; need to change them. Change them directly only if your intention
738;; is to change the calling environment.
739
740(defmacro eshell-do-subjob (object)
741 "Evaluate a command OBJECT as a subjob.
6b6f91b3 742We indicate that the process was run in the background by returning it
25fffb31
GM
743ensconced in a list."
744 `(let ((eshell-current-subjob-p t))
745 ,object))
746
747(defmacro eshell-commands (object &optional silent)
748 "Place a valid set of handles, and context, around command OBJECT."
749 `(let ((eshell-current-handles
750 (eshell-create-handles ,(not silent) 'append))
751 eshell-current-subjob-p)
752 ,object))
753
754(defmacro eshell-trap-errors (object)
755 "Trap any errors that occur, so they are not entirely fatal.
756Also, the variable `eshell-this-command-hook' is available for the
757duration of OBJECT's evaluation. Note that functions should be added
758to this hook using `nconc', and *not* `add-hook'.
759
760Someday, when Scheme will become the dominant Emacs language, all of
761this grossness will be made to disappear by using `call/cc'..."
762 `(let ((eshell-this-command-hook (list 'ignore)))
763 (eshell-condition-case err
764 (prog1
765 ,object
766 (run-hooks 'eshell-this-command-hook))
767 (error
768 (run-hooks 'eshell-this-command-hook)
769 (eshell-errorn (error-message-string err))
770 (eshell-close-handles 1)))))
771
ca7aae91
JW
772(defmacro eshell-copy-handles (object)
773 "Duplicate current I/O handles, so OBJECT works with its own copy."
774 `(let ((eshell-current-handles
775 (eshell-create-handles
776 (car (aref eshell-current-handles
777 eshell-output-handle)) nil
778 (car (aref eshell-current-handles
779 eshell-error-handle)) nil)))
780 ,object))
781
25fffb31
GM
782(defmacro eshell-protect (object)
783 "Protect I/O handles, so they aren't get closed after eval'ing OBJECT."
784 `(progn
785 (eshell-protect-handles eshell-current-handles)
786 ,object))
787
5101a9dc
GM
788(defmacro eshell-do-pipelines (pipeline &optional notfirst)
789 "Execute the commands in PIPELINE, connecting each to one another.
790This macro calls itself recursively, with NOTFIRST non-nil."
25fffb31 791 (when (setq pipeline (cadr pipeline))
ca7aae91
JW
792 `(eshell-copy-handles
793 (progn
794 ,(when (cdr pipeline)
795 `(let (nextproc)
796 (progn
797 (set 'nextproc
5101a9dc 798 (eshell-do-pipelines (quote ,(cdr pipeline)) t))
ca7aae91
JW
799 (eshell-set-output-handle ,eshell-output-handle
800 'append nextproc)
801 (eshell-set-output-handle ,eshell-error-handle
802 'append nextproc)
803 (set 'tailproc (or tailproc nextproc)))))
804 ,(let ((head (car pipeline)))
805 (if (memq (car head) '(let progn))
806 (setq head (car (last head))))
807 (when (memq (car head) eshell-deferrable-commands)
808 (ignore
809 (setcar head
810 (intern-soft
811 (concat (symbol-name (car head)) "*"))))))
5101a9dc
GM
812 ;; First and last elements in a pipeline may need special treatment.
813 ;; (Currently only eshell-ls-files uses 'last.)
814 ;; Affects process-connection-type in eshell-gather-process-output.
815 (let ((eshell-in-pipeline-p
816 ,(cond ((not notfirst) (quote 'first))
817 ((cdr pipeline) t)
818 (t (quote 'last)))))
3fe3fd2c 819 ,(car pipeline))))))
ca7aae91
JW
820
821(defmacro eshell-do-pipelines-synchronously (pipeline)
822 "Execute the commands in PIPELINE in sequence synchronously.
823Output of each command is passed as input to the next one in the pipeline.
824This is used on systems where `start-process' is not supported."
825 (when (setq pipeline (cadr pipeline))
826 `(let (result)
25fffb31
GM
827 (progn
828 ,(when (cdr pipeline)
ca7aae91 829 `(let (output-marker)
25fffb31 830 (progn
ca7aae91 831 (set 'output-marker ,(point-marker))
25fffb31 832 (eshell-set-output-handle ,eshell-output-handle
ca7aae91 833 'append output-marker)
25fffb31 834 (eshell-set-output-handle ,eshell-error-handle
ca7aae91 835 'append output-marker))))
25fffb31
GM
836 ,(let ((head (car pipeline)))
837 (if (memq (car head) '(let progn))
838 (setq head (car (last head))))
ca7aae91 839 ;;; FIXME: is deferrable significant here?
25fffb31
GM
840 (when (memq (car head) eshell-deferrable-commands)
841 (ignore
842 (setcar head
843 (intern-soft
844 (concat (symbol-name (car head)) "*"))))))
ca7aae91
JW
845 ;; The last process in the pipe should get its handles
846 ;; redirected as we found them before running the pipe.
847 ,(if (null (cdr pipeline))
848 `(progn
849 (set 'eshell-current-handles tail-handles)
850 (set 'eshell-in-pipeline-p nil)))
851 (set 'result ,(car pipeline))
852 ;; tailproc gets the result of the last successful process in
853 ;; the pipeline.
854 (set 'tailproc (or result tailproc))
855 ,(if (cdr pipeline)
856 `(eshell-do-pipelines-synchronously (quote ,(cdr pipeline))))
857 result))))
25fffb31
GM
858
859(defalias 'eshell-process-identity 'identity)
860
861(defmacro eshell-execute-pipeline (pipeline)
862 "Execute the commands in PIPELINE, connecting each to one another."
863 `(let ((eshell-in-pipeline-p t) tailproc)
864 (progn
ca7aae91
JW
865 ,(if (fboundp 'start-process)
866 `(eshell-do-pipelines ,pipeline)
867 `(let ((tail-handles (eshell-create-handles
868 (car (aref eshell-current-handles
869 ,eshell-output-handle)) nil
870 (car (aref eshell-current-handles
871 ,eshell-error-handle)) nil)))
872 (eshell-do-pipelines-synchronously ,pipeline)))
25fffb31
GM
873 (eshell-process-identity tailproc))))
874
875(defmacro eshell-as-subcommand (command)
876 "Execute COMMAND using a temp buffer.
877This is used so that certain Lisp commands, such as `cd', when
878executed in a subshell, do not disturb the environment of the main
879Eshell buffer."
880 `(let ,eshell-subcommand-bindings
881 ,command))
882
883(defmacro eshell-do-command-to-value (object)
884 "Run a subcommand prepared by `eshell-command-to-value'.
885This avoids the need to use `let*'."
886 `(let ((eshell-current-handles
887 (eshell-create-handles value 'overwrite)))
888 (progn
889 ,object
890 (symbol-value value))))
891
892(defmacro eshell-command-to-value (object)
893 "Run OBJECT synchronously, returning its result as a string.
894Returns a string comprising the output from the command."
895 `(let ((value (make-symbol "eshell-temp")))
896 (eshell-do-command-to-value ,object)))
897
898;;;_* Iterative evaluation
899;;
900;; Eshell runs all of its external commands asynchronously, so that
901;; Emacs is not blocked while the operation is being performed.
902;; However, this introduces certain synchronization difficulties,
903;; since the Lisp code, once it returns, will not "go back" to finish
904;; executing the commands which haven't yet been started.
905;;
906;; What Eshell does to work around this problem (basically, the lack
907;; of threads in Lisp), is that it evaluates the command sequence
908;; iteratively. Whenever an asynchronous process is begun, evaluation
909;; terminates and control is given back to Emacs. When that process
910;; finishes, it will resume the evaluation using the remainder of the
911;; command tree.
912
913(defun eshell/eshell-debug (&rest args)
914 "A command for toggling certain debug variables."
915 (ignore
916 (cond
917 ((not args)
918 (if eshell-handle-errors
919 (eshell-print "errors\n"))
920 (if eshell-debug-command
921 (eshell-print "commands\n")))
922 ((or (string= (car args) "-h")
923 (string= (car args) "--help"))
924 (eshell-print "usage: eshell-debug [kinds]
925
926This command is used to aid in debugging problems related to Eshell
927itself. It is not useful for anything else. The recognized `kinds'
928at the moment are:
929
930 errors stops Eshell from trapping errors
931 commands shows command execution progress in `*eshell last cmd*'
932"))
933 (t
934 (while args
935 (cond
936 ((string= (car args) "errors")
937 (setq eshell-handle-errors (not eshell-handle-errors)))
938 ((string= (car args) "commands")
939 (setq eshell-debug-command (not eshell-debug-command))))
940 (setq args (cdr args)))))))
941
942(defun pcomplete/eshell-mode/eshell-debug ()
943 "Completion for the `debug' command."
944 (while (pcomplete-here '("errors" "commands"))))
945
dace60cf
JW
946(defun eshell-invoke-directly (command input)
947 (let ((base (cadr (nth 2 (nth 2 (cadr command))))) name)
948 (if (and (eq (car base) 'eshell-trap-errors)
949 (eq (car (cadr base)) 'eshell-named-command))
950 (setq name (cadr (cadr base))))
951 (and name (stringp name)
952 (not (member name eshell-complex-commands))
953 (catch 'simple
954 (progn
a9eeff78 955 (dolist (pred eshell-complex-commands)
dace60cf
JW
956 (if (and (functionp pred)
957 (funcall pred name))
958 (throw 'simple nil)))
959 t))
960 (fboundp (intern-soft (concat "eshell/" name))))))
961
25fffb31
GM
962(defun eshell-eval-command (command &optional input)
963 "Evaluate the given COMMAND iteratively."
964 (if eshell-current-command
965 ;; we can just stick the new command at the end of the current
966 ;; one, and everything will happen as it should
967 (setcdr (last (cdr eshell-current-command))
968 (list (list 'let '((here (and (eobp) (point))))
969 (and input
970 (list 'insert-and-inherit
971 (concat input "\n")))
972 '(if here
973 (eshell-update-markers here))
974 (list 'eshell-do-eval
975 (list 'quote command)))))
976 (and eshell-debug-command
ee5b7365
SM
977 (with-current-buffer (get-buffer-create "*eshell last cmd*")
978 (erase-buffer)
979 (insert "command: \"" input "\"\n")))
25fffb31 980 (setq eshell-current-command command)
ca7aae91
JW
981 (let ((delim (catch 'eshell-incomplete
982 (eshell-resume-eval))))
4c334f5b
EZ
983 ;; On systems that don't support async subprocesses, eshell-resume
984 ;; can return t. Don't treat that as an error.
6b6f91b3
JW
985 (if (listp delim)
986 (setq delim (car delim)))
4c334f5b 987 (if (and delim (not (eq delim t)))
6b6f91b3 988 (error "Unmatched delimiter: %c" delim)))))
25fffb31
GM
989
990(defun eshell-resume-command (proc status)
991 "Resume the current command when a process ends."
992 (when proc
ca7aae91
JW
993 (unless (or (not (stringp status))
994 (string= "stopped" status)
25fffb31
GM
995 (string-match eshell-reset-signals status))
996 (if (eq proc (eshell-interactive-process))
997 (eshell-resume-eval)))))
998
999(defun eshell-resume-eval ()
1000 "Destructively evaluate a form which may need to be deferred."
1001 (eshell-condition-case err
1002 (progn
1003 (setq eshell-last-async-proc nil)
1004 (when eshell-current-command
1005 (let* (retval
1006 (proc (catch 'eshell-defer
1007 (ignore
1008 (setq retval
1009 (eshell-do-eval
1010 eshell-current-command))))))
ca7aae91 1011 (if (eshell-processp proc)
25fffb31
GM
1012 (ignore (setq eshell-last-async-proc proc))
1013 (cadr retval)))))
1014 (error
1015 (error (error-message-string err)))))
1016
1017(defmacro eshell-manipulate (tag &rest commands)
1018 "Manipulate a COMMAND form, with TAG as a debug identifier."
ee5b7365
SM
1019 ;; Check `bound'ness since at compile time the code until here has not
1020 ;; executed yet.
1021 (if (not (and (boundp 'eshell-debug-command) eshell-debug-command))
25fffb31
GM
1022 `(progn ,@commands)
1023 `(progn
1024 (eshell-debug-command ,(eval tag) form)
1025 ,@commands
1026 (eshell-debug-command ,(concat "done " (eval tag)) form))))
1027
1028(put 'eshell-manipulate 'lisp-indent-function 1)
1029
1030;; eshell-lookup-function, eshell-functionp, and eshell-macrop taken
1031;; from edebug
1032
1033(defsubst eshell-lookup-function (object)
1034 "Return the ultimate function definition of OBJECT."
1035 (while (and (symbolp object) (fboundp object))
1036 (setq object (symbol-function object)))
1037 object)
1038
1039(defconst function-p-func
38c1b27a 1040 (if (fboundp 'compiled-function-p)
25fffb31
GM
1041 'compiled-function-p
1042 'byte-code-function-p))
1043
1044(defsubst eshell-functionp (object)
1045 "Returns the function named by OBJECT, or nil if it is not a function."
1046 (setq object (eshell-lookup-function object))
1047 (if (or (subrp object)
1048 (funcall function-p-func object)
1049 (and (listp object)
1050 (eq (car object) 'lambda)
1051 (listp (car (cdr object)))))
1052 object))
1053
1054(defsubst eshell-macrop (object)
1055 "Return t if OBJECT is a macro or nil otherwise."
1056 (setq object (eshell-lookup-function object))
1057 (if (and (listp object)
1058 (eq 'macro (car object))
1059 (eshell-functionp (cdr object)))
1060 t))
1061
1062(defun eshell-do-eval (form &optional synchronous-p)
1063 "Evaluate form, simplifying it as we go.
1064Unless SYNCHRONOUS-P is non-nil, throws `eshell-defer' if it needs to
1065be finished later after the completion of an asynchronous subprocess."
1066 (cond
1067 ((not (listp form))
1068 (list 'quote (eval form)))
1069 ((memq (car form) '(quote function))
1070 form)
1071 (t
1072 ;; skip past the call to `eshell-do-eval'
1073 (when (eq (car form) 'eshell-do-eval)
1074 (setq form (cadr (cadr form))))
1075 ;; expand any macros directly into the form. This is done so that
1076 ;; we can modify any `let' forms to evaluate only once.
1077 (if (eshell-macrop (car form))
1078 (let ((exp (eshell-copy-tree (macroexpand form))))
1079 (eshell-manipulate (format "expanding macro `%s'"
1080 (symbol-name (car form)))
1081 (setcar form (car exp))
1082 (setcdr form (cdr exp)))))
1083 (let ((args (cdr form)))
1084 (cond
1085 ((eq (car form) 'while)
1086 ;; `eshell-copy-tree' is needed here so that the test argument
1087 ;; doesn't get modified and thus always yield the same result.
1088 (when (car eshell-command-body)
1089 (assert (not synchronous-p))
1090 (eshell-do-eval (car eshell-command-body))
ca7aae91
JW
1091 (setcar eshell-command-body nil)
1092 (setcar eshell-test-body nil))
25fffb31
GM
1093 (unless (car eshell-test-body)
1094 (setcar eshell-test-body (eshell-copy-tree (car args))))
ca7aae91
JW
1095 (while (cadr (eshell-do-eval (car eshell-test-body)))
1096 (setcar eshell-command-body (eshell-copy-tree (cadr args)))
1097 (eshell-do-eval (car eshell-command-body) synchronous-p)
1098 (setcar eshell-command-body nil)
1099 (setcar eshell-test-body (eshell-copy-tree (car args))))
25fffb31
GM
1100 (setcar eshell-command-body nil))
1101 ((eq (car form) 'if)
1102 ;; `eshell-copy-tree' is needed here so that the test argument
1103 ;; doesn't get modified and thus always yield the same result.
ca7aae91
JW
1104 (if (car eshell-command-body)
1105 (progn
1106 (assert (not synchronous-p))
1107 (eshell-do-eval (car eshell-command-body)))
1108 (unless (car eshell-test-body)
1109 (setcar eshell-test-body (eshell-copy-tree (car args))))
1110 (if (cadr (eshell-do-eval (car eshell-test-body)))
1111 (setcar eshell-command-body (eshell-copy-tree (cadr args)))
1112 (setcar eshell-command-body (eshell-copy-tree (car (cddr args)))))
1113 (eshell-do-eval (car eshell-command-body) synchronous-p))
1114 (setcar eshell-command-body nil)
1115 (setcar eshell-test-body nil))
25fffb31
GM
1116 ((eq (car form) 'setcar)
1117 (setcar (cdr args) (eshell-do-eval (cadr args) synchronous-p))
1118 (eval form))
1119 ((eq (car form) 'setcdr)
1120 (setcar (cdr args) (eshell-do-eval (cadr args) synchronous-p))
1121 (eval form))
1122 ((memq (car form) '(let catch condition-case unwind-protect))
1123 ;; `let', `condition-case' and `unwind-protect' have to be
1124 ;; handled specially, because we only want to call
1125 ;; `eshell-do-eval' on their first form.
1126 ;;
1127 ;; NOTE: This requires obedience by all forms which this
1128 ;; function might encounter, that they do not contain
1129 ;; other special forms.
1130 (if (and (eq (car form) 'let)
1131 (not (eq (car (cadr args)) 'eshell-do-eval)))
1132 (eshell-manipulate "evaluating let args"
a9eeff78 1133 (dolist (letarg (car args))
25fffb31
GM
1134 (if (and (listp letarg)
1135 (not (eq (cadr letarg) 'quote)))
1136 (setcdr letarg
1137 (list (eshell-do-eval
1138 (cadr letarg) synchronous-p)))))))
1139 (unless (eq (car form) 'unwind-protect)
1140 (setq args (cdr args)))
1141 (unless (eq (caar args) 'eshell-do-eval)
1142 (eshell-manipulate "handling special form"
1143 (setcar args (list 'eshell-do-eval
1144 (list 'quote (car args))
1145 synchronous-p))))
1146 (eval form))
1147 (t
1148 (if (and args (not (memq (car form) '(run-hooks))))
1149 (eshell-manipulate
1150 (format "evaluating arguments to `%s'"
1151 (symbol-name (car form)))
1152 (while args
1153 (setcar args (eshell-do-eval (car args) synchronous-p))
1154 (setq args (cdr args)))))
1155 (cond
1156 ((eq (car form) 'progn)
1157 (car (last form)))
1158 ((eq (car form) 'prog1)
1159 (cadr form))
1160 (t
dace60cf
JW
1161 ;; If a command desire to replace its execution form with
1162 ;; another command form, all it needs to do is throw the new
1163 ;; form using the exception tag `eshell-replace-command'.
1164 ;; For example, let's say that the form currently being
1165 ;; eval'd is:
1166 ;;
1167 ;; (eshell-named-command "hello")
1168 ;;
1169 ;; Now, let's assume the 'hello' command is an Eshell alias,
1170 ;; the definition of which yields the command:
1171 ;;
1172 ;; (eshell-named-command "echo" (list "Hello" "world"))
1173 ;;
1174 ;; What the alias code would like to do is simply substitute
1175 ;; the alias form for the original form. To accomplish
1176 ;; this, all it needs to do is to throw the substitution
1177 ;; form with the `eshell-replace-command' tag, and the form
1178 ;; will be replaced within the current command, and
1179 ;; execution will then resume (iteratively) as before.
1180 ;; Thus, aliases can even contain references to asynchronous
1181 ;; sub-commands, and things will still work out as they
1182 ;; should.
25fffb31 1183 (let (result new-form)
25fffb31
GM
1184 (if (setq new-form
1185 (catch 'eshell-replace-command
1186 (ignore
1187 (setq result (eval form)))))
1188 (progn
1189 (eshell-manipulate "substituting replacement form"
1190 (setcar form (car new-form))
1191 (setcdr form (cdr new-form)))
1192 (eshell-do-eval form synchronous-p))
1193 (if (and (memq (car form) eshell-deferrable-commands)
1194 (not eshell-current-subjob-p)
1195 result
ca7aae91 1196 (eshell-processp result))
25fffb31
GM
1197 (if synchronous-p
1198 (eshell/wait result)
1199 (eshell-manipulate "inserting ignore form"
1200 (setcar form 'ignore)
1201 (setcdr form nil))
1202 (throw 'eshell-defer result))
1203 (list 'quote result))))))))))))
1204
1205;; command invocation
1206
1207(defun eshell/which (command &rest names)
1208 "Identify the COMMAND, and where it is located."
a9eeff78 1209 (dolist (name (cons command names))
25fffb31 1210 (let (program alias direct)
94d13633 1211 (if (eq (aref name 0) eshell-explicit-command-char)
25fffb31
GM
1212 (setq name (substring name 1)
1213 direct t))
1214 (if (and (not direct)
1215 (eshell-using-module 'eshell-alias)
1216 (setq alias
1217 (funcall (symbol-function 'eshell-lookup-alias)
1218 name)))
1219 (setq program
1220 (concat name " is an alias, defined as \""
1221 (cadr alias) "\"")))
1222 (unless program
1223 (setq program (eshell-search-path name))
1224 (let* ((esym (eshell-find-alias-function name))
1225 (sym (or esym (intern-soft name))))
ac03c474
JW
1226 (if (and (or esym (and sym (fboundp sym)))
1227 (or eshell-prefer-lisp-functions (not direct)))
25fffb31
GM
1228 (let ((desc (let ((inhibit-redisplay t))
1229 (save-window-excursion
1230 (prog1
1231 (describe-function sym)
1232 (message nil))))))
c1043701
GM
1233 (setq desc (if desc (substring desc 0
1234 (1- (or (string-match "\n" desc)
1235 (length desc))))
1236 ;; This should not happen.
1237 (format "%s is defined, \
1238but no documentation was found" name)))
ca7aae91
JW
1239 (if (buffer-live-p (get-buffer "*Help*"))
1240 (kill-buffer "*Help*"))
25fffb31
GM
1241 (setq program (or desc name))))))
1242 (if (not program)
1243 (eshell-error (format "which: no %s in (%s)\n"
1244 name (getenv "PATH")))
1245 (eshell-printn program)))))
1246
3cb27fd7
JW
1247(put 'eshell/which 'eshell-no-numeric-conversions t)
1248
25fffb31
GM
1249(defun eshell-named-command (command &optional args)
1250 "Insert output from a plain COMMAND, using ARGS.
1251COMMAND may result in an alias being executed, or a plain command."
1252 (setq eshell-last-arguments args
1253 eshell-last-command-name (eshell-stringify command))
1254 (run-hook-with-args 'eshell-prepare-command-hook)
1255 (assert (stringp eshell-last-command-name))
1256 (if eshell-last-command-name
1257 (or (run-hook-with-args-until-success
1258 'eshell-named-command-hook eshell-last-command-name
1259 eshell-last-arguments)
1260 (eshell-plain-command eshell-last-command-name
1261 eshell-last-arguments))))
1262
1263(defalias 'eshell-named-command* 'eshell-named-command)
1264
1265(defun eshell-find-alias-function (name)
1266 "Check whether a function called `eshell/NAME' exists."
1267 (let* ((sym (intern-soft (concat "eshell/" name)))
5cb345c1 1268 (file (symbol-file sym 'defun)))
c7b1b508
JW
1269 ;; If the function exists, but is defined in an eshell module
1270 ;; that's not currently enabled, don't report it as found
25fffb31
GM
1271 (if (and file
1272 (string-match "\\(em\\|esh\\)-\\(.*\\)\\(\\.el\\)?\\'" file))
c7b1b508 1273 (let ((module-sym
25fffb31 1274 (intern (file-name-sans-extension
c7b1b508
JW
1275 (file-name-nondirectory
1276 (concat "eshell-" (match-string 2 file)))))))
2e88b53c
JW
1277 (if (and (functionp sym)
1278 (or (null module-sym)
1279 (eshell-using-module module-sym)
1280 (memq module-sym (eshell-subgroups 'eshell))))
c7b1b508
JW
1281 sym))
1282 ;; Otherwise, if it's bound, return it.
1283 (if (functionp sym)
1284 sym))))
25fffb31
GM
1285
1286(defun eshell-plain-command (command args)
1287 "Insert output from a plain COMMAND, using ARGS.
1288COMMAND may result in either a Lisp function being executed by name,
1289or an external command."
1290 (let* ((esym (eshell-find-alias-function command))
1291 (sym (or esym (intern-soft command))))
1292 (if (and sym (fboundp sym)
1293 (or esym eshell-prefer-lisp-functions
1294 (not (eshell-search-path command))))
1295 (eshell-lisp-command sym args)
1296 (eshell-external-command command args))))
1297
1298(defun eshell-exec-lisp (printer errprint func-or-form args form-p)
1299 "Execute a lisp FUNC-OR-FORM, maybe passing ARGS.
1300PRINTER and ERRPRINT are functions to use for printing regular
1301messages, and errors. FORM-P should be non-nil if FUNC-OR-FORM
1302represent a lisp form; ARGS will be ignored in that case."
1303 (let (result)
1304 (eshell-condition-case err
1305 (progn
1306 (setq result
1307 (save-current-buffer
1308 (if form-p
1309 (eval func-or-form)
1310 (apply func-or-form args))))
1311 (and result (funcall printer result))
1312 result)
1313 (error
1314 (let ((msg (error-message-string err)))
1315 (if (and (not form-p)
1316 (string-match "^Wrong number of arguments" msg)
1317 (fboundp 'eldoc-get-fnsym-args-string))
1318 (let ((func-doc (eldoc-get-fnsym-args-string func-or-form)))
1319 (setq msg (format "usage: %s" func-doc))))
1320 (funcall errprint msg))
1321 nil))))
1322
1323(defsubst eshell-apply* (printer errprint func args)
1324 "Call FUNC, with ARGS, trapping errors and return them as output.
1325PRINTER and ERRPRINT are functions to use for printing regular
1326messages, and errors."
1327 (eshell-exec-lisp printer errprint func args nil))
1328
1329(defsubst eshell-funcall* (printer errprint func &rest args)
1330 "Call FUNC, with ARGS, trapping errors and return them as output."
1331 (eshell-apply* printer errprint func args))
1332
1333(defsubst eshell-eval* (printer errprint form)
1334 "Evaluate FORM, trapping errors and returning them."
1335 (eshell-exec-lisp printer errprint form nil t))
1336
1337(defsubst eshell-apply (func args)
1338 "Call FUNC, with ARGS, trapping errors and return them as output.
1339PRINTER and ERRPRINT are functions to use for printing regular
1340messages, and errors."
1341 (eshell-apply* 'eshell-print 'eshell-error func args))
1342
1343(defsubst eshell-funcall (func &rest args)
1344 "Call FUNC, with ARGS, trapping errors and return them as output."
1345 (eshell-apply func args))
1346
1347(defsubst eshell-eval (form)
1348 "Evaluate FORM, trapping errors and returning them."
1349 (eshell-eval* 'eshell-print 'eshell-error form))
1350
1351(defsubst eshell-applyn (func args)
1352 "Call FUNC, with ARGS, trapping errors and return them as output.
1353PRINTER and ERRPRINT are functions to use for printing regular
1354messages, and errors."
1355 (eshell-apply* 'eshell-printn 'eshell-errorn func args))
1356
1357(defsubst eshell-funcalln (func &rest args)
1358 "Call FUNC, with ARGS, trapping errors and return them as output."
1359 (eshell-applyn func args))
1360
1361(defsubst eshell-evaln (form)
1362 "Evaluate FORM, trapping errors and returning them."
1363 (eshell-eval* 'eshell-printn 'eshell-errorn form))
1364
1365(defun eshell-lisp-command (object &optional args)
1366 "Insert Lisp OBJECT, using ARGS if a function."
25fffb31
GM
1367 (catch 'eshell-external ; deferred to an external command
1368 (let* ((eshell-ensure-newline-p (eshell-interactive-output-p))
1369 (result
1370 (if (functionp object)
3cb27fd7
JW
1371 (progn
1372 (setq eshell-last-arguments args
1373 eshell-last-command-name
1374 (concat "#<function " (symbol-name object) ">"))
1375 ;; if any of the arguments are flagged as numbers
1376 ;; waiting for conversion, convert them now
1377 (unless (get object 'eshell-no-numeric-conversions)
1378 (while args
1379 (let ((arg (car args)))
1380 (if (and (stringp arg)
1381 (> (length arg) 0)
175acc2d
JW
1382 (not (text-property-not-all
1383 0 (length arg) 'number t arg)))
ea7974a6 1384 (setcar args (string-to-number arg))))
3cb27fd7
JW
1385 (setq args (cdr args))))
1386 (eshell-apply object eshell-last-arguments))
1387 (setq eshell-last-arguments args
1388 eshell-last-command-name "#<Lisp object>")
25fffb31
GM
1389 (eshell-eval object))))
1390 (if (and eshell-ensure-newline-p
1391 (save-excursion
1392 (goto-char eshell-last-output-end)
1393 (not (bolp))))
1394 (eshell-print "\n"))
1395 (eshell-close-handles 0 (list 'quote result)))))
1396
1397(defalias 'eshell-lisp-command* 'eshell-lisp-command)
1398
56590d2f
GM
1399(provide 'esh-cmd)
1400
25fffb31 1401;;; esh-cmd.el ends here