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