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