Merge branch 'master' into comment-cache
[emacs.git] / lisp / dired-x.el
blob86c95372c251704f83e7524a1a2214a82e51c55d
1 ;;; dired-x.el --- extra Dired functionality -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1994, 1997, 2001-2017 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
7 ;; Lawrence R. Dodd <dodd@roebling.poly.edu>
8 ;; Maintainer: Romain Francoise <rfrancoise@gnu.org>
9 ;; Keywords: dired extensions files
10 ;; Package: emacs
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; This is based on Sebastian Kremer's excellent dired-x.el (Dired Extra),
30 ;; version 1.191, adapted for GNU Emacs. See the `dired-x' info pages.
32 ;; At load time dired-x.el will install itself and bind some dired keys.
33 ;; Some dired.el and dired-aux.el functions have extra features if
34 ;; dired-x is loaded.
36 ;; User customization: M-x customize-group RET dired-x RET.
38 ;; *Please* see the `dired-x' info pages for more details.
41 ;;; Code:
43 ;; This is a no-op if dired-x is being loaded via `dired-load-hook',
44 ;; but maybe not if a dired-x function is being autoloaded.
45 (require 'dired)
47 ;;; User-defined variables.
49 (defgroup dired-x nil
50 "Extended directory editing (dired-x)."
51 :group 'dired)
53 (defgroup dired-keys nil
54 "Dired keys customizations."
55 :prefix "dired-"
56 :group 'dired-x)
58 (defcustom dired-bind-vm nil
59 "Non-nil means \"V\" runs `dired-vm', otherwise \"V\" runs `dired-rmail'.
60 RMAIL files in the old Babyl format (used before before Emacs 23.1)
61 contain \"-*- rmail -*-\" at the top, so `dired-find-file'
62 will run `rmail' on these files. New RMAIL files use the standard
63 mbox format, and so cannot be distinguished in this way."
64 :type 'boolean
65 :group 'dired-keys)
67 (defcustom dired-bind-jump t
68 "Non-nil means bind `dired-jump' to C-x C-j, otherwise do not.
69 Setting this variable directly after dired-x is loaded has no effect -
70 use \\[customize]."
71 :type 'boolean
72 :set (lambda (sym val)
73 (if (set sym val)
74 (progn
75 (define-key ctl-x-map "\C-j" 'dired-jump)
76 (define-key ctl-x-4-map "\C-j" 'dired-jump-other-window))
77 (if (eq 'dired-jump (lookup-key ctl-x-map "\C-j"))
78 (define-key ctl-x-map "\C-j" nil))
79 (if (eq 'dired-jump-other-window (lookup-key ctl-x-4-map "\C-j"))
80 (define-key ctl-x-4-map "\C-j" nil))))
81 :group 'dired-keys)
83 (defcustom dired-bind-man t
84 "Non-nil means bind `dired-man' to \"N\" in Dired, otherwise do not.
85 Setting this variable directly after dired-x is loaded has no effect -
86 use \\[customize]."
87 :type 'boolean
88 :set (lambda (sym val)
89 (if (set sym val)
90 (define-key dired-mode-map "N" 'dired-man)
91 (if (eq 'dired-man (lookup-key dired-mode-map "N"))
92 (define-key dired-mode-map "N" nil))))
93 :group 'dired-keys)
95 (defcustom dired-bind-info t
96 "Non-nil means bind `dired-info' to \"I\" in Dired, otherwise do not.
97 Setting this variable directly after dired-x is loaded has no effect -
98 use \\[customize]."
99 :type 'boolean
100 :set (lambda (sym val)
101 (if (set sym val)
102 (define-key dired-mode-map "I" 'dired-info)
103 (if (eq 'dired-info (lookup-key dired-mode-map "I"))
104 (define-key dired-mode-map "I" nil))))
105 :group 'dired-keys)
107 (defcustom dired-vm-read-only-folders nil
108 "If non-nil, \\[dired-vm] will visit all folders read-only.
109 If neither nil nor t, e.g. the symbol `if-file-read-only', only
110 files not writable by you are visited read-only."
111 :type '(choice (const :tag "off" nil)
112 (const :tag "on" t)
113 (other :tag "non-writable only" if-file-read-only))
114 :group 'dired-x)
116 (defcustom dired-omit-size-limit 30000
117 "Maximum size for the \"omitting\" feature.
118 If nil, there is no maximum size."
119 :type '(choice (const :tag "no maximum" nil) integer)
120 :group 'dired-x)
122 (defcustom dired-omit-case-fold 'filesystem
123 "Determine whether \"omitting\" patterns are case-sensitive.
124 When nil, always be case-sensitive; when t, always be
125 case-insensitive; the default value, `filesystem', causes case
126 folding to be used on case-insensitive filesystems only."
127 :type '(choice (const :tag "Always case-sensitive" nil)
128 (const :tag "Always case-insensitive" t)
129 (const :tag "According to filesystem" filesystem))
130 :group 'dired-x
131 :version "26.1")
133 (declare-function file-name-case-insensitive-p "fileio.c" (filename))
134 (defun dired-omit-case-fold-p (dir)
135 "Non-nil if `dired-omit-mode' should be case-insensitive in DIR."
136 (if (eq dired-omit-case-fold 'filesystem)
137 (file-name-case-insensitive-p dir)
138 dired-omit-case-fold))
140 ;; For backward compatibility
141 (define-obsolete-variable-alias 'dired-omit-files-p 'dired-omit-mode "22.1")
142 (define-minor-mode dired-omit-mode
143 "Toggle omission of uninteresting files in Dired (Dired-Omit mode).
144 With a prefix argument ARG, enable Dired-Omit mode if ARG is
145 positive, and disable it otherwise. If called from Lisp, enable
146 the mode if ARG is omitted or nil.
148 Dired-Omit mode is a buffer-local minor mode. When enabled in a
149 Dired buffer, Dired does not list files whose filenames match
150 regexp `dired-omit-files', nor files ending with extensions in
151 `dired-omit-extensions'.
153 To enable omitting in every Dired buffer, you can put this in
154 your init file:
156 (add-hook \\='dired-mode-hook (lambda () (dired-omit-mode)))
158 See Info node `(dired-x) Omitting Variables' for more information."
159 :group 'dired-x
160 (if dired-omit-mode
161 ;; This will mention how many lines were omitted:
162 (let ((dired-omit-size-limit nil)) (dired-omit-expunge))
163 (revert-buffer)))
165 (put 'dired-omit-mode 'safe-local-variable 'booleanp)
167 (defcustom dired-omit-files "^\\.?#\\|^\\.$\\|^\\.\\.$"
168 "Filenames matching this regexp will not be displayed.
169 This only has effect when `dired-omit-mode' is t. See interactive function
170 `dired-omit-mode' (\\[dired-omit-mode]) and variable
171 `dired-omit-extensions'. The default is to omit `.', `..', auto-save
172 files and lock files."
173 :type 'regexp
174 :group 'dired-x)
176 (defcustom dired-omit-verbose t
177 "When non-nil, show messages when omitting files.
178 When nil, don't show messages."
179 :version "24.1"
180 :type 'boolean
181 :group 'dired-x)
183 (defcustom dired-find-subdir nil ; t is pretty near to DWIM...
184 "If non-nil, Dired always finds a directory in a buffer of its own.
185 If nil, Dired finds the directory as a subdirectory in some other buffer
186 if it is present as one.
188 If there are several Dired buffers for a directory, the most recently
189 used is chosen.
191 Dired avoids switching to the current buffer, so that if you have
192 a normal and a wildcard buffer for the same directory, \\[dired] will
193 toggle between those two."
194 :type 'boolean
195 :group 'dired-x)
197 (defcustom dired-enable-local-variables t
198 "Control use of local-variables lists in Dired.
199 This temporarily overrides the value of `enable-local-variables' when
200 listing a directory. See also `dired-local-variables-file'."
201 :risky t
202 :type '(choice (const :tag "Query Unsafe" t)
203 (const :tag "Safe Only" :safe)
204 (const :tag "Do all" :all)
205 (const :tag "Ignore" nil)
206 (other :tag "Query" other))
207 :group 'dired-x)
209 (make-obsolete-variable 'dired-enable-local-variables
210 "use a standard `dir-locals-file' instead." "24.1")
212 (defcustom dired-guess-shell-gnutar
213 (catch 'found
214 (dolist (exe '("tar" "gtar"))
215 (if (with-temp-buffer
216 (ignore-errors (call-process exe nil t nil "--version"))
217 (and (re-search-backward "GNU tar" nil t) t))
218 (throw 'found exe))))
219 "If non-nil, name of GNU tar executable.
220 \(E.g., \"tar\" or \"gtar\"). The `z' switch will be used with it for
221 compressed or gzip'ed tar files. If you don't have GNU tar, set this
222 to nil: a pipe using `zcat' or `gunzip -c' will be used."
223 ;; Changed from system-type test to testing --version output.
224 ;; Maybe test --help for -z instead?
225 :version "24.1"
226 :type '(choice (const :tag "Not GNU tar" nil)
227 (string :tag "Command name"))
228 :group 'dired-x)
230 (defcustom dired-guess-shell-gzip-quiet t
231 "Non-nil says pass -q to gzip overriding verbose GZIP environment."
232 :type 'boolean
233 :group 'dired-x)
235 (defcustom dired-guess-shell-znew-switches nil
236 "If non-nil, then string of switches passed to `znew', example: \"-K\"."
237 :type '(choice (const :tag "None" nil)
238 (string :tag "Switches"))
239 :group 'dired-x)
241 (defcustom dired-clean-up-buffers-too t
242 "Non-nil means offer to kill buffers visiting files and dirs deleted in Dired."
243 :type 'boolean
244 :group 'dired-x)
246 ;;; KEY BINDINGS.
248 (define-key dired-mode-map "\C-x\M-o" 'dired-omit-mode)
249 (define-key dired-mode-map "*O" 'dired-mark-omitted)
250 (define-key dired-mode-map "\M-(" 'dired-mark-sexp)
251 (define-key dired-mode-map "*(" 'dired-mark-sexp)
252 (define-key dired-mode-map "*." 'dired-mark-extension)
253 (define-key dired-mode-map "\M-!" 'dired-smart-shell-command)
254 (define-key dired-mode-map "\M-G" 'dired-goto-subdir)
255 (define-key dired-mode-map "F" 'dired-do-find-marked-files)
256 (define-key dired-mode-map "Y" 'dired-do-relsymlink)
257 (define-key dired-mode-map "%Y" 'dired-do-relsymlink-regexp)
258 (define-key dired-mode-map "V" 'dired-do-run-mail)
260 ;;; MENU BINDINGS
262 (require 'easymenu)
264 (let ((menu (lookup-key dired-mode-map [menu-bar])))
265 (easy-menu-add-item menu '("Operate")
266 ["Find Files" dired-do-find-marked-files
267 :help "Find current or marked files"]
268 "Shell Command...")
269 (easy-menu-add-item menu '("Operate")
270 ["Relative Symlink to..." dired-do-relsymlink
271 :visible (fboundp 'make-symbolic-link)
272 :help "Make relative symbolic links for current or \
273 marked files"]
274 "Hardlink to...")
275 (easy-menu-add-item menu '("Mark")
276 ["Flag Extension..." dired-flag-extension
277 :help "Flag files with a certain extension for deletion"]
278 "Mark Executables")
279 (easy-menu-add-item menu '("Mark")
280 ["Mark Extension..." dired-mark-extension
281 :help "Mark files with a certain extension"]
282 "Unmark All")
283 (easy-menu-add-item menu '("Mark")
284 ["Mark Omitted" dired-mark-omitted
285 :help "Mark files matching `dired-omit-files' \
286 and `dired-omit-extensions'"]
287 "Unmark All")
288 (easy-menu-add-item menu '("Regexp")
289 ["Relative Symlink..." dired-do-relsymlink-regexp
290 :visible (fboundp 'make-symbolic-link)
291 :help "Make relative symbolic links for files \
292 matching regexp"]
293 "Hardlink...")
294 (easy-menu-add-item menu '("Immediate")
295 ["Omit Mode" dired-omit-mode
296 :style toggle :selected dired-omit-mode
297 :help "Enable or disable omitting \"uninteresting\" \
298 files"]
299 "Refresh"))
302 ;; Install into appropriate hooks.
304 (add-hook 'dired-mode-hook 'dired-extra-startup)
305 (add-hook 'dired-after-readin-hook 'dired-omit-expunge)
307 (defun dired-extra-startup ()
308 "Automatically put on `dired-mode-hook' to get extra Dired features:
309 \\<dired-mode-map>
310 \\[dired-do-run-mail]\t-- run mail on folder (see `dired-bind-vm')
311 \\[dired-info]\t-- run info on file
312 \\[dired-man]\t-- run man on file
313 \\[dired-do-find-marked-files]\t-- visit all marked files simultaneously
314 \\[dired-omit-mode]\t-- toggle omitting of files
315 \\[dired-mark-sexp]\t-- mark by Lisp expression
317 To see the options you can set, use M-x customize-group RET dired-x RET.
318 See also the functions:
319 `dired-flag-extension'
320 `dired-virtual'
321 `dired-jump'
322 `dired-man'
323 `dired-vm'
324 `dired-rmail'
325 `dired-info'
326 `dired-do-find-marked-files'"
327 (interactive)
328 ;; These must be done in each new dired buffer.
329 (dired-hack-local-variables)
330 (dired-omit-startup))
333 ;;; EXTENSION MARKING FUNCTIONS.
335 ;; Mark files with some extension.
336 (defun dired-mark-extension (extension &optional marker-char)
337 "Mark all files with a certain EXTENSION for use in later commands.
338 A `.' is *not* automatically prepended to the string entered.
339 EXTENSION may also be a list of extensions instead of a single one.
340 Optional MARKER-CHAR is marker to use.
341 Interactively, ask for EXTENSION.
342 Prefixed with one C-u, unmark files instead.
343 Prefixed with two C-u's, prompt for MARKER-CHAR and mark files with it."
344 (interactive
345 (let ((suffix
346 (read-string (format "%s extension: "
347 (if (equal current-prefix-arg '(4))
348 "UNmarking"
349 "Marking"))))
350 (marker
351 (pcase current-prefix-arg
352 ('(4) ?\s)
353 ('(16)
354 (let* ((dflt (char-to-string dired-marker-char))
355 (input (read-string
356 (format
357 "Marker character to use (default %s): " dflt)
358 nil nil dflt)))
359 (aref input 0)))
360 (_ dired-marker-char))))
361 (list suffix marker)))
362 (or (listp extension)
363 (setq extension (list extension)))
364 (dired-mark-files-regexp
365 (concat ".";; don't match names with nothing but an extension
366 "\\("
367 (mapconcat 'regexp-quote extension "\\|")
368 "\\)$")
369 marker-char))
371 (defun dired-flag-extension (extension)
372 "In Dired, flag all files with a certain EXTENSION for deletion.
373 A `.' is *not* automatically prepended to the string entered."
374 (interactive "sFlagging extension: ")
375 (dired-mark-extension extension dired-del-marker))
377 ;; Define some unpopular file extensions. Used for cleaning and omitting.
379 (defvar dired-patch-unclean-extensions
380 '(".rej" ".orig")
381 "List of extensions of dispensable files created by the `patch' program.")
383 (defvar dired-tex-unclean-extensions
384 '(".toc" ".log" ".aux");; these are already in completion-ignored-extensions
385 "List of extensions of dispensable files created by TeX.")
387 (defvar dired-latex-unclean-extensions
388 '(".idx" ".lof" ".lot" ".glo")
389 "List of extensions of dispensable files created by LaTeX.")
391 (defvar dired-bibtex-unclean-extensions
392 '(".blg" ".bbl")
393 "List of extensions of dispensable files created by BibTeX.")
395 (defvar dired-texinfo-unclean-extensions
396 '(".cp" ".cps" ".fn" ".fns" ".ky" ".kys" ".pg" ".pgs"
397 ".tp" ".tps" ".vr" ".vrs")
398 "List of extensions of dispensable files created by texinfo.")
400 (defun dired-clean-patch ()
401 "Flag dispensable files created by patch for deletion.
402 See variable `dired-patch-unclean-extensions'."
403 (interactive)
404 (dired-flag-extension dired-patch-unclean-extensions))
406 (defun dired-clean-tex ()
407 "Flag dispensable files created by [La]TeX etc. for deletion.
408 See variables `dired-tex-unclean-extensions',
409 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions' and
410 `dired-texinfo-unclean-extensions'."
411 (interactive)
412 (dired-flag-extension (append dired-texinfo-unclean-extensions
413 dired-latex-unclean-extensions
414 dired-bibtex-unclean-extensions
415 dired-tex-unclean-extensions)))
417 (defun dired-very-clean-tex ()
418 "Flag dispensable files created by [La]TeX *and* \".dvi\" for deletion.
419 See variables `dired-texinfo-unclean-extensions',
420 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions' and
421 `dired-texinfo-unclean-extensions'."
422 (interactive)
423 (dired-flag-extension (append dired-texinfo-unclean-extensions
424 dired-latex-unclean-extensions
425 dired-bibtex-unclean-extensions
426 dired-tex-unclean-extensions
427 (list ".dvi"))))
429 (defvar tar-superior-buffer)
430 ;;; JUMP.
432 ;;;###autoload
433 (defun dired-jump (&optional other-window file-name)
434 "Jump to Dired buffer corresponding to current buffer.
435 If in a file, Dired the current directory and move to file's line.
436 If in Dired already, pop up a level and goto old directory's line.
437 In case the proper Dired file line cannot be found, refresh the dired
438 buffer and try again.
439 When OTHER-WINDOW is non-nil, jump to Dired buffer in other window.
440 When FILE-NAME is non-nil, jump to its line in Dired.
441 Interactively with prefix argument, read FILE-NAME."
442 (interactive
443 (list nil (and current-prefix-arg
444 (read-file-name "Jump to Dired file: "))))
445 (if (bound-and-true-p tar-subfile-mode)
446 (switch-to-buffer tar-superior-buffer)
447 ;; Expand file-name before `dired-goto-file' call:
448 ;; `dired-goto-file' requires its argument to be an absolute
449 ;; file name; the result of `read-file-name' could be
450 ;; an abbreviated file name (Bug#24409).
451 (let* ((file (or (and file-name (expand-file-name file-name))
452 buffer-file-name))
453 (dir (if file (file-name-directory file) default-directory)))
454 (if (and (eq major-mode 'dired-mode) (null file-name))
455 (progn
456 (setq dir (dired-current-directory))
457 (dired-up-directory other-window)
458 (unless (dired-goto-file dir)
459 ;; refresh and try again
460 (dired-insert-subdir (file-name-directory dir))
461 (dired-goto-file dir)))
462 (if other-window
463 (dired-other-window dir)
464 (dired dir))
465 (if file
466 (or (dired-goto-file file)
467 ;; refresh and try again
468 (progn
469 (dired-insert-subdir (file-name-directory file))
470 (dired-goto-file file))
471 ;; Toggle omitting, if it is on, and try again.
472 (when dired-omit-mode
473 (dired-omit-mode)
474 (dired-goto-file file))))))))
476 ;;;###autoload
477 (defun dired-jump-other-window (&optional file-name)
478 "Like \\[dired-jump] (`dired-jump') but in other window."
479 (interactive
480 (list (and current-prefix-arg
481 (read-file-name "Jump to Dired file: "))))
482 (dired-jump t file-name))
484 ;;; OMITTING.
486 ;; Enhanced omitting of lines from directory listings.
487 ;; Marked files are never omitted.
489 ;; should probably get rid of this and always use 'no-dir.
490 ;; sk 28-Aug-1991 09:37
491 (defvar dired-omit-localp 'no-dir
492 "The LOCALP argument `dired-omit-expunge' passes to `dired-get-filename'.
493 If it is `no-dir', omitting is much faster, but you can only match
494 against the non-directory part of the file name. Set it to nil if you
495 need to match the entire file name.")
497 ;; \017=^O for Omit - other packages can chose other control characters.
498 (defvar dired-omit-marker-char ?\017
499 "Temporary marker used by Dired-Omit.
500 Should never be used as marker by the user or other packages.")
502 (defun dired-omit-startup ()
503 (or (assq 'dired-omit-mode minor-mode-alist)
504 (setq minor-mode-alist
505 (append '((dired-omit-mode
506 (:eval (if (eq major-mode 'dired-mode)
507 " Omit" ""))))
508 minor-mode-alist))))
510 (defun dired-mark-omitted ()
511 "Mark files matching `dired-omit-files' and `dired-omit-extensions'."
512 (interactive)
513 (let ((dired-omit-mode nil)) (revert-buffer)) ;; Show omitted files
514 (dired-mark-unmarked-files (dired-omit-regexp) nil nil dired-omit-localp
515 (dired-omit-case-fold-p dired-directory)))
517 (defcustom dired-omit-extensions
518 (append completion-ignored-extensions
519 dired-latex-unclean-extensions
520 dired-bibtex-unclean-extensions
521 dired-texinfo-unclean-extensions)
522 "If non-nil, a list of extensions (strings) to omit from Dired listings.
523 Defaults to elements of `completion-ignored-extensions',
524 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions', and
525 `dired-texinfo-unclean-extensions'.
527 See interactive function `dired-omit-mode' (\\[dired-omit-mode]) and
528 variables `dired-omit-mode' and `dired-omit-files'."
529 :type '(repeat string)
530 :group 'dired-x)
532 (defun dired-omit-expunge (&optional regexp)
533 "Erases all unmarked files matching REGEXP.
534 Does nothing if global variable `dired-omit-mode' is nil, or if called
535 non-interactively and buffer is bigger than `dired-omit-size-limit'.
536 If REGEXP is nil or not specified, uses `dired-omit-files', and also omits
537 filenames ending in `dired-omit-extensions'.
538 If REGEXP is the empty string, this function is a no-op.
540 This functions works by temporarily binding `dired-marker-char' to
541 `dired-omit-marker-char' and calling `dired-do-kill-lines'."
542 (interactive "sOmit files (regexp): ")
543 (if (and dired-omit-mode
544 (or (called-interactively-p 'interactive)
545 (not dired-omit-size-limit)
546 (< (buffer-size) dired-omit-size-limit)
547 (progn
548 (when dired-omit-verbose
549 (message "Not omitting: directory larger than %d characters."
550 dired-omit-size-limit))
551 (setq dired-omit-mode nil)
552 nil)))
553 (let ((omit-re (or regexp (dired-omit-regexp)))
554 (old-modified-p (buffer-modified-p))
555 count)
556 (or (string= omit-re "")
557 (let ((dired-marker-char dired-omit-marker-char))
558 (when dired-omit-verbose (message "Omitting..."))
559 (if (dired-mark-unmarked-files omit-re nil nil dired-omit-localp
560 (dired-omit-case-fold-p dired-directory))
561 (progn
562 (setq count (dired-do-kill-lines
564 (if dired-omit-verbose "Omitted %d line%s." "")))
565 (force-mode-line-update))
566 (when dired-omit-verbose (message "(Nothing to omit)")))))
567 ;; Try to preserve modified state of buffer. So `%*' doesn't appear
568 ;; in mode-line of omitted buffers.
569 (set-buffer-modified-p (and old-modified-p
570 (save-excursion
571 (goto-char (point-min))
572 (re-search-forward dired-re-mark nil t))))
573 count)))
575 (defun dired-omit-regexp ()
576 (concat (if dired-omit-files (concat "\\(" dired-omit-files "\\)") "")
577 (if (and dired-omit-files dired-omit-extensions) "\\|" "")
578 (if dired-omit-extensions
579 (concat ".";; a non-extension part should exist
580 "\\("
581 (mapconcat 'regexp-quote dired-omit-extensions "\\|")
582 "\\)$")
583 "")))
585 ;; Returns t if any work was done, nil otherwise.
586 (defun dired-mark-unmarked-files (regexp msg &optional unflag-p localp case-fold-p)
587 "Mark unmarked files matching REGEXP, displaying MSG.
588 REGEXP is matched against the entire file name. When called
589 interactively, prompt for REGEXP.
590 With prefix argument, unflag all those files.
591 Optional fourth argument LOCALP is as in `dired-get-filename'.
592 Optional fifth argument CASE-FOLD-P specifies the value of
593 `case-fold-search' used for matching REGEXP."
594 (interactive
595 (list (read-regexp
596 "Mark unmarked files matching regexp (default all): "
597 nil 'dired-regexp-history)
598 nil current-prefix-arg nil))
599 (let ((dired-marker-char (if unflag-p ?\s dired-marker-char)))
600 (dired-mark-if
601 (and
602 ;; not already marked
603 (looking-at-p " ")
604 ;; uninteresting
605 (let ((fn (dired-get-filename localp t))
606 ;; Match patterns case-insensitively on case-insensitive
607 ;; systems
608 (case-fold-search case-fold-p))
609 (and fn (string-match-p regexp fn))))
610 msg)))
613 ;;; VIRTUAL DIRED MODE.
615 ;; For browsing `ls -lR' listings in a dired-like fashion.
617 (defalias 'virtual-dired 'dired-virtual)
618 (defun dired-virtual (dirname &optional switches)
619 "Put this buffer into Virtual Dired mode.
621 In Virtual Dired mode, all commands that do not actually consult the
622 filesystem will work.
624 This is useful if you want to peruse and move around in an ls -lR
625 output file, for example one you got from an ftp server. With
626 ange-ftp, you can even Dired a directory containing an ls-lR file,
627 visit that file and turn on Virtual Dired mode. But don't try to save
628 this file, as dired-virtual indents the listing and thus changes the
629 buffer.
631 If you have save a Dired buffer in a file you can use \\[dired-virtual] to
632 resume it in a later session.
634 Type \\<dired-mode-map>\\[revert-buffer] \
635 in the Virtual Dired buffer and answer `y' to convert
636 the virtual to a real Dired buffer again. You don't have to do this, though:
637 you can relist single subdirs using \\[dired-do-redisplay]."
639 ;; DIRNAME is the top level directory of the buffer. It will become
640 ;; its `default-directory'. If nil, the old value of
641 ;; default-directory is used.
643 ;; Optional SWITCHES are the ls switches to use.
645 ;; Shell wildcards will be used if there already is a `wildcard'
646 ;; line in the buffer (thus it is a saved Dired buffer), but there
647 ;; is no other way to get wildcards. Insert a `wildcard' line by
648 ;; hand if you want them.
650 (interactive
651 (list (read-string "Virtual Dired directory: " (dired-virtual-guess-dir))))
652 (goto-char (point-min))
653 (or (looking-at-p " ")
654 ;; if not already indented, do it now:
655 (indent-region (point-min) (point-max) 2))
656 (or dirname (setq dirname default-directory))
657 (setq dirname (expand-file-name (file-name-as-directory dirname)))
658 (setq default-directory dirname) ; contains no wildcards
659 (let ((wildcard (save-excursion
660 (goto-char (point-min))
661 (forward-line 1)
662 (and (looking-at "^ wildcard ")
663 (buffer-substring (match-end 0)
664 (line-end-position))))))
665 (if wildcard
666 (setq dirname (expand-file-name wildcard default-directory))))
667 ;; If raw ls listing (not a saved old dired buffer), give it a
668 ;; decent subdir headerline:
669 (goto-char (point-min))
670 (or (looking-at-p dired-subdir-regexp)
671 (insert " "
672 (directory-file-name (file-name-directory default-directory))
673 ":\n"))
674 (dired-mode dirname (or switches dired-listing-switches))
675 (setq mode-name "Virtual Dired"
676 revert-buffer-function 'dired-virtual-revert)
677 (set (make-local-variable 'dired-subdir-alist) nil)
678 (dired-build-subdir-alist)
679 (goto-char (point-min))
680 (dired-initial-position dirname))
682 (defun dired-virtual-guess-dir ()
683 "Guess and return appropriate working directory of this buffer.
684 The buffer is assumed to be in Dired or ls -lR format. The guess is
685 based upon buffer contents. If nothing could be guessed, returns
686 nil."
688 (let ((regexp "^\\( \\)?\\([^ \n\r]*\\)\\(:\\)[\n\r]")
689 (subexpr 2))
690 (goto-char (point-min))
691 (cond ((looking-at regexp)
692 ;; If a saved dired buffer, look to which dir and
693 ;; perhaps wildcard it belongs:
694 (let ((dir (buffer-substring (match-beginning subexpr)
695 (match-end subexpr))))
696 (file-name-as-directory dir)))
697 ;; Else no match for headerline found. It's a raw ls listing.
698 ;; In raw ls listings the directory does not have a headerline
699 ;; try parent of first subdir, if any
700 ((re-search-forward regexp nil t)
701 (file-name-directory
702 (directory-file-name
703 (file-name-as-directory
704 (buffer-substring (match-beginning subexpr)
705 (match-end subexpr))))))
706 (t ; if all else fails
707 nil))))
710 (defun dired-virtual-revert (&optional _arg _noconfirm)
711 (if (not
712 (y-or-n-p "Cannot revert a Virtual Dired buffer - switch to Real Dired mode? "))
713 (error "Cannot revert a Virtual Dired buffer")
714 (setq mode-name "Dired"
715 revert-buffer-function 'dired-revert)
716 (revert-buffer)))
718 ;; A zero-arg version of dired-virtual.
719 (defun dired-virtual-mode ()
720 "Put current buffer into Virtual Dired mode (see `dired-virtual').
721 Useful on `magic-mode-alist' with the regexp
723 \"^ \\\\(/[^ /]+\\\\)+/?:$\"
725 to put saved Dired buffers automatically into Virtual Dired mode.
727 Also useful for `auto-mode-alist' like this:
729 (add-to-list \\='auto-mode-alist
730 \\='(\"[^/]\\\\.dired\\\\\\='\" . dired-virtual-mode))"
731 (interactive)
732 (dired-virtual (dired-virtual-guess-dir)))
735 ;;; SMART SHELL.
737 ;; An Emacs buffer can have but one working directory, stored in the
738 ;; buffer-local variable `default-directory'. A Dired buffer may have
739 ;; several subdirectories inserted, but still has but one working directory:
740 ;; that of the top level Dired directory in that buffer. For some commands
741 ;; it is appropriate that they use the current Dired directory instead of
742 ;; `default-directory', e.g., `find-file' and `compile'. This is a general
743 ;; mechanism is provided for special handling of the working directory in
744 ;; special major modes.
746 (define-obsolete-variable-alias 'default-directory-alist
747 'dired-default-directory-alist "24.1")
749 ;; It's easier to add to this alist than redefine function
750 ;; default-directory while keeping the old information.
751 (defconst dired-default-directory-alist
752 '((dired-mode . (if (fboundp 'dired-current-directory)
753 (dired-current-directory)
754 default-directory)))
755 "Alist of major modes and their opinion on `default-directory'.
756 Each element has the form (MAJOR . EXPRESSION).
757 The function `dired-default-directory' evaluates EXPRESSION to
758 determine a default directory.")
760 (put 'dired-default-directory-alist 'risky-local-variable t) ; gets eval'd
761 (make-obsolete-variable 'dired-default-directory-alist
762 "this feature is due to be removed." "24.1")
764 (defun dired-default-directory ()
765 "Return the `dired-default-directory-alist' entry for the current major-mode.
766 If none, return `default-directory'."
767 ;; It looks like this was intended to be something of a "general"
768 ;; feature, but it only ever seems to have been used in
769 ;; dired-smart-shell-command, and doesn't seem worth keeping around.
770 (declare (obsolete nil "24.1"))
771 (or (eval (cdr (assq major-mode dired-default-directory-alist)))
772 default-directory))
774 (defun dired-smart-shell-command (command &optional output-buffer error-buffer)
775 "Like function `shell-command', but in the current Virtual Dired directory."
776 (interactive
777 (list
778 (read-shell-command "Shell command: " nil nil
779 (cond
780 (buffer-file-name (file-relative-name buffer-file-name))
781 ((eq major-mode 'dired-mode) (dired-get-filename t t))))
782 current-prefix-arg
783 shell-command-default-error-buffer))
784 (let ((default-directory (or (and (eq major-mode 'dired-mode)
785 (dired-current-directory))
786 default-directory)))
787 (shell-command command output-buffer error-buffer)))
790 ;;; LOCAL VARIABLES FOR DIRED BUFFERS.
792 ;; Brief Description (This feature is obsolete as of Emacs 24.1)
794 ;; * `dired-extra-startup' is part of the `dired-mode-hook'.
796 ;; * `dired-extra-startup' calls `dired-hack-local-variables'
798 ;; * `dired-hack-local-variables' checks the value of
799 ;; `dired-local-variables-file'
801 ;; * Check if `dired-local-variables-file' is a non-nil string and is a
802 ;; filename found in the directory of the Dired Buffer being created.
804 ;; * If `dired-local-variables-file' satisfies the above, then temporarily
805 ;; include it in the Dired Buffer at the bottom.
807 ;; * Set `enable-local-variables' temporarily to the user variable
808 ;; `dired-enable-local-variables' and run `hack-local-variables' on the
809 ;; Dired Buffer.
811 (defcustom dired-local-variables-file (convert-standard-filename ".dired")
812 "Filename, as string, containing local Dired buffer variables to be hacked.
813 If this file found in current directory, then it will be inserted into dired
814 buffer and `hack-local-variables' will be run. See Info node
815 `(emacs)File Variables' for more information on local variables.
816 See also `dired-enable-local-variables'."
817 :type 'file
818 :group 'dired)
820 (make-obsolete-variable 'dired-local-variables-file 'dir-locals-file "24.1")
822 (defun dired-hack-local-variables ()
823 "Evaluate local variables in `dired-local-variables-file' for Dired buffer."
824 (declare (obsolete hack-dir-local-variables-non-file-buffer "24.1"))
825 (and (stringp dired-local-variables-file)
826 (file-exists-p dired-local-variables-file)
827 (let ((opoint (point-max))
828 (inhibit-read-only t)
829 ;; In case user has `enable-local-variables' set to nil we
830 ;; override it locally with dired's variable.
831 (enable-local-variables dired-enable-local-variables))
832 ;; Insert 'em.
833 (save-excursion
834 (goto-char opoint)
835 (insert "\^L\n")
836 (insert-file-contents dired-local-variables-file))
837 ;; Hack 'em.
838 (unwind-protect
839 (let ((buffer-file-name dired-local-variables-file))
840 (hack-local-variables))
841 ;; Delete this stuff: `eobp' is used to find last subdir by dired.el.
842 (delete-region opoint (point-max)))
843 ;; Make sure that the mode line shows the proper information.
844 (dired-sort-set-mode-line))))
846 ;; Does not seem worth a dedicated command.
847 ;; See the more general features in files-x.el.
848 (defun dired-omit-here-always ()
849 "Create `dir-locals-file' setting `dired-omit-mode' to t in `dired-mode'.
850 If in a Dired buffer, reverts it."
851 (declare (obsolete add-dir-local-variable "24.1"))
852 (interactive)
853 (if (file-exists-p dired-local-variables-file)
854 (error "Old-style dired-local-variables-file `./%s' found;
855 replace it with a dir-locals-file `./%s'"
856 dired-local-variables-file
857 dir-locals-file))
858 (if (file-exists-p dir-locals-file)
859 (message "File `./%s' already exists." dir-locals-file)
860 (add-dir-local-variable 'dired-mode 'subdirs nil)
861 (add-dir-local-variable 'dired-mode 'dired-omit-mode t)
862 ;; Run extra-hooks and revert directory.
863 (when (derived-mode-p 'dired-mode)
864 (hack-dir-local-variables-non-file-buffer)
865 (dired-extra-startup)
866 (dired-revert))))
869 ;;; GUESS SHELL COMMAND.
871 ;; Brief Description:
873 ;; * `dired-do-shell-command' is bound to `!' by dired.el.
875 ;; * `dired-guess-shell-command' provides smarter defaults for
876 ;;; dired-aux.el's `dired-read-shell-command'.
878 ;; * `dired-guess-shell-command' calls `dired-guess-default' with list of
879 ;;; marked files.
881 ;; * Parse `dired-guess-shell-alist-user' and
882 ;;; `dired-guess-shell-alist-default' (in that order) for the first REGEXP
883 ;;; that matches the first file in the file list.
885 ;; * If the REGEXP matches all the entries of the file list then evaluate
886 ;;; COMMAND, which is either a string or a Lisp expression returning a
887 ;;; string. COMMAND may be a list of commands.
889 ;; * Return this command to `dired-guess-shell-command' which prompts user
890 ;;; with it. The list of commands is put into the list of default values.
891 ;;; If a command is used successfully then it is stored permanently in
892 ;;; `dired-shell-command-history'.
894 ;; Guess what shell command to apply to a file.
895 (defvar dired-shell-command-history nil
896 "History list for commands that read dired-shell commands.")
898 ;; Default list of shell commands.
900 ;; NOTE: Use `gunzip -c' instead of `zcat' on `.gz' files. Some do not
901 ;; install GNU zip's version of zcat.
903 (autoload 'Man-support-local-filenames "man")
905 (defvar dired-guess-shell-alist-default
906 (list
907 (list "\\.tar\\'"
908 '(if dired-guess-shell-gnutar
909 (concat dired-guess-shell-gnutar " xvf")
910 "tar xvf")
911 ;; Extract files into a separate subdirectory
912 '(if dired-guess-shell-gnutar
913 (concat "mkdir " (file-name-sans-extension file)
914 "; " dired-guess-shell-gnutar " -C "
915 (file-name-sans-extension file) " -xvf")
916 (concat "mkdir " (file-name-sans-extension file)
917 "; tar -C " (file-name-sans-extension file) " -xvf"))
918 ;; List archive contents.
919 '(if dired-guess-shell-gnutar
920 (concat dired-guess-shell-gnutar " tvf")
921 "tar tvf"))
923 ;; REGEXPS for compressed archives must come before the .Z rule to
924 ;; be recognized:
925 (list "\\.tar\\.Z\\'"
926 ;; Untar it.
927 '(if dired-guess-shell-gnutar
928 (concat dired-guess-shell-gnutar " zxvf")
929 (concat "zcat * | tar xvf -"))
930 ;; Optional conversion to gzip format.
931 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
932 " " dired-guess-shell-znew-switches))
934 ;; gzip'ed archives
935 (list "\\.t\\(ar\\.\\)?gz\\'"
936 '(if dired-guess-shell-gnutar
937 (concat dired-guess-shell-gnutar " zxvf")
938 (concat "gunzip -qc * | tar xvf -"))
939 ;; Extract files into a separate subdirectory
940 '(if dired-guess-shell-gnutar
941 (concat "mkdir " (file-name-sans-extension file)
942 "; " dired-guess-shell-gnutar " -C "
943 (file-name-sans-extension file) " -zxvf")
944 (concat "mkdir " (file-name-sans-extension file)
945 "; gunzip -qc * | tar -C "
946 (file-name-sans-extension file) " -xvf -"))
947 ;; Optional decompression.
948 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q" ""))
949 ;; List archive contents.
950 '(if dired-guess-shell-gnutar
951 (concat dired-guess-shell-gnutar " ztvf")
952 (concat "gunzip -qc * | tar tvf -")))
954 ;; bzip2'ed archives
955 (list "\\.t\\(ar\\.bz2\\|bz\\)\\'"
956 "bunzip2 -c * | tar xvf -"
957 ;; Extract files into a separate subdirectory
958 '(concat "mkdir " (file-name-sans-extension file)
959 "; bunzip2 -c * | tar -C "
960 (file-name-sans-extension file) " -xvf -")
961 ;; Optional decompression.
962 "bunzip2")
964 ;; xz'ed archives
965 (list "\\.t\\(ar\\.\\)?xz\\'"
966 "unxz -c * | tar xvf -"
967 ;; Extract files into a separate subdirectory
968 '(concat "mkdir " (file-name-sans-extension file)
969 "; unxz -c * | tar -C "
970 (file-name-sans-extension file) " -xvf -")
971 ;; Optional decompression.
972 "unxz")
974 '("\\.shar\\.Z\\'" "zcat * | unshar")
975 '("\\.shar\\.g?z\\'" "gunzip -qc * | unshar")
977 '("\\.e?ps\\'" "ghostview" "xloadimage" "lpr")
978 (list "\\.e?ps\\.g?z\\'" "gunzip -qc * | ghostview -"
979 ;; Optional decompression.
980 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
981 (list "\\.e?ps\\.Z\\'" "zcat * | ghostview -"
982 ;; Optional conversion to gzip format.
983 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
984 " " dired-guess-shell-znew-switches))
986 '("\\.patch\\'" "cat * | patch")
987 (list "\\.patch\\.g?z\\'" "gunzip -qc * | patch"
988 ;; Optional decompression.
989 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
990 (list "\\.patch\\.Z\\'" "zcat * | patch"
991 ;; Optional conversion to gzip format.
992 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
993 " " dired-guess-shell-znew-switches))
995 ;; The following four extensions are useful with dired-man ("N" key)
996 ;; FIXME "man ./" does not work with dired-do-shell-command,
997 ;; because there seems to be no way for us to modify the filename,
998 ;; only the command. Hmph. `dired-man' works though.
999 (list "\\.\\(?:[0-9]\\|man\\)\\'"
1000 '(let ((loc (Man-support-local-filenames)))
1001 (cond ((eq loc 'man-db) "man -l")
1002 ((eq loc 'man) "man ./")
1004 "cat * | tbl | nroff -man -h | col -b"))))
1005 (list "\\.\\(?:[0-9]\\|man\\)\\.g?z\\'"
1006 '(let ((loc (Man-support-local-filenames)))
1007 (cond ((eq loc 'man-db)
1008 "man -l")
1009 ((eq loc 'man)
1010 "man ./")
1011 (t "gunzip -qc * | tbl | nroff -man -h | col -b")))
1012 ;; Optional decompression.
1013 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1014 (list "\\.[0-9]\\.Z\\'"
1015 '(let ((loc (Man-support-local-filenames)))
1016 (cond ((eq loc 'man-db) "man -l")
1017 ((eq loc 'man) "man ./")
1018 (t "zcat * | tbl | nroff -man -h | col -b")))
1019 ;; Optional conversion to gzip format.
1020 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1021 " " dired-guess-shell-znew-switches))
1022 '("\\.pod\\'" "perldoc" "pod2man * | nroff -man")
1024 '("\\.dvi\\'" "xdvi" "dvips") ; preview and printing
1025 '("\\.au\\'" "play") ; play Sun audiofiles
1026 '("\\.mpe?g\\'\\|\\.avi\\'" "xine -p")
1027 '("\\.ogg\\'" "ogg123")
1028 '("\\.mp3\\'" "mpg123")
1029 '("\\.wav\\'" "play")
1030 '("\\.uu\\'" "uudecode") ; for uudecoded files
1031 '("\\.hqx\\'" "mcvert")
1032 '("\\.sh\\'" "sh") ; execute shell scripts
1033 '("\\.xbm\\'" "bitmap") ; view X11 bitmaps
1034 '("\\.gp\\'" "gnuplot")
1035 '("\\.p[bgpn]m\\'" "xloadimage")
1036 '("\\.gif\\'" "xloadimage") ; view gif pictures
1037 '("\\.tif\\'" "xloadimage")
1038 '("\\.png\\'" "display") ; xloadimage 4.1 doesn't grok PNG
1039 '("\\.jpe?g\\'" "xloadimage")
1040 '("\\.fig\\'" "xfig") ; edit fig pictures
1041 '("\\.out\\'" "xgraph") ; for plotting purposes.
1042 '("\\.tex\\'" "latex" "tex")
1043 '("\\.texi\\(nfo\\)?\\'" "makeinfo" "texi2dvi")
1044 '("\\.pdf\\'" "xpdf")
1045 '("\\.doc\\'" "antiword" "strings")
1046 '("\\.rpm\\'" "rpm -qilp" "rpm -ivh")
1047 '("\\.dia\\'" "dia")
1048 '("\\.mgp\\'" "mgp")
1050 ;; Some other popular archivers.
1051 (list "\\.zip\\'" "unzip" "unzip -l"
1052 ;; Extract files into a separate subdirectory
1053 '(concat "unzip" (if dired-guess-shell-gzip-quiet " -q")
1054 " -d " (file-name-sans-extension file)))
1055 '("\\.zoo\\'" "zoo x//")
1056 '("\\.lzh\\'" "lharc x")
1057 '("\\.arc\\'" "arc x")
1058 '("\\.shar\\'" "unshar")
1059 '("\\.rar\\'" "unrar x")
1060 '("\\.7z\\'" "7z x")
1062 ;; Compression.
1063 (list "\\.g?z\\'" '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1064 (list "\\.dz\\'" "dictunzip")
1065 (list "\\.bz2\\'" "bunzip2")
1066 (list "\\.xz\\'" "unxz")
1067 (list "\\.Z\\'" "uncompress"
1068 ;; Optional conversion to gzip format.
1069 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1070 " " dired-guess-shell-znew-switches))
1072 '("\\.sign?\\'" "gpg --verify"))
1074 "Default alist used for shell command guessing.
1075 See `dired-guess-shell-alist-user'.")
1077 (defcustom dired-guess-shell-alist-user nil
1078 "User-defined alist of rules for suggested commands.
1079 These rules take precedence over the predefined rules in the variable
1080 `dired-guess-shell-alist-default' (to which they are prepended).
1082 Each element of this list looks like
1084 (REGEXP COMMAND...)
1086 where each COMMAND can either be a string or a Lisp expression that evaluates
1087 to a string. This expression can access the file name as the variable `file'.
1088 If several COMMANDs are given, the first one will be the default
1089 and the rest will be added temporarily to the history and can be retrieved
1090 with \\[previous-history-element] (M-p) .
1092 The variable `dired-guess-shell-case-fold-search' controls whether
1093 REGEXP is matched case-sensitively."
1094 :group 'dired-x
1095 :type '(alist :key-type regexp :value-type (repeat sexp)))
1097 (defcustom dired-guess-shell-case-fold-search t
1098 "If non-nil, `dired-guess-shell-alist-default' and
1099 `dired-guess-shell-alist-user' are matched case-insensitively."
1100 :group 'dired-x
1101 :type 'boolean)
1103 (defun dired-guess-default (files)
1104 "Return a shell command, or a list of commands, appropriate for FILES.
1105 See `dired-guess-shell-alist-user'."
1107 (let* ((case-fold-search dired-guess-shell-case-fold-search)
1108 ;; Prepend the user's alist to the default alist.
1109 (alist (append dired-guess-shell-alist-user
1110 dired-guess-shell-alist-default))
1111 (file (car files))
1112 (flist (cdr files))
1113 elt regexp cmds)
1115 ;; Find the first match in the alist for first file in FILES.
1116 (while alist
1117 (setq elt (car alist)
1118 regexp (car elt)
1119 alist (cdr alist))
1120 (if (string-match-p regexp file)
1121 (setq cmds (cdr elt)
1122 alist nil)))
1124 ;; If more than one file, see if all of FILES match regular expression.
1125 (while (and flist
1126 (string-match-p regexp (car flist)))
1127 (setq flist (cdr flist)))
1129 ;; If flist is still non-nil, then do not guess since this means that not
1130 ;; all the files in FILES were matched by the regexp.
1131 (setq cmds (and (not flist) cmds))
1133 ;; Return commands or nil if flist is still non-nil.
1134 ;; Evaluate the commands in order that any logical testing will be done.
1135 (if (cdr cmds)
1136 (delete-dups (mapcar (lambda (cmd) (eval cmd `((file . ,file)))) cmds))
1137 (eval (car cmds) `((file . ,file)))))) ; single command
1139 (defun dired-guess-shell-command (prompt files)
1140 "Ask user with PROMPT for a shell command, guessing a default from FILES."
1141 (let ((default (dired-guess-default files))
1142 default-list val)
1143 (if (null default)
1144 ;; Nothing to guess
1145 (read-shell-command prompt nil 'dired-shell-command-history)
1146 (setq prompt (replace-regexp-in-string ": $" " " prompt))
1147 (if (listp default)
1148 ;; More than one guess
1149 (setq default-list default
1150 default (car default)
1151 prompt (concat
1152 prompt
1153 (format "{%d guesses} " (length default-list))))
1154 ;; Just one guess
1155 (setq default-list (list default)))
1156 ;; Put the first guess in the prompt but not in the initial value.
1157 (setq prompt (concat prompt (format "[%s]: " default)))
1158 ;; All guesses can be retrieved with M-n
1159 (setq val (read-shell-command prompt nil
1160 'dired-shell-command-history
1161 default-list))
1162 ;; If we got a return, then return default.
1163 (if (equal val "") default val))))
1166 ;;; RELATIVE SYMBOLIC LINKS.
1168 (declare-function make-symbolic-link "fileio.c")
1170 (defvar dired-keep-marker-relsymlink ?S
1171 "See variable `dired-keep-marker-move'.")
1173 (defun dired-make-relative-symlink (file1 file2 &optional ok-if-already-exists)
1174 "Make a symbolic link (pointing to FILE1) in FILE2.
1175 The link is relative (if possible), for example
1177 \"/vol/tex/bin/foo\" \"/vol/local/bin/foo\"
1179 results in
1181 \"../../tex/bin/foo\" \"/vol/local/bin/foo\""
1182 (interactive "FRelSymLink: \nFRelSymLink %s: \np")
1183 (let (name1 name2 len1 len2 (index 0) sub)
1184 (setq file1 (expand-file-name file1)
1185 file2 (expand-file-name file2)
1186 len1 (length file1)
1187 len2 (length file2))
1188 ;; Find common initial file name components:
1189 (let (next)
1190 (while (and (setq next (string-match "/" file1 index))
1191 (< (setq next (1+ next)) (min len1 len2))
1192 ;; For the comparison, both substrings must end in
1193 ;; `/', so NEXT is *one plus* the result of the
1194 ;; string-match.
1195 ;; E.g., consider the case of linking "/tmp/a/abc"
1196 ;; to "/tmp/abc" erroneously giving "/tmp/a" instead
1197 ;; of "/tmp/" as common initial component
1198 (string-equal (substring file1 0 next)
1199 (substring file2 0 next)))
1200 (setq index next))
1201 (setq name2 file2
1202 sub (substring file1 0 index)
1203 name1 (substring file1 index)))
1204 (if (string-equal sub "/")
1205 ;; No common initial file name found
1206 (setq name1 file1)
1207 ;; Else they have a common parent directory
1208 (let ((tem (substring file2 index))
1209 (start 0)
1210 (count 0))
1211 ;; Count number of slashes we must compensate for ...
1212 (while (setq start (string-match "/" tem start))
1213 (setq count (1+ count)
1214 start (1+ start)))
1215 ;; ... and prepend a "../" for each slash found:
1216 (dotimes (_ count)
1217 (setq name1 (concat "../" name1)))))
1218 (make-symbolic-link
1219 (directory-file-name name1) ; must not link to foo/
1220 ; (trailing slash!)
1221 name2 ok-if-already-exists)))
1223 (autoload 'dired-do-create-files "dired-aux")
1225 ;;;###autoload
1226 (defun dired-do-relsymlink (&optional arg)
1227 "Relative symlink all marked (or next ARG) files into a directory.
1228 Otherwise make a relative symbolic link to the current file.
1229 This creates relative symbolic links like
1231 foo -> ../bar/foo
1233 not absolute ones like
1235 foo -> /ugly/file/name/that/may/change/any/day/bar/foo
1237 For absolute symlinks, use \\[dired-do-symlink]."
1238 (interactive "P")
1239 (dired-do-create-files 'relsymlink #'dired-make-relative-symlink
1240 "RelSymLink" arg dired-keep-marker-relsymlink))
1242 (autoload 'dired-mark-read-regexp "dired-aux")
1243 (autoload 'dired-do-create-files-regexp "dired-aux")
1245 (defun dired-do-relsymlink-regexp (regexp newname &optional arg whole-name)
1246 "RelSymlink all marked files containing REGEXP to NEWNAME.
1247 See functions `dired-do-rename-regexp' and `dired-do-relsymlink'
1248 for more info."
1249 (interactive (dired-mark-read-regexp "RelSymLink"))
1250 (dired-do-create-files-regexp
1251 #'dired-make-relative-symlink
1252 "RelSymLink" arg regexp newname whole-name dired-keep-marker-relsymlink))
1255 ;;; VISIT ALL MARKED FILES SIMULTANEOUSLY.
1257 ;; Brief Description:
1259 ;; `dired-do-find-marked-files' is bound to `F' by dired-x.el.
1261 ;; * Use `dired-get-marked-files' to collect the marked files in the current
1262 ;;; Dired Buffer into a list of filenames `FILE-LIST'.
1264 ;; * Pass FILE-LIST to `dired-simultaneous-find-file' all with
1265 ;;; `dired-do-find-marked-files''s prefix argument NOSELECT.
1267 ;; * `dired-simultaneous-find-file' runs through FILE-LIST decrementing the
1268 ;;; list each time.
1270 ;; * If NOSELECT is non-nil then just run `find-file-noselect' on each
1271 ;;; element of FILE-LIST.
1273 ;; * If NOSELECT is nil then calculate the `size' of the window for each file
1274 ;;; by dividing the `window-height' by length of FILE-LIST. Thus, `size' is
1275 ;;; cognizant of the window-configuration.
1277 ;; * If `size' is too small abort, otherwise run `find-file' on each element
1278 ;;; of FILE-LIST giving each a window of height `size'.
1280 (defun dired-do-find-marked-files (&optional noselect)
1281 "Find all marked files displaying all of them simultaneously.
1282 With optional NOSELECT just find files but do not select them.
1284 The current window is split across all files marked, as evenly as possible.
1285 Remaining lines go to bottom-most window. The number of files that can be
1286 displayed this way is restricted by the height of the current window and
1287 `window-min-height'.
1289 To keep Dired buffer displayed, type \\[split-window-below] first.
1290 To display just marked files, type \\[delete-other-windows] first."
1291 (interactive "P")
1292 (dired-simultaneous-find-file (dired-get-marked-files) noselect))
1294 (defun dired-simultaneous-find-file (file-list noselect)
1295 "Visit all files in FILE-LIST and display them simultaneously.
1296 The current window is split across all files in FILE-LIST, as evenly as
1297 possible. Remaining lines go to the bottom-most window. The number of
1298 files that can be displayed this way is restricted by the height of the
1299 current window and the variable `window-min-height'. With non-nil
1300 NOSELECT the files are merely found but not selected."
1301 ;; We don't make this function interactive because it is usually too clumsy
1302 ;; to specify FILE-LIST interactively unless via dired.
1303 (let (size)
1304 (if noselect
1305 ;; Do not select the buffer.
1306 (find-file-noselect (car file-list))
1307 ;; We will have to select the buffer. Calculate and check window size.
1308 (setq size (/ (window-height) (length file-list)))
1309 (or (<= window-min-height size)
1310 (error "Too many files to visit simultaneously. Try C-u prefix"))
1311 (find-file (car file-list)))
1312 ;; Decrement.
1313 (dolist (file (cdr file-list))
1314 (if noselect
1315 ;; Do not select the buffer.
1316 (find-file-noselect file)
1317 ;; Vertically split off a window of desired size. Upper window will
1318 ;; have SIZE lines. Select lower (larger) window. We split it again.
1319 (select-window (split-window nil size))
1320 (find-file file)))))
1323 ;;; MISCELLANEOUS COMMANDS.
1325 ;; Run man on files.
1327 (declare-function Man-getpage-in-background "man" (topic))
1329 (defvar manual-program) ; from man.el
1331 (defun dired-man ()
1332 "Run `man' on this file."
1333 ;; Used also to say: "Display old buffer if buffer name matches filename."
1334 ;; but I have no idea what that means.
1335 (interactive)
1336 (require 'man)
1337 (let* ((file (dired-get-filename))
1338 (manual-program (replace-regexp-in-string "\\*" "%s"
1339 (dired-guess-shell-command
1340 "Man command: " (list file)))))
1341 (Man-getpage-in-background file)))
1343 ;; Run Info on files.
1345 (defun dired-info ()
1346 "Run `info' on this file."
1347 (interactive)
1348 (info (dired-get-filename)))
1350 ;; Run mail on mail folders.
1352 (declare-function vm-visit-folder "ext:vm" (folder &optional read-only))
1353 (defvar vm-folder-directory)
1355 (defun dired-vm (&optional read-only)
1356 "Run VM on this file.
1357 With optional prefix argument, visits the folder read-only.
1358 Otherwise obeys the value of `dired-vm-read-only-folders'."
1359 (interactive "P")
1360 (let ((dir (dired-current-directory))
1361 (fil (dired-get-filename)))
1362 (vm-visit-folder fil (or read-only
1363 (eq t dired-vm-read-only-folders)
1364 (and dired-vm-read-only-folders
1365 (not (file-writable-p fil)))))
1366 ;; So that pressing `v' inside VM does prompt within current directory:
1367 (set (make-local-variable 'vm-folder-directory) dir)))
1369 (defun dired-rmail ()
1370 "Run RMAIL on this file."
1371 (interactive)
1372 (rmail (dired-get-filename)))
1374 (defun dired-do-run-mail ()
1375 "Visit the current file as a mailbox, using VM or RMAIL.
1376 Prompt for confirmation first; if the user says yes, call
1377 `dired-vm' if `dired-bind-vm' is non-nil, `dired-rmail'
1378 otherwise."
1379 (interactive)
1380 (let ((file (dired-get-filename t)))
1381 (if dired-bind-vm
1382 (if (y-or-n-p (format-message
1383 "Visit `%s' as a mail folder with VM?" file))
1384 (dired-vm))
1385 ;; Read mail folder using rmail.
1386 (if (y-or-n-p (format-message
1387 "Visit `%s' as a mailbox with RMAIL?" file))
1388 (dired-rmail)))))
1391 ;;; MISCELLANEOUS INTERNAL FUNCTIONS.
1393 ;; This should be a builtin
1394 (defun dired-buffer-more-recently-used-p (buffer1 buffer2)
1395 "Return t if BUFFER1 is more recently used than BUFFER2.
1396 Considers buffers closer to the car of `buffer-list' to be more recent."
1397 (and (not (equal buffer1 buffer2))
1398 (memq buffer1 (buffer-list))
1399 (not (memq buffer1 (memq buffer2 (buffer-list))))))
1402 ;; Needed if ls -lh is supported and also for GNU ls -ls.
1403 (defun dired-x--string-to-number (str)
1404 "Like `string-to-number' but recognize a trailing unit prefix.
1405 For example, 2K is expanded to 2048.0. The caller should make
1406 sure that a trailing letter in STR is one of BKkMGTPEZY."
1407 (let* ((val (string-to-number str))
1408 (u (unless (zerop val)
1409 (aref str (1- (length str))))))
1410 (when (and u (> u ?9))
1411 (when (= u ?k)
1412 (setq u ?K))
1413 (let ((units '(?B ?K ?M ?G ?T ?P ?E ?Z ?Y)))
1414 (while (and units (/= (pop units) u))
1415 (setq val (* 1024.0 val)))))
1416 val))
1418 (defun dired-mark-sexp (predicate &optional unflag-p)
1419 "Mark files for which PREDICATE returns non-nil.
1420 With a prefix arg, unmark or unflag those files instead.
1422 PREDICATE is a lisp expression that can refer to the following symbols:
1424 inode [integer] the inode of the file (only for ls -i output)
1425 s [integer] the size of the file for ls -s output
1426 (usually in blocks or, with -k, in KByte)
1427 mode [string] file permission bits, e.g. \"-rw-r--r--\"
1428 nlink [integer] number of links to file
1429 uid [string] owner
1430 gid [string] group (If the gid is not displayed by ls,
1431 this will still be set (to the same as uid))
1432 size [integer] file size in bytes
1433 time [string] the time that ls displays, e.g. \"Feb 12 14:17\"
1434 name [string] the name of the file
1435 sym [string] if file is a symbolic link, the linked-to name, else \"\"
1437 For example, use
1439 (equal 0 size)
1441 to mark all zero length files.
1443 There's an ambiguity when a single integer not followed by a unit
1444 prefix precedes the file mode: It is then parsed as inode number
1445 and not as block size (this always works for GNU coreutils ls).
1447 Another limitation is that the uid field is needed for the
1448 function to work correctly. In particular, the field is not
1449 present for some values of `ls-lisp-emulation'.
1451 This function operates only on the buffer content and does not
1452 refer at all to the underlying file system. Contrast this with
1453 `find-dired', which might be preferable for the task at hand."
1454 ;; Using sym="" instead of nil avoids the trap of
1455 ;; (string-match "foo" sym) into which a user would soon fall.
1456 ;; Give `equal' instead of `=' in the example, as this works on
1457 ;; integers and strings.
1458 (interactive
1459 (list (read--expression
1460 (format "%s if (lisp expr): "
1461 (if current-prefix-arg
1462 "UNmark"
1463 "Mark")))
1464 current-prefix-arg))
1465 (message "%s" predicate)
1466 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char))
1467 inode s mode nlink uid gid size time name sym)
1468 (dired-mark-if
1469 (save-excursion
1470 (and
1471 ;; Sets vars
1472 ;; inode s mode nlink uid gid size time name sym
1474 ;; according to current file line. Returns t for success, nil if
1475 ;; there is no file line. Upon success, all variables are set, either
1476 ;; to nil or the appropriate value, so they need not be initialized.
1477 ;; Moves point within the current line.
1478 (dired-move-to-filename)
1479 (let ((mode-len 10) ; length of mode string
1480 ;; like in dired.el, but with subexpressions \1=inode, \2=s:
1481 ;; GNU ls -hs suffixes the block count with a unit and
1482 ;; prints it as a float, FreeBSD does neither.
1483 (dired-re-inode-size "\\=\\s *\\([0-9]+\\s +\\)?\
1484 \\(?:\\([0-9]+\\(?:\\.[0-9]*\\)?[BkKMGTPEZY]?\\)? ?\\)"))
1485 (beginning-of-line)
1486 (forward-char 2)
1487 (search-forward-regexp dired-re-inode-size nil t)
1488 ;; XXX Might be a size not followed by a unit prefix.
1489 ;; We could set s to inode if it were otherwise nil,
1490 ;; with a similar reasoning as below for setting gid to uid,
1491 ;; but it would be even more whimsical.
1492 (setq inode (when (match-string 1)
1493 (string-to-number (match-string 1))))
1494 (setq s (when (match-string 2)
1495 (dired-x--string-to-number (match-string 2))))
1496 (setq mode (buffer-substring (point) (+ mode-len (point))))
1497 (forward-char mode-len)
1498 ;; Skip any extended attributes marker ("." or "+").
1499 (or (looking-at " ")
1500 (forward-char 1))
1501 (setq nlink (read (current-buffer)))
1502 ;; Karsten Wenger <kw@cis.uni-muenchen.de> fixed uid.
1503 ;; Another issue is that GNU ls -n right-justifies numerical
1504 ;; UIDs and GIDs, while FreeBSD left-justifies them, so
1505 ;; don't rely on a specific whitespace layout. Both of them
1506 ;; right-justify all other numbers, though.
1507 ;; XXX Return a number if the uid or gid seems to be
1508 ;; numerical?
1509 (setq uid (buffer-substring (progn
1510 (skip-chars-forward " \t")
1511 (point))
1512 (progn
1513 (skip-chars-forward "^ \t")
1514 (point))))
1515 (dired-move-to-filename)
1516 (save-excursion
1517 (setq time
1518 ;; The regexp below tries to match from the last
1519 ;; digit of the size field through a space after the
1520 ;; date. Also, dates may have different formats
1521 ;; depending on file age, so the date column need
1522 ;; not be aligned to the right.
1523 (buffer-substring (save-excursion
1524 (skip-chars-backward " \t")
1525 (point))
1526 (progn
1527 (re-search-backward
1528 directory-listing-before-filename-regexp)
1529 (skip-chars-forward "^ \t")
1530 (1+ (point))))
1531 size (dired-x--string-to-number
1532 ;; We know that there's some kind of number
1533 ;; before point because the regexp search
1534 ;; above succeeded. I don't think it's worth
1535 ;; doing an extra check for leading garbage.
1536 (buffer-substring (point)
1537 (progn
1538 (skip-chars-backward "^ \t")
1539 (point))))
1540 ;; If no gid is displayed, gid will be set to uid
1541 ;; but the user will then not reference it anyway in
1542 ;; PREDICATE.
1543 gid (buffer-substring (progn
1544 (skip-chars-backward " \t")
1545 (point))
1546 (progn
1547 (skip-chars-backward "^ \t")
1548 (point)))))
1549 (setq name (buffer-substring (point)
1551 (dired-move-to-end-of-filename t)
1552 (point)))
1553 sym (if (looking-at " -> ")
1554 (buffer-substring (progn (forward-char 4) (point))
1555 (line-end-position))
1556 ""))
1558 (eval predicate
1559 `((inode . ,inode)
1560 (s . ,s)
1561 (mode . ,mode)
1562 (nlink . ,nlink)
1563 (uid . ,uid)
1564 (gid . ,gid)
1565 (size . ,size)
1566 (time . ,time)
1567 (name . ,name)
1568 (sym . ,sym)))))
1569 (format "'%s file" predicate))))
1572 ;;; FIND FILE AT POINT.
1574 (defcustom dired-x-hands-off-my-keys t
1575 "Non-nil means don't remap `find-file' to `dired-x-find-file'.
1576 Similarly for `find-file-other-window' and `dired-x-find-file-other-window'.
1577 If you change this variable without using \\[customize] after `dired-x.el'
1578 is loaded then call \\[dired-x-bind-find-file]."
1579 :type 'boolean
1580 :initialize 'custom-initialize-default
1581 :set (lambda (symbol value)
1582 (set symbol value)
1583 (dired-x-bind-find-file))
1584 :group 'dired-x)
1586 (defun dired-x-bind-find-file ()
1587 "Bind `dired-x-find-file' in place of `find-file' (or vice-versa).
1588 Similarly for `dired-x-find-file-other-window' and `find-file-other-window'.
1589 Binding direction based on `dired-x-hands-off-my-keys'."
1590 (interactive)
1591 (if (called-interactively-p 'interactive)
1592 (setq dired-x-hands-off-my-keys
1593 (not (y-or-n-p "Bind dired-x-find-file over find-file? "))))
1594 (define-key (current-global-map) [remap find-file]
1595 (if (not dired-x-hands-off-my-keys) 'dired-x-find-file))
1596 (define-key (current-global-map) [remap find-file-other-window]
1597 (if (not dired-x-hands-off-my-keys) 'dired-x-find-file-other-window)))
1599 ;; Now call it so binding is correct. This could go in the :initialize
1600 ;; slot, but then dired-x-bind-find-file has to be defined before the
1601 ;; defcustom, and we get free variable warnings.
1602 (dired-x-bind-find-file)
1604 (defun dired-x-find-file (filename)
1605 "Edit file FILENAME.
1606 Like `find-file', except that when called interactively with a
1607 prefix argument, it offers the filename near point as a default."
1608 (interactive (list (dired-x-read-filename-at-point "Find file: ")))
1609 (find-file filename))
1611 (defun dired-x-find-file-other-window (filename)
1612 "Edit file FILENAME, in another window.
1613 Like `find-file-other-window', except that when called interactively with
1614 a prefix argument, when it offers the filename near point as a default."
1615 (interactive (list (dired-x-read-filename-at-point "Find file: ")))
1616 (find-file-other-window filename))
1618 ;;; Internal functions.
1620 ;; Fixme: This should probably use `thing-at-point'. -- fx
1621 (defun dired-filename-at-point ()
1622 "Return the filename closest to point, expanded.
1623 Point should be in or after a filename."
1624 (save-excursion
1625 ;; First see if just past a filename.
1626 (or (eobp) ; why?
1627 (when (looking-at-p "[] \t\n[{}()]") ; whitespace or some parens
1628 (skip-chars-backward " \n\t\r({[]})")
1629 (or (bobp) (backward-char 1))))
1630 (let ((filename-chars "-.[:alnum:]_/:$+@")
1631 start prefix)
1632 (if (looking-at-p (format "[%s]" filename-chars))
1633 (progn
1634 (skip-chars-backward filename-chars)
1635 (setq start (point)
1636 prefix
1637 ;; This is something to do with ange-ftp filenames.
1638 ;; It convert foo@bar to /foo@bar.
1639 ;; But when does the former occur in dired buffers?
1640 (and (string-match-p
1641 "^\\w+@"
1642 (buffer-substring start (line-end-position)))
1643 "/"))
1644 (if (string-match-p "[/~]" (char-to-string (preceding-char)))
1645 (setq start (1- start)))
1646 (skip-chars-forward filename-chars))
1647 (error "No file found around point!"))
1648 ;; Return string.
1649 (expand-file-name (concat prefix (buffer-substring start (point)))))))
1651 (defun dired-x-read-filename-at-point (prompt)
1652 "Return filename prompting with PROMPT with completion.
1653 If `current-prefix-arg' is non-nil, uses name at point as guess."
1654 (if current-prefix-arg
1655 (let ((guess (dired-filename-at-point)))
1656 (read-file-name prompt
1657 (file-name-directory guess)
1658 guess
1659 nil (file-name-nondirectory guess)))
1660 (read-file-name prompt default-directory)))
1662 (define-obsolete-function-alias 'read-filename-at-point
1663 'dired-x-read-filename-at-point "24.1") ; is this even needed?
1665 ;;; BUG REPORTS
1667 (define-obsolete-function-alias 'dired-x-submit-report 'report-emacs-bug "24.1")
1670 ;; As Barry Warsaw would say: "This might be useful..."
1671 (provide 'dired-x)
1673 ;; Local Variables:
1674 ;; byte-compile-dynamic: t
1675 ;; generated-autoload-file: "dired-loaddefs.el"
1676 ;; End:
1678 ;;; dired-x.el ends here