Improve responsiveness while in 'replace-buffer-contents'
[emacs.git] / lisp / dired-x.el
bloba90f1f4adcd0610ffb09f77742fef097095dd050
1 ;;; dired-x.el --- extra Dired functionality -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1994, 1997, 2001-2018 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 <https://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 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 (defcustom dired-clean-confirm-killing-deleted-buffers t
247 "If nil, don't ask whether to kill buffers visiting deleted files."
248 :version "26.1"
249 :type 'boolean
250 :group 'dired-x)
252 ;;; KEY BINDINGS.
254 (define-key dired-mode-map "\C-x\M-o" 'dired-omit-mode)
255 (define-key dired-mode-map "*O" 'dired-mark-omitted)
256 (define-key dired-mode-map "\M-(" 'dired-mark-sexp)
257 (define-key dired-mode-map "*(" 'dired-mark-sexp)
258 (define-key dired-mode-map "*." 'dired-mark-extension)
259 (define-key dired-mode-map "\M-!" 'dired-smart-shell-command)
260 (define-key dired-mode-map "\M-G" 'dired-goto-subdir)
261 (define-key dired-mode-map "F" 'dired-do-find-marked-files)
262 (define-key dired-mode-map "Y" 'dired-do-relsymlink)
263 (define-key dired-mode-map "%Y" 'dired-do-relsymlink-regexp)
264 (define-key dired-mode-map "V" 'dired-do-run-mail)
266 ;;; MENU BINDINGS
268 (require 'easymenu)
270 (let ((menu (lookup-key dired-mode-map [menu-bar])))
271 (easy-menu-add-item menu '("Operate")
272 ["Find Files" dired-do-find-marked-files
273 :help "Find current or marked files"]
274 "Shell Command...")
275 (easy-menu-add-item menu '("Operate")
276 ["Relative Symlink to..." dired-do-relsymlink
277 :visible (fboundp 'make-symbolic-link)
278 :help "Make relative symbolic links for current or \
279 marked files"]
280 "Hardlink to...")
281 (easy-menu-add-item menu '("Mark")
282 ["Flag Extension..." dired-flag-extension
283 :help "Flag files with a certain extension for deletion"]
284 "Mark Executables")
285 (easy-menu-add-item menu '("Mark")
286 ["Mark Extension..." dired-mark-extension
287 :help "Mark files with a certain extension"]
288 "Unmark All")
289 (easy-menu-add-item menu '("Mark")
290 ["Mark Omitted" dired-mark-omitted
291 :help "Mark files matching `dired-omit-files' \
292 and `dired-omit-extensions'"]
293 "Unmark All")
294 (easy-menu-add-item menu '("Regexp")
295 ["Relative Symlink..." dired-do-relsymlink-regexp
296 :visible (fboundp 'make-symbolic-link)
297 :help "Make relative symbolic links for files \
298 matching regexp"]
299 "Hardlink...")
300 (easy-menu-add-item menu '("Immediate")
301 ["Omit Mode" dired-omit-mode
302 :style toggle :selected dired-omit-mode
303 :help "Enable or disable omitting \"uninteresting\" \
304 files"]
305 "Refresh"))
308 ;; Install into appropriate hooks.
310 (add-hook 'dired-mode-hook 'dired-extra-startup)
311 (add-hook 'dired-after-readin-hook 'dired-omit-expunge)
313 (defun dired-extra-startup ()
314 "Automatically put on `dired-mode-hook' to get extra Dired features:
315 \\<dired-mode-map>
316 \\[dired-do-run-mail]\t-- run mail on folder (see `dired-bind-vm')
317 \\[dired-info]\t-- run info on file
318 \\[dired-man]\t-- run man on file
319 \\[dired-do-find-marked-files]\t-- visit all marked files simultaneously
320 \\[dired-omit-mode]\t-- toggle omitting of files
321 \\[dired-mark-sexp]\t-- mark by Lisp expression
323 To see the options you can set, use M-x customize-group RET dired-x RET.
324 See also the functions:
325 `dired-flag-extension'
326 `dired-virtual'
327 `dired-jump'
328 `dired-man'
329 `dired-vm'
330 `dired-rmail'
331 `dired-info'
332 `dired-do-find-marked-files'"
333 (interactive)
334 ;; These must be done in each new dired buffer.
335 (dired-hack-local-variables)
336 (dired-omit-startup))
339 ;;; EXTENSION MARKING FUNCTIONS.
341 (defun dired--mark-suffix-interactive-spec ()
342 (let* ((default
343 (let ((file (dired-get-filename nil t)))
344 (when file
345 (file-name-extension file))))
346 (suffix
347 (read-string (format "%s extension%s: "
348 (if (equal current-prefix-arg '(4))
349 "UNmarking"
350 "Marking")
351 (if default
352 (format " (default %s)" default)
353 "")) nil nil default))
354 (marker
355 (pcase current-prefix-arg
356 ('(4) ?\s)
357 ('(16)
358 (let* ((dflt (char-to-string dired-marker-char))
359 (input (read-string
360 (format
361 "Marker character to use (default %s): " dflt)
362 nil nil dflt)))
363 (aref input 0)))
364 (_ dired-marker-char))))
365 (list suffix marker)))
367 ;; Mark files with some extension.
368 (defun dired-mark-extension (extension &optional marker-char)
369 "Mark all files with a certain EXTENSION for use in later commands.
370 A `.' is automatically prepended to EXTENSION when not present.
371 EXTENSION may also be a list of extensions instead of a single one.
372 Optional MARKER-CHAR is marker to use.
373 Interactively, ask for EXTENSION.
374 Prefixed with one C-u, unmark files instead.
375 Prefixed with two C-u's, prompt for MARKER-CHAR and mark files with it."
376 (interactive (dired--mark-suffix-interactive-spec))
377 (unless (listp extension)
378 (setq extension (list extension)))
379 (dired-mark-files-regexp
380 (concat ".";; don't match names with nothing but an extension
381 "\\("
382 (mapconcat
383 (lambda (x)
384 (regexp-quote
385 (if (string-prefix-p "." x) x (concat "." x))))
386 extension "\\|")
387 "\\)$")
388 marker-char))
390 ;; Mark files ending with some suffix.
391 (defun dired-mark-suffix (suffix &optional marker-char)
392 "Mark all files with a certain SUFFIX for use in later commands.
393 A `.' is *not* automatically prepended to the string entered; see
394 also `dired-mark-extension', which is similar but automatically
395 prepends `.' when not present.
396 SUFFIX may also be a list of suffixes instead of a single one.
397 Optional MARKER-CHAR is marker to use.
398 Interactively, ask for SUFFIX.
399 Prefixed with one C-u, unmark files instead.
400 Prefixed with two C-u's, prompt for MARKER-CHAR and mark files with it."
401 (interactive (dired--mark-suffix-interactive-spec))
402 (unless (listp suffix)
403 (setq suffix (list suffix)))
404 (dired-mark-files-regexp
405 (concat ".";; don't match names with nothing but an extension
406 "\\("
407 (mapconcat 'regexp-quote suffix "\\|")
408 "\\)$")
409 marker-char))
411 (defun dired-flag-extension (extension)
412 "In Dired, flag all files with a certain EXTENSION for deletion.
413 A `.' is *not* automatically prepended to the string entered."
414 (interactive "sFlagging extension: ")
415 (dired-mark-extension extension dired-del-marker))
417 ;; Define some unpopular file extensions. Used for cleaning and omitting.
419 (defvar dired-patch-unclean-extensions
420 '(".rej" ".orig")
421 "List of extensions of dispensable files created by the `patch' program.")
423 (defvar dired-tex-unclean-extensions
424 '(".toc" ".log" ".aux");; these are already in completion-ignored-extensions
425 "List of extensions of dispensable files created by TeX.")
427 (defvar dired-latex-unclean-extensions
428 '(".idx" ".lof" ".lot" ".glo")
429 "List of extensions of dispensable files created by LaTeX.")
431 (defvar dired-bibtex-unclean-extensions
432 '(".blg" ".bbl")
433 "List of extensions of dispensable files created by BibTeX.")
435 (defvar dired-texinfo-unclean-extensions
436 '(".cp" ".cps" ".fn" ".fns" ".ky" ".kys" ".pg" ".pgs"
437 ".tp" ".tps" ".vr" ".vrs")
438 "List of extensions of dispensable files created by texinfo.")
440 (defun dired-clean-patch ()
441 "Flag dispensable files created by patch for deletion.
442 See variable `dired-patch-unclean-extensions'."
443 (interactive)
444 (dired-flag-extension dired-patch-unclean-extensions))
446 (defun dired-clean-tex ()
447 "Flag dispensable files created by [La]TeX etc. for deletion.
448 See variables `dired-tex-unclean-extensions',
449 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions' and
450 `dired-texinfo-unclean-extensions'."
451 (interactive)
452 (dired-flag-extension (append dired-texinfo-unclean-extensions
453 dired-latex-unclean-extensions
454 dired-bibtex-unclean-extensions
455 dired-tex-unclean-extensions)))
457 (defun dired-very-clean-tex ()
458 "Flag dispensable files created by [La]TeX *and* \".dvi\" for deletion.
459 See variables `dired-texinfo-unclean-extensions',
460 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions' and
461 `dired-texinfo-unclean-extensions'."
462 (interactive)
463 (dired-flag-extension (append dired-texinfo-unclean-extensions
464 dired-latex-unclean-extensions
465 dired-bibtex-unclean-extensions
466 dired-tex-unclean-extensions
467 (list ".dvi"))))
469 (defvar tar-superior-buffer)
470 ;;; JUMP.
472 ;;;###autoload
473 (defun dired-jump (&optional other-window file-name)
474 "Jump to Dired buffer corresponding to current buffer.
475 If in a file, Dired the current directory and move to file's line.
476 If in Dired already, pop up a level and goto old directory's line.
477 In case the proper Dired file line cannot be found, refresh the dired
478 buffer and try again.
479 When OTHER-WINDOW is non-nil, jump to Dired buffer in other window.
480 When FILE-NAME is non-nil, jump to its line in Dired.
481 Interactively with prefix argument, read FILE-NAME."
482 (interactive
483 (list nil (and current-prefix-arg
484 (read-file-name "Jump to Dired file: "))))
485 (if (bound-and-true-p tar-subfile-mode)
486 (switch-to-buffer tar-superior-buffer)
487 ;; Expand file-name before `dired-goto-file' call:
488 ;; `dired-goto-file' requires its argument to be an absolute
489 ;; file name; the result of `read-file-name' could be
490 ;; an abbreviated file name (Bug#24409).
491 (let* ((file (or (and file-name (expand-file-name file-name))
492 buffer-file-name))
493 (dir (if file (file-name-directory file) default-directory)))
494 (if (and (eq major-mode 'dired-mode) (null file-name))
495 (progn
496 (setq dir (dired-current-directory))
497 (dired-up-directory other-window)
498 (unless (dired-goto-file dir)
499 ;; refresh and try again
500 (dired-insert-subdir (file-name-directory dir))
501 (dired-goto-file dir)))
502 (if other-window
503 (dired-other-window dir)
504 (dired dir))
505 (if file
506 (or (dired-goto-file file)
507 ;; refresh and try again
508 (progn
509 (dired-insert-subdir (file-name-directory file))
510 (dired-goto-file file))
511 ;; Toggle omitting, if it is on, and try again.
512 (when dired-omit-mode
513 (dired-omit-mode)
514 (dired-goto-file file))))))))
516 ;;;###autoload
517 (defun dired-jump-other-window (&optional file-name)
518 "Like \\[dired-jump] (`dired-jump') but in other window."
519 (interactive
520 (list (and current-prefix-arg
521 (read-file-name "Jump to Dired file: "))))
522 (dired-jump t file-name))
524 ;;; OMITTING.
526 ;; Enhanced omitting of lines from directory listings.
527 ;; Marked files are never omitted.
529 ;; should probably get rid of this and always use 'no-dir.
530 ;; sk 28-Aug-1991 09:37
531 (defvar dired-omit-localp 'no-dir
532 "The LOCALP argument `dired-omit-expunge' passes to `dired-get-filename'.
533 If it is `no-dir', omitting is much faster, but you can only match
534 against the non-directory part of the file name. Set it to nil if you
535 need to match the entire file name.")
537 ;; \017=^O for Omit - other packages can chose other control characters.
538 (defvar dired-omit-marker-char ?\017
539 "Temporary marker used by Dired-Omit.
540 Should never be used as marker by the user or other packages.")
542 (defun dired-omit-startup ()
543 (or (assq 'dired-omit-mode minor-mode-alist)
544 (setq minor-mode-alist
545 (append '((dired-omit-mode
546 (:eval (if (eq major-mode 'dired-mode)
547 " Omit" ""))))
548 minor-mode-alist))))
550 (defun dired-mark-omitted ()
551 "Mark files matching `dired-omit-files' and `dired-omit-extensions'."
552 (interactive)
553 (let ((dired-omit-mode nil)) (revert-buffer)) ;; Show omitted files
554 (dired-mark-unmarked-files (dired-omit-regexp) nil nil dired-omit-localp
555 (dired-omit-case-fold-p (if (stringp dired-directory)
556 dired-directory
557 (car dired-directory)))))
559 (defcustom dired-omit-extensions
560 (append completion-ignored-extensions
561 dired-latex-unclean-extensions
562 dired-bibtex-unclean-extensions
563 dired-texinfo-unclean-extensions)
564 "If non-nil, a list of extensions (strings) to omit from Dired listings.
565 Defaults to elements of `completion-ignored-extensions',
566 `dired-latex-unclean-extensions', `dired-bibtex-unclean-extensions', and
567 `dired-texinfo-unclean-extensions'.
569 See interactive function `dired-omit-mode' (\\[dired-omit-mode]) and
570 variables `dired-omit-mode' and `dired-omit-files'."
571 :type '(repeat string)
572 :group 'dired-x)
574 (defun dired-omit-expunge (&optional regexp)
575 "Erases all unmarked files matching REGEXP.
576 Does nothing if global variable `dired-omit-mode' is nil, or if called
577 non-interactively and buffer is bigger than `dired-omit-size-limit'.
578 If REGEXP is nil or not specified, uses `dired-omit-files', and also omits
579 filenames ending in `dired-omit-extensions'.
580 If REGEXP is the empty string, this function is a no-op.
582 This functions works by temporarily binding `dired-marker-char' to
583 `dired-omit-marker-char' and calling `dired-do-kill-lines'."
584 (interactive "sOmit files (regexp): ")
585 (if (and dired-omit-mode
586 (or (called-interactively-p 'interactive)
587 (not dired-omit-size-limit)
588 (< (buffer-size) dired-omit-size-limit)
589 (progn
590 (when dired-omit-verbose
591 (message "Not omitting: directory larger than %d characters."
592 dired-omit-size-limit))
593 (setq dired-omit-mode nil)
594 nil)))
595 (let ((omit-re (or regexp (dired-omit-regexp)))
596 (old-modified-p (buffer-modified-p))
597 count)
598 (or (string= omit-re "")
599 (let ((dired-marker-char dired-omit-marker-char))
600 (when dired-omit-verbose (message "Omitting..."))
601 (if (dired-mark-unmarked-files omit-re nil nil dired-omit-localp
602 (dired-omit-case-fold-p (if (stringp dired-directory)
603 dired-directory
604 (car dired-directory))))
605 (progn
606 (setq count (dired-do-kill-lines
608 (if dired-omit-verbose "Omitted %d line%s." "")))
609 (force-mode-line-update))
610 (when dired-omit-verbose (message "(Nothing to omit)")))))
611 ;; Try to preserve modified state of buffer. So `%*' doesn't appear
612 ;; in mode-line of omitted buffers.
613 (set-buffer-modified-p (and old-modified-p
614 (save-excursion
615 (goto-char (point-min))
616 (re-search-forward dired-re-mark nil t))))
617 count)))
619 (defun dired-omit-regexp ()
620 (concat (if dired-omit-files (concat "\\(" dired-omit-files "\\)") "")
621 (if (and dired-omit-files dired-omit-extensions) "\\|" "")
622 (if dired-omit-extensions
623 (concat ".";; a non-extension part should exist
624 "\\("
625 (mapconcat 'regexp-quote dired-omit-extensions "\\|")
626 "\\)$")
627 "")))
629 ;; Returns t if any work was done, nil otherwise.
630 (defun dired-mark-unmarked-files (regexp msg &optional unflag-p localp case-fold-p)
631 "Mark unmarked files matching REGEXP, displaying MSG.
632 REGEXP is matched against the entire file name. When called
633 interactively, prompt for REGEXP.
634 With prefix argument, unflag all those files.
635 Optional fourth argument LOCALP is as in `dired-get-filename'.
636 Optional fifth argument CASE-FOLD-P specifies the value of
637 `case-fold-search' used for matching REGEXP."
638 (interactive
639 (list (read-regexp
640 "Mark unmarked files matching regexp (default all): "
641 nil 'dired-regexp-history)
642 nil current-prefix-arg nil))
643 (let ((dired-marker-char (if unflag-p ?\s dired-marker-char)))
644 (dired-mark-if
645 (and
646 ;; not already marked
647 (= (following-char) ?\s)
648 ;; uninteresting
649 (let ((fn (dired-get-filename localp t))
650 ;; Match patterns case-insensitively on case-insensitive
651 ;; systems
652 (case-fold-search case-fold-p))
653 (and fn (string-match-p regexp fn))))
654 msg)))
657 ;;; VIRTUAL DIRED MODE.
659 ;; For browsing `ls -lR' listings in a dired-like fashion.
661 (defalias 'virtual-dired 'dired-virtual)
662 (defun dired-virtual (dirname &optional switches)
663 "Put this buffer into Virtual Dired mode.
665 In Virtual Dired mode, all commands that do not actually consult the
666 filesystem will work.
668 This is useful if you want to peruse and move around in an ls -lR
669 output file, for example one you got from an ftp server. With
670 ange-ftp, you can even Dired a directory containing an ls-lR file,
671 visit that file and turn on Virtual Dired mode. But don't try to save
672 this file, as dired-virtual indents the listing and thus changes the
673 buffer.
675 If you have save a Dired buffer in a file you can use \\[dired-virtual] to
676 resume it in a later session.
678 Type \\<dired-mode-map>\\[revert-buffer] \
679 in the Virtual Dired buffer and answer `y' to convert
680 the virtual to a real Dired buffer again. You don't have to do this, though:
681 you can relist single subdirs using \\[dired-do-redisplay]."
683 ;; DIRNAME is the top level directory of the buffer. It will become
684 ;; its `default-directory'. If nil, the old value of
685 ;; default-directory is used.
687 ;; Optional SWITCHES are the ls switches to use.
689 ;; Shell wildcards will be used if there already is a `wildcard'
690 ;; line in the buffer (thus it is a saved Dired buffer), but there
691 ;; is no other way to get wildcards. Insert a `wildcard' line by
692 ;; hand if you want them.
694 (interactive
695 (list (read-string "Virtual Dired directory: " (dired-virtual-guess-dir))))
696 (goto-char (point-min))
697 (or (looking-at-p " ")
698 ;; if not already indented, do it now:
699 (indent-region (point-min) (point-max) 2))
700 (or dirname (setq dirname default-directory))
701 (setq dirname (expand-file-name (file-name-as-directory dirname)))
702 (setq default-directory dirname) ; contains no wildcards
703 (let ((wildcard (save-excursion
704 (goto-char (point-min))
705 (forward-line 1)
706 (and (looking-at "^ wildcard ")
707 (buffer-substring (match-end 0)
708 (line-end-position))))))
709 (if wildcard
710 (setq dirname (expand-file-name wildcard default-directory))))
711 ;; If raw ls listing (not a saved old dired buffer), give it a
712 ;; decent subdir headerline:
713 (goto-char (point-min))
714 (or (looking-at-p dired-subdir-regexp)
715 (insert " "
716 (directory-file-name (file-name-directory default-directory))
717 ":\n"))
718 (dired-mode dirname (or switches dired-listing-switches))
719 (setq mode-name "Virtual Dired"
720 revert-buffer-function 'dired-virtual-revert)
721 (set (make-local-variable 'dired-subdir-alist) nil)
722 (dired-build-subdir-alist)
723 (goto-char (point-min))
724 (dired-initial-position dirname))
726 (defun dired-virtual-guess-dir ()
727 "Guess and return appropriate working directory of this buffer.
728 The buffer is assumed to be in Dired or ls -lR format. The guess is
729 based upon buffer contents. If nothing could be guessed, returns
730 nil."
732 (let ((regexp "^\\( \\)?\\([^ \n\r]*\\)\\(:\\)[\n\r]")
733 (subexpr 2))
734 (goto-char (point-min))
735 (cond ((looking-at regexp)
736 ;; If a saved dired buffer, look to which dir and
737 ;; perhaps wildcard it belongs:
738 (let ((dir (buffer-substring (match-beginning subexpr)
739 (match-end subexpr))))
740 (file-name-as-directory dir)))
741 ;; Else no match for headerline found. It's a raw ls listing.
742 ;; In raw ls listings the directory does not have a headerline
743 ;; try parent of first subdir, if any
744 ((re-search-forward regexp nil t)
745 (file-name-directory
746 (directory-file-name
747 (file-name-as-directory
748 (buffer-substring (match-beginning subexpr)
749 (match-end subexpr))))))
750 (t ; if all else fails
751 nil))))
754 (defun dired-virtual-revert (&optional _arg _noconfirm)
755 (if (not
756 (y-or-n-p "Cannot revert a Virtual Dired buffer - switch to Real Dired mode? "))
757 (error "Cannot revert a Virtual Dired buffer")
758 (setq mode-name "Dired"
759 revert-buffer-function 'dired-revert)
760 (revert-buffer)))
762 ;; A zero-arg version of dired-virtual.
763 (defun dired-virtual-mode ()
764 "Put current buffer into Virtual Dired mode (see `dired-virtual').
765 Useful on `magic-mode-alist' with the regexp
767 \"^ \\\\(/[^ /]+\\\\)+/?:$\"
769 to put saved Dired buffers automatically into Virtual Dired mode.
771 Also useful for `auto-mode-alist' like this:
773 (add-to-list \\='auto-mode-alist
774 \\='(\"[^/]\\\\.dired\\\\\\='\" . dired-virtual-mode))"
775 (interactive)
776 (dired-virtual (dired-virtual-guess-dir)))
779 ;;; SMART SHELL.
781 ;; An Emacs buffer can have but one working directory, stored in the
782 ;; buffer-local variable `default-directory'. A Dired buffer may have
783 ;; several subdirectories inserted, but still has but one working directory:
784 ;; that of the top level Dired directory in that buffer. For some commands
785 ;; it is appropriate that they use the current Dired directory instead of
786 ;; `default-directory', e.g., `find-file' and `compile'. This is a general
787 ;; mechanism is provided for special handling of the working directory in
788 ;; special major modes.
790 (define-obsolete-variable-alias 'default-directory-alist
791 'dired-default-directory-alist "24.1")
793 ;; It's easier to add to this alist than redefine function
794 ;; default-directory while keeping the old information.
795 (defconst dired-default-directory-alist
796 '((dired-mode . (if (fboundp 'dired-current-directory)
797 (dired-current-directory)
798 default-directory)))
799 "Alist of major modes and their opinion on `default-directory'.
800 Each element has the form (MAJOR . EXPRESSION).
801 The function `dired-default-directory' evaluates EXPRESSION to
802 determine a default directory.")
804 (put 'dired-default-directory-alist 'risky-local-variable t) ; gets eval'd
805 (make-obsolete-variable 'dired-default-directory-alist
806 "this feature is due to be removed." "24.1")
808 (defun dired-default-directory ()
809 "Return the `dired-default-directory-alist' entry for the current major-mode.
810 If none, return `default-directory'."
811 ;; It looks like this was intended to be something of a "general"
812 ;; feature, but it only ever seems to have been used in
813 ;; dired-smart-shell-command, and doesn't seem worth keeping around.
814 (declare (obsolete nil "24.1"))
815 (or (eval (cdr (assq major-mode dired-default-directory-alist)))
816 default-directory))
818 (defun dired-smart-shell-command (command &optional output-buffer error-buffer)
819 "Like function `shell-command', but in the current Virtual Dired directory."
820 (interactive
821 (list
822 (read-shell-command "Shell command: " nil nil
823 (cond
824 (buffer-file-name (file-relative-name buffer-file-name))
825 ((eq major-mode 'dired-mode) (dired-get-filename t t))))
826 current-prefix-arg
827 shell-command-default-error-buffer))
828 (let ((default-directory (or (and (eq major-mode 'dired-mode)
829 (dired-current-directory))
830 default-directory)))
831 (shell-command command output-buffer error-buffer)))
834 ;;; LOCAL VARIABLES FOR DIRED BUFFERS.
836 ;; Brief Description (This feature is obsolete as of Emacs 24.1)
838 ;; * `dired-extra-startup' is part of the `dired-mode-hook'.
840 ;; * `dired-extra-startup' calls `dired-hack-local-variables'
842 ;; * `dired-hack-local-variables' checks the value of
843 ;; `dired-local-variables-file'
845 ;; * Check if `dired-local-variables-file' is a non-nil string and is a
846 ;; filename found in the directory of the Dired Buffer being created.
848 ;; * If `dired-local-variables-file' satisfies the above, then temporarily
849 ;; include it in the Dired Buffer at the bottom.
851 ;; * Set `enable-local-variables' temporarily to the user variable
852 ;; `dired-enable-local-variables' and run `hack-local-variables' on the
853 ;; Dired Buffer.
855 (defcustom dired-local-variables-file (convert-standard-filename ".dired")
856 "Filename, as string, containing local Dired buffer variables to be hacked.
857 If this file found in current directory, then it will be inserted into dired
858 buffer and `hack-local-variables' will be run. See Info node
859 `(emacs)File Variables' for more information on local variables.
860 See also `dired-enable-local-variables'."
861 :type 'file
862 :group 'dired)
864 (make-obsolete-variable 'dired-local-variables-file 'dir-locals-file "24.1")
866 (defun dired-hack-local-variables ()
867 "Evaluate local variables in `dired-local-variables-file' for Dired buffer."
868 (declare (obsolete hack-dir-local-variables-non-file-buffer "24.1"))
869 (and (stringp dired-local-variables-file)
870 (file-exists-p dired-local-variables-file)
871 (let ((opoint (point-max))
872 (inhibit-read-only t)
873 ;; In case user has `enable-local-variables' set to nil we
874 ;; override it locally with dired's variable.
875 (enable-local-variables dired-enable-local-variables))
876 ;; Insert 'em.
877 (save-excursion
878 (goto-char opoint)
879 (insert "\^L\n")
880 (insert-file-contents dired-local-variables-file))
881 ;; Hack 'em.
882 (unwind-protect
883 (let ((buffer-file-name dired-local-variables-file))
884 (hack-local-variables))
885 ;; Delete this stuff: `eobp' is used to find last subdir by dired.el.
886 (delete-region opoint (point-max)))
887 ;; Make sure that the mode line shows the proper information.
888 (dired-sort-set-mode-line))))
890 ;; Does not seem worth a dedicated command.
891 ;; See the more general features in files-x.el.
892 (defun dired-omit-here-always ()
893 "Create `dir-locals-file' setting `dired-omit-mode' to t in `dired-mode'.
894 If in a Dired buffer, reverts it."
895 (declare (obsolete add-dir-local-variable "24.1"))
896 (interactive)
897 (if (file-exists-p dired-local-variables-file)
898 (error "Old-style dired-local-variables-file `./%s' found;
899 replace it with a dir-locals-file `./%s'"
900 dired-local-variables-file
901 dir-locals-file))
902 (if (file-exists-p dir-locals-file)
903 (message "File `./%s' already exists." dir-locals-file)
904 (add-dir-local-variable 'dired-mode 'subdirs nil)
905 (add-dir-local-variable 'dired-mode 'dired-omit-mode t)
906 ;; Run extra-hooks and revert directory.
907 (when (derived-mode-p 'dired-mode)
908 (hack-dir-local-variables-non-file-buffer)
909 (dired-extra-startup)
910 (dired-revert))))
913 ;;; GUESS SHELL COMMAND.
915 ;; Brief Description:
917 ;; * `dired-do-shell-command' is bound to `!' by dired.el.
919 ;; * `dired-guess-shell-command' provides smarter defaults for
920 ;;; dired-aux.el's `dired-read-shell-command'.
922 ;; * `dired-guess-shell-command' calls `dired-guess-default' with list of
923 ;;; marked files.
925 ;; * Parse `dired-guess-shell-alist-user' and
926 ;;; `dired-guess-shell-alist-default' (in that order) for the first REGEXP
927 ;;; that matches the first file in the file list.
929 ;; * If the REGEXP matches all the entries of the file list then evaluate
930 ;;; COMMAND, which is either a string or a Lisp expression returning a
931 ;;; string. COMMAND may be a list of commands.
933 ;; * Return this command to `dired-guess-shell-command' which prompts user
934 ;;; with it. The list of commands is put into the list of default values.
935 ;;; If a command is used successfully then it is stored permanently in
936 ;;; `dired-shell-command-history'.
938 ;; Guess what shell command to apply to a file.
939 (defvar dired-shell-command-history nil
940 "History list for commands that read dired-shell commands.")
942 ;; Default list of shell commands.
944 ;; NOTE: Use `gunzip -c' instead of `zcat' on `.gz' files. Some do not
945 ;; install GNU zip's version of zcat.
947 (autoload 'Man-support-local-filenames "man")
949 (defvar dired-guess-shell-alist-default
950 (list
951 (list "\\.tar\\'"
952 '(if dired-guess-shell-gnutar
953 (concat dired-guess-shell-gnutar " xvf")
954 "tar xvf")
955 ;; Extract files into a separate subdirectory
956 '(if dired-guess-shell-gnutar
957 (concat "mkdir " (file-name-sans-extension file)
958 "; " dired-guess-shell-gnutar " -C "
959 (file-name-sans-extension file) " -xvf")
960 (concat "mkdir " (file-name-sans-extension file)
961 "; tar -C " (file-name-sans-extension file) " -xvf"))
962 ;; List archive contents.
963 '(if dired-guess-shell-gnutar
964 (concat dired-guess-shell-gnutar " tvf")
965 "tar tvf"))
967 ;; REGEXPS for compressed archives must come before the .Z rule to
968 ;; be recognized:
969 (list "\\.tar\\.Z\\'"
970 ;; Untar it.
971 '(if dired-guess-shell-gnutar
972 (concat dired-guess-shell-gnutar " zxvf")
973 (concat "zcat * | tar xvf -"))
974 ;; Optional conversion to gzip format.
975 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
976 " " dired-guess-shell-znew-switches))
978 ;; gzip'ed archives
979 (list "\\.t\\(ar\\.\\)?gz\\'"
980 '(if dired-guess-shell-gnutar
981 (concat dired-guess-shell-gnutar " zxvf")
982 (concat "gunzip -qc * | tar xvf -"))
983 ;; Extract files into a separate subdirectory
984 '(if dired-guess-shell-gnutar
985 (concat "mkdir " (file-name-sans-extension file)
986 "; " dired-guess-shell-gnutar " -C "
987 (file-name-sans-extension file) " -zxvf")
988 (concat "mkdir " (file-name-sans-extension file)
989 "; gunzip -qc * | tar -C "
990 (file-name-sans-extension file) " -xvf -"))
991 ;; Optional decompression.
992 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q" ""))
993 ;; List archive contents.
994 '(if dired-guess-shell-gnutar
995 (concat dired-guess-shell-gnutar " ztvf")
996 (concat "gunzip -qc * | tar tvf -")))
998 ;; bzip2'ed archives
999 (list "\\.t\\(ar\\.bz2\\|bz\\)\\'"
1000 "bunzip2 -c * | tar xvf -"
1001 ;; Extract files into a separate subdirectory
1002 '(concat "mkdir " (file-name-sans-extension file)
1003 "; bunzip2 -c * | tar -C "
1004 (file-name-sans-extension file) " -xvf -")
1005 ;; Optional decompression.
1006 "bunzip2")
1008 ;; xz'ed archives
1009 (list "\\.t\\(ar\\.\\)?xz\\'"
1010 "unxz -c * | tar xvf -"
1011 ;; Extract files into a separate subdirectory
1012 '(concat "mkdir " (file-name-sans-extension file)
1013 "; unxz -c * | tar -C "
1014 (file-name-sans-extension file) " -xvf -")
1015 ;; Optional decompression.
1016 "unxz")
1018 '("\\.shar\\.Z\\'" "zcat * | unshar")
1019 '("\\.shar\\.g?z\\'" "gunzip -qc * | unshar")
1021 '("\\.e?ps\\'" "ghostview" "xloadimage" "lpr")
1022 (list "\\.e?ps\\.g?z\\'" "gunzip -qc * | ghostview -"
1023 ;; Optional decompression.
1024 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1025 (list "\\.e?ps\\.Z\\'" "zcat * | ghostview -"
1026 ;; Optional conversion to gzip format.
1027 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1028 " " dired-guess-shell-znew-switches))
1030 '("\\.patch\\'" "cat * | patch")
1031 (list "\\.patch\\.g?z\\'" "gunzip -qc * | patch"
1032 ;; Optional decompression.
1033 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1034 (list "\\.patch\\.Z\\'" "zcat * | patch"
1035 ;; Optional conversion to gzip format.
1036 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1037 " " dired-guess-shell-znew-switches))
1039 ;; The following four extensions are useful with dired-man ("N" key)
1040 ;; FIXME "man ./" does not work with dired-do-shell-command,
1041 ;; because there seems to be no way for us to modify the filename,
1042 ;; only the command. Hmph. `dired-man' works though.
1043 (list "\\.\\(?:[0-9]\\|man\\)\\'"
1044 '(let ((loc (Man-support-local-filenames)))
1045 (cond ((eq loc 'man-db) "man -l")
1046 ((eq loc 'man) "man ./")
1048 "cat * | tbl | nroff -man -h | col -b"))))
1049 (list "\\.\\(?:[0-9]\\|man\\)\\.g?z\\'"
1050 '(let ((loc (Man-support-local-filenames)))
1051 (cond ((eq loc 'man-db)
1052 "man -l")
1053 ((eq loc 'man)
1054 "man ./")
1055 (t "gunzip -qc * | tbl | nroff -man -h | col -b")))
1056 ;; Optional decompression.
1057 '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1058 (list "\\.[0-9]\\.Z\\'"
1059 '(let ((loc (Man-support-local-filenames)))
1060 (cond ((eq loc 'man-db) "man -l")
1061 ((eq loc 'man) "man ./")
1062 (t "zcat * | tbl | nroff -man -h | col -b")))
1063 ;; Optional conversion to gzip format.
1064 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1065 " " dired-guess-shell-znew-switches))
1066 '("\\.pod\\'" "perldoc" "pod2man * | nroff -man")
1068 '("\\.dvi\\'" "xdvi" "dvips") ; preview and printing
1069 '("\\.au\\'" "play") ; play Sun audiofiles
1070 '("\\.mpe?g\\'\\|\\.avi\\'" "xine -p")
1071 '("\\.ogg\\'" "ogg123")
1072 '("\\.mp3\\'" "mpg123")
1073 '("\\.wav\\'" "play")
1074 '("\\.uu\\'" "uudecode") ; for uudecoded files
1075 '("\\.hqx\\'" "mcvert")
1076 '("\\.sh\\'" "sh") ; execute shell scripts
1077 '("\\.xbm\\'" "bitmap") ; view X11 bitmaps
1078 '("\\.gp\\'" "gnuplot")
1079 '("\\.p[bgpn]m\\'" "xloadimage")
1080 '("\\.gif\\'" "xloadimage") ; view gif pictures
1081 '("\\.tif\\'" "xloadimage")
1082 '("\\.png\\'" "display") ; xloadimage 4.1 doesn't grok PNG
1083 '("\\.jpe?g\\'" "xloadimage")
1084 '("\\.fig\\'" "xfig") ; edit fig pictures
1085 '("\\.out\\'" "xgraph") ; for plotting purposes.
1086 '("\\.tex\\'" "latex" "tex")
1087 '("\\.texi\\(nfo\\)?\\'" "makeinfo" "texi2dvi")
1088 '("\\.pdf\\'" "xpdf")
1089 '("\\.doc\\'" "antiword" "strings")
1090 '("\\.rpm\\'" "rpm -qilp" "rpm -ivh")
1091 '("\\.dia\\'" "dia")
1092 '("\\.mgp\\'" "mgp")
1094 ;; Some other popular archivers.
1095 (list "\\.zip\\'" "unzip" "unzip -l"
1096 ;; Extract files into a separate subdirectory
1097 '(concat "unzip" (if dired-guess-shell-gzip-quiet " -q")
1098 " -d " (file-name-sans-extension file)))
1099 '("\\.zoo\\'" "zoo x//")
1100 '("\\.lzh\\'" "lharc x")
1101 '("\\.arc\\'" "arc x")
1102 '("\\.shar\\'" "unshar")
1103 '("\\.rar\\'" "unrar x")
1104 '("\\.7z\\'" "7z x")
1106 ;; Compression.
1107 (list "\\.g?z\\'" '(concat "gunzip" (if dired-guess-shell-gzip-quiet " -q")))
1108 (list "\\.dz\\'" "dictunzip")
1109 (list "\\.bz2\\'" "bunzip2")
1110 (list "\\.xz\\'" "unxz")
1111 (list "\\.Z\\'" "uncompress"
1112 ;; Optional conversion to gzip format.
1113 '(concat "znew" (if dired-guess-shell-gzip-quiet " -q")
1114 " " dired-guess-shell-znew-switches))
1116 '("\\.sign?\\'" "gpg --verify"))
1118 "Default alist used for shell command guessing.
1119 See `dired-guess-shell-alist-user'.")
1121 (defcustom dired-guess-shell-alist-user nil
1122 "User-defined alist of rules for suggested commands.
1123 These rules take precedence over the predefined rules in the variable
1124 `dired-guess-shell-alist-default' (to which they are prepended).
1126 Each element of this list looks like
1128 (REGEXP COMMAND...)
1130 where each COMMAND can either be a string or a Lisp expression that evaluates
1131 to a string. If this expression needs to consult the name of the file for
1132 which the shell commands are being requested, it can access that file name
1133 as the variable `file'.
1134 If several COMMANDs are given, the first one will be the default
1135 and the rest will be added temporarily to the history and can be retrieved
1136 with \\[previous-history-element] (M-p) .
1138 The variable `dired-guess-shell-case-fold-search' controls whether
1139 REGEXP is matched case-sensitively."
1140 :group 'dired-x
1141 :type '(alist :key-type regexp :value-type (repeat sexp)))
1143 (defcustom dired-guess-shell-case-fold-search t
1144 "If non-nil, `dired-guess-shell-alist-default' and
1145 `dired-guess-shell-alist-user' are matched case-insensitively."
1146 :group 'dired-x
1147 :type 'boolean)
1149 (defun dired-guess-default (files)
1150 "Return a shell command, or a list of commands, appropriate for FILES.
1151 See `dired-guess-shell-alist-user'."
1153 (let* ((case-fold-search dired-guess-shell-case-fold-search)
1154 ;; Prepend the user's alist to the default alist.
1155 (alist (append dired-guess-shell-alist-user
1156 dired-guess-shell-alist-default))
1157 (file (car files))
1158 (flist (cdr files))
1159 elt regexp cmds)
1161 ;; Find the first match in the alist for first file in FILES.
1162 (while alist
1163 (setq elt (car alist)
1164 regexp (car elt)
1165 alist (cdr alist))
1166 (if (string-match-p regexp file)
1167 (setq cmds (cdr elt)
1168 alist nil)))
1170 ;; If more than one file, see if all of FILES match regular expression.
1171 (while (and flist
1172 (string-match-p regexp (car flist)))
1173 (setq flist (cdr flist)))
1175 ;; If flist is still non-nil, then do not guess since this means that not
1176 ;; all the files in FILES were matched by the regexp.
1177 (setq cmds (and (not flist) cmds))
1179 ;; Return commands or nil if flist is still non-nil.
1180 ;; Evaluate the commands in order that any logical testing will be done.
1181 (if (cdr cmds)
1182 (delete-dups (mapcar (lambda (cmd) (eval cmd `((file . ,file)))) cmds))
1183 (eval (car cmds) `((file . ,file)))))) ; single command
1185 (defun dired-guess-shell-command (prompt files)
1186 "Ask user with PROMPT for a shell command, guessing a default from FILES."
1187 (let ((default (dired-guess-default files))
1188 default-list val)
1189 (if (null default)
1190 ;; Nothing to guess
1191 (read-shell-command prompt nil 'dired-shell-command-history)
1192 (setq prompt (replace-regexp-in-string ": $" " " prompt))
1193 (if (listp default)
1194 ;; More than one guess
1195 (setq default-list default
1196 default (car default)
1197 prompt (concat
1198 prompt
1199 (format "{%d guesses} " (length default-list))))
1200 ;; Just one guess
1201 (setq default-list (list default)))
1202 ;; Put the first guess in the prompt but not in the initial value.
1203 (setq prompt (concat prompt (format "[%s]: " default)))
1204 ;; All guesses can be retrieved with M-n
1205 (setq val (read-shell-command prompt nil
1206 'dired-shell-command-history
1207 default-list))
1208 ;; If we got a return, then return default.
1209 (if (equal val "") default val))))
1212 ;;; RELATIVE SYMBOLIC LINKS.
1214 (declare-function make-symbolic-link "fileio.c")
1216 (defvar dired-keep-marker-relsymlink ?S
1217 "See variable `dired-keep-marker-move'.")
1219 (defun dired-make-relative-symlink (file1 file2 &optional ok-if-already-exists)
1220 "Make a symbolic link (pointing to FILE1) in FILE2.
1221 The link is relative (if possible), for example
1223 \"/vol/tex/bin/foo\" \"/vol/local/bin/foo\"
1225 results in
1227 \"../../tex/bin/foo\" \"/vol/local/bin/foo\""
1228 (interactive "FRelSymLink: \nFRelSymLink %s: \np")
1229 (let (name1 name2 len1 len2 (index 0) sub)
1230 (setq file1 (expand-file-name file1)
1231 file2 (expand-file-name file2)
1232 len1 (length file1)
1233 len2 (length file2))
1234 ;; Find common initial file name components:
1235 (let (next)
1236 (while (and (setq next (string-match "/" file1 index))
1237 (< (setq next (1+ next)) (min len1 len2))
1238 ;; For the comparison, both substrings must end in
1239 ;; `/', so NEXT is *one plus* the result of the
1240 ;; string-match.
1241 ;; E.g., consider the case of linking "/tmp/a/abc"
1242 ;; to "/tmp/abc" erroneously giving "/tmp/a" instead
1243 ;; of "/tmp/" as common initial component
1244 (string-equal (substring file1 0 next)
1245 (substring file2 0 next)))
1246 (setq index next))
1247 (setq name2 file2
1248 sub (substring file1 0 index)
1249 name1 (substring file1 index)))
1250 (if (string-equal sub "/")
1251 ;; No common initial file name found
1252 (setq name1 file1)
1253 ;; Else they have a common parent directory
1254 (let ((tem (substring file2 index))
1255 (start 0)
1256 (count 0))
1257 ;; Count number of slashes we must compensate for ...
1258 (while (setq start (string-match "/" tem start))
1259 (setq count (1+ count)
1260 start (1+ start)))
1261 ;; ... and prepend a "../" for each slash found:
1262 (dotimes (_ count)
1263 (setq name1 (concat "../" name1)))))
1264 (make-symbolic-link
1265 (directory-file-name name1) ; must not link to foo/
1266 ; (trailing slash!)
1267 name2 ok-if-already-exists)))
1269 (autoload 'dired-do-create-files "dired-aux")
1271 ;;;###autoload
1272 (defun dired-do-relsymlink (&optional arg)
1273 "Relative symlink all marked (or next ARG) files into a directory.
1274 Otherwise make a relative symbolic link to the current file.
1275 This creates relative symbolic links like
1277 foo -> ../bar/foo
1279 not absolute ones like
1281 foo -> /ugly/file/name/that/may/change/any/day/bar/foo
1283 For absolute symlinks, use \\[dired-do-symlink]."
1284 (interactive "P")
1285 (dired-do-create-files 'relsymlink #'dired-make-relative-symlink
1286 "RelSymLink" arg dired-keep-marker-relsymlink))
1288 (autoload 'dired-mark-read-regexp "dired-aux")
1289 (autoload 'dired-do-create-files-regexp "dired-aux")
1291 (defun dired-do-relsymlink-regexp (regexp newname &optional arg whole-name)
1292 "RelSymlink all marked files containing REGEXP to NEWNAME.
1293 See functions `dired-do-rename-regexp' and `dired-do-relsymlink'
1294 for more info."
1295 (interactive (dired-mark-read-regexp "RelSymLink"))
1296 (dired-do-create-files-regexp
1297 #'dired-make-relative-symlink
1298 "RelSymLink" arg regexp newname whole-name dired-keep-marker-relsymlink))
1301 ;;; VISIT ALL MARKED FILES SIMULTANEOUSLY.
1303 ;; Brief Description:
1305 ;; `dired-do-find-marked-files' is bound to `F' by dired-x.el.
1307 ;; * Use `dired-get-marked-files' to collect the marked files in the current
1308 ;;; Dired Buffer into a list of filenames `FILE-LIST'.
1310 ;; * Pass FILE-LIST to `dired-simultaneous-find-file' all with
1311 ;;; `dired-do-find-marked-files''s prefix argument NOSELECT.
1313 ;; * `dired-simultaneous-find-file' runs through FILE-LIST decrementing the
1314 ;;; list each time.
1316 ;; * If NOSELECT is non-nil then just run `find-file-noselect' on each
1317 ;;; element of FILE-LIST.
1319 ;; * If NOSELECT is nil then calculate the `size' of the window for each file
1320 ;;; by dividing the `window-height' by length of FILE-LIST. Thus, `size' is
1321 ;;; cognizant of the window-configuration.
1323 ;; * If `size' is too small abort, otherwise run `find-file' on each element
1324 ;;; of FILE-LIST giving each a window of height `size'.
1326 (defun dired-do-find-marked-files (&optional noselect)
1327 "Find all marked files displaying all of them simultaneously.
1328 With optional NOSELECT just find files but do not select them.
1330 The current window is split across all files marked, as evenly as possible.
1331 Remaining lines go to bottom-most window. The number of files that can be
1332 displayed this way is restricted by the height of the current window and
1333 `window-min-height'.
1335 To keep Dired buffer displayed, type \\[split-window-below] first.
1336 To display just marked files, type \\[delete-other-windows] first."
1337 (interactive "P")
1338 (dired-simultaneous-find-file (dired-get-marked-files) noselect))
1340 (defun dired-simultaneous-find-file (file-list noselect)
1341 "Visit all files in FILE-LIST and display them simultaneously.
1342 The current window is split across all files in FILE-LIST, as evenly as
1343 possible. Remaining lines go to the bottom-most window. The number of
1344 files that can be displayed this way is restricted by the height of the
1345 current window and the variable `window-min-height'. With non-nil
1346 NOSELECT the files are merely found but not selected."
1347 ;; We don't make this function interactive because it is usually too clumsy
1348 ;; to specify FILE-LIST interactively unless via dired.
1349 (let (size)
1350 (if noselect
1351 ;; Do not select the buffer.
1352 (find-file-noselect (car file-list))
1353 ;; We will have to select the buffer. Calculate and check window size.
1354 (setq size (/ (window-height) (length file-list)))
1355 (or (<= window-min-height size)
1356 (error "Too many files to visit simultaneously. Try C-u prefix"))
1357 (find-file (car file-list)))
1358 ;; Decrement.
1359 (dolist (file (cdr file-list))
1360 (if noselect
1361 ;; Do not select the buffer.
1362 (find-file-noselect file)
1363 ;; Vertically split off a window of desired size. Upper window will
1364 ;; have SIZE lines. Select lower (larger) window. We split it again.
1365 (select-window (split-window nil size))
1366 (find-file file)))))
1369 ;;; MISCELLANEOUS COMMANDS.
1371 ;; Run man on files.
1373 (declare-function Man-getpage-in-background "man" (topic))
1375 (defvar manual-program) ; from man.el
1377 (defun dired-man ()
1378 "Run `man' on this file."
1379 ;; Used also to say: "Display old buffer if buffer name matches filename."
1380 ;; but I have no idea what that means.
1381 (interactive)
1382 (require 'man)
1383 (let* ((file (dired-get-filename))
1384 (manual-program (replace-regexp-in-string "\\*" "%s"
1385 (dired-guess-shell-command
1386 "Man command: " (list file)))))
1387 (Man-getpage-in-background file)))
1389 ;; Run Info on files.
1391 (defun dired-info ()
1392 "Run `info' on this file."
1393 (interactive)
1394 (info (dired-get-filename)))
1396 ;; Run mail on mail folders.
1398 (declare-function vm-visit-folder "ext:vm" (folder &optional read-only))
1399 (defvar vm-folder-directory)
1401 (defun dired-vm (&optional read-only)
1402 "Run VM on this file.
1403 With optional prefix argument, visits the folder read-only.
1404 Otherwise obeys the value of `dired-vm-read-only-folders'."
1405 (interactive "P")
1406 (let ((dir (dired-current-directory))
1407 (fil (dired-get-filename)))
1408 (vm-visit-folder fil (or read-only
1409 (eq t dired-vm-read-only-folders)
1410 (and dired-vm-read-only-folders
1411 (not (file-writable-p fil)))))
1412 ;; So that pressing `v' inside VM does prompt within current directory:
1413 (set (make-local-variable 'vm-folder-directory) dir)))
1415 (defun dired-rmail ()
1416 "Run RMAIL on this file."
1417 (interactive)
1418 (rmail (dired-get-filename)))
1420 (defun dired-do-run-mail ()
1421 "Visit the current file as a mailbox, using VM or RMAIL.
1422 Prompt for confirmation first; if the user says yes, call
1423 `dired-vm' if `dired-bind-vm' is non-nil, `dired-rmail'
1424 otherwise."
1425 (interactive)
1426 (let ((file (dired-get-filename t)))
1427 (if dired-bind-vm
1428 (if (y-or-n-p (format-message
1429 "Visit `%s' as a mail folder with VM?" file))
1430 (dired-vm))
1431 ;; Read mail folder using rmail.
1432 (if (y-or-n-p (format-message
1433 "Visit `%s' as a mailbox with RMAIL?" file))
1434 (dired-rmail)))))
1437 ;;; MISCELLANEOUS INTERNAL FUNCTIONS.
1439 ;; This should be a builtin
1440 (defun dired-buffer-more-recently-used-p (buffer1 buffer2)
1441 "Return t if BUFFER1 is more recently used than BUFFER2.
1442 Considers buffers closer to the car of `buffer-list' to be more recent."
1443 (and (not (equal buffer1 buffer2))
1444 (memq buffer1 (buffer-list))
1445 (not (memq buffer1 (memq buffer2 (buffer-list))))))
1448 ;; Needed if ls -lh is supported and also for GNU ls -ls.
1449 (defun dired-x--string-to-number (str)
1450 "Like `string-to-number' but recognize a trailing unit prefix.
1451 For example, 2K is expanded to 2048.0. The caller should make
1452 sure that a trailing letter in STR is one of BKkMGTPEZY."
1453 (let* ((val (string-to-number str))
1454 (u (unless (zerop val)
1455 (aref str (1- (length str))))))
1456 (when (and u (> u ?9))
1457 (when (= u ?k)
1458 (setq u ?K))
1459 (let ((units '(?B ?K ?M ?G ?T ?P ?E ?Z ?Y)))
1460 (while (and units (/= (pop units) u))
1461 (setq val (* 1024.0 val)))))
1462 val))
1464 (defun dired-mark-sexp (predicate &optional unflag-p)
1465 "Mark files for which PREDICATE returns non-nil.
1466 With a prefix arg, unmark or unflag those files instead.
1468 PREDICATE is a lisp expression that can refer to the following symbols:
1470 inode [integer] the inode of the file (only for ls -i output)
1471 s [integer] the size of the file for ls -s output
1472 (usually in blocks or, with -k, in KByte)
1473 mode [string] file permission bits, e.g. \"-rw-r--r--\"
1474 nlink [integer] number of links to file
1475 uid [string] owner
1476 gid [string] group (If the gid is not displayed by ls,
1477 this will still be set (to the same as uid))
1478 size [integer] file size in bytes
1479 time [string] the time that ls displays, e.g. \"Feb 12 14:17\"
1480 name [string] the name of the file
1481 sym [string] if file is a symbolic link, the linked-to name, else \"\"
1483 For example, use
1485 (equal 0 size)
1487 to mark all zero length files.
1489 There's an ambiguity when a single integer not followed by a unit
1490 prefix precedes the file mode: It is then parsed as inode number
1491 and not as block size (this always works for GNU coreutils ls).
1493 Another limitation is that the uid field is needed for the
1494 function to work correctly. In particular, the field is not
1495 present for some values of `ls-lisp-emulation'.
1497 This function operates only on the buffer content and does not
1498 refer at all to the underlying file system. Contrast this with
1499 `find-dired', which might be preferable for the task at hand."
1500 ;; Using sym="" instead of nil avoids the trap of
1501 ;; (string-match "foo" sym) into which a user would soon fall.
1502 ;; Give `equal' instead of `=' in the example, as this works on
1503 ;; integers and strings.
1504 (interactive
1505 (list (read--expression
1506 (format "%s if (lisp expr): "
1507 (if current-prefix-arg
1508 "UNmark"
1509 "Mark")))
1510 current-prefix-arg))
1511 (message "%s" predicate)
1512 (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char))
1513 inode s mode nlink uid gid size time name sym)
1514 (dired-mark-if
1515 (save-excursion
1516 (and
1517 ;; Sets vars
1518 ;; inode s mode nlink uid gid size time name sym
1520 ;; according to current file line. Returns t for success, nil if
1521 ;; there is no file line. Upon success, all variables are set, either
1522 ;; to nil or the appropriate value, so they need not be initialized.
1523 ;; Moves point within the current line.
1524 (dired-move-to-filename)
1525 (let ((mode-len 10) ; length of mode string
1526 ;; like in dired.el, but with subexpressions \1=inode, \2=s:
1527 ;; GNU ls -hs suffixes the block count with a unit and
1528 ;; prints it as a float, FreeBSD does neither.
1529 (dired-re-inode-size "\\=\\s *\\([0-9]+\\s +\\)?\
1530 \\(?:\\([0-9]+\\(?:\\.[0-9]*\\)?[BkKMGTPEZY]?\\)? ?\\)"))
1531 (beginning-of-line)
1532 (forward-char 2)
1533 (search-forward-regexp dired-re-inode-size nil t)
1534 ;; XXX Might be a size not followed by a unit prefix.
1535 ;; We could set s to inode if it were otherwise nil,
1536 ;; with a similar reasoning as below for setting gid to uid,
1537 ;; but it would be even more whimsical.
1538 (setq inode (when (match-string 1)
1539 (string-to-number (match-string 1))))
1540 (setq s (when (match-string 2)
1541 (dired-x--string-to-number (match-string 2))))
1542 (setq mode (buffer-substring (point) (+ mode-len (point))))
1543 (forward-char mode-len)
1544 ;; Skip any extended attributes marker ("." or "+").
1545 (or (= (following-char) ?\s)
1546 (forward-char 1))
1547 (setq nlink (read (current-buffer)))
1548 ;; Karsten Wenger <kw@cis.uni-muenchen.de> fixed uid.
1549 ;; Another issue is that GNU ls -n right-justifies numerical
1550 ;; UIDs and GIDs, while FreeBSD left-justifies them, so
1551 ;; don't rely on a specific whitespace layout. Both of them
1552 ;; right-justify all other numbers, though.
1553 ;; XXX Return a number if the uid or gid seems to be
1554 ;; numerical?
1555 (setq uid (buffer-substring (progn
1556 (skip-chars-forward " \t")
1557 (point))
1558 (progn
1559 (skip-chars-forward "^ \t")
1560 (point))))
1561 (dired-move-to-filename)
1562 (save-excursion
1563 (setq time
1564 ;; The regexp below tries to match from the last
1565 ;; digit of the size field through a space after the
1566 ;; date. Also, dates may have different formats
1567 ;; depending on file age, so the date column need
1568 ;; not be aligned to the right.
1569 (buffer-substring (save-excursion
1570 (skip-chars-backward " \t")
1571 (point))
1572 (progn
1573 (re-search-backward
1574 directory-listing-before-filename-regexp)
1575 (skip-chars-forward "^ \t")
1576 (1+ (point))))
1577 size (dired-x--string-to-number
1578 ;; We know that there's some kind of number
1579 ;; before point because the regexp search
1580 ;; above succeeded. I don't think it's worth
1581 ;; doing an extra check for leading garbage.
1582 (buffer-substring (point)
1583 (progn
1584 (skip-chars-backward "^ \t")
1585 (point))))
1586 ;; If no gid is displayed, gid will be set to uid
1587 ;; but the user will then not reference it anyway in
1588 ;; PREDICATE.
1589 gid (buffer-substring (progn
1590 (skip-chars-backward " \t")
1591 (point))
1592 (progn
1593 (skip-chars-backward "^ \t")
1594 (point)))))
1595 (setq name (buffer-substring (point)
1597 (dired-move-to-end-of-filename t)
1598 (point)))
1599 sym (if (looking-at " -> ")
1600 (buffer-substring (progn (forward-char 4) (point))
1601 (line-end-position))
1602 ""))
1604 (eval predicate
1605 `((inode . ,inode)
1606 (s . ,s)
1607 (mode . ,mode)
1608 (nlink . ,nlink)
1609 (uid . ,uid)
1610 (gid . ,gid)
1611 (size . ,size)
1612 (time . ,time)
1613 (name . ,name)
1614 (sym . ,sym)))))
1615 (format "'%s file" predicate))))
1618 ;;; FIND FILE AT POINT.
1620 (defcustom dired-x-hands-off-my-keys t
1621 "Non-nil means don't remap `find-file' to `dired-x-find-file'.
1622 Similarly for `find-file-other-window' and `dired-x-find-file-other-window'.
1623 If you change this variable without using \\[customize] after `dired-x.el'
1624 is loaded then call \\[dired-x-bind-find-file]."
1625 :type 'boolean
1626 :initialize 'custom-initialize-default
1627 :set (lambda (symbol value)
1628 (set symbol value)
1629 (dired-x-bind-find-file))
1630 :group 'dired-x)
1632 (defun dired-x-bind-find-file ()
1633 "Bind `dired-x-find-file' in place of `find-file' (or vice-versa).
1634 Similarly for `dired-x-find-file-other-window' and `find-file-other-window'.
1635 Binding direction based on `dired-x-hands-off-my-keys'."
1636 (interactive)
1637 (if (called-interactively-p 'interactive)
1638 (setq dired-x-hands-off-my-keys
1639 (not (y-or-n-p "Bind dired-x-find-file over find-file? "))))
1640 (unless dired-x-hands-off-my-keys
1641 (define-key (current-global-map) [remap find-file]
1642 'dired-x-find-file)
1643 (define-key (current-global-map) [remap find-file-other-window]
1644 'dired-x-find-file-other-window)))
1646 ;; Now call it so binding is correct. This could go in the :initialize
1647 ;; slot, but then dired-x-bind-find-file has to be defined before the
1648 ;; defcustom, and we get free variable warnings.
1649 (dired-x-bind-find-file)
1651 (defun dired-x-find-file (filename)
1652 "Edit file FILENAME.
1653 Like `find-file', except that when called interactively with a
1654 prefix argument, it offers the filename near point as a default."
1655 (interactive (list (dired-x-read-filename-at-point "Find file: ")))
1656 (find-file filename))
1658 (defun dired-x-find-file-other-window (filename)
1659 "Edit file FILENAME, in another window.
1660 Like `find-file-other-window', except that when called interactively with
1661 a prefix argument, when it offers the filename near point as a default."
1662 (interactive (list (dired-x-read-filename-at-point "Find file: ")))
1663 (find-file-other-window filename))
1665 ;;; Internal functions.
1667 ;; Fixme: This should probably use `thing-at-point'. -- fx
1668 (defun dired-filename-at-point ()
1669 "Return the filename closest to point, expanded.
1670 Point should be in or after a filename."
1671 (save-excursion
1672 ;; First see if just past a filename.
1673 (or (eobp) ; why?
1674 (when (looking-at-p "[] \t\n[{}()]") ; whitespace or some parens
1675 (skip-chars-backward " \n\t\r({[]})")
1676 (or (bobp) (backward-char 1))))
1677 (let ((filename-chars "-.[:alnum:]_/:$+@")
1678 start prefix)
1679 (if (looking-at-p (format "[%s]" filename-chars))
1680 (progn
1681 (skip-chars-backward filename-chars)
1682 (setq start (point)
1683 prefix
1684 ;; This is something to do with ange-ftp filenames.
1685 ;; It convert foo@bar to /foo@bar.
1686 ;; But when does the former occur in dired buffers?
1687 (and (string-match-p
1688 "^\\w+@"
1689 (buffer-substring start (line-end-position)))
1690 "/"))
1691 (if (string-match-p "[/~]" (char-to-string (preceding-char)))
1692 (setq start (1- start)))
1693 (skip-chars-forward filename-chars))
1694 (error "No file found around point!"))
1695 ;; Return string.
1696 (expand-file-name (concat prefix (buffer-substring start (point)))))))
1698 (defun dired-x-read-filename-at-point (prompt)
1699 "Return filename prompting with PROMPT with completion.
1700 If `current-prefix-arg' is non-nil, uses name at point as guess."
1701 (if current-prefix-arg
1702 (let ((guess (dired-filename-at-point)))
1703 (read-file-name prompt
1704 (file-name-directory guess)
1705 guess
1706 nil (file-name-nondirectory guess)))
1707 (read-file-name prompt default-directory)))
1709 (define-obsolete-function-alias 'read-filename-at-point
1710 'dired-x-read-filename-at-point "24.1") ; is this even needed?
1712 ;;; BUG REPORTS
1714 (define-obsolete-function-alias 'dired-x-submit-report 'report-emacs-bug "24.1")
1717 ;; As Barry Warsaw would say: "This might be useful..."
1718 (provide 'dired-x)
1720 ;; Local Variables:
1721 ;; byte-compile-dynamic: t
1722 ;; generated-autoload-file: "dired-loaddefs.el"
1723 ;; End:
1725 ;;; dired-x.el ends here