Some fixes to follow coding conventions in files from Gnus.
[bpt/emacs.git] / lisp / eshell / em-pred.el
CommitLineData
affbf647
GM
1;;; em-pred --- argument predicates and modifiers (ala zsh)
2
faadfb0a 3;; Copyright (C) 1999, 2000 Free Software Foundation
affbf647 4
7de5b421
GM
5;; Author: John Wiegley <johnw@gnu.org>
6
affbf647
GM
7;; This file is part of GNU Emacs.
8
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 2, or (at your option)
12;; any later version.
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
20;; along with GNU Emacs; see the file COPYING. If not, write to the
21;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22;; Boston, MA 02111-1307, USA.
23
24(provide 'em-pred)
25
26(eval-when-compile (require 'esh-maint))
27
28(defgroup eshell-pred nil
29 "This module allows for predicates to be applied to globbing
30patterns (similar to zsh), in addition to string modifiers which can
31be applied either to globbing results, variable references, or just
32ordinary strings."
33 :tag "Value modifiers and predicates"
34 :group 'eshell-module)
35
36;;; Commentary:
37
38;; Argument predication is used to affect which members of a list are
39;; selected for use as argument. This is most useful with globbing,
40;; but can be used on any list argument, to select certain members.
41;;
42;; Argument modifiers are used to manipulate argument values. For
43;; example, sorting lists, upcasing words, substituting characters,
44;; etc.
45;;
46;; Here are some examples of how to use argument predication. Most of
47;; the predicates and modifiers are modeled after those provided by
48;; zsh.
49;;
50;; ls -ld *(/) ; list all directories
51;; ls -l *(@u'johnw') ; list all symlinks owned by 'johnw'
52;; bzip2 -9v **/*(a+30) ; compress everything which hasn't been
53;; accessed in 30 days
54;; echo *.c(:o:R) ; a reversed, sorted list of C files
55;; *(^@:U^u0) ; all non-symlinks not owned by 'root', upcased
56;; chmod u-x *(U*) : remove exec bit on all executables owned by user
57;;
58;; See the zsh docs for more on the syntax ([(zsh.info)Filename
59;; Generation]).
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.
105The 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.
154The 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
168FILE 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
175PERMISSION 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
180OWNERSHIP:
181 U owned by effective uid
182 u(UID|'user') owned by UID/user
183 g(GID|'group') owned by GID/group
184
185FILE ATTRIBUTES:
186 l[+-]N +/-/= N links
187 a[Mwhm][+-](N|'FILE') access time +/-/= N mnths/weeks/days/mins
188 if FILE specified, use as comparison basis;
189 so a+'file.c' shows files accessed before
190 file.c was last accessed
191 m[Mwhm][+-](N|'FILE') modification time...
192 c[Mwhm][+-](N|'FILE') change time...
193 L[kmp][+-]N file size +/-/= N Kb/Mb/blocks
194
195EXAMPLES:
196 *(^@) all non-dot files which are not symlinks
197 .#*(^@) all files which are not symbolic links
198 **/.#*(*) all executable files, searched recursively
199 ***/*~f*(-/) recursively (though not traversing symlinks),
200 find all directories (or symlinks referring to
201 directories) whose names do not begin with f.
202 e*(*Lk+50) executables 50k or larger beginning with 'e'")
203
204(defvar eshell-modifier-help-string
205 "Eshell modifier quick reference:
206
207FOR SINGLE ARGUMENTS, or each argument of a list of strings:
208 e evaluate again
209 L lowercase
210 U uppercase
211 C capitalize
212 h dirname
213 t basename
214 e file extension
215 r strip file extension
216 q escape special characters
217
218 S split string at any whitespace character
219 S/PAT/ split string at each occurance of PAT
220
221FOR LISTS OF ARGUMENTS:
222 o sort alphabetically
223 O reverse sort alphabetically
224 u uniq list (typically used after :o or :O)
225 R reverse list
226
227 j join list members, separated by a space
228 j/PAT/ join list members, separated by PAT
229 i/PAT/ exclude all members not matching PAT
230 x/PAT/ exclude all members matching PAT
231
232 s/pat/match/ substitute PAT with MATCH
233 g/pat/match/ substitute PAT with MATCH for all occurances
234
235EXAMPLES:
236 *.c(:o) sorted list of .c files")
237
238;;; Functions:
239
240(defun eshell-display-predicate-help ()
241 (interactive)
242 (with-electric-help
243 (function
244 (lambda ()
245 (insert eshell-predicate-help-string)))))
246
247(defun eshell-display-modifier-help ()
248 (interactive)
249 (with-electric-help
250 (function
251 (lambda ()
252 (insert eshell-modifier-help-string)))))
253
254(defun eshell-pred-initialize ()
255 "Initialize the predicate/modifier code."
256 (make-local-hook 'eshell-parse-argument-hook)
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.
280This 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.
307If ALLOW-PREDS is non-nil, predicates will be parsed as well.
308Return a cons cell of the form
309
310 (PRED-FUNC-LIST . MOD-FUNC-LIST)
311
312NEW-STRING is STRING minus any modifiers. PRED-FUNC-LIST is a list of
313predicate functions. MOD-FUNC-LIST is a list of result modifier
314functions. PRED-FUNCS take a filename and return t if the test
315succeeds; MOD-FUNCS take any string and preform a modification,
316returning 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))
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.
461TYPE must be a character, and should be one of the possible options
462that '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)
8c6b1d83 469 (let ((attrs (eshell-file-attributes (directory-file-name file))))
affbf647
GM
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)
8c6b1d83 494 (let ((attrs (eshell-file-attributes file)))
affbf647
GM
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)
8c6b1d83 523 (let ((attrs (eshell-file-attributes file)))
affbf647
GM
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
affbf647 602;;; em-pred.el ends here