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