doc/lispref/frames.texi: (Multiple Terminals): Fix last commit.
[emacs.git] / lisp / eshell / em-pred.el
blobf55d68717a4dca9670f3998125e81925f80009ab
1 ;;; em-pred.el --- argument predicates and modifiers (ala zsh) -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999-2014 Free Software Foundation, Inc.
5 ;; Author: John Wiegley <johnw@gnu.org>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
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.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;;; Commentary:
24 ;; Argument predication is used to affect which members of a list are
25 ;; selected for use as argument. This is most useful with globbing,
26 ;; but can be used on any list argument, to select certain members.
28 ;; Argument modifiers are used to manipulate argument values. For
29 ;; example, sorting lists, upcasing words, substituting characters,
30 ;; etc.
32 ;; Here are some examples of how to use argument predication. Most of
33 ;; the predicates and modifiers are modeled after those provided by
34 ;; zsh.
36 ;; ls -ld *(/) ; list all directories
37 ;; ls -l *(@u'johnw') ; list all symlinks owned by 'johnw'
38 ;; bzip2 -9v **/*(a+30) ; compress everything which hasn't been
39 ;; accessed in 30 days
40 ;; echo *.c(:o:R) ; a reversed, sorted list of C files
41 ;; *(^@:U^u0) ; all non-symlinks not owned by 'root', upcased
42 ;; chmod u-x *(U*) : remove exec bit on all executables owned by user
44 ;; See the zsh docs for more on the syntax ([(zsh.info)Filename
45 ;; Generation]).
47 ;;; Code:
49 (require 'esh-util)
50 (require 'esh-arg)
51 (eval-when-compile (require 'eshell))
53 ;;;###autoload
54 (progn
55 (defgroup eshell-pred nil
56 "This module allows for predicates to be applied to globbing
57 patterns (similar to zsh), in addition to string modifiers which can
58 be applied either to globbing results, variable references, or just
59 ordinary strings."
60 :tag "Value modifiers and predicates"
61 :group 'eshell-module))
63 ;;; User Variables:
65 (defcustom eshell-pred-load-hook nil
66 "A list of functions to run when `eshell-pred' is loaded."
67 :version "24.1" ; removed eshell-pred-initialize
68 :type 'hook
69 :group 'eshell-pred)
71 (defcustom eshell-predicate-alist
72 '((?/ . (eshell-pred-file-type ?d)) ; directories
73 (?. . (eshell-pred-file-type ?-)) ; regular files
74 (?s . (eshell-pred-file-type ?s)) ; sockets
75 (?p . (eshell-pred-file-type ?p)) ; named pipes
76 (?@ . (eshell-pred-file-type ?l)) ; symbolic links
77 (?% . (eshell-pred-file-type ?%)) ; allow user to specify (c def.)
78 (?r . (eshell-pred-file-mode 0400)) ; owner-readable
79 (?w . (eshell-pred-file-mode 0200)) ; owner-writable
80 (?x . (eshell-pred-file-mode 0100)) ; owner-executable
81 (?A . (eshell-pred-file-mode 0040)) ; group-readable
82 (?I . (eshell-pred-file-mode 0020)) ; group-writable
83 (?E . (eshell-pred-file-mode 0010)) ; group-executable
84 (?R . (eshell-pred-file-mode 0004)) ; world-readable
85 (?W . (eshell-pred-file-mode 0002)) ; world-writable
86 (?X . (eshell-pred-file-mode 0001)) ; world-executable
87 (?s . (eshell-pred-file-mode 4000)) ; setuid
88 (?S . (eshell-pred-file-mode 2000)) ; setgid
89 (?t . (eshell-pred-file-mode 1000)) ; sticky bit
90 (?U . #'(lambda (file) ; owned by effective uid
91 (if (file-exists-p file)
92 (= (nth 2 (file-attributes file)) (user-uid)))))
93 ;; (?G . #'(lambda (file) ; owned by effective gid
94 ;; (if (file-exists-p file)
95 ;; (= (nth 2 (file-attributes file)) (user-uid)))))
96 (?* . #'(lambda (file)
97 (and (file-regular-p file)
98 (not (file-symlink-p file))
99 (file-executable-p file))))
100 (?l . (eshell-pred-file-links))
101 (?u . (eshell-pred-user-or-group ?u "user" 2 'eshell-user-id))
102 (?g . (eshell-pred-user-or-group ?g "group" 3 'eshell-group-id))
103 (?a . (eshell-pred-file-time ?a "access" 4))
104 (?m . (eshell-pred-file-time ?m "modification" 5))
105 (?c . (eshell-pred-file-time ?c "change" 6))
106 (?L . (eshell-pred-file-size)))
107 "A list of predicates than can be applied to a globbing pattern.
108 The format of each entry is
110 (CHAR . PREDICATE-FUNC-SEXP)"
111 :type '(repeat (cons character sexp))
112 :group 'eshell-pred)
114 (put 'eshell-predicate-alist 'risky-local-variable t)
116 (defcustom eshell-modifier-alist
117 '((?E . #'(lambda (lst)
118 (mapcar
119 (function
120 (lambda (str)
121 (eshell-stringify
122 (car (eshell-parse-argument str))))) lst)))
123 (?L . #'(lambda (lst) (mapcar 'downcase lst)))
124 (?U . #'(lambda (lst) (mapcar 'upcase lst)))
125 (?C . #'(lambda (lst) (mapcar 'capitalize lst)))
126 (?h . #'(lambda (lst) (mapcar 'file-name-directory lst)))
127 (?i . (eshell-include-members))
128 (?x . (eshell-include-members t))
129 (?r . #'(lambda (lst) (mapcar 'file-name-sans-extension lst)))
130 (?e . #'(lambda (lst) (mapcar 'file-name-extension lst)))
131 (?t . #'(lambda (lst) (mapcar 'file-name-nondirectory lst)))
132 (?q . #'(lambda (lst) (mapcar 'eshell-escape-arg lst)))
133 (?u . #'(lambda (lst) (eshell-uniqify-list lst)))
134 (?o . #'(lambda (lst) (sort lst 'string-lessp)))
135 (?O . #'(lambda (lst) (nreverse (sort lst 'string-lessp))))
136 (?j . (eshell-join-members))
137 (?S . (eshell-split-members))
138 (?R . 'reverse)
139 (?g . (progn
140 (forward-char)
141 (if (eq (char-before) ?s)
142 (eshell-pred-substitute t)
143 (error "`g' modifier cannot be used alone"))))
144 (?s . (eshell-pred-substitute)))
145 "A list of modifiers than can be applied to an argument expansion.
146 The format of each entry is
148 (CHAR ENTRYWISE-P MODIFIER-FUNC-SEXP)"
149 :type '(repeat (cons character sexp))
150 :group 'eshell-pred)
152 (put 'eshell-modifier-alist 'risky-local-variable t)
154 (defvar eshell-predicate-help-string
155 "Eshell predicate quick reference:
157 - follow symbolic references for predicates after the `-'
158 ^ invert sense of predicates after the `^'
160 FILE TYPE:
161 / directories s sockets
162 . regular files p named pipes
163 * executable (files only) @ symbolic links
165 %x file type == `x' (as by ls -l; so `c' = char device, etc.)
167 PERMISSION BITS (for owner/group/world):
168 r/A/R readable s setuid
169 w/I/W writable S setgid
170 x/E/X executable t sticky bit
172 OWNERSHIP:
173 U owned by effective uid
174 u(UID|'user') owned by UID/user
175 g(GID|'group') owned by GID/group
177 FILE ATTRIBUTES:
178 l[+-]N +/-/= N links
179 a[Mwhms][+-](N|'FILE') access time +/-/= N months/weeks/hours/mins/secs
180 (days if unspecified) if FILE specified,
181 use as comparison basis; so a+'file.c'
182 shows files accessed before file.c was
183 last accessed
184 m[Mwhms][+-](N|'FILE') modification time...
185 c[Mwhms][+-](N|'FILE') change time...
186 L[kmp][+-]N file size +/-/= N Kb/Mb/blocks
188 EXAMPLES:
189 *(^@) all non-dot files which are not symlinks
190 .#*(^@) all files which are not symbolic links
191 **/.#*(*) all executable files, searched recursively
192 ***/*~f*(-/) recursively (though not traversing symlinks),
193 find all directories (or symlinks referring to
194 directories) whose names do not begin with f.
195 e*(*Lk+50) executables 50k or larger beginning with 'e'")
197 (defvar eshell-modifier-help-string
198 "Eshell modifier quick reference:
200 FOR SINGLE ARGUMENTS, or each argument of a list of strings:
201 E evaluate again
202 L lowercase
203 U uppercase
204 C capitalize
205 h dirname
206 t basename
207 e file extension
208 r strip file extension
209 q escape special characters
211 S split string at any whitespace character
212 S/PAT/ split string at each occurrence of PAT
214 FOR LISTS OF ARGUMENTS:
215 o sort alphabetically
216 O reverse sort alphabetically
217 u uniq list (typically used after :o or :O)
218 R reverse list
220 j join list members, separated by a space
221 j/PAT/ join list members, separated by PAT
222 i/PAT/ exclude all members not matching PAT
223 x/PAT/ exclude all members matching PAT
225 s/pat/match/ substitute PAT with MATCH
226 g/pat/match/ substitute PAT with MATCH for all occurrences
228 EXAMPLES:
229 *.c(:o) sorted list of .c files")
231 ;;; Functions:
233 (defun eshell-display-predicate-help ()
234 (interactive)
235 (with-electric-help
236 (function
237 (lambda ()
238 (insert eshell-predicate-help-string)))))
240 (defun eshell-display-modifier-help ()
241 (interactive)
242 (with-electric-help
243 (function
244 (lambda ()
245 (insert eshell-modifier-help-string)))))
247 (defun eshell-pred-initialize ()
248 "Initialize the predicate/modifier code."
249 (add-hook 'eshell-parse-argument-hook
250 'eshell-parse-arg-modifier t t)
251 (define-key eshell-command-map [(meta ?q)] 'eshell-display-predicate-help)
252 (define-key eshell-command-map [(meta ?m)] 'eshell-display-modifier-help))
254 (defun eshell-apply-modifiers (lst predicates modifiers)
255 "Apply to LIST a series of PREDICATES and MODIFIERS."
256 (let (stringified)
257 (if (stringp lst)
258 (setq lst (list lst)
259 stringified t))
260 (when (listp lst)
261 (setq lst (eshell-winnow-list lst nil predicates))
262 (while modifiers
263 (setq lst (funcall (car modifiers) lst)
264 modifiers (cdr modifiers)))
265 (if (and stringified
266 (= (length lst) 1))
267 (car lst)
268 lst))))
270 (defun eshell-parse-arg-modifier ()
271 "Parse a modifier that has been specified after an argument.
272 This function is specially for adding onto `eshell-parse-argument-hook'."
273 (when (eq (char-after) ?\()
274 (forward-char)
275 (let ((end (eshell-find-delimiter ?\( ?\))))
276 (if (not end)
277 (throw 'eshell-incomplete ?\()
278 (when (eshell-arg-delimiter (1+ end))
279 (save-restriction
280 (narrow-to-region (point) end)
281 (let* ((modifiers (eshell-parse-modifiers))
282 (preds (car modifiers))
283 (mods (cdr modifiers)))
284 (if (or preds mods)
285 ;; has to go at the end, which is only natural since
286 ;; syntactically it can only occur at the end
287 (setq eshell-current-modifiers
288 (append
289 eshell-current-modifiers
290 (list
291 `(lambda (lst)
292 (eshell-apply-modifiers
293 lst (quote ,preds) (quote ,mods)))))))))
294 (goto-char (1+ end))
295 (eshell-finish-arg))))))
297 (defun eshell-parse-modifiers ()
298 "Parse value modifiers and predicates at point.
299 If ALLOW-PREDS is non-nil, predicates will be parsed as well.
300 Return a cons cell of the form
302 (PRED-FUNC-LIST . MOD-FUNC-LIST)
304 NEW-STRING is STRING minus any modifiers. PRED-FUNC-LIST is a list of
305 predicate functions. MOD-FUNC-LIST is a list of result modifier
306 functions. PRED-FUNCS take a filename and return t if the test
307 succeeds; MOD-FUNCS take any string and preform a modification,
308 returning the resultant string."
309 (let (negate follow preds mods)
310 (condition-case nil
311 (while (not (eobp))
312 (let ((char (char-after)))
313 (cond
314 ((eq char ?')
315 (forward-char)
316 (if (looking-at "[^|':]")
317 (let ((func (read (current-buffer))))
318 (if (and func (functionp func))
319 (setq preds (eshell-add-pred-func func preds
320 negate follow))
321 (error "Invalid function predicate '%s'"
322 (eshell-stringify func))))
323 (error "Invalid function predicate")))
324 ((eq char ?^)
325 (forward-char)
326 (setq negate (not negate)))
327 ((eq char ?-)
328 (forward-char)
329 (setq follow (not follow)))
330 ((eq char ?|)
331 (forward-char)
332 (if (looking-at "[^|':]")
333 (let ((func (read (current-buffer))))
334 (if (and func (functionp func))
335 (setq mods
336 (cons `(lambda (lst)
337 (mapcar (function ,func) lst))
338 mods))
339 (error "Invalid function modifier '%s'"
340 (eshell-stringify func))))
341 (error "Invalid function modifier")))
342 ((eq char ?:)
343 (forward-char)
344 (let ((mod (assq (char-after) eshell-modifier-alist)))
345 (if (not mod)
346 (error "Unknown modifier character '%c'" (char-after))
347 (forward-char)
348 (setq mods (cons (eval (cdr mod)) mods)))))
350 (let ((pred (assq char eshell-predicate-alist)))
351 (if (not pred)
352 (error "Unknown predicate character '%c'" char)
353 (forward-char)
354 (setq preds
355 (eshell-add-pred-func (eval (cdr pred)) preds
356 negate follow))))))))
357 (end-of-buffer
358 (error "Predicate or modifier ended prematurely")))
359 (cons (nreverse preds) (nreverse mods))))
361 (defun eshell-add-pred-func (pred funcs negate follow)
362 "Add the predicate function PRED to FUNCS."
363 (if negate
364 (setq pred `(lambda (file)
365 (not (funcall ,pred file)))))
366 (if follow
367 (setq pred `(lambda (file)
368 (funcall ,pred (file-truename file)))))
369 (cons pred funcs))
371 (defun eshell-pred-user-or-group (mod-char mod-type attr-index get-id-func)
372 "Return a predicate to test whether a file match a given user/group id."
373 (let (ugid open close end)
374 (if (looking-at "[0-9]+")
375 (progn
376 (setq ugid (string-to-number (match-string 0)))
377 (goto-char (match-end 0)))
378 (setq open (char-after))
379 (if (setq close (memq open '(?\( ?\[ ?\< ?\{)))
380 (setq close (car (last '(?\) ?\] ?\> ?\})
381 (length close))))
382 (setq close open))
383 (forward-char)
384 (setq end (eshell-find-delimiter open close))
385 (unless end
386 (error "Malformed %s name string for modifier `%c'"
387 mod-type mod-char))
388 (setq ugid
389 (funcall get-id-func (buffer-substring (point) end)))
390 (goto-char (1+ end)))
391 (unless ugid
392 (error "Unknown %s name specified for modifier `%c'"
393 mod-type mod-char))
394 `(lambda (file)
395 (let ((attrs (file-attributes file)))
396 (if attrs
397 (= (nth ,attr-index attrs) ,ugid))))))
399 (defun eshell-pred-file-time (mod-char mod-type attr-index)
400 "Return a predicate to test whether a file matches a certain time."
401 (let* ((quantum 86400)
402 qual when open close end)
403 (when (memq (char-after) '(?M ?w ?h ?m ?s))
404 (setq quantum (char-after))
405 (cond
406 ((eq quantum ?M)
407 (setq quantum (* 60 60 24 30)))
408 ((eq quantum ?w)
409 (setq quantum (* 60 60 24 7)))
410 ((eq quantum ?h)
411 (setq quantum (* 60 60)))
412 ((eq quantum ?m)
413 (setq quantum 60))
414 ((eq quantum ?s)
415 (setq quantum 1)))
416 (forward-char))
417 (when (memq (char-after) '(?+ ?-))
418 (setq qual (char-after))
419 (forward-char))
420 (if (looking-at "[0-9]+")
421 (progn
422 (setq when (- (float-time)
423 (* (string-to-number (match-string 0))
424 quantum)))
425 (goto-char (match-end 0)))
426 (setq open (char-after))
427 (if (setq close (memq open '(?\( ?\[ ?\< ?\{)))
428 (setq close (car (last '(?\) ?\] ?\> ?\})
429 (length close))))
430 (setq close open))
431 (forward-char)
432 (setq end (eshell-find-delimiter open close))
433 (unless end
434 (error "Malformed %s time modifier `%c'" mod-type mod-char))
435 (let* ((file (buffer-substring (point) end))
436 (attrs (file-attributes file)))
437 (unless attrs
438 (error "Cannot stat file `%s'" file))
439 (setq when (float-time (nth attr-index attrs))))
440 (goto-char (1+ end)))
441 `(lambda (file)
442 (let ((attrs (file-attributes file)))
443 (if attrs
444 (,(if (eq qual ?-)
446 (if (eq qual ?+)
448 '=)) ,when (float-time
449 (nth ,attr-index attrs))))))))
451 (defun eshell-pred-file-type (type)
452 "Return a test which tests that the file is of a certain TYPE.
453 TYPE must be a character, and should be one of the possible options
454 that 'ls -l' will show in the first column of its display. "
455 (when (eq type ?%)
456 (setq type (char-after))
457 (if (memq type '(?b ?c))
458 (forward-char)
459 (setq type ?%)))
460 `(lambda (file)
461 (let ((attrs (eshell-file-attributes (directory-file-name file))))
462 (if attrs
463 (memq (aref (nth 8 attrs) 0)
464 ,(if (eq type ?%)
465 '(?b ?c)
466 (list 'quote (list type))))))))
468 (defsubst eshell-pred-file-mode (mode)
469 "Return a test which tests that MODE pertains to the file."
470 `(lambda (file)
471 (let ((modes (file-modes file)))
472 (if modes
473 (logand ,mode modes)))))
475 (defun eshell-pred-file-links ()
476 "Return a predicate to test whether a file has a given number of links."
477 (let (qual amount)
478 (when (memq (char-after) '(?- ?+))
479 (setq qual (char-after))
480 (forward-char))
481 (unless (looking-at "[0-9]+")
482 (error "Invalid file link count modifier `l'"))
483 (setq amount (string-to-number (match-string 0)))
484 (goto-char (match-end 0))
485 `(lambda (file)
486 (let ((attrs (eshell-file-attributes file)))
487 (if attrs
488 (,(if (eq qual ?-)
490 (if (eq qual ?+)
492 '=)) (nth 1 attrs) ,amount))))))
494 (defun eshell-pred-file-size ()
495 "Return a predicate to test whether a file is of a given size."
496 (let ((quantum 1) qual amount)
497 (when (memq (downcase (char-after)) '(?k ?m ?p))
498 (setq qual (downcase (char-after)))
499 (cond
500 ((eq qual ?k)
501 (setq quantum 1024))
502 ((eq qual ?m)
503 (setq quantum (* 1024 1024)))
504 ((eq qual ?p)
505 (setq quantum 512)))
506 (forward-char))
507 (when (memq (char-after) '(?- ?+))
508 (setq qual (char-after))
509 (forward-char))
510 (unless (looking-at "[0-9]+")
511 (error "Invalid file size modifier `L'"))
512 (setq amount (* (string-to-number (match-string 0)) quantum))
513 (goto-char (match-end 0))
514 `(lambda (file)
515 (let ((attrs (eshell-file-attributes file)))
516 (if attrs
517 (,(if (eq qual ?-)
519 (if (eq qual ?+)
521 '=)) (nth 7 attrs) ,amount))))))
523 (defun eshell-pred-substitute (&optional repeat)
524 "Return a modifier function that will substitute matches."
525 (let ((delim (char-after))
526 match replace end)
527 (forward-char)
528 (setq end (eshell-find-delimiter delim delim nil nil t)
529 match (buffer-substring-no-properties (point) end))
530 (goto-char (1+ end))
531 (setq end (eshell-find-delimiter delim delim nil nil t)
532 replace (buffer-substring-no-properties (point) end))
533 (goto-char (1+ end))
534 (if repeat
535 `(lambda (lst)
536 (mapcar
537 (function
538 (lambda (str)
539 (let ((i 0))
540 (while (setq i (string-match ,match str i))
541 (setq str (replace-match ,replace t nil str))))
542 str)) lst))
543 `(lambda (lst)
544 (mapcar
545 (function
546 (lambda (str)
547 (if (string-match ,match str)
548 (setq str (replace-match ,replace t nil str)))
549 str)) lst)))))
551 (defun eshell-include-members (&optional invert-p)
552 "Include only lisp members matching a regexp."
553 (let ((delim (char-after))
554 regexp end)
555 (forward-char)
556 (setq end (eshell-find-delimiter delim delim nil nil t)
557 regexp (buffer-substring-no-properties (point) end))
558 (goto-char (1+ end))
559 `(lambda (lst)
560 (eshell-winnow-list
561 lst nil '((lambda (elem)
562 ,(if invert-p
563 `(not (string-match ,regexp elem))
564 `(string-match ,regexp elem))))))))
566 (defun eshell-join-members ()
567 "Return a modifier function that join matches."
568 (let ((delim (char-after))
569 str end)
570 (if (not (memq delim '(?' ?/)))
571 (setq delim " ")
572 (forward-char)
573 (setq end (eshell-find-delimiter delim delim nil nil t)
574 str (buffer-substring-no-properties (point) end))
575 (goto-char (1+ end)))
576 `(lambda (lst)
577 (mapconcat 'identity lst ,str))))
579 (defun eshell-split-members ()
580 "Return a modifier function that splits members."
581 (let ((delim (char-after))
582 sep end)
583 (when (memq delim '(?' ?/))
584 (forward-char)
585 (setq end (eshell-find-delimiter delim delim nil nil t)
586 sep (buffer-substring-no-properties (point) end))
587 (goto-char (1+ end)))
588 `(lambda (lst)
589 (mapcar
590 (function
591 (lambda (str)
592 (split-string str ,sep))) lst))))
594 (provide 'em-pred)
596 ;; Local Variables:
597 ;; generated-autoload-file: "esh-groups.el"
598 ;; End:
600 ;;; em-pred.el ends here