Merge branch 'master' of git.sv.gnu.org:/srv/git/emacs
[emacs.git] / lisp / eshell / em-pred.el
blob219c86b4746503ed815962bd5d9afc2b3ddafcaa
1 ;;; em-pred.el --- argument predicates and modifiers (ala zsh) -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999-2016 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)))))
123 lst)))
124 (?L . #'(lambda (lst) (mapcar 'downcase lst)))
125 (?U . #'(lambda (lst) (mapcar 'upcase lst)))
126 (?C . #'(lambda (lst) (mapcar 'capitalize lst)))
127 (?h . #'(lambda (lst) (mapcar 'file-name-directory lst)))
128 (?i . (eshell-include-members))
129 (?x . (eshell-include-members t))
130 (?r . #'(lambda (lst) (mapcar 'file-name-sans-extension lst)))
131 (?e . #'(lambda (lst) (mapcar 'file-name-extension lst)))
132 (?t . #'(lambda (lst) (mapcar 'file-name-nondirectory lst)))
133 (?q . #'(lambda (lst) (mapcar 'eshell-escape-arg lst)))
134 (?u . #'(lambda (lst) (eshell-uniqify-list lst)))
135 (?o . #'(lambda (lst) (sort lst 'string-lessp)))
136 (?O . #'(lambda (lst) (nreverse (sort lst 'string-lessp))))
137 (?j . (eshell-join-members))
138 (?S . (eshell-split-members))
139 (?R . 'reverse)
140 (?g . (progn
141 (forward-char)
142 (if (eq (char-before) ?s)
143 (eshell-pred-substitute t)
144 (error "`g' modifier cannot be used alone"))))
145 (?s . (eshell-pred-substitute)))
146 "A list of modifiers than can be applied to an argument expansion.
147 The format of each entry is
149 (CHAR ENTRYWISE-P MODIFIER-FUNC-SEXP)"
150 :type '(repeat (cons character sexp))
151 :group 'eshell-pred)
153 (put 'eshell-modifier-alist 'risky-local-variable t)
155 (defvar eshell-predicate-help-string
156 "Eshell predicate quick reference:
158 - follow symbolic references for predicates after the `-'
159 ^ invert sense of predicates after the `^'
161 FILE TYPE:
162 / directories s sockets
163 . regular files p named pipes
164 * executable (files only) @ symbolic links
166 %x file type == `x' (as by ls -l; so `c' = char device, etc.)
168 PERMISSION BITS (for owner/group/world):
169 r/A/R readable s setuid
170 w/I/W writable S setgid
171 x/E/X executable t sticky bit
173 OWNERSHIP:
174 U owned by effective uid
175 u(UID|\\='user\\=') owned by UID/user
176 g(GID|\\='group\\=') owned by GID/group
178 FILE ATTRIBUTES:
179 l[+-]N +/-/= N links
180 a[Mwhms][+-](N|\\='FILE\\=') access time +/-/= N months/weeks/hours/mins/secs
181 (days if unspecified) if FILE specified,
182 use as comparison basis; so a+\\='file.c\\='
183 shows files accessed before file.c was
184 last accessed
185 m[Mwhms][+-](N|\\='FILE\\=') modification time...
186 c[Mwhms][+-](N|\\='FILE\\=') change time...
187 L[kmp][+-]N file size +/-/= N Kb/Mb/blocks
189 EXAMPLES:
190 *(^@) all non-dot files which are not symlinks
191 .#*(^@) all files which are not symbolic links
192 **/.#*(*) all executable files, searched recursively
193 ***/*~f*(-/) recursively (though not traversing symlinks),
194 find all directories (or symlinks referring to
195 directories) whose names do not begin with f.
196 e*(*Lk+50) executables 50k or larger beginning with `e'")
198 (defvar eshell-modifier-help-string
199 "Eshell modifier quick reference:
201 FOR SINGLE ARGUMENTS, or each argument of a list of strings:
202 E evaluate again
203 L lowercase
204 U uppercase
205 C capitalize
206 h dirname
207 t basename
208 e file extension
209 r strip file extension
210 q escape special characters
212 S split string at any whitespace character
213 S/PAT/ split string at each occurrence of PAT
215 FOR LISTS OF ARGUMENTS:
216 o sort alphabetically
217 O reverse sort alphabetically
218 u uniq list (typically used after :o or :O)
219 R reverse list
221 j join list members, separated by a space
222 j/PAT/ join list members, separated by PAT
223 i/PAT/ exclude all members not matching PAT
224 x/PAT/ exclude all members matching PAT
226 s/pat/match/ substitute PAT with MATCH
227 g/pat/match/ substitute PAT with MATCH for all occurrences
229 EXAMPLES:
230 *.c(:o) sorted list of .c files")
232 ;;; Functions:
234 (defun eshell-display-predicate-help ()
235 (interactive)
236 (with-electric-help
237 (function
238 (lambda ()
239 (insert eshell-predicate-help-string)))))
241 (defun eshell-display-modifier-help ()
242 (interactive)
243 (with-electric-help
244 (function
245 (lambda ()
246 (insert eshell-modifier-help-string)))))
248 (defun eshell-pred-initialize ()
249 "Initialize the predicate/modifier code."
250 (add-hook 'eshell-parse-argument-hook
251 'eshell-parse-arg-modifier t t)
252 (define-key eshell-command-map [(meta ?q)] 'eshell-display-predicate-help)
253 (define-key eshell-command-map [(meta ?m)] 'eshell-display-modifier-help))
255 (defun eshell-apply-modifiers (lst predicates modifiers)
256 "Apply to LIST a series of PREDICATES and MODIFIERS."
257 (let (stringified)
258 (if (stringp lst)
259 (setq lst (list lst)
260 stringified t))
261 (when (listp lst)
262 (setq lst (eshell-winnow-list lst nil predicates))
263 (while modifiers
264 (setq lst (funcall (car modifiers) lst)
265 modifiers (cdr modifiers)))
266 (if (and stringified
267 (= (length lst) 1))
268 (car lst)
269 lst))))
271 (defun eshell-parse-arg-modifier ()
272 "Parse a modifier that has been specified after an argument.
273 This function is specially for adding onto `eshell-parse-argument-hook'."
274 (when (eq (char-after) ?\()
275 (forward-char)
276 (let ((end (eshell-find-delimiter ?\( ?\))))
277 (if (not end)
278 (throw 'eshell-incomplete ?\()
279 (when (eshell-arg-delimiter (1+ end))
280 (save-restriction
281 (narrow-to-region (point) end)
282 (let* ((modifiers (eshell-parse-modifiers))
283 (preds (car modifiers))
284 (mods (cdr modifiers)))
285 (if (or preds mods)
286 ;; has to go at the end, which is only natural since
287 ;; syntactically it can only occur at the end
288 (setq eshell-current-modifiers
289 (append
290 eshell-current-modifiers
291 (list
292 `(lambda (lst)
293 (eshell-apply-modifiers
294 lst (quote ,preds) (quote ,mods)))))))))
295 (goto-char (1+ end))
296 (eshell-finish-arg))))))
298 (defun eshell-parse-modifiers ()
299 "Parse value modifiers and predicates at point.
300 Return a cons cell of the form
302 (PRED-FUNC-LIST . MOD-FUNC-LIST)
304 PRED-FUNC-LIST is a list of predicate functions. MOD-FUNC-LIST
305 is a list of result modifier functions. PRED-FUNCS take a
306 filename and return t if the test succeeds; MOD-FUNCS take any
307 list of strings and perform a modification, returning the
308 resultant list of strings."
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