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