Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / eshell / em-pred.el
blobc3b942d25a7d0e2403669e8d31c596c8459bf17b
1 ;;; em-pred.el --- argument predicates and modifiers (ala zsh) -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999-2018 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 <https://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 (= (file-attribute-user-id (file-attributes file))
93 (user-uid)))))
94 ;; (?G . #'(lambda (file) ; owned by effective gid
95 ;; (if (file-exists-p file)
96 ;; (= (file-attribute-user-id (file-attributes file))
97 ;; (user-uid)))))
98 (?* . #'(lambda (file)
99 (and (file-regular-p file)
100 (not (file-symlink-p file))
101 (file-executable-p file))))
102 (?l . (eshell-pred-file-links))
103 (?u . (eshell-pred-user-or-group ?u "user" 2 'eshell-user-id))
104 (?g . (eshell-pred-user-or-group ?g "group" 3 'eshell-group-id))
105 (?a . (eshell-pred-file-time ?a "access" 4))
106 (?m . (eshell-pred-file-time ?m "modification" 5))
107 (?c . (eshell-pred-file-time ?c "change" 6))
108 (?L . (eshell-pred-file-size)))
109 "A list of predicates than can be applied to a globbing pattern.
110 The format of each entry is
112 (CHAR . PREDICATE-FUNC-SEXP)"
113 :type '(repeat (cons character sexp))
114 :group 'eshell-pred)
116 (put 'eshell-predicate-alist 'risky-local-variable t)
118 (defcustom eshell-modifier-alist
119 '((?E . #'(lambda (lst)
120 (mapcar
121 (function
122 (lambda (str)
123 (eshell-stringify
124 (car (eshell-parse-argument str)))))
125 lst)))
126 (?L . #'(lambda (lst) (mapcar 'downcase lst)))
127 (?U . #'(lambda (lst) (mapcar 'upcase lst)))
128 (?C . #'(lambda (lst) (mapcar 'capitalize lst)))
129 (?h . #'(lambda (lst) (mapcar 'file-name-directory lst)))
130 (?i . (eshell-include-members))
131 (?x . (eshell-include-members t))
132 (?r . #'(lambda (lst) (mapcar 'file-name-sans-extension lst)))
133 (?e . #'(lambda (lst) (mapcar 'file-name-extension lst)))
134 (?t . #'(lambda (lst) (mapcar 'file-name-nondirectory lst)))
135 (?q . #'(lambda (lst) (mapcar 'eshell-escape-arg lst)))
136 (?u . #'(lambda (lst) (eshell-uniquify-list lst)))
137 (?o . #'(lambda (lst) (sort lst 'string-lessp)))
138 (?O . #'(lambda (lst) (nreverse (sort lst 'string-lessp))))
139 (?j . (eshell-join-members))
140 (?S . (eshell-split-members))
141 (?R . 'reverse)
142 (?g . (progn
143 (forward-char)
144 (if (eq (char-before) ?s)
145 (eshell-pred-substitute t)
146 (error "`g' modifier cannot be used alone"))))
147 (?s . (eshell-pred-substitute)))
148 "A list of modifiers than can be applied to an argument expansion.
149 The format of each entry is
151 (CHAR ENTRYWISE-P MODIFIER-FUNC-SEXP)"
152 :type '(repeat (cons character sexp))
153 :group 'eshell-pred)
155 (put 'eshell-modifier-alist 'risky-local-variable t)
157 (defvar eshell-predicate-help-string
158 "Eshell predicate quick reference:
160 - follow symbolic references for predicates after the `-'
161 ^ invert sense of predicates after the `^'
163 FILE TYPE:
164 / directories s sockets
165 . regular files p named pipes
166 * executable (files only) @ symbolic links
168 %x file type == `x' (as by ls -l; so `c' = char device, etc.)
170 PERMISSION BITS (for owner/group/world):
171 r/A/R readable s setuid
172 w/I/W writable S setgid
173 x/E/X executable t sticky bit
175 OWNERSHIP:
176 U owned by effective uid
177 u(UID|\\='user\\=') owned by UID/user
178 g(GID|\\='group\\=') owned by GID/group
180 FILE ATTRIBUTES:
181 l[+-]N +/-/= N links
182 a[Mwhms][+-](N|\\='FILE\\=') access time +/-/= N months/weeks/hours/mins/secs
183 (days if unspecified) if FILE specified,
184 use as comparison basis; so a+\\='file.c\\='
185 shows files accessed before file.c was
186 last accessed
187 m[Mwhms][+-](N|\\='FILE\\=') modification time...
188 c[Mwhms][+-](N|\\='FILE\\=') change time...
189 L[kmp][+-]N file size +/-/= N Kb/Mb/blocks
191 EXAMPLES:
192 *(^@) all non-dot files which are not symlinks
193 .#*(^@) all files which are not symbolic links
194 **/.#*(*) all executable files, searched recursively
195 ***/*~f*(-/) recursively (though not traversing symlinks),
196 find all directories (or symlinks referring to
197 directories) whose names do not begin with f.
198 e*(*Lk+50) executables 50k or larger beginning with `e'")
200 (defvar eshell-modifier-help-string
201 "Eshell modifier quick reference:
203 FOR SINGLE ARGUMENTS, or each argument of a list of strings:
204 E evaluate again
205 L lowercase
206 U uppercase
207 C capitalize
208 h dirname
209 t basename
210 e file extension
211 r strip file extension
212 q escape special characters
214 S split string at any whitespace character
215 S/PAT/ split string at each occurrence of PAT
217 FOR LISTS OF ARGUMENTS:
218 o sort alphabetically
219 O reverse sort alphabetically
220 u uniq list (typically used after :o or :O)
221 R reverse list
223 j join list members, separated by a space
224 j/PAT/ join list members, separated by PAT
225 i/PAT/ exclude all members not matching PAT
226 x/PAT/ exclude all members matching PAT
228 s/pat/match/ substitute PAT with MATCH
229 g/pat/match/ substitute PAT with MATCH for all occurrences
231 EXAMPLES:
232 *.c(:o) sorted list of .c files")
234 ;;; Functions:
236 (defun eshell-display-predicate-help ()
237 (interactive)
238 (with-electric-help
239 (function
240 (lambda ()
241 (insert eshell-predicate-help-string)))))
243 (defun eshell-display-modifier-help ()
244 (interactive)
245 (with-electric-help
246 (function
247 (lambda ()
248 (insert eshell-modifier-help-string)))))
250 (defun eshell-pred-initialize ()
251 "Initialize the predicate/modifier code."
252 (add-hook 'eshell-parse-argument-hook
253 'eshell-parse-arg-modifier t t)
254 (define-key eshell-command-map [(meta ?q)] 'eshell-display-predicate-help)
255 (define-key eshell-command-map [(meta ?m)] 'eshell-display-modifier-help))
257 (defun eshell-apply-modifiers (lst predicates modifiers)
258 "Apply to LIST a series of PREDICATES and MODIFIERS."
259 (let (stringified)
260 (if (stringp lst)
261 (setq lst (list lst)
262 stringified t))
263 (when (listp lst)
264 (setq lst (eshell-winnow-list lst nil predicates))
265 (while modifiers
266 (setq lst (funcall (car modifiers) lst)
267 modifiers (cdr modifiers)))
268 (if (and stringified
269 (= (length lst) 1))
270 (car lst)
271 lst))))
273 (defun eshell-parse-arg-modifier ()
274 "Parse a modifier that has been specified after an argument.
275 This function is specially for adding onto `eshell-parse-argument-hook'."
276 (when (eq (char-after) ?\()
277 (forward-char)
278 (let ((end (eshell-find-delimiter ?\( ?\))))
279 (if (not end)
280 (throw 'eshell-incomplete ?\()
281 (when (eshell-arg-delimiter (1+ end))
282 (save-restriction
283 (narrow-to-region (point) end)
284 (let* ((modifiers (eshell-parse-modifiers))
285 (preds (car modifiers))
286 (mods (cdr modifiers)))
287 (if (or preds mods)
288 ;; has to go at the end, which is only natural since
289 ;; syntactically it can only occur at the end
290 (setq eshell-current-modifiers
291 (append
292 eshell-current-modifiers
293 (list
294 `(lambda (lst)
295 (eshell-apply-modifiers
296 lst (quote ,preds) (quote ,mods)))))))))
297 (goto-char (1+ end))
298 (eshell-finish-arg))))))
300 (defun eshell-parse-modifiers ()
301 "Parse value modifiers and predicates at point.
302 Return a cons cell of the form
304 (PRED-FUNC-LIST . MOD-FUNC-LIST)
306 PRED-FUNC-LIST is a list of predicate functions. MOD-FUNC-LIST
307 is a list of result modifier functions. PRED-FUNCS take a
308 filename and return t if the test succeeds; MOD-FUNCS take any
309 list of strings and perform a modification, returning the
310 resultant list of strings."
311 (let (negate follow preds mods)
312 (condition-case nil
313 (while (not (eobp))
314 (let ((char (char-after)))
315 (cond
316 ((eq char ?')
317 (forward-char)
318 (if (looking-at "[^|':]")
319 (let ((func (read (current-buffer))))
320 (if (and func (functionp func))
321 (setq preds (eshell-add-pred-func func preds
322 negate follow))
323 (error "Invalid function predicate `%s'"
324 (eshell-stringify func))))
325 (error "Invalid function predicate")))
326 ((eq char ?^)
327 (forward-char)
328 (setq negate (not negate)))
329 ((eq char ?-)
330 (forward-char)
331 (setq follow (not follow)))
332 ((eq char ?|)
333 (forward-char)
334 (if (looking-at "[^|':]")
335 (let ((func (read (current-buffer))))
336 (if (and func (functionp func))
337 (setq mods
338 (cons `(lambda (lst)
339 (mapcar (function ,func) lst))
340 mods))
341 (error "Invalid function modifier `%s'"
342 (eshell-stringify func))))
343 (error "Invalid function modifier")))
344 ((eq char ?:)
345 (forward-char)
346 (let ((mod (assq (char-after) eshell-modifier-alist)))
347 (if (not mod)
348 (error "Unknown modifier character `%c'" (char-after))
349 (forward-char)
350 (setq mods (cons (eval (cdr mod)) mods)))))
352 (let ((pred (assq char eshell-predicate-alist)))
353 (if (not pred)
354 (error "Unknown predicate character `%c'" char)
355 (forward-char)
356 (setq preds
357 (eshell-add-pred-func (eval (cdr pred)) preds
358 negate follow))))))))
359 (end-of-buffer
360 (error "Predicate or modifier ended prematurely")))
361 (cons (nreverse preds) (nreverse mods))))
363 (defun eshell-add-pred-func (pred funcs negate follow)
364 "Add the predicate function PRED to FUNCS."
365 (if negate
366 (setq pred `(lambda (file)
367 (not (funcall ,pred file)))))
368 (if follow
369 (setq pred `(lambda (file)
370 (funcall ,pred (file-truename file)))))
371 (cons pred funcs))
373 (defun eshell-pred-user-or-group (mod-char mod-type attr-index get-id-func)
374 "Return a predicate to test whether a file match a given user/group id."
375 (let (ugid open close end)
376 (if (looking-at "[0-9]+")
377 (progn
378 (setq ugid (string-to-number (match-string 0)))
379 (goto-char (match-end 0)))
380 (setq open (char-after))
381 (if (setq close (memq open '(?\( ?\[ ?\< ?\{)))
382 (setq close (car (last '(?\) ?\] ?\> ?\})
383 (length close))))
384 (setq close open))
385 (forward-char)
386 (setq end (eshell-find-delimiter open close))
387 (unless end
388 (error "Malformed %s name string for modifier `%c'"
389 mod-type mod-char))
390 (setq ugid
391 (funcall get-id-func (buffer-substring (point) end)))
392 (goto-char (1+ end)))
393 (unless ugid
394 (error "Unknown %s name specified for modifier `%c'"
395 mod-type mod-char))
396 `(lambda (file)
397 (let ((attrs (file-attributes file)))
398 (if attrs
399 (= (nth ,attr-index attrs) ,ugid))))))
401 (defun eshell-pred-file-time (mod-char mod-type attr-index)
402 "Return a predicate to test whether a file matches a certain time."
403 (let* ((quantum 86400)
404 qual when open close end)
405 (when (memq (char-after) '(?M ?w ?h ?m ?s))
406 (setq quantum (char-after))
407 (cond
408 ((eq quantum ?M)
409 (setq quantum (* 60 60 24 30)))
410 ((eq quantum ?w)
411 (setq quantum (* 60 60 24 7)))
412 ((eq quantum ?h)
413 (setq quantum (* 60 60)))
414 ((eq quantum ?m)
415 (setq quantum 60))
416 ((eq quantum ?s)
417 (setq quantum 1)))
418 (forward-char))
419 (when (memq (char-after) '(?+ ?-))
420 (setq qual (char-after))
421 (forward-char))
422 (if (looking-at "[0-9]+")
423 (progn
424 (setq when (- (float-time)
425 (* (string-to-number (match-string 0))
426 quantum)))
427 (goto-char (match-end 0)))
428 (setq open (char-after))
429 (if (setq close (memq open '(?\( ?\[ ?\< ?\{)))
430 (setq close (car (last '(?\) ?\] ?\> ?\})
431 (length close))))
432 (setq close open))
433 (forward-char)
434 (setq end (eshell-find-delimiter open close))
435 (unless end
436 (error "Malformed %s time modifier `%c'" mod-type mod-char))
437 (let* ((file (buffer-substring (point) end))
438 (attrs (file-attributes file)))
439 (unless attrs
440 (error "Cannot stat file `%s'" file))
441 (setq when (float-time (nth attr-index attrs))))
442 (goto-char (1+ end)))
443 `(lambda (file)
444 (let ((attrs (file-attributes file)))
445 (if attrs
446 (,(if (eq qual ?-)
448 (if (eq qual ?+)
450 '=)) ,when (float-time
451 (nth ,attr-index attrs))))))))
453 (defun eshell-pred-file-type (type)
454 "Return a test which tests that the file is of a certain TYPE.
455 TYPE must be a character, and should be one of the possible options
456 that `ls -l' will show in the first column of its display. "
457 (when (eq type ?%)
458 (setq type (char-after))
459 (if (memq type '(?b ?c))
460 (forward-char)
461 (setq type ?%)))
462 `(lambda (file)
463 (let ((attrs (eshell-file-attributes (directory-file-name file))))
464 (if attrs
465 (memq (aref (file-attribute-modes attrs) 0)
466 ,(if (eq type ?%)
467 '(?b ?c)
468 (list 'quote (list type))))))))
470 (defsubst eshell-pred-file-mode (mode)
471 "Return a test which tests that MODE pertains to the file."
472 `(lambda (file)
473 (let ((modes (file-modes file)))
474 (if modes
475 (logand ,mode modes)))))
477 (defun eshell-pred-file-links ()
478 "Return a predicate to test whether a file has a given number of links."
479 (let (qual amount)
480 (when (memq (char-after) '(?- ?+))
481 (setq qual (char-after))
482 (forward-char))
483 (unless (looking-at "[0-9]+")
484 (error "Invalid file link count modifier `l'"))
485 (setq amount (string-to-number (match-string 0)))
486 (goto-char (match-end 0))
487 `(lambda (file)
488 (let ((attrs (eshell-file-attributes file)))
489 (if attrs
490 (,(if (eq qual ?-)
492 (if (eq qual ?+)
494 '=))
495 (file-attribute-link-number attrs) ,amount))))))
497 (defun eshell-pred-file-size ()
498 "Return a predicate to test whether a file is of a given size."
499 (let ((quantum 1) qual amount)
500 (when (memq (downcase (char-after)) '(?k ?m ?p))
501 (setq qual (downcase (char-after)))
502 (cond
503 ((eq qual ?k)
504 (setq quantum 1024))
505 ((eq qual ?m)
506 (setq quantum (* 1024 1024)))
507 ((eq qual ?p)
508 (setq quantum 512)))
509 (forward-char))
510 (when (memq (char-after) '(?- ?+))
511 (setq qual (char-after))
512 (forward-char))
513 (unless (looking-at "[0-9]+")
514 (error "Invalid file size modifier `L'"))
515 (setq amount (* (string-to-number (match-string 0)) quantum))
516 (goto-char (match-end 0))
517 `(lambda (file)
518 (let ((attrs (eshell-file-attributes file)))
519 (if attrs
520 (,(if (eq qual ?-)
522 (if (eq qual ?+)
524 '=))
525 (file-attribute-size attrs) ,amount))))))
527 (defun eshell-pred-substitute (&optional repeat)
528 "Return a modifier function that will substitute matches."
529 (let ((delim (char-after))
530 match replace end)
531 (forward-char)
532 (setq end (eshell-find-delimiter delim delim nil nil t)
533 match (buffer-substring-no-properties (point) end))
534 (goto-char (1+ end))
535 (setq end (eshell-find-delimiter delim delim nil nil t)
536 replace (buffer-substring-no-properties (point) end))
537 (goto-char (1+ end))
538 (if repeat
539 `(lambda (lst)
540 (mapcar
541 (function
542 (lambda (str)
543 (let ((i 0))
544 (while (setq i (string-match ,match str i))
545 (setq str (replace-match ,replace t nil str))))
546 str)) lst))
547 `(lambda (lst)
548 (mapcar
549 (function
550 (lambda (str)
551 (if (string-match ,match str)
552 (setq str (replace-match ,replace t nil str))
553 (error (concat str ": substitution failed")))
554 str)) lst)))))
556 (defun eshell-include-members (&optional invert-p)
557 "Include only lisp members matching a regexp."
558 (let ((delim (char-after))
559 regexp end)
560 (forward-char)
561 (setq end (eshell-find-delimiter delim delim nil nil t)
562 regexp (buffer-substring-no-properties (point) end))
563 (goto-char (1+ end))
564 `(lambda (lst)
565 (eshell-winnow-list
566 lst nil '((lambda (elem)
567 ,(if invert-p
568 `(not (string-match ,regexp elem))
569 `(string-match ,regexp elem))))))))
571 (defun eshell-join-members ()
572 "Return a modifier function that join matches."
573 (let ((delim (char-after))
574 str end)
575 (if (not (memq delim '(?' ?/)))
576 (setq delim " ")
577 (forward-char)
578 (setq end (eshell-find-delimiter delim delim nil nil t)
579 str (buffer-substring-no-properties (point) end))
580 (goto-char (1+ end)))
581 `(lambda (lst)
582 (mapconcat 'identity lst ,str))))
584 (defun eshell-split-members ()
585 "Return a modifier function that splits members."
586 (let ((delim (char-after))
587 sep end)
588 (when (memq delim '(?' ?/))
589 (forward-char)
590 (setq end (eshell-find-delimiter delim delim nil nil t)
591 sep (buffer-substring-no-properties (point) end))
592 (goto-char (1+ end)))
593 `(lambda (lst)
594 (mapcar
595 (function
596 (lambda (str)
597 (split-string str ,sep))) lst))))
599 (provide 'em-pred)
601 ;; Local Variables:
602 ;; generated-autoload-file: "esh-groups.el"
603 ;; End:
605 ;;; em-pred.el ends here