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