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