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