home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / dired / dired.el < prev    next >
Encoding:
Text File  |  1992-11-12  |  140.2 KB  |  3,676 lines

  1. ;; DIRED commands for Emacs. Revision: 6.0 
  2. ;; Copyright (C) 1985, 1986, 1991, 1992 Free Software Foundation, Inc.
  3.  
  4. ;; This file is part of GNU Emacs.
  5.  
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation; either version 2, or (at your option)
  9. ;; any later version.
  10.  
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ;; GNU General Public License for more details.
  15.  
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  18. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. ;; Rewritten in 1990/1991 to add tree features, file marking and
  21. ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
  22.  
  23. (provide 'dired)
  24.  
  25. (defconst dired-version (substring "!Revision: 6.0 !" 11 -2)
  26.   "The revision number of Tree Dired (as string).  The complete RCS id is:
  27.  
  28.   !Id: dired.el,v 6.0 1992/05/15 14:25:45 sk RelBeta !
  29.  
  30. Don't forget to mention this when reporting bugs to:
  31.  
  32.   Sebastian Kremer <sk@thp.uni-koeln.de>
  33.  
  34. Tree dired is available for anonymous ftp in USA in:
  35.  
  36.   ftp.cs.buffalo.edu:pub/Emacs/diredall.tar.Z
  37.  
  38. and in Europe at my own site in Germany:
  39.  
  40.   ftp.uni-koeln.de:/pub/gnu/emacs/diredall.tar.Z")
  41. ;; Should perhaps later give bug-gnu-emacs@prep.gnu.ai.mit.edu instead.
  42.  
  43. ;; compatibility package when using Emacs 18.55
  44. (defvar dired-emacs-19-p (equal (substring emacs-version 0 2) "19"))
  45. ;;;>>> install (is there a better way to test for Emacs 19?)
  46. (or dired-emacs-19-p
  47.     (require 'emacs-19))
  48.  
  49. ;;; Customizable variables
  50.  
  51. ;;; The funny comments are for autoload.el, to automagically update
  52. ;;; loaddefs.
  53.  
  54. ;;;###autoload
  55. (defvar dired-listing-switches "-al"
  56.   "*Switches passed to ls for dired. MUST contain the `l' option.
  57. Can contain even `F', `b', `i' and `s'.")
  58.  
  59. ; Don't use absolute paths as /bin should be in any PATH and people
  60. ; may prefer /usr/local/gnu/bin or whatever.  However, chown is
  61. ; usually not in PATH.
  62.  
  63. ;;;###autoload
  64. (defvar dired-chown-program
  65.   (if (memq system-type '(dgux-unix hpux usg-unix-v silicon-graphics-unix))
  66.       "chown" "/etc/chown")
  67.   "*Name of chown command (usully `chown' or `/etc/chown').")
  68.  
  69. ;;;###autoload
  70. (defvar dired-ls-program "ls"
  71.   "*Absolute or relative name of the ls program used by dired.")
  72.  
  73. ;;;###autoload
  74. (defvar dired-ls-F-marks-symlinks t
  75.   "*Informs dired about how ls -lF marks symbolic links.
  76. Set this to t if `dired-ls-program' with -lF marks the symbolic link
  77. itself with a trailing @ (usually the case under Ultrix).
  78.  
  79. Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
  80. nil, if it gives `bar@ -> foo', set it to t.
  81.  
  82. Dired checks if there is really a @ appended.  Thus, if you have a
  83. marking ls program on one host and a non-marking on another host, and
  84. don't care about symbolic links which really end in a @, you can
  85. always set this variable to t.")
  86.  
  87. ;;;###autoload
  88. (defvar dired-trivial-filenames "^\\.\\.?$\\|^#"
  89.   "*Regexp of files to skip when moving point to the first file of a new directory listing.
  90. Nil means move to the subdir line, t means move to first file.")
  91.  
  92. ;;;###autoload
  93. (defvar dired-keep-marker-move t
  94.   ;; Use t as default so that moved files `take their markers with them'
  95.   "If t, moved marked files are marked if their originals were.
  96. If a character, those files (marked or not) are marked with that character.")
  97.  
  98. ;;;###autoload
  99. (defvar dired-keep-marker-copy ?C
  100.     "If t, copied files are marked if their source files were.
  101. If a character, those files are always marked with that character.")
  102.  
  103. ;;;###autoload
  104. (defvar dired-keep-marker-hardlink ?H
  105.     "If t, hard-linked files are marked if the linked-to files were.
  106. If a character, those files are always marked with that character.")
  107.  
  108. ;;;###autoload
  109. (defvar dired-keep-marker-symlink ?Y
  110.     "If t, symlinked marked files are marked if the linked-to files were.
  111. If a character, those files are always marked with that character.")
  112.  
  113. ;;;###autoload
  114. (defvar dired-dwim-target nil
  115.   "*If non-nil, dired tries to guess a default target directory:
  116. If there is a dired buffer displayed in the next window, use
  117. its current subdir, instead of the current subdir of this dired
  118. buffer.
  119.  
  120. The target is used in the prompt for file copy, move etc.")
  121.  
  122. ;;;###autoload
  123. (defvar dired-copy-preserve-time nil
  124.   "*If non-nil, Dired preserves the last-modified time in a file copy.
  125. \(This works on only some systems.)\\<dired-mode-map>
  126. Use `\\[dired-do-copy]' with a zero prefix argument to toggle its value.")
  127.  
  128. ;;; Hook variables
  129.  
  130. (defvar dired-load-hook nil
  131.   "Run after loading dired.
  132. You can customize key bindings or load extensions with this.")
  133.  
  134. (defvar dired-mode-hook nil
  135.   "Run at the very end of dired-mode.")
  136.  
  137. (defvar dired-before-readin-hook nil
  138.   "This hook is run before a dired buffer is newly read in (created or reverted).")
  139.  
  140. (defvar dired-after-readin-hook nil
  141.   "After each listing of a file or directory, this hook is run
  142. with the buffer narrowed to the listing.")
  143. ;; Note this can't simply be run inside function dired-ls as the hook
  144. ;; functions probably depend on the dired-subdir-alist to be OK.
  145.  
  146. ;;; Internal variables
  147.  
  148. (defvar dired-marker-char ?*        ; the answer is 42
  149.   ;; so that you can write things like
  150.   ;; (let ((dired-marker-char ?X))
  151.   ;;    ;; great code using X markers ...
  152.   ;;    )
  153.   ;; For example, commands operating on two sets of files, A and B.
  154.   ;; Or marking files with digits 0-9.  This could implicate
  155.   ;; concentric sets or an order for the marked files.
  156.   ;; The code depends on dynamic scoping on the marker char.
  157.   "In dired, character used to mark files for later commands.")
  158.  
  159. (defvar dired-del-marker ?D
  160.   "Character used to flag files for deletion.")
  161.  
  162. (defvar dired-shrink-to-fit
  163.   (if (fboundp 'baud-rate) (> (baud-rate) search-slow-speed) t)
  164.   "Whether dired shrinks the display buffer to fit the marked files.")
  165.  
  166. (defvar dired-flagging-regexp nil);; Last regexp used to flag files.
  167.  
  168. (defvar dired-directory nil
  169.   "The directory name or shell wildcard passed as argument to ls.
  170. Local to each dired buffer.")
  171.  
  172. (defvar dired-actual-switches nil
  173.   "The actual (buffer-local) value of `dired-listing-switches'.")
  174.  
  175. (defvar dired-re-inode-size "[0-9 \t]*"
  176.   "Regexp for optional initial inode and file size as produced by ls' -i and -s flags.")
  177.  
  178. ;; These regexps must be tested at beginning-of-line, but are also
  179. ;; used to search for next matches, so neither omitting "^" nor
  180. ;; replacing "^" by "\n" (to make it slightly faster) will work.
  181.  
  182. (defvar dired-re-mark "^[^ \n]")
  183. ;; "Regexp matching a marked line.
  184. ;; Important: the match ends just after the marker."
  185. (defvar dired-re-maybe-mark "^. ")
  186. ;; Note that dired-re-inode-size allows for an arbitray amount of
  187. ;; whitespace, making nested indentation in dired-nstd.el work.
  188. (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
  189. (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
  190. (defvar dired-re-exe;; match ls permission string of an executable file
  191.   (mapconcat (function
  192.           (lambda (x)
  193.         (concat dired-re-maybe-mark dired-re-inode-size x)))
  194.          '("-[-r][-w][xs][-r][-w].[-r][-w]."
  195.            "-[-r][-w].[-r][-w][xs][-r][-w]."
  196.            "-[-r][-w].[-r][-w].[-r][-w][xst]")
  197.          "\\|"))
  198. (defvar dired-re-dot "^.* \\.\\.?/?$")    ; with -F, might end in `/'
  199.  
  200. (defvar dired-subdir-alist nil
  201.   "Association list of subdirectories and their buffer positions:
  202.  
  203.   \((LASTDIR . LASTMARKER) ... (DEFAULT-DIRECTORY . FIRSTMARKER)).")
  204.  
  205. (defvar dired-subdir-regexp "^. \\([^ \n\r]+\\)\\(:\\)[\n\r]"
  206.   "Regexp matching a maybe hidden subdirectory line in ls -lR output.
  207. Subexpression 1 is the subdirectory proper, no trailing colon.
  208. The match starts at the beginning of the line and ends after the end
  209. of the line (\\n or \\r).
  210. Subexpression 2 must end right before the \\n or \\r.")
  211.  
  212.  
  213. ;;; Macros must be defined before they are used - for the byte compiler.
  214.  
  215. ;; Returns the count if any work was done, nil otherwise.
  216. (defmacro dired-mark-if (predicate msg)
  217.   (` (let (buffer-read-only count)
  218.        (save-excursion
  219.      (setq count 0)
  220.      (if (, msg) (message "Marking %ss..." (, msg)))
  221.      (goto-char (point-min))
  222.      (while (not (eobp))
  223.        (if (, predicate)
  224.            (progn
  225.          (delete-char 1)
  226.          (insert dired-marker-char)
  227.          (setq count (1+ count))))
  228.        (forward-line 1))
  229.      (if (, msg) (message "%s %s%s %s%s."
  230.               count
  231.               (, msg)
  232.               (dired-plural-s count)
  233.               (if (eq dired-marker-char ?\040) "un" "")
  234.               (if (eq dired-marker-char dired-del-marker)
  235.                   "flagged" "marked"))))
  236.        (and (> count 0) count))))
  237.  
  238. (defmacro dired-mark-map (body arg &optional show-progress)
  239. ;;  "Macro: Perform BODY with point somewhere on each marked line
  240. ;;and return a list of BODY's results.
  241. ;;If no marked file could be found, execute BODY on the current line.
  242. ;;  If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
  243. ;;  files instead of the marked files.
  244. ;;  In that case point is dragged along.  This is so that commands on
  245. ;;  the next ARG (instead of the marked) files can be chained easily.
  246. ;;  If ARG is otherwise non-nil, use current file instead.
  247. ;;If optional third arg SHOW-PROGRESS evaluates to non-nil,
  248. ;;   redisplay the dired buffer after each file is processed.
  249. ;;No guarantee is made about the position on the marked line.
  250. ;;  BODY must ensure this itself if it depends on this.
  251. ;;Search starts at the beginning of the buffer, thus the car of the list
  252. ;;  corresponds to the line nearest to the buffer's bottom.  This
  253. ;;  is also true for (positive and negative) integer values of ARG.
  254. ;;BODY should not be too long as it is expanded four times."
  255. ;;
  256. ;;Warning: BODY must not add new lines before point - this may cause an
  257. ;;endless loop.
  258. ;;This warning should not apply any longer, sk  2-Sep-1991 14:10.
  259.   (` (prog1
  260.      (let (buffer-read-only case-fold-search found results)
  261.        (if (, arg)
  262.            (if (integerp (, arg))
  263.            (progn;; no save-excursion, want to move point.
  264.              (dired-repeat-over-lines
  265.               (, arg)
  266.               (function (lambda ()
  267.                   (if (, show-progress) (sit-for 0))
  268.                   (setq results (cons (, body) results)))))
  269.              (if (< (, arg) 0)
  270.              (nreverse results)
  271.                results))
  272.          ;; non-nil, non-integer ARG means use current file:
  273.          (list (, body)))
  274.          (let ((regexp (dired-marker-regexp)) next-position)
  275.            (save-excursion
  276.          (goto-char (point-min))
  277.          ;; remember position of next marked file before BODY
  278.          ;; can insert lines before the just found file,
  279.          ;; confusing us by finding the same marked file again
  280.          ;; and again and...
  281.          (setq next-position (and (re-search-forward regexp nil t)
  282.                       (point-marker))
  283.                found (not (null next-position)))
  284.          (while next-position
  285.            (goto-char next-position)
  286.            (if (, show-progress) (sit-for 0))
  287.            (setq results (cons (, body) results))
  288.            ;; move after last match
  289.            (goto-char next-position)
  290.            (forward-line 1)
  291.            (set-marker next-position nil)
  292.            (setq next-position (and (re-search-forward regexp nil t)
  293.                         (point-marker)))))
  294.            (if found
  295.            results
  296.          (list (, body))))))
  297.        ;; save-excursion loses, again
  298.        (dired-move-to-filename))))
  299.  
  300. (defun dired-mark-get-files (&optional localp arg)
  301.   "Return the marked files as list of strings.
  302. The list is in the same order as the buffer, that is, the car is the
  303.   first marked file.
  304. Values returned are normally absolute pathnames.
  305. Optional arg LOCALP as in `dired-get-filename'.
  306. Optional second argument ARG forces to use other files.  If ARG is an
  307.   integer, use the next ARG files.  If ARG is otherwise non-nil, use
  308.   current file.  Usually ARG comes from the current prefix arg."
  309.   (nreverse (save-excursion (dired-mark-map (dired-get-filename localp) arg))))
  310.  
  311.  
  312. ;; Function dired-ls is redefinable for VMS, ange-ftp, Prospero or
  313. ;; other special applications.
  314.  
  315. ;; dired-ls
  316. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  317. ;;   FULL-DIRECTORY-P is nil.
  318. ;;   The single line of output must display FILE's name as it was
  319. ;;   given, namely, an absolute path name.
  320. ;; - must insert exactly one line for each file if WILDCARD or
  321. ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
  322. ;;   before the file lines, plus optional text after the file lines.
  323. ;;   Lines are delimited by "\n", so filenames containing "\n" are not
  324. ;;   allowed.
  325. ;;   File lines should display the basename, not a path name.
  326. ;; - must drag point after inserted text
  327. ;; - must be consistent with
  328. ;;   - functions dired-move-to-filename, (these two define what a file line is)
  329. ;;            dired-move-to-end-of-filename,
  330. ;;         dired-between-files, (shortcut for (not (dired-move-to-filename)))
  331. ;;            dired-insert-headerline
  332. ;;            dired-after-subdir-garbage (defines what a "total" line is)
  333. ;;   - variables dired-subdir-regexp
  334. (defun dired-ls (file switches &optional wildcard full-directory-p)
  335. ;  "Insert ls output of FILE, formatted according to SWITCHES.
  336. ;Optional third arg WILDCARD means treat FILE as shell wildcard.
  337. ;Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  338. ;switches do not contain `d', so that a full listing is expected.
  339. ;
  340. ;Uses dired-ls-program (and shell-file-name if WILDCARD) to do the work."
  341.   (if wildcard
  342.       (let ((default-directory (file-name-directory file)))
  343.     (call-process shell-file-name nil t nil
  344.               "-c" (concat dired-ls-program " -d " switches " "
  345.                    (file-name-nondirectory file))))
  346.     (call-process dired-ls-program nil t nil switches file)))
  347.  
  348. ;; The dired command
  349.  
  350. (defun dired-read-dir-and-switches (str)
  351.   ;; For use in interactive.
  352.   (reverse (list
  353.         (if current-prefix-arg
  354.         (read-string "Dired listing switches: "
  355.                  dired-listing-switches))
  356.         (read-file-name (format "Dired %s(directory): " str)
  357.                 nil default-directory nil))))
  358.  
  359. ;;;###autoload (define-key ctl-x-map "d" 'dired)
  360. ;;;###autoload
  361. (defun dired (dirname &optional switches)
  362.   "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
  363. With an optional prefix argument you can specify the ls SWITCHES that are used.
  364. Dired displays a list of files in DIRNAME (which may also have
  365.   shell wildcards appended to select certain files).
  366. You can move around in it with the usual commands.
  367. You can flag files for deletion with \\<dired-mode-map>\\[dired-flag-file-deleted] and then delete them by
  368.   typing \\[dired-do-deletions].
  369. Type \\[describe-mode] after entering dired for more info.
  370.  
  371. If DIRNAME is already in a dired buffer, that buffer is used without refresh."
  372.   ;; Cannot use (interactive "D") because of wildcards.
  373.   (interactive (dired-read-dir-and-switches ""))
  374.   (switch-to-buffer (dired-noselect dirname switches)))
  375.  
  376. ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
  377. ;;;###autoload
  378. (defun dired-other-window (dirname &optional switches)
  379.   "\"Edit\" directory DIRNAME.  Like `dired' but selects in another window."
  380.   (interactive (dired-read-dir-and-switches "in other window "))
  381.   (switch-to-buffer-other-window (dired-noselect dirname switches)))
  382.  
  383. ;;;###autoload
  384. (defun dired-noselect (dirname &optional switches)
  385.   "Like `dired' but returns the dired buffer as value, does not select it."
  386.   (or dirname (setq dirname default-directory))
  387.   ;; This loses the distinction between "/foo/*/" and "/foo/*" that
  388.   ;; some shells make:
  389.   (setq dirname (expand-file-name (directory-file-name dirname)))
  390.   (if (file-directory-p dirname)
  391.       (setq dirname (file-name-as-directory dirname)))
  392.   (dired-internal-noselect dirname switches))
  393.  
  394. ;; Separate function from dired-noselect for the sake of dired-vms.el.
  395. (defun dired-internal-noselect (dirname &optional switches)
  396.   ;; If there is an existing dired buffer for DIRNAME, just leave
  397.   ;; buffer as it is (don't even call dired-revert).
  398.   ;; This saves time especially for deep trees or with ange-ftp.
  399.   ;; The user can type `g'easily, and it is more consistent with find-file.
  400.   ;; But if SWITCHES are given they are probably different from the
  401.   ;; buffer's old value, so call dired-sort-other, which does
  402.   ;; revert the buffer.
  403.   ;; A pity we can't possibly do "Directory has changed - refresh? "
  404.   ;; like find-file does...maybe in the GNU OS.
  405.   (let* ((buffer (dired-find-buffer-nocreate dirname))
  406.      ;; note that buffer already is in dired-mode, if found
  407.      (new-buffer-p (not buffer))
  408.      (old-buf (current-buffer)))
  409.     (or buffer
  410.     (let ((default-major-mode 'fundamental-mode))
  411.       ;; We don't want default-major-mode to run hooks and set auto-fill
  412.       ;; or whatever, now that dired-mode does not
  413.       ;; kill-all-local-variables any longer.
  414.       (setq buffer (create-file-buffer (directory-file-name dirname)))))
  415.     (set-buffer buffer)
  416.     (if (not new-buffer-p)        ; existing buffer ...
  417.     (if switches            ; ... but new switches
  418.         (dired-sort-other switches))    ; this calls dired-revert
  419.       ;; Else a new buffer
  420.       (setq default-directory (if (file-directory-p dirname)
  421.                   dirname
  422.                 (file-name-directory dirname)))
  423.       (or switches (setq switches dired-listing-switches))
  424.       (dired-mode dirname switches)
  425.       ;; default-directory and dired-actual-switches are set now
  426.       ;; (buffer-local), so we can call dired-readin:
  427.       (let ((failed t))
  428.     (unwind-protect
  429.         (progn (dired-readin dirname buffer)
  430.            (setq failed nil))
  431.       ;; dired-readin can fail if parent directories are inaccessible.
  432.       ;; Don't leave an empty buffer around in that case.
  433.       (if failed (kill-buffer buffer))))
  434.       ;; No need to narrow since the whole buffer contains just
  435.       ;; dired-readin's output, nothing else.  The hook can
  436.       ;; successfully use dired functions (e.g. dired-get-filename)
  437.       ;; as the subdir-alist has been built in dired-readin.
  438.       (run-hooks 'dired-after-readin-hook)
  439.       (goto-char (point-min))
  440.       (dired-initial-position dirname))
  441.     (set-buffer old-buf)
  442.     buffer))
  443.  
  444. ;; This differs from dired-buffers-for-dir in that it does not consider
  445. ;; subdirs of default-directory and searches for the first match only
  446. (defun dired-find-buffer-nocreate (dirname)
  447.   (let (found (blist (buffer-list)))
  448.     (while blist
  449.       (save-excursion
  450.         (set-buffer (car blist))
  451.     (if (and (eq major-mode 'dired-mode)
  452.          (equal dired-directory dirname))
  453.         (setq found (car blist)
  454.           blist nil)
  455.       (setq blist (cdr blist)))))
  456.     found))
  457.  
  458.  
  459. ;; Read in a new dired buffer
  460.  
  461. ;; dired-readin differs from dired-insert-subdir in that it accepts
  462. ;; wildcards, erases the buffer, and builds the subdir-alist anew
  463. ;; (including making it buffer-local and clearing it first).
  464. (defun dired-readin (dirname buffer)
  465.   ;; default-directory and dired-actual-switches must be buffer-local
  466.   ;; and initialized by now.
  467.   ;; Thus we can test (equal default-directory dirname) instead of
  468.   ;; (file-directory-p dirname) and save a filesystem transaction.
  469.   ;; Also, we can run this hook which may want to modify the switches
  470.   ;; based on default-directory, e.g. with ange-ftp to a SysV host
  471.   ;; where ls won't understand -Al switches.
  472.   (setq dirname (expand-file-name dirname))
  473.   (run-hooks 'dired-before-readin-hook)
  474.   (save-excursion
  475.     (message "Reading directory %s..." dirname)
  476.     (set-buffer buffer)
  477.     (let (buffer-read-only)
  478.       (widen)
  479.       (erase-buffer)
  480.       (dired-readin-insert dirname)
  481.       (indent-rigidly (point-min) (point-max) 2)
  482.       ;; We need this to make the root dir have a header line as all
  483.       ;; other subdirs have:
  484.       (goto-char (point-min))
  485.       (dired-insert-headerline default-directory)
  486.       ;; can't run dired-after-readin-hook here, it may depend on the subdir
  487.       ;; alist to be OK.
  488.       )
  489.     (message "Reading directory %s...done" dirname)
  490.     (set-buffer-modified-p nil)
  491.     ;; Must first make alist buffer local and set it to nil because
  492.     ;; dired-build-subdir-alist will call dired-clear-alist first
  493.     (set (make-local-variable 'dired-subdir-alist) nil)
  494.     (let (case-fold-search)
  495.       (if (string-match "R" dired-actual-switches)
  496.       (dired-build-subdir-alist)
  497.     ;; no need to parse the buffer if listing is not recursive
  498.     (dired-simple-subdir-alist)))))
  499.  
  500. ;; Subroutines of dired-readin
  501.  
  502. (defun dired-readin-insert (dirname)
  503.   ;; Just insert listing for DIRNAME, assuming a clean buffer.
  504.   (if (equal default-directory dirname);; i.e., (file-directory-p dirname)
  505.       (dired-ls (if (or (let (case-fold-search)
  506.               (string-match "R" dired-actual-switches))
  507.             (eq system-type 'vax-vms))
  508.             dirname
  509.           ;; On SysV derived system, symbolic links to
  510.           ;; directories are not resolved, while on BSD
  511.           ;; derived it suffices to let DIRNAME end in slash.
  512.           ;; We always let it end in "/." since it does no
  513.           ;; harm on BSD and makes Dired work on such links on
  514.           ;; SysV.
  515.           ;; Cannot do this with -R since "dir/./subdir"
  516.           ;; headerlines would result, utterly confusing dired.
  517.           (concat dirname "."))
  518.         dired-actual-switches nil t)
  519.     (if (not (file-readable-p
  520.           (directory-file-name (file-name-directory dirname))))
  521.     (error "Directory %s inaccessible or nonexistent" dirname)
  522.       ;; else assume it contains wildcards:
  523.       (dired-ls dirname dired-actual-switches t)
  524.       (save-excursion;; insert wildcard instead of total line:
  525.     (goto-char (point-min))
  526.     (insert "wildcard " (file-name-nondirectory dirname) "\n")))))
  527.  
  528. (defun dired-insert-headerline (dir);; also used by dired-insert-subdir
  529.   ;; Insert DIR's headerline with no trailing slash, exactly like ls
  530.   ;; would, and put cursor where dired-build-subdir-alist puts subdir
  531.   ;; boundaries.
  532.   (save-excursion (insert "  " (directory-file-name dir) ":\n")))
  533.  
  534.  
  535. ;; Reverting a dired buffer
  536.  
  537. (defun dired-revert (&optional arg noconfirm)
  538.   ;; Reread the dired buffer.  Must also be called after
  539.   ;; dired-actual-switches have changed.
  540.   ;; Should not fail even on completely garbaged buffers.
  541.   ;; Preserves old cursor, marks/flags, hidden-p.
  542.   (widen)                ; just in case user narrowed
  543.   (let ((opoint (point))
  544.     (ofile (dired-get-filename nil t))
  545.     (mark-alist nil)        ; save marked files
  546.     (hidden-subdirs (dired-remember-hidden))
  547.     (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
  548.     case-fold-search        ; we check for upper case ls flags
  549.     buffer-read-only)
  550.     (goto-char (point-min))
  551.     (setq mark-alist;; only after dired-remember-hidden since this unhides:
  552.       (dired-remember-marks (point-min) (point-max)))
  553.     ;; treat top level dir extra (it may contain wildcards)
  554.     (dired-readin dired-directory (current-buffer))
  555.     (let ((dired-after-readin-hook nil))
  556.       ;; don't run that hook for each subdir...
  557.       (dired-insert-old-subdirs old-subdir-alist))
  558.     (dired-mark-remembered mark-alist)    ; mark files that were marked
  559.     ;; ... run the hook for the whole buffer, and only after markers
  560.     ;; have been reinserted (else omitting in dired-x would omit marked files)
  561.     (run-hooks 'dired-after-readin-hook)    ; no need to narrow
  562.     (or (and ofile (dired-goto-file ofile)) ; move cursor to where it
  563.     (goto-char opoint))        ; was before
  564.     (dired-move-to-filename)
  565.     (save-excursion            ; hide subdirs that were hidden
  566.       (mapcar (function (lambda (dir)
  567.               (if (dired-goto-subdir dir)
  568.                   (dired-hide-subdir 1))))
  569.           hidden-subdirs)))
  570.   ;; outside of the let scope
  571.   (setq buffer-read-only t))
  572.  
  573. ;; Subroutines of dired-revert
  574. ;; Some of these are also used when inserting subdirs.
  575.  
  576. (defun dired-remember-marks (beg end)
  577.   ;; Return alist of files and their marks, from BEG to END.
  578.   (if selective-display            ; must unhide to make this work.
  579.       (let (buffer-read-only)
  580.     (subst-char-in-region beg end ?\r ?\n)))
  581.   (let (fil chr alist)
  582.     (save-excursion
  583.       (goto-char beg)
  584.       (while (re-search-forward dired-re-mark end t)
  585.     (if (setq fil (dired-get-filename nil t))
  586.         (setq chr (preceding-char)
  587.           alist (cons (cons fil chr) alist)))))
  588.     alist))
  589.  
  590. (defun dired-mark-remembered (alist)
  591.   ;; Mark all files remembered in ALIST.
  592.   (let (elt fil chr)
  593.     (while alist
  594.       (setq elt (car alist)
  595.         alist (cdr alist)
  596.         fil (car elt)
  597.         chr (cdr elt))
  598.       (if (dired-goto-file fil)
  599.       (save-excursion
  600.         (beginning-of-line)
  601.         (delete-char 1)
  602.         (insert chr))))))
  603.  
  604. (defun dired-remember-hidden ()
  605.   (let ((l dired-subdir-alist) dir result)
  606.     (while l
  607.       (setq dir (car (car l))
  608.         l (cdr l))
  609.       (if (dired-subdir-hidden-p dir)
  610.       (setq result (cons dir result))))
  611.     result))
  612.  
  613. (defun dired-insert-old-subdirs (old-subdir-alist)
  614.   ;; Try to insert all subdirs that were displayed before
  615.   (or (string-match "R" dired-actual-switches)
  616.       (let (elt dir)
  617.     (while old-subdir-alist
  618.       (setq elt (car old-subdir-alist)
  619.         old-subdir-alist (cdr old-subdir-alist)
  620.         dir (car elt))
  621.       (condition-case ()
  622.           (dired-insert-subdir dir)
  623.         (error nil))))))
  624.  
  625.  
  626. ;; dired mode key bindings and initialization
  627.  
  628. (defvar dired-mode-map nil "Local keymap for dired-mode buffers.")
  629. (if dired-mode-map
  630.     nil
  631.   ;; Force `f' rather than `e' in the mode doc:
  632.   (fset 'dired-advertised-find-file 'dired-find-file)
  633.   ;; This looks ugly when substitute-command-keys uses C-d instead d:
  634.   ;;  (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
  635.  
  636.   (setq dired-mode-map (make-keymap))
  637.   (suppress-keymap dired-mode-map)
  638.   ;; Commands to mark certain categories of files
  639.   (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
  640.   (define-key dired-mode-map "*" 'dired-mark-executables)
  641.   (define-key dired-mode-map "." 'dired-clean-directory)
  642.   (define-key dired-mode-map "/" 'dired-mark-directories)
  643.   (define-key dired-mode-map "@" 'dired-mark-symlinks)
  644.   ;; Upper case keys (except !, c, r) for operating on the marked files
  645.   (define-key dired-mode-map "c" 'dired-do-copy)
  646.   (define-key dired-mode-map "r" 'dired-do-move)
  647.   (define-key dired-mode-map "!" 'dired-do-shell-command)
  648.   (define-key dired-mode-map "B" 'dired-do-byte-compile)
  649.   (define-key dired-mode-map "C" 'dired-do-compress)
  650.   (define-key dired-mode-map "G" 'dired-do-chgrp)
  651.   (define-key dired-mode-map "H" 'dired-do-hardlink)
  652.   (define-key dired-mode-map "L" 'dired-do-load)
  653.   (define-key dired-mode-map "M" 'dired-do-chmod)
  654.   (define-key dired-mode-map "O" 'dired-do-chown)
  655.   (define-key dired-mode-map "P" 'dired-do-print)
  656.   (define-key dired-mode-map "U" 'dired-do-uncompress)
  657.   (define-key dired-mode-map "X" 'dired-do-delete)
  658.   (define-key dired-mode-map "Y" 'dired-do-symlink)
  659.   ;; exceptions to the upper key rule
  660.   (define-key dired-mode-map "D" 'dired-diff)
  661.   (define-key dired-mode-map "W" 'dired-why)
  662.   ;; Tree Dired commands
  663.   (define-key dired-mode-map "\M-\C-?" 'dired-unflag-all-files)
  664.   (define-key dired-mode-map "\M-\C-d" 'dired-tree-down)
  665.   (define-key dired-mode-map "\M-\C-u" 'dired-tree-up)
  666.   (define-key dired-mode-map "\M-\C-n" 'dired-next-subdir)
  667.   (define-key dired-mode-map "\M-\C-p" 'dired-prev-subdir)
  668.   ;; move to marked files
  669.   (define-key dired-mode-map "\M-{" 'dired-prev-marked-file)
  670.   (define-key dired-mode-map "\M-}" 'dired-next-marked-file)
  671.   ;; kill marked files
  672.   (define-key dired-mode-map "\M-k" 'dired-do-kill)
  673.   ;; Make all regexp commands share a `%' prefix:
  674.   (fset 'dired-regexp-prefix (make-sparse-keymap))
  675.   (define-key dired-mode-map "%" 'dired-regexp-prefix)
  676.   (define-key dired-mode-map "%u" 'dired-upcase)
  677.   (define-key dired-mode-map "%l" 'dired-downcase)
  678.   (define-key dired-mode-map "%d" 'dired-flag-regexp-files)
  679.   (define-key dired-mode-map "%m" 'dired-mark-files-regexp)
  680.   (define-key dired-mode-map "%r" 'dired-do-rename-regexp)
  681.   (define-key dired-mode-map "%c" 'dired-do-copy-regexp)
  682.   (define-key dired-mode-map "%H" 'dired-do-hardlink-regexp)
  683.   (define-key dired-mode-map "%Y" 'dired-do-symlink-regexp)
  684.   ;; Lower keys for commands not operating on all the marked files
  685.   (define-key dired-mode-map "d" 'dired-flag-file-deleted)
  686.   (define-key dired-mode-map "e" 'dired-find-file)
  687.   (define-key dired-mode-map "f" 'dired-advertised-find-file)
  688.   (define-key dired-mode-map "g" 'revert-buffer)
  689.   (define-key dired-mode-map "h" 'describe-mode)
  690.   (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
  691.   (define-key dired-mode-map "k" 'dired-kill-line-or-subdir)
  692.   (define-key dired-mode-map "l" 'dired-do-redisplay)
  693.   (define-key dired-mode-map "m" 'dired-mark-subdir-or-file)
  694.   (define-key dired-mode-map "n" 'dired-next-line)
  695.   (define-key dired-mode-map "o" 'dired-find-file-other-window)
  696.   (define-key dired-mode-map "p" 'dired-previous-line)
  697.   (define-key dired-mode-map "q" 'dired-quit)
  698.   (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
  699.   (define-key dired-mode-map "u" 'dired-unmark-subdir-or-file)
  700.   (define-key dired-mode-map "v" 'dired-view-file)
  701.   (define-key dired-mode-map "x" 'dired-do-deletions)
  702.   (define-key dired-mode-map "~" 'dired-flag-backup-files)
  703.   (define-key dired-mode-map "\M-~" 'dired-backup-diff)
  704.   (define-key dired-mode-map "+" 'dired-create-directory)
  705.   ;; moving
  706.   (define-key dired-mode-map "<" 'dired-prev-dirline)
  707.   (define-key dired-mode-map ">" 'dired-next-dirline)
  708.   (define-key dired-mode-map "^" 'dired-up-directory)
  709.   (define-key dired-mode-map " "  'dired-next-line)
  710.   (define-key dired-mode-map "\C-n" 'dired-next-line)
  711.   (define-key dired-mode-map "\C-p" 'dired-previous-line)
  712.   ;; hiding
  713.   (define-key dired-mode-map "$" 'dired-hide-subdir)
  714.   (define-key dired-mode-map "=" 'dired-hide-all)
  715.   ;; misc
  716.   (define-key dired-mode-map "?" 'dired-summary)
  717.   (define-key dired-mode-map "\177" 'dired-backup-unflag)
  718.   (define-key dired-mode-map "\C-_" 'dired-undo)
  719.   (define-key dired-mode-map "\C-xu" 'dired-undo)
  720.   )
  721.  
  722. (or (equal (assq 'dired-sort-mode minor-mode-alist)
  723.        '(dired-sort-mode dired-sort-mode))
  724.     ;; Test whether this has already been done in case dired is reloaded
  725.     ;; There may be several elements with dired-sort-mode as car.
  726.     (setq minor-mode-alist
  727.       (cons '(dired-sort-mode dired-sort-mode)
  728.         ;; dired-sort-mode is nil outside dired
  729.         minor-mode-alist)))
  730.  
  731. ;; Dired mode is suitable only for specially formatted data.
  732. (put 'dired-mode 'mode-class 'special)
  733.  
  734. (defun dired-mode (&optional dirname switches)
  735.   "\
  736. Mode for \"editing\" directory listings.
  737. In dired, you are \"editing\" a list of the files in a directory and
  738.   \(optionally) its subdirectories, in the format of `ls -lR'.
  739.   Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
  740. \"Editing\" means that you can run shell commands on files, visit,
  741.   compress, load or byte-compile them, change their file attributes
  742.   and insert subdirectories into the same buffer.  You can \"mark\"
  743.   files for later commands or \"flag\" them for deletion, either file
  744.   by file or all files matching certain criteria.
  745. You can move using the usual cursor motion commands.\\<dired-mode-map>
  746. Letters no longer insert themselves.  Digits are prefix arguments.
  747. Instead, type \\[dired-flag-file-deleted] to flag a file for Deletion.
  748. Type \\[dired-mark-subdir-or-file] to Mark a file or subdirectory for later commands.
  749.   Most commands operate on the marked files and use the current file
  750.   if no files are marked.  Use a numeric prefix argument to operate on
  751.   the next ARG (or previous -ARG if ARG<0) files, or just `1'
  752.   to operate on the current file only.  Prefix arguments override marks.
  753.   Mark-using commands display a list of failures afterwards.  Type \\[dired-why] to see
  754.   why something went wrong.
  755. Type \\[dired-unmark-subdir-or-file] to Unmark a file or all files of a subdirectory.
  756. Type \\[dired-backup-unflag] to back up one line and unflag.
  757. Type \\[dired-do-deletions] to eXecute the deletions requested.
  758. Type \\[dired-advertised-find-file] to Find the current line's file
  759.   (or dired it in another buffer, if it is a directory).
  760. Type \\[dired-find-file-other-window] to find file or dired directory in Other window.
  761. Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
  762. Type \\[dired-do-move] to Rename a file or move the marked files to another directory.
  763. Type \\[dired-do-copy] to Copy files.
  764. Type \\[dired-sort-toggle-or-edit] to toggle sorting by name/date or change the ls switches.
  765. Type \\[revert-buffer] to read all currently expanded directories again.
  766.   This retains all marks and hides subdirs again that were hidden before.
  767. SPC and DEL can be used to move down and up by lines.
  768.  
  769. If dired ever gets confused, you can either type \\[revert-buffer] \
  770. to read the
  771. directories again, type \\[dired-do-redisplay] \
  772. to relist a single or the marked files or a
  773. subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
  774. again for the directory tree.
  775.  
  776. Customization variables (rename this buffer and type \\[describe-variable] on each line
  777. for more info):
  778.  
  779.   dired-listing-switches
  780.   dired-trivial-filenames
  781.   dired-shrink-to-fit
  782.   dired-marker-char
  783.   dired-del-marker
  784.   dired-keep-marker-move
  785.   dired-keep-marker-copy
  786.   dired-keep-marker-hardlink
  787.   dired-keep-marker-symlink
  788.  
  789. Hooks (use \\[describe-variable] to see their documentation):
  790.  
  791.   dired-before-readin-hook
  792.   dired-after-readin-hook
  793.   dired-mode-hook
  794.   dired-load-hook
  795.  
  796. Keybindings:
  797. \\{dired-mode-map}"
  798.   ;; Not to be called interactively (e.g. dired-directory will be set
  799.   ;; to default-directory, which is wrong with wildcards).
  800.   (kill-all-local-variables)
  801.   (use-local-map dired-mode-map)
  802.   (dired-advertise)            ; default-directory is already set
  803.   (setq major-mode 'dired-mode
  804.     mode-name "Dired"
  805.     case-fold-search nil
  806.     buffer-read-only t
  807.     selective-display t        ; for subdirectory hiding
  808.     mode-line-buffer-identification '("Dired: %17b"))
  809.   (set (make-local-variable 'revert-buffer-function)
  810.        (function dired-revert))
  811.   (set (make-local-variable 'page-delimiter)
  812.        "\n\n")
  813.   (set (make-local-variable 'dired-directory)
  814.        (or dirname default-directory))
  815.   (set (make-local-variable 'list-buffers-directory)
  816.        dired-directory)
  817.   (set (make-local-variable 'dired-actual-switches)
  818.        (or switches dired-listing-switches))
  819.   (make-local-variable 'dired-sort-mode)
  820.   (dired-sort-other dired-actual-switches t)
  821.   (run-hooks 'dired-mode-hook))
  822.  
  823.  
  824. (defun dired-check-ls-l ()
  825.   (let (case-fold-search)
  826.     (or (string-match "l" dired-actual-switches)
  827.     (error "Dired needs -l in ls switches"))))
  828.  
  829. (defun dired-repeat-over-lines (arg function)
  830.   ;; This version skips non-file lines.
  831.   (beginning-of-line)
  832.   (while (and (> arg 0) (not (eobp)))
  833.     (setq arg (1- arg))
  834.     (beginning-of-line)
  835.     (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
  836.     (save-excursion (funcall function))
  837.     (forward-line 1))
  838.   (while (and (< arg 0) (not (bobp)))
  839.     (setq arg (1+ arg))
  840.     (forward-line -1)
  841.     (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
  842.     (beginning-of-line)
  843.     (save-excursion (funcall function))
  844.     (dired-move-to-filename))
  845.   (dired-move-to-filename))
  846.  
  847. (defun dired-flag-file-deleted (arg)
  848.   "In dired, flag the current line's file for deletion.
  849. With prefix arg, repeat over several lines.
  850.  
  851. If on a subdir headerline, mark all its files except `.' and `..'."
  852.   (interactive "P")
  853.   (let ((dired-marker-char dired-del-marker))
  854.     (dired-mark-subdir-or-file arg)))
  855.  
  856. (defun dired-quit ()
  857.   "Bury the current dired buffer."
  858.   (interactive)
  859.   (bury-buffer))
  860.  
  861. (defun dired-summary ()
  862.   (interactive)
  863.   ;>> this should check the key-bindings and use substitute-command-keys if non-standard
  864.   (message
  865.    "d-elete, u-ndelete, x-punge, f-ind, o-ther window, r-ename, c-opy, h-elp"))
  866.  
  867. (defun dired-create-directory (directory)
  868.   "Create a directory called DIRECTORY."
  869.   (interactive
  870.    (list (read-file-name "Create directory: " (dired-current-directory))))
  871.   (let ((expanded (directory-file-name (expand-file-name directory))))
  872.     (make-directory expanded)
  873.     (dired-add-file expanded)
  874.     (dired-move-to-filename)))
  875.  
  876. (defun dired-undo ()
  877.   "Undo in a dired buffer.
  878. This doesn't recover lost files, it is just normal undo with temporarily
  879. writeable buffer.  You can use it to recover marks, killed lines or subdirs.
  880. In the latter case, you have to do \\[dired-build-subdir-alist] to
  881. parse the buffer again."
  882.   (interactive)
  883.   (let (buffer-read-only)
  884.     (undo)))
  885.  
  886. (defun dired-unflag (arg)
  887.   "In dired, remove the current line's delete flag then move to next line.
  888. Optional prefix ARG says how many lines to unflag."
  889.   (interactive "p")
  890.   (dired-repeat-over-lines arg
  891.     '(lambda ()
  892.        (let (buffer-read-only)
  893.      (delete-char 1)
  894.      (insert " ")
  895.      (forward-char -1)
  896.      nil))))
  897.  
  898. (defun dired-backup-unflag (arg)
  899.   "In dired, move up lines and remove deletion flag there.
  900. Optional prefix ARG says how many lines to unflag; default is one line."
  901.   (interactive "p")
  902.   (dired-unflag (- arg)))
  903.  
  904. (defun dired-next-line (arg)
  905.   "Move down lines then position at filename.
  906. Optional prefix ARG says how many lines to move; default is one line."
  907.   (interactive "p")
  908.   (next-line arg)
  909.   (dired-move-to-filename))
  910.  
  911. (defun dired-previous-line (arg)
  912.   "Move up lines then position at filename.
  913. Optional prefix ARG says how many lines to move; default is one line."
  914.   (interactive "p")
  915.   (previous-line arg)
  916.   (dired-move-to-filename))
  917.  
  918. (defun dired-up-directory ()
  919.   "Run dired on parent directory of current directory.
  920. Find the parent directory either in this buffer or another buffer.
  921. Creates a buffer if necessary."
  922.   (interactive)
  923.   (let* ((dir (dired-current-directory))
  924.      (up (file-name-directory (directory-file-name dir))))
  925.     (or (dired-goto-file (directory-file-name dir))
  926.     (dired-goto-subdir up)
  927.     (progn
  928.       (dired up)
  929.       (dired-goto-file dir)))))
  930.  
  931. (defun dired-find-file ()
  932.   "In dired, visit the file or directory named on this line."
  933.   (interactive)
  934.   (find-file (dired-get-filename)))
  935.  
  936. (defun dired-view-file ()
  937.   "In dired, examine a file in view mode, returning to dired when done.
  938. When file is a directory, show it in this buffer if it is inserted;
  939. otherwise, display it in another buffer."
  940.   (interactive)
  941.   (if (file-directory-p (dired-get-filename))
  942.       (or (dired-goto-subdir (dired-get-filename))
  943.       (dired (dired-get-filename)))
  944.     (view-file (dired-get-filename))))
  945.  
  946. (defun dired-find-file-other-window ()
  947.   "In dired, visit this file or directory in another window."
  948.   (interactive)
  949.   (find-file-other-window (dired-get-filename)))
  950.  
  951. (defun dired-get-filename (&optional localp no-error-if-not-filep)
  952.   "In dired, return name of file mentioned on this line.
  953. Value returned normally includes the directory name.
  954. Optional arg LOCALP with value `no-dir' means don't include directory
  955.   name in result.  A value of t means use path name relative to
  956.   `default-directory', which still may contain slashes if in a subdirectory.
  957. Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
  958.   this line, otherwise an error occurs."
  959.   (let (case-fold-search file p1 p2)
  960.     (save-excursion
  961.       (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
  962.       (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
  963.     ;; nil if no file on this line, but no-error-if-not-filep is t:
  964.     (if (setq file (and p1 p2 (buffer-substring p1 p2)))
  965.     ;; Check if ls quoted the names, and unquote them.
  966.     ;; Using read to unquote is much faster than substituting
  967.     ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
  968.     (cond ((string-match "b" dired-actual-switches) ; System V ls
  969.            ;; This case is about 20% slower than without -b.
  970.            (setq file
  971.              (read
  972.               (concat "\""
  973.                   ;; some ls -b don't escape quotes, argh!
  974.                   ;; This is not needed for GNU ls, though.
  975.                   (or (dired-string-replace-match
  976.                    "\\([^\\]\\)\"" file "\\1\\\\\"")
  977.                   file)
  978.                   "\""))))
  979.           ;; If you do this, update dired-insert-subdir-validate too
  980.           ;; ((string-match "Q" dired-actual-switches) ; GNU ls
  981.           ;;  (setq file (read file)))
  982.           ))
  983.     (if (eq localp 'no-dir)
  984.     file
  985.       (and file (concat (dired-current-directory localp) file)))))
  986.  
  987. (defun dired-move-to-filename (&optional raise-error eol)
  988.   "In dired, move to first char of filename on this line.
  989. Returns position (point) or nil if no filename on this line."
  990.   ;; This is the UNIX version.
  991.   (or eol (setq eol (progn (end-of-line) (point))))
  992.   (beginning-of-line)
  993.   (if (string-match "l" dired-actual-switches)
  994.       (if (re-search-forward
  995.        "\\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\)[ ]+[0-9]+"
  996.        eol t)
  997.       (progn
  998.         (skip-chars-forward " ")    ; there is one SPC after day of month
  999.         (skip-chars-forward "^ " eol) ; move after time of day (or year)
  1000.         (skip-chars-forward " " eol) ; there is space before the file name
  1001.         ;; Actually, if the year instead of clock time is displayed,
  1002.         ;; there are (only for some ls programs?) two spaces instead
  1003.         ;; of one before the name.
  1004.         ;; If we could depend on ls inserting exactly one SPC we
  1005.         ;; would not bomb on names _starting_ with SPC.
  1006.         (point))
  1007.     (if raise-error
  1008.         (error "No file on this line")
  1009.       nil))
  1010.     ;; else ls switches don't contain -l.
  1011.     ;; Note that even if we make dired-move-to-filename and
  1012.     ;; dired-move-to-end-of-filename (and thus dired-get-filename)
  1013.     ;; work, all commands that gleaned information from the permission
  1014.     ;; bits (like dired-mark-directories) will cease to work properly.
  1015.     (if (eolp)
  1016.     (if raise-error
  1017.         (error "No file on this line")
  1018.       nil)
  1019.       ;; skip marker, if any
  1020.       (forward-char))
  1021.     (skip-chars-forward " ")
  1022.     (point)))
  1023.  
  1024. (defun dired-move-to-end-of-filename (&optional no-error)
  1025.   ;; Assumes point is at beginning of filename,
  1026.   ;; thus the rwx bit re-search-backward below will succeed in *this*
  1027.   ;; line if at all.  So, it should be called only after
  1028.   ;; (dired-move-to-filename t).
  1029.   ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
  1030.   ;; This is the UNIX version.
  1031.   (let (opoint file-type executable symlink hidden case-fold-search used-F eol)
  1032.     ;; case-fold-search is nil now, so we can test for capital F:
  1033.     (setq used-F (string-match "F" dired-actual-switches)
  1034.       opoint (point)
  1035.           eol (save-excursion (end-of-line) (point))
  1036.       hidden (and selective-display
  1037.               (save-excursion (search-forward "\r" eol t))))
  1038.     (if hidden
  1039.     nil
  1040.       (save-excursion;; Find out what kind of file this is:
  1041.     ;; Restrict perm bits to be non-blank,
  1042.     ;; otherwise this matches one char to early (looking backward):
  1043.     ;; "l---------" (some systems make symlinks that way)
  1044.     ;; "----------" (plain file with zero perms)
  1045.     (if (re-search-backward
  1046.          "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
  1047.          nil t)
  1048.         (setq file-type (char-after (match-beginning 1))
  1049.           symlink (eq file-type ?l)
  1050.           ;; Only with -F we need to know whether it's an executable
  1051.           executable (and
  1052.                   used-F
  1053.                   (string-match
  1054.                    "[xst]";; execute bit set anywhere?
  1055.                    (concat
  1056.                 (buffer-substring (match-beginning 2)
  1057.                           (match-end 2))
  1058.                 (buffer-substring (match-beginning 3)
  1059.                           (match-end 3))
  1060.                 (buffer-substring (match-beginning 4)
  1061.                           (match-end 4))))))
  1062.       (or no-error
  1063.           (not (string-match "l" dired-actual-switches))
  1064.           (error "No file on this line"))))
  1065.       ;; Move point to end of name:
  1066.       (if symlink
  1067.       (if (search-forward " ->" eol t)
  1068.           (progn
  1069.         (forward-char -3)
  1070.         (and used-F
  1071.              dired-ls-F-marks-symlinks
  1072.              (eq (preceding-char) ?@);; did ls really mark the link?
  1073.              (forward-char -1))))
  1074.     (goto-char eol);; else not a symbolic link
  1075.     ;; ls -lF marks dirs, sockets and executables with exactly one
  1076.     ;; trailing character. (Executable bits on symlinks ain't mean
  1077.     ;; a thing, even to ls, but we know it's not a symlink.)
  1078.     (and used-F
  1079.          ;; -F may not actually be honored, e.g. by an FTP ls in ange-ftp
  1080.          (let ((char (preceding-char)))
  1081.            (or (and (eq file-type ?d) (eq char ?/))
  1082.            (and executable (eq char ?*))
  1083.            (and (eq file-type ?s) (eq char ?=))))
  1084.          (forward-char -1))))
  1085.     (or no-error
  1086.     (not (eq opoint (point)))
  1087.     (error (if hidden
  1088.            (substitute-command-keys
  1089.             "File line is hidden, type \\[dired-hide-subdir] to unhide")
  1090.          "No file on this line")))
  1091.     (if (eq opoint (point))
  1092.     nil
  1093.       (point))))
  1094.  
  1095.  
  1096. ;; Perhaps something could be done to handle VMS' own backups.
  1097.  
  1098. (defun dired-clean-directory (keep)
  1099.   "Flag numerical backups for deletion.
  1100. Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
  1101. Positive prefix arg KEEP overrides `dired-kept-versions';
  1102. Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
  1103.  
  1104. To clear the flags on these files, you can use \\[dired-flag-backup-files]
  1105. with a prefix argument."
  1106.   (interactive "P")
  1107.   (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
  1108.   (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
  1109.     (late-retention (if (<= keep 0) dired-kept-versions keep))
  1110.     (file-version-assoc-list ()))
  1111.     (message "Cleaning numerical backups (keeping %d late, %d old)..."
  1112.          late-retention early-retention)
  1113.     ;; Look at each file.
  1114.     ;; If the file has numeric backup versions,
  1115.     ;; put on file-version-assoc-list an element of the form
  1116.     ;; (FILENAME . VERSION-NUMBER-LIST)
  1117.     (dired-map-dired-file-lines (function dired-collect-file-versions))
  1118.     ;; Sort each VERSION-NUMBER-LIST,
  1119.     ;; and remove the versions not to be deleted.
  1120.     (let ((fval file-version-assoc-list))
  1121.       (while fval
  1122.     (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
  1123.            (v-count (length sorted-v-list)))
  1124.       (if (> v-count (+ early-retention late-retention))
  1125.           (rplacd (nthcdr early-retention sorted-v-list)
  1126.               (nthcdr (- v-count late-retention)
  1127.                   sorted-v-list)))
  1128.       (rplacd (car fval)
  1129.           (cdr sorted-v-list)))
  1130.     (setq fval (cdr fval))))
  1131.     ;; Look at each file.  If it is a numeric backup file,
  1132.     ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
  1133.     (dired-map-dired-file-lines (function dired-trample-file-versions))
  1134.     (message "Cleaning numerical backups...done")))
  1135.  
  1136. ;;; Subroutines of dired-clean-directory.
  1137.  
  1138. (defun dired-map-dired-file-lines (fun)
  1139.   ;; Perform FUN with point at the end of each non-directory line.
  1140.   ;; FUN takes one argument, the filename (complete pathname).
  1141.   (dired-check-ls-l)
  1142.   (save-excursion
  1143.     (let (file buffer-read-only)
  1144.       (goto-char (point-min))
  1145.       (while (not (eobp))
  1146.     (save-excursion
  1147.       (and (not (looking-at dired-re-dir))
  1148.            (not (eolp))
  1149.            (setq file (dired-get-filename nil t)) ; nil on non-file
  1150.            (progn (end-of-line)
  1151.               (funcall fun file))))
  1152.     (forward-line 1)))))
  1153.  
  1154. (defun dired-collect-file-versions (fn)
  1155.   ;;  "If it looks like file FN has versions, return a list of the versions.
  1156.   ;;That is a list of strings which are file names.
  1157.   ;;The caller may want to flag some of these files for deletion."
  1158.     (let* ((base-versions
  1159.         (concat (file-name-nondirectory fn) ".~"))
  1160.        (bv-length (length base-versions))
  1161.        (possibilities (file-name-all-completions
  1162.                base-versions
  1163.                (file-name-directory fn)))
  1164.        (versions (mapcar 'backup-extract-version possibilities)))
  1165.       (if versions
  1166.       (setq file-version-assoc-list (cons (cons fn versions)
  1167.                           file-version-assoc-list)))))
  1168.  
  1169. (defun dired-trample-file-versions (fn)
  1170.   (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
  1171.      base-version-list)
  1172.     (and start-vn
  1173.      (setq base-version-list    ; there was a base version to which
  1174.            (assoc (substring fn 0 start-vn)    ; this looks like a
  1175.               file-version-assoc-list))    ; subversion
  1176.      (not (memq (string-to-int (substring fn (+ 2 start-vn)))
  1177.             base-version-list))    ; this one doesn't make the cut
  1178.      (progn (beginning-of-line)
  1179.         (delete-char 1)
  1180.         (insert dired-del-marker)))))
  1181.  
  1182.  
  1183. ;; Keeping Dired buffers in sync with the filesystem and with each other
  1184.  
  1185. (defvar dired-buffers nil
  1186.   ;; Enlarged by dired-advertise
  1187.   ;; Queried by function dired-buffers-for-dir. When this detects a
  1188.   ;; killed buffer, it is removed from this list.
  1189.   "Alist of directories and their associated dired buffers.")
  1190.  
  1191. (defun dired-buffers-for-dir (dir)
  1192. ;; Return a list of buffers that dired DIR (top level or in-situ subdir).
  1193. ;; The list is in reverse order of buffer creation, most recent last.
  1194. ;; As a side effect, killed dired buffers for DIR are removed from
  1195. ;; dired-buffers.
  1196.   (setq dir (file-name-as-directory dir))
  1197.   (let ((alist dired-buffers) result elt)
  1198.     (while alist
  1199.       (setq elt (car alist))
  1200.       (if (dired-in-this-tree dir (car elt))
  1201.       (let ((buf (cdr elt)))
  1202.         (if (buffer-name buf)
  1203.         (if (assoc dir (save-excursion
  1204.                  (set-buffer buf)
  1205.                  dired-subdir-alist))
  1206.             (setq result (cons buf result)))
  1207.           ;; else buffer is killed - clean up:
  1208.           (setq dired-buffers (delq elt dired-buffers)))))
  1209.       (setq alist (cdr alist)))
  1210.     result))
  1211.  
  1212. (defun dired-advertise ()
  1213.   ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
  1214.   ;; With wildcards we actually advertise too much.
  1215.   (if (memq (current-buffer) (dired-buffers-for-dir default-directory))
  1216.       t                    ; we have already advertised ourselves
  1217.     (setq dired-buffers
  1218.       (cons (cons default-directory (current-buffer))
  1219.         dired-buffers))))
  1220.  
  1221. (defun dired-unadvertise (dir)
  1222.   ;; Remove DIR from the buffer alist in variable dired-buffers.
  1223.   ;; This has the effect of removing any buffer whose main directory is DIR.
  1224.   ;; It does not affect buffers in which DIR is a subdir.
  1225.   ;; Removing is also done as a side-effect in dired-buffer-for-dir.
  1226.   (setq dired-buffers
  1227.       (delq (assoc dir dired-buffers) dired-buffers)))
  1228.  
  1229. (defun dired-fun-in-all-buffers (directory fun &rest args)
  1230.   ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
  1231.   ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
  1232.   (let ((buf-list (dired-buffers-for-dir directory))
  1233.     (obuf (current-buffer))
  1234.     buf success-list)
  1235.     (while buf-list
  1236.       (setq buf (car buf-list)
  1237.         buf-list (cdr buf-list))
  1238.       (unwind-protect
  1239.       (progn
  1240.         (set-buffer buf)
  1241.         (if (apply fun args)
  1242.         (setq success-list (cons (buffer-name buf) success-list))))
  1243.     (set-buffer obuf)))
  1244.     success-list))
  1245.  
  1246. (defun dired-add-file (filename &optional marker-char)
  1247.   (dired-fun-in-all-buffers
  1248.    (file-name-directory filename)
  1249.    (function dired-add-entry) filename marker-char))
  1250.  
  1251. (defun dired-add-entry (filename &optional marker-char)
  1252.   ;; Add a new entry for FILENAME, optionally marking it
  1253.   ;; with MARKER-CHAR (a character, else dired-marker-char is used).
  1254.   ;; Note that this adds the entry `out of order' if files sorted by
  1255.   ;; time, etc.
  1256.   ;; At least this version inserts in the right subdirectory (if present).
  1257.   ;; And it skips "." or ".." (see `dired-trivial-filenames').
  1258.   ;; Hidden subdirs are exposed if a file is added there.
  1259.   (setq filename (directory-file-name filename))
  1260.   ;; Entry is always for files, even if they happen to also be directories
  1261.   (let ((opoint (point))
  1262.     (cur-dir (dired-current-directory))
  1263.     (directory (file-name-directory filename))
  1264.     reason)
  1265.     (setq filename (file-name-nondirectory filename)
  1266.       reason
  1267.       (catch 'not-found
  1268.         (if (string= directory cur-dir)
  1269.         (progn
  1270.           (if (dired-subdir-hidden-p cur-dir)
  1271.               (dired-unhide-subdir))
  1272.           ;; We are already where we should be, except when
  1273.           ;; point is before the subdir line or its total line.
  1274.           (let ((p (dired-after-subdir-garbage cur-dir)))
  1275.             (if (< (point) p)
  1276.             (goto-char p))))
  1277.           ;; else try to find correct place to insert
  1278.           (if (dired-goto-subdir directory)
  1279.           (progn;; unhide if necessary
  1280.             (if (looking-at "\r");; point is at end of subdir line
  1281.             (dired-unhide-subdir))
  1282.             ;; found - skip subdir and `total' line
  1283.             ;; and uninteresting files like . and ..
  1284.             ;; This better not moves into the next subdir!
  1285.             (dired-goto-next-nontrivial-file))
  1286.         ;; not found
  1287.         (throw 'not-found "Subdir not found")))
  1288.         ;; found and point is at The Right Place:
  1289.         (let (buffer-read-only)
  1290.           (beginning-of-line)
  1291.           (dired-add-entry-do-indentation marker-char)
  1292.           (dired-ls (dired-make-absolute filename directory);; don't expand `.' !
  1293.             (concat dired-actual-switches "d"))
  1294.           (forward-line -1)
  1295.           ;; We want to have the non-directory part, only:
  1296.           (let* ((beg (dired-move-to-filename t)) ; error for strange output
  1297.              (end (dired-move-to-end-of-filename)))
  1298.         (setq filename (buffer-substring beg end))
  1299.         (delete-region beg end)
  1300.         (insert (file-name-nondirectory filename)))
  1301.           (if dired-after-readin-hook;; the subdir-alist is not affected...
  1302.           (save-excursion;; ...so we can run it right now:
  1303.             (save-restriction
  1304.               (beginning-of-line)
  1305.               (narrow-to-region (point) (save-excursion
  1306.                           (forward-line 1) (point)))
  1307.               (run-hooks 'dired-after-readin-hook))))
  1308.           (dired-move-to-filename))
  1309.         ;; return nil if all went well
  1310.         nil))
  1311.     (if reason                ; don't move away on failure
  1312.     (goto-char opoint))
  1313.     (not reason)))            ; return t on succes, nil else
  1314.  
  1315. ;; This is a separate function for the sake of nested dired format.
  1316. (defun dired-add-entry-do-indentation (marker-char)
  1317.   ;; two spaces or a marker plus a space:
  1318.   (insert (if marker-char
  1319.           (if (integerp marker-char) marker-char dired-marker-char)
  1320.         ?\040)
  1321.       ?\040))
  1322.  
  1323. (defun dired-after-subdir-garbage (dir)
  1324.   ;; Return pos of first file line of DIR, skipping header and total
  1325.   ;; or wildcard lines.
  1326.   ;; Important: never moves into the next subdir.
  1327.   ;; DIR is assumed to be unhidden.
  1328.   ;; Will probably be redefined for VMS etc.
  1329.   (save-excursion
  1330.     (or (dired-goto-subdir dir) (error "This cannot happen"))
  1331.     (forward-line 1)
  1332.     (while (and (not (eolp))        ; don't cross subdir boundary
  1333.         (not (dired-move-to-filename)))
  1334.     (forward-line 1))
  1335.     (point)))
  1336.  
  1337. (defun dired-remove-file (file)
  1338.   (dired-fun-in-all-buffers
  1339.    (file-name-directory file) (function dired-remove-entry) file))
  1340.  
  1341. (defun dired-remove-entry (file)
  1342.   (save-excursion
  1343.     (and (dired-goto-file file)
  1344.      (let (buffer-read-only)
  1345.        (delete-region (progn (beginning-of-line) (point))
  1346.               (save-excursion (forward-line 1) (point)))))))
  1347.  
  1348. (defun dired-relist-file (file)
  1349.   (dired-fun-in-all-buffers (file-name-directory file)
  1350.                 (function dired-relist-entry) file))
  1351.  
  1352. (defun dired-relist-entry (file)
  1353.   ;; Relist the line for FILE, or just add it if it did not exist.
  1354.   ;; FILE must be an absolute pathname.
  1355.   (let (buffer-read-only marker)
  1356.     ;; If cursor is already on FILE's line delete-region will cause
  1357.     ;; save-excursion to fail because of floating makers,
  1358.     ;; moving point to beginning of line.  Sigh.
  1359.     (save-excursion
  1360.       (and (dired-goto-file file)
  1361.        (delete-region (progn (beginning-of-line)
  1362.                  (setq marker (following-char))
  1363.                  (point))
  1364.               (save-excursion (forward-line 1) (point))))
  1365.       (setq file (directory-file-name file))
  1366.       (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
  1367.  
  1368. (defun dired-update-file-line (file)
  1369.   ;; Delete the current line, and insert an entry for FILE.
  1370.   ;; If FILE is nil, then just delete the current line.
  1371.   ;; Keeps any marks that may be present in column one (doing this
  1372.   ;; here is faster than with dired-add-entry's optional arg).
  1373.   ;; Does not update other dired buffers.  Use dired-relist-entry for that.
  1374.   (beginning-of-line)
  1375.   (let ((char (following-char)) (opoint (point)))
  1376.     (delete-region (point) (progn (forward-line 1) (point)))
  1377.     (if file
  1378.     (progn
  1379.       (dired-add-entry file)
  1380.       ;; Replace space by old marker without moving point.
  1381.       ;; Faster than goto+insdel inside a save-excursion?
  1382.       (subst-char-in-region opoint (1+ opoint) ?\040 char))))
  1383.   (dired-move-to-filename))
  1384.  
  1385.  
  1386. ;; Running subprocesses, checking and logging of their errors.
  1387.  
  1388. (defvar dired-log-buf "*Dired log*")
  1389.  
  1390. (defun dired-why ()
  1391.   "Pop up a buffer with error log output from Dired.
  1392. A group of errors from a single command ends with a formfeed.
  1393. Thus, use \\[backward-page] to find the beginning of a group of errors."
  1394.   (interactive)
  1395.   (let ((obuf (current-buffer)))
  1396.     (pop-to-buffer dired-log-buf)
  1397.     (goto-char (point-max))
  1398.     (recenter -1)
  1399.     (switch-to-buffer-other-window obuf)))
  1400.  
  1401. (defun dired-log (log &rest args)
  1402.   ;; Log a message or the contents of a buffer.
  1403.   ;; If LOG is a string and there are more args, it is formatted with
  1404.   ;; those ARGS.  Usually the LOG string ends with a \n.
  1405.   ;; End each bunch of errors with (dired-log t): this inserts
  1406.   ;; current time and buffer, and a \f (formfeed).
  1407.   (let ((obuf (current-buffer)))
  1408.     (unwind-protect            ; want to move point
  1409.     (progn
  1410.       (set-buffer (get-buffer-create dired-log-buf))
  1411.       (goto-char (point-max))
  1412.       (let (buffer-read-only)
  1413.         (cond ((stringp log)
  1414.            (insert (if args
  1415.                    (apply (function format) log args)
  1416.                  log)))
  1417.           ((bufferp log)
  1418.            (insert-buffer log))
  1419.           ((eq t log)
  1420.            (insert "\n\t" (current-time-string)
  1421.                "\tBuffer `" (buffer-name obuf) "'\n\f\n")))))
  1422.       (set-buffer obuf))))
  1423.  
  1424. (defun dired-log-summary (log &rest args)
  1425.   ;; Log a summary describing a bunch of errors.
  1426.   (apply (function dired-log) (concat "\n" log) args)
  1427.   (dired-log t))
  1428.  
  1429. ;; In Emacs 19 this will return program's exit status.
  1430. ;; This is a separate function so that ange-ftp can redefine it.
  1431. (defun dired-call-process (program discard &rest arguments)
  1432. ;  "Run PROGRAM with output to current buffer unless DISCARD is t.
  1433. ;Remaining arguments are strings passed as command arguments to PROGRAM."
  1434.   (apply 'call-process program nil (not discard) nil arguments))
  1435.  
  1436. (defun dired-check-process-checker (exit-status)
  1437.   ;; In Emacs 19, EXIT-STATUS comes from (dired-)call-process
  1438.   ;; Then this function should return (/= 0 exit-status)
  1439.   ;; In Emacs 18 the exit status is not accessible, so we
  1440.   ;; do the following which is not always correct as some compress
  1441.   ;; programs are verbose by default or otherwise braindamaged
  1442.   (if dired-emacs-19-p
  1443.       (/= 0 exit-status);; >>> install (does it work in Emacs 19?)
  1444.     (/= 0 (buffer-size)))        ; run in program's output buffer
  1445.   ;; If have you one of those compress programs, you might
  1446.   ;; want to redefine this function to look closer at compress' output.
  1447.   ;; This is why it is a separate function.
  1448.   )
  1449.  
  1450. (defun dired-check-process (msg program &rest arguments)
  1451. ;  "Display MSG while running PROGRAM, and check for output.
  1452. ;Remaining arguments are strings passed as command arguments to PROGRAM.
  1453. ; On error as determined by dired-check-process-checker, insert output
  1454. ; in a log buffer and return the offending ARGUMENTS or PROGRAM.
  1455. ; Caller can cons up a list of failed args.
  1456. ;Else returns nil for success."
  1457.   (let (err-buffer err (dir default-directory))
  1458.     (message "%s..." msg)
  1459.     (save-excursion
  1460.       ;; Get a clean buffer for error output:
  1461.       (setq err-buffer (get-buffer-create " *dired-check-process output*"))
  1462.       (set-buffer err-buffer)
  1463.       (erase-buffer)
  1464.       (setq default-directory dir    ; caller's default-directory
  1465.         err (dired-check-process-checker
  1466.          (apply (function dired-call-process) program nil arguments)))
  1467.       (if err
  1468.       (progn
  1469.         (dired-log (concat program " " (prin1-to-string arguments) "\n"))
  1470.         (dired-log err-buffer)
  1471.         (or arguments program t))
  1472.     (kill-buffer err-buffer)
  1473.     (message "%s...done" msg)
  1474.     nil))))
  1475.  
  1476. ;;; 7K
  1477. ;;;###begin dired-cmd.el
  1478. ;; Diffing and compressing
  1479.  
  1480. (defun dired-diff (file &optional switches)
  1481.   "Compare file at point with file FILE using `diff'.
  1482. FILE defaults to the file at the mark.
  1483. The prompted-for file is the first file given to `diff'.
  1484. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1485.   (interactive
  1486.    (let ((default (if (mark)
  1487.               (save-excursion (goto-char (mark))
  1488.                       (dired-get-filename t t)))))
  1489.      (list (read-file-name (format "Diff %s with: %s"
  1490.                    (dired-get-filename t)
  1491.                    (if default
  1492.                        (concat "(default " default ") ")
  1493.                      ""))
  1494.                (dired-current-directory) default t)
  1495.        (if (fboundp 'diff-read-switches)
  1496.            (diff-read-switches "Options for diff: ")))))
  1497.   (if switches                ; Emacs 19's diff has but two
  1498.       (diff file (dired-get-filename t) switches) ; args (yet ;-)
  1499.     (diff file (dired-get-filename t))))
  1500.  
  1501. (defun dired-backup-diff (&optional switches)
  1502.   "Diff this file with its backup file or vice versa.
  1503. Uses the latest backup, if there are several numerical backups.
  1504. If this file is a backup, diff it with its original.
  1505. The backup file is the first file given to `diff'.
  1506. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1507.   (interactive (list (if (fboundp 'diff-read-switches)
  1508.              (diff-read-switches "Diff with switches: "))))
  1509.   (let (bak ori (file (dired-get-filename)))
  1510.     (if (backup-file-name-p file)
  1511.     (setq bak file
  1512.           ori (file-name-sans-versions file))
  1513.       (setq bak (or (latest-backup-file file)
  1514.             (error "No backup found for %s" file))
  1515.         ori file))
  1516.     (if switches
  1517.     (diff bak ori switches)
  1518.       (diff bak ori))))
  1519.  
  1520. ;;>>> install (move this function into files.el)
  1521. (defun latest-backup-file (fn)    ; actually belongs into files.el
  1522.   "Return the latest existing backup of FILE, or nil."
  1523.   ;; First try simple backup, then the highest numbered of the
  1524.   ;; numbered backups.
  1525.   ;; Ignore the value of version-control because we look for existing
  1526.   ;; backups, which maybe were made earlier or by another user with
  1527.   ;; a different value of version-control.
  1528.   (setq fn (expand-file-name fn))
  1529.   (or
  1530.    (let ((bak (make-backup-file-name fn)))
  1531.      (if (file-exists-p bak) bak))
  1532.    (let* ((dir (file-name-directory fn))
  1533.       (base-versions (concat (file-name-nondirectory fn) ".~"))
  1534.       (bv-length (length base-versions)))
  1535.      (concat dir
  1536.          (car (sort
  1537.            (file-name-all-completions base-versions dir)
  1538.            ;; bv-length is a fluid var for backup-extract-version:
  1539.            (function
  1540.             (lambda (fn1 fn2)
  1541.               (> (backup-extract-version fn1)
  1542.              (backup-extract-version fn2))))))))))
  1543.  
  1544. ;; This is a separate function for the sake of ange-ftp.el
  1545. (defun dired-compress-make-compressed-filename (from-file &optional reverse)
  1546. ;;  "Converts a filename FROM-FILE to the filename of the associated
  1547. ;;  compressed file.  With an optional argument REVERSE, the reverse
  1548. ;;  conversion is done."
  1549.   (if reverse
  1550.       (substring from-file 0 -2)
  1551.     (concat from-file ".Z")))
  1552.  
  1553. (defun dired-compress ()
  1554.   ;; Compress current file.  Return nil for success, offending filename else.
  1555.   (dired-check-ls-l)
  1556.   (let* (buffer-read-only
  1557.      (from-file (dired-get-filename))
  1558.      (to-file (dired-compress-make-compressed-filename from-file)))
  1559.     (cond ((save-excursion (beginning-of-line)
  1560.                (looking-at dired-re-sym))
  1561.        (dired-log (concat "Attempt to compress a symbolic link:\n"
  1562.                   from-file))
  1563.        (dired-make-relative from-file))
  1564.       ((dired-check-process (concat "Compressing " from-file)
  1565.                 "compress" "-f" from-file)
  1566.        ;; errors from the process are already logged by dired-check-process
  1567.        (dired-make-relative from-file))
  1568.     (t
  1569.      (dired-update-file-line to-file)
  1570.      nil))))
  1571.  
  1572. (defun dired-uncompress ()
  1573.   ;; Uncompress current file.  Return nil for success, offending filename else.
  1574.   (let* (buffer-read-only
  1575.      (from-file (dired-get-filename))
  1576.      (to-file (dired-compress-make-compressed-filename from-file t)))
  1577.     (if (dired-check-process (concat "Uncompressing " from-file)
  1578.                  "uncompress" from-file)
  1579.     (dired-make-relative from-file)
  1580.       (dired-update-file-line to-file)
  1581.       nil)))
  1582.  
  1583. (defun dired-mark-map-check (fun arg op-symbol &optional show-progress)
  1584. ;  "Map FUN over marked files (with second ARG like in dired-mark-map)
  1585. ; and display failures.
  1586.  
  1587. ; FUN takes zero args.  It returns non-nil (the offending object, e.g.
  1588. ; the short form of the filename) for a failure and probably logs a
  1589. ; detailed error explanation using function `dired-log'.
  1590.  
  1591. ; OP-SYMBOL is a symbol describing the operation performed (e.g.
  1592. ; `compress').  It is used with `dired-mark-pop-up' to prompt the user
  1593. ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
  1594. ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
  1595.  
  1596. ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
  1597.   (if (dired-mark-confirm op-symbol arg)
  1598.       (let* ((total-list;; all of FUN's return values
  1599.           (dired-mark-map (funcall fun) arg show-progress))
  1600.          (total (length total-list))
  1601.          (failures (delq nil total-list))
  1602.          (count (length failures)))
  1603.     (if (not failures)
  1604.         (message "%s: %d file%s."
  1605.              (capitalize (symbol-name op-symbol))
  1606.              total (dired-plural-s total))
  1607.       (message "Failed to %s %d of %d file%s - type W to see why %s"
  1608.            (symbol-name op-symbol) count total (dired-plural-s total)
  1609.            ;; this gives a short list of failed files in parens
  1610.            ;; which may be sufficient for the user even
  1611.            ;; without typing `W' for the process' diagnostics
  1612.            failures)
  1613.       ;; end this bunch of errors:
  1614.       (dired-log-summary
  1615.        "Failed to %s %d of %d file%s"
  1616.        (symbol-name op-symbol) count total (dired-plural-s total))))))
  1617.  
  1618. (defun dired-do-compress (&optional arg)
  1619.   "Compress marked (or next ARG) files.
  1620. Type \\[dired-do-uncompress] to uncompress again."
  1621.   (interactive "P")
  1622.   (dired-mark-map-check (function dired-compress) arg 'compress t))
  1623.  
  1624. (defun dired-do-uncompress (&optional arg)
  1625.   "Uncompress marked (or next ARG) files."
  1626.   (interactive "P")
  1627.   (dired-mark-map-check (function dired-uncompress) arg 'uncompress t))
  1628.  
  1629. ;; Commands for Emacs Lisp files - load and byte compile
  1630.  
  1631. (defun dired-byte-compile ()
  1632.   ;; Return nil for success, offending file name else.
  1633.   (let* ((filename (dired-get-filename))
  1634.      (elc-file
  1635.       (if (eq system-type 'vax-vms)
  1636.           (concat (substring filename 0 (string-match ";" filename)) "c")
  1637.         (concat filename "c")))
  1638.      buffer-read-only failure)
  1639.     (condition-case err
  1640.     (save-excursion (byte-compile-file filename))
  1641.       (error
  1642.        (setq failure err)))
  1643.     (if failure
  1644.     (progn
  1645.       (dired-log "Byte compile error for %s:\n%s\n" filename failure)
  1646.       (dired-make-relative filename))
  1647.       (dired-remove-file elc-file)
  1648.       (forward-line)            ; insert .elc after its .el file
  1649.       (dired-add-file elc-file)
  1650.       nil)))
  1651.  
  1652. (defun dired-do-byte-compile (&optional arg)
  1653.   "Byte compile marked (or next ARG) Emacs lisp files."
  1654.   (interactive "P")
  1655.   (dired-mark-map-check (function dired-byte-compile) arg 'byte-compile t))
  1656.  
  1657. (defun dired-load ()
  1658.   ;; Return nil for success, offending file name else.
  1659.   (let ((file (dired-get-filename)) failure)
  1660.     (condition-case err
  1661.       (load file nil nil t)
  1662.       (error (setq failure err)))
  1663.     (if (not failure)
  1664.     nil
  1665.       (dired-log "Load error for %s:\n%s\n" file failure)
  1666.       (dired-make-relative file))))
  1667.  
  1668. (defun dired-do-load (&optional arg)
  1669.   "Load the marked (or next ARG) Emacs lisp files."
  1670.   (interactive "P")
  1671.   (dired-mark-map-check (function dired-load) arg 'load t))
  1672.  
  1673. (defun dired-do-chxxx (attribute-name program op-symbol arg)
  1674.   ;; Change file attributes (mode, group, owner) of marked files and
  1675.   ;; refresh their file lines.
  1676.   ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  1677.   ;; PROGRAM is the program used to change the attribute.
  1678.   ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
  1679.   ;; ARG describes which files to use, like in dired-mark-get-files.
  1680.   (let* ((files (dired-mark-get-files t arg))
  1681.      (new-attribute
  1682.       (dired-mark-read-string
  1683.        (concat "Change " attribute-name " of %s to: ")
  1684.        nil op-symbol arg files))
  1685.      (operation (concat program " " new-attribute))
  1686.      (failure (apply (function dired-check-process)
  1687.              operation program new-attribute
  1688.              files)))
  1689.     (dired-do-redisplay arg);; moves point if ARG is an integer
  1690.     (if failure
  1691.     (dired-log-summary
  1692.      (message "%s: error - type W to see why." operation)))))
  1693.  
  1694. (defun dired-do-chmod (&optional arg)
  1695.   "Change the mode of the marked (or next ARG) files.
  1696. This calls chmod, thus symbolic modes like `g+w' are allowed."
  1697.   (interactive "P")
  1698.   (dired-do-chxxx "Mode" "chmod" 'chmod arg))
  1699.  
  1700. (defun dired-do-chgrp (&optional arg)
  1701.   "Change the group of the marked (or next ARG) files."
  1702.   (interactive "P")
  1703.   (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
  1704.  
  1705. (defun dired-do-chown (&optional arg)
  1706.   "Change the owner of the marked (or next ARG) files."
  1707.   (interactive "P")
  1708.   (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
  1709.  
  1710. ;;;###end dired-cmd.el
  1711.  
  1712.  
  1713. ;; Deleting files
  1714.  
  1715. (defun dired-do-deletions ()
  1716.   "In dired, delete the files flagged for deletion."
  1717.   (interactive)
  1718.   (let* ((dired-marker-char dired-del-marker)
  1719.      (regexp (dired-marker-regexp))
  1720.      case-fold-search)
  1721.     (if (save-excursion (goto-char (point-min))
  1722.             (re-search-forward regexp nil t))
  1723.     (dired-internal-do-deletions
  1724.      ;; this can't move point since ARG is nil
  1725.      (dired-mark-map (cons (dired-get-filename) (point))
  1726.              nil)
  1727.      nil)
  1728.       (message "(No deletions requested)"))))
  1729.  
  1730. (defun dired-do-delete (&optional arg)
  1731.   "Delete all marked (or next ARG) files."
  1732.   ;; This is more consistent with the file marking feature than
  1733.   ;; dired-do-deletions.
  1734.   (interactive "P")
  1735.   (dired-internal-do-deletions
  1736.    ;; this may move point if ARG is an integer
  1737.    (dired-mark-map (cons (dired-get-filename) (point))
  1738.            arg)
  1739.    arg))
  1740.  
  1741. (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
  1742.  
  1743. (defun dired-internal-do-deletions (l arg)
  1744.   ;; L is an alist of files to delete, with their buffer positions.
  1745.   ;; ARG is the prefix arg.
  1746.   ;; Filenames are absolute (VMS needs this for logical search paths).
  1747.   ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
  1748.   ;; That way as changes are made in the buffer they do not shift the
  1749.   ;; lines still to be changed, so the (point) values in L stay valid.
  1750.   ;; Also, for subdirs in natural order, a subdir's files are deleted
  1751.   ;; before the subdir itself - the other way around would not work.
  1752.   (let ((files (mapcar (function car) l))
  1753.     (count (length l))
  1754.     (succ 0))
  1755.     ;; canonicalize file list for pop up
  1756.     (setq files (nreverse (mapcar (function dired-make-relative) files)))
  1757.     (if (dired-mark-pop-up
  1758.      " *Deletions*" 'delete files dired-deletion-confirmer
  1759.      (format "Delete %s " (dired-mark-prompt arg files)))
  1760.     (save-excursion
  1761.       (let (failures);; files better be in reverse order for this loop!
  1762.         (while l
  1763.           (goto-char (cdr (car l)))
  1764.           (let (buffer-read-only)
  1765.         (condition-case err
  1766.             (let ((fn (car (car l))))
  1767.               ;; This test is equivalent to
  1768.               ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1769.               ;; but more efficient
  1770.               (if (eq t (car (file-attributes fn)))
  1771.               (remove-directory fn)
  1772.             (delete-file fn))
  1773.               ;; if we get here, removing worked
  1774.               (setq succ (1+ succ))
  1775.               (message "%s of %s deletions" succ count)
  1776.               (delete-region (progn (beginning-of-line) (point))
  1777.                      (progn (forward-line 1) (point)))
  1778.               (dired-clean-up-after-deletion fn))
  1779.           (error;; catch errors from failed deletions
  1780.            (dired-log "%s\n" err)
  1781.            (setq failures (cons (car (car l)) failures)))))
  1782.           (setq l (cdr l)))
  1783.         (if (not failures)
  1784.         (message "%d deletion%s done" count (dired-plural-s count))
  1785.           (dired-log-summary
  1786.            (message "%d of %d deletion%s failed: %s"
  1787.             (length failures) count
  1788.             (dired-plural-s count)
  1789.             (prin1-to-string failures))))))
  1790.       (message "(No deletions performed)")))
  1791.   (dired-move-to-filename))
  1792.  
  1793. ;; This is a separate function for the sake of dired-x.el.
  1794. (defun dired-clean-up-after-deletion (fn)
  1795.   ;; Clean up after a deleted file or directory FN.
  1796.   (save-excursion (and (dired-goto-subdir fn)
  1797.                (dired-kill-subdir))))
  1798.  
  1799.  
  1800. (defun dired-replace-in-string (regexp newtext string)
  1801.   ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
  1802.   ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
  1803.   (let ((result "") (start 0) mb me)
  1804.     (while (string-match regexp string start)
  1805.       (setq mb (match-beginning 0)
  1806.         me (match-end 0)
  1807.         result (concat result (substring string start mb) newtext)
  1808.         start me))
  1809.     (concat result (substring string start))))
  1810.  
  1811. (defun dired-next-dirline (arg &optional opoint)
  1812.   "Goto ARG'th next directory file line."
  1813.   (interactive "p")
  1814.   (dired-check-ls-l)
  1815.   (or opoint (setq opoint (point)))
  1816.   (if (if (> arg 0)
  1817.       (re-search-forward dired-re-dir nil t arg)
  1818.     (beginning-of-line)
  1819.     (re-search-backward dired-re-dir nil t (- arg)))
  1820.       (dired-move-to-filename)        ; user may type `i' or `f'
  1821.     (goto-char opoint)
  1822.     (error "No more subdirectories")))
  1823.  
  1824. (defun dired-prev-dirline (arg)
  1825.   "Goto ARG'th previous directory file line."
  1826.   (interactive "p")
  1827.   (dired-next-dirline (- arg)))
  1828.  
  1829. (defun dired-unflag-all-files (flag &optional arg)
  1830.   "Remove a specific or all flags from every file.
  1831. With an arg, queries for each marked file.
  1832. Type \\[help-command] at that time for help."
  1833.   (interactive "sRemove flag: (default: all flags) \nP")
  1834.   (let ((count 0)
  1835.     (re (if (zerop (length flag)) dired-re-mark
  1836.           (concat "^" (regexp-quote flag)))))
  1837.     (save-excursion
  1838.       (let (buffer-read-only case-fold-search query
  1839.                  (help-form "\
  1840. Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
  1841. `!' to unflag all remaining files with no more questions."))
  1842.     (goto-char (point-min))
  1843.     (while (re-search-forward re nil t)
  1844.       (if (or (not arg)
  1845.           (dired-query 'query "Unflag file `%s' ? "
  1846.                    (dired-get-filename t)))
  1847.           (progn (delete-char -1) (insert " ") (setq count (1+ count))))
  1848.       (forward-line 1))))
  1849.     (message "%s" (format "Flags removed: %d %s" count flag) )))
  1850.  
  1851. ;; pop ups and user input for file marking
  1852.  
  1853. (defun dired-marker-regexp ()
  1854.   (concat "^" (regexp-quote (char-to-string dired-marker-char))))
  1855.  
  1856. (defun dired-plural-s (count)
  1857.   (if (= 1 count) "" "s"))
  1858.  
  1859. (defun dired-mark-prompt (arg files)
  1860.   ;; Return a string for use in a prompt, either the current file
  1861.   ;; name, or the marker and a count of marked files.
  1862.   (let ((count (length files)))
  1863.     (if (= count 1)
  1864.     (car files)
  1865.       ;; more than 1 file:
  1866.       (if (integerp arg)
  1867.       ;; abs(arg) = count
  1868.       ;; Perhaps this is nicer, but it also takes more screen space:
  1869.       ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
  1870.       ;;                        count)
  1871.       (format "[next %d files]" arg)
  1872.     (format "%c [%d files]" dired-marker-char count)))))
  1873.  
  1874. (defvar dired-query-alist
  1875.   '((?\y . y) (?\040 . y)        ; `y' or SPC means accept once
  1876.     (?n . n) (?\177 . n)        ; `n' or DEL skips once
  1877.     (?! . yes)                ; `!' accepts rest
  1878.     (?q. no) (?\e . no)            ; `q' or ESC skips rest
  1879.     ;; None of these keys quit - use C-g for that.
  1880.     ))
  1881.  
  1882. (defun dired-query (qs-var qs-prompt &rest qs-args)
  1883.   ;; Query user and return nil or t.
  1884.   ;; Store answer in symbol VAR (which must initially be bound to nil).
  1885.   ;; Format PROMPT with ARGS.
  1886.   ;; Binding variable help-form will help the user who types C-h.
  1887.   (let* ((char (symbol-value qs-var))
  1888.      (action (cdr (assoc char dired-query-alist))))
  1889.     (cond ((eq 'yes action)
  1890.        t)                ; accept, and don't ask again
  1891.       ((eq 'no action)
  1892.        nil)                ; skip, and don't ask again
  1893.       (t;; no lasting effects from last time we asked - ask now
  1894.        (let ((qprompt (concat qs-prompt
  1895.                   (if help-form
  1896.                       (format " [Type yn!q or %s] "
  1897.                           (key-description
  1898.                            (char-to-string help-char)))
  1899.                     " [Type y, n, q or !] ")))
  1900.          result elt)
  1901.          ;; Actually it looks nicer without cursor-in-echo-area - you can
  1902.          ;; look at the dired buffer instead of at the prompt to decide.
  1903.          (apply 'message qprompt qs-args)
  1904.          (setq char (set qs-var (read-char)))
  1905.          (while (not (setq elt (assoc char dired-query-alist)))
  1906.            (message "Invalid char - type %c for help." help-char)
  1907.            (ding)
  1908.            (sit-for 1)
  1909.            (apply 'message qprompt qs-args)
  1910.            (setq char (set qs-var (read-char))))
  1911.          (memq (cdr elt) '(t y yes)))))))
  1912.  
  1913. (defun dired-pop-to-buffer (buf)
  1914.   ;; Pop up buffer BUF.
  1915.   ;; If dired-shrink-to-fit is t, make its window fit its contents.
  1916.   (if (not dired-shrink-to-fit)
  1917.       (pop-to-buffer (get-buffer-create buf))
  1918.     ;; let window shrink to fit:
  1919.     (let ((window (selected-window))
  1920.       target-lines w2)
  1921.       (cond ;; if split-window-threshold is enabled, use the largest window
  1922.             ((and (> (window-height (setq w2 (get-largest-window)))
  1923.              split-height-threshold)
  1924.           (= (screen-width) (window-width w2)))
  1925.          (setq window w2))
  1926.         ;; if the least-recently-used window is big enough, use it
  1927.         ((and (> (window-height (setq w2 (get-lru-window)))
  1928.              (* 2 window-min-height))
  1929.           (= (screen-width) (window-width w2)))
  1930.          (setq window w2)))
  1931.       (save-excursion
  1932.     (set-buffer buf)
  1933.     (goto-char (point-max))
  1934.     (skip-chars-backward "\n\r\t ")
  1935.     (setq target-lines (count-lines (point-min) (point))))
  1936.       (if (<= (window-height window) (* 2 window-min-height))
  1937.       ;; At this point, every window on the screen is too small to split.
  1938.       (setq w2 (display-buffer buf))
  1939.     (setq w2 (split-window window
  1940.           (max window-min-height
  1941.                (- (window-height window)
  1942.               (1+ (max window-min-height target-lines)))))))
  1943.       (set-window-buffer w2 buf)
  1944.       (if (< (1- (window-height w2)) target-lines)
  1945.       (progn
  1946.         (select-window w2)
  1947.         (enlarge-window (- target-lines (1- (window-height w2))))))
  1948.       (set-window-start w2 1)
  1949.       )))
  1950.  
  1951. (defvar dired-no-confirm nil
  1952. ;;  "If non-nil, list of symbols for commands dired should not confirm.
  1953. ;;It can be a sublist of
  1954. ;;
  1955. ;;  '(byte-compile chgrp chmod chown compress copy delete hardlink load
  1956. ;;    move print shell symlink uncompress)"
  1957.   )
  1958.  
  1959. (defun dired-mark-confirm (op-symbol arg)
  1960.   ;; Request confirmation from the user that the operation described
  1961.   ;; by OP-SYMBOL is to be performed on the marked files.
  1962.   ;; Confirmation consists in a y-or-n question with a file list
  1963.   ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
  1964.   ;; The files used are determined by ARG (like in dired-mark-get-files).
  1965.   (or (memq op-symbol dired-no-confirm)
  1966.       (let ((files (dired-mark-get-files t arg)))
  1967.     (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
  1968.                (concat (capitalize (symbol-name op-symbol)) " "
  1969.                    (dired-mark-prompt arg files) "? ")))))
  1970.  
  1971. (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
  1972.   ;;"Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
  1973.   ;;Return FUNCTION's result on ARGS after popping up a window (in a buffer
  1974.   ;;named BUFNAME, nil gives \" *Marked Files*\") showing the marked
  1975.   ;;files.  Uses function `dired-pop-to-buffer' to do that.
  1976.   ;; FUNCTION should not manipulate files.
  1977.   ;; It should only read input (an argument or confirmation).
  1978.   ;;The window is not shown if there is just one file or
  1979.   ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
  1980.   ;;FILES is the list of marked files."
  1981.   (or bufname (setq bufname  " *Marked Files*"))
  1982.   (if (or (memq op-symbol dired-no-confirm)
  1983.       (= (length files) 1))
  1984.       (apply function args)
  1985.     (save-excursion
  1986.       (set-buffer (get-buffer-create bufname))
  1987.       (erase-buffer)
  1988.       (dired-format-columns-of-files files))
  1989.     (save-window-excursion
  1990.       (dired-pop-to-buffer bufname)
  1991.       (apply function args))))
  1992.  
  1993. (defun dired-format-columns-of-files (files)
  1994.   ;; Files should be in forward order for this loop.
  1995.   ;; i.e., (car files) = first file in buffer.
  1996.   ;; Returns the number of lines used.
  1997.   (let* ((maxlen (+ 2 (apply 'max (mapcar 'length files))))
  1998.      (width (- (window-width (selected-window)) 2))
  1999.      (columns (max 1 (/ width maxlen)))
  2000.      (nfiles (length files))
  2001.      (rows (+ (/ nfiles columns)
  2002.           (if (zerop (% nfiles columns)) 0 1)))
  2003.      (i 0)
  2004.      (j 0))
  2005.     (setq files (nconc (copy-sequence files) ; fill up with empty fns
  2006.                (make-list (- (* columns rows) nfiles) "")))
  2007.     (setcdr (nthcdr (1- (length files)) files) files) ; make circular
  2008.     (while (< j rows)
  2009.       (while (< i columns)
  2010.     (indent-to (* i maxlen))
  2011.     (insert (car files))
  2012.     (setq files (nthcdr rows files)
  2013.           i (1+ i)))
  2014.       (insert "\n")
  2015.       (setq i 0
  2016.         j (1+ j)
  2017.         files (cdr files)))
  2018.     rows))
  2019.  
  2020. ;; Read arguments for a mark command of type OP-SYMBOL,
  2021. ;; perhaps popping up the list of marked files.
  2022. ;; ARG is the prefix arg and indicates whether the files came from
  2023. ;; marks (ARG=nil) or a repeat factor (integerp ARG).
  2024. ;; If the current file was used, the list has but one element and ARG
  2025. ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
  2026.  
  2027. (defun dired-mark-read-string (prompt initial op-symbol arg files)
  2028.   ;; PROMPT for a string, with INITIAL input.
  2029.   ;; Other args are used to give user feedback and pop-up:
  2030.   ;; OP-SYMBOL of command, prefix ARG, marked FILES.
  2031.   (dired-mark-pop-up
  2032.    nil op-symbol files
  2033.    (function read-string)
  2034.    (format prompt (dired-mark-prompt arg files)) initial))
  2035.  
  2036. (defun dired-mark-read-file-name (prompt dir op-symbol arg files)
  2037.   (dired-mark-pop-up
  2038.    nil op-symbol files
  2039.    (function read-file-name)
  2040.    (format prompt (dired-mark-prompt arg files)) dir))
  2041.  
  2042. (defun dired-mark-file (arg)
  2043.   "In dired, mark the current line's file for later commands.
  2044. With arg, repeat over several lines.
  2045. Use \\[dired-unflag-all-files] to remove all flags."
  2046.   (interactive "p")
  2047.   (let (buffer-read-only)
  2048.     (dired-repeat-over-lines
  2049.      arg
  2050.      (function (lambda () (delete-char 1) (insert dired-marker-char))))))
  2051.  
  2052. (defun dired-next-marked-file (arg &optional wrap opoint)
  2053.   "Move to the next marked file, wrapping around the end of the buffer."
  2054.   (interactive "p\np")
  2055.   (or opoint (setq opoint (point)));; return to where interactively started
  2056.   (if (if (> arg 0)
  2057.       (re-search-forward dired-re-mark nil t arg)
  2058.     (beginning-of-line)
  2059.     (re-search-backward dired-re-mark nil t (- arg)))
  2060.       (dired-move-to-filename)
  2061.     (if (null wrap)
  2062.     (progn
  2063.       (goto-char opoint)
  2064.       (error "No next marked file"))
  2065.       (message "(Wraparound for next marked file)")
  2066.       (goto-char (if (> arg 0) (point-min) (point-max)))
  2067.       (dired-next-marked-file arg nil opoint))))
  2068.  
  2069. (defun dired-prev-marked-file (arg &optional wrap)
  2070.   "Move to the previous marked file, wrapping around the end of the buffer."
  2071.   (interactive "p\np")
  2072.   (dired-next-marked-file (- arg) wrap))
  2073.  
  2074. (defun dired-file-marker (file)
  2075.   ;; Return FILE's marker, or nil if unmarked.
  2076.   (save-excursion
  2077.     (and (dired-goto-file file)
  2078.      (progn
  2079.        (beginning-of-line)
  2080.        (if (not (equal ?\040 (following-char)))
  2081.            (following-char))))))
  2082.  
  2083. (defun dired-read-regexp (prompt &optional initial)
  2084. ;; This is an extra function so that gmhist can redefine it.
  2085.   (setq dired-flagging-regexp
  2086.     (read-string prompt (or initial dired-flagging-regexp))))
  2087.  
  2088. (defun dired-mark-files-regexp (regexp &optional marker-char)
  2089.   "Mark all files matching REGEXP for use in later commands.
  2090. A prefix argument means to unmark them instead.
  2091. `.' and `..' are never marked.
  2092.  
  2093. REGEXP is an Emacs regexp, not a shell wildcard.  Thus, use `\\.o$' for
  2094. object files--just `.o' will mark more than you might think."
  2095.   (interactive
  2096.    (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
  2097.                     " files (regexp): "))
  2098.      (if current-prefix-arg ?\040)))
  2099.   (let ((dired-marker-char (or marker-char dired-marker-char)))
  2100.     (dired-mark-if
  2101.      (and (not (looking-at dired-re-dot))
  2102.       (not (eolp))            ; empty line
  2103.       (let ((fn (dired-get-filename nil t)))
  2104.         (and fn (string-match regexp (file-name-nondirectory fn)))))
  2105.      "matching file")))
  2106.  
  2107. (defun dired-flag-regexp-files (regexp)
  2108.   "In dired, flag all files containing the specified REGEXP for deletion.
  2109. The match is against the non-directory part of the filename.  Use `^'
  2110.   and `$' to anchor matches.  Exclude subdirs by hiding them.
  2111. `.' and `..' are never flagged."
  2112.   (interactive (list (dired-read-regexp "Flag for deletion (regexp): ")))
  2113.   (dired-mark-files-regexp regexp dired-del-marker))
  2114.  
  2115. (defun dired-mark-symlinks (unflag-p)
  2116.   "Mark all symbolic links.
  2117. With prefix argument, unflag all those files."
  2118.   (interactive "P")
  2119.   (dired-check-ls-l)
  2120.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2121.     (dired-mark-if (looking-at dired-re-sym) "symbolic link")))
  2122.  
  2123. (defun dired-mark-directories (unflag-p)
  2124.   "Mark all directory file lines except `.' and `..'.
  2125. With prefix argument, unflag all those files."
  2126.   (interactive "P")
  2127.   (dired-check-ls-l)
  2128.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2129.     (dired-mark-if (and (looking-at dired-re-dir)
  2130.             (not (looking-at dired-re-dot)))
  2131.            "directory file")))
  2132.  
  2133. (defun dired-mark-executables (unflag-p)
  2134.   "Mark all executable files.
  2135. With prefix argument, unflag all those files."
  2136.   (interactive "P")
  2137.   (dired-check-ls-l)
  2138.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2139.     (dired-mark-if (looking-at dired-re-exe) "executable file")))
  2140.  
  2141. ;; dired-x.el has a dired-mark-sexp interactive command: mark
  2142. ;; files for which PREDICATE returns non-nil.
  2143.  
  2144. (defun dired-flag-auto-save-files (&optional unflag-p)
  2145.   "Flag for deletion files whose names suggest they are auto save files.
  2146. A prefix argument says to unflag those files instead."
  2147.   (interactive "P")
  2148.   (dired-check-ls-l)
  2149.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2150.     (dired-mark-if
  2151.        (and (not (looking-at dired-re-dir))
  2152.         (let ((fn (dired-get-filename t t)))
  2153.           (if fn (auto-save-file-name-p
  2154.               (file-name-nondirectory fn)))))
  2155.        "auto save file")))
  2156.  
  2157. (defun dired-flag-backup-files (&optional unflag-p)
  2158.   "Flag all backup files (names ending with `~') for deletion.
  2159. With prefix argument, unflag these files."
  2160.   (interactive "P")
  2161.   (dired-check-ls-l)
  2162.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2163.     (dired-mark-if
  2164.      (and (not (looking-at dired-re-dir))
  2165.       (let ((fn (dired-get-filename t t)))
  2166.         (if fn (backup-file-name-p fn))))
  2167.      "backup file")))
  2168.  
  2169.  
  2170. ;;; Shell commands
  2171. ;;>>> install (move this function into simple.el)
  2172. (defun shell-quote (filename)        ; actually belongs into simple.el
  2173.   "Quote a file name for inferior shell (see variable shell-file-name)."
  2174.   ;; Quote everything except POSIX filename characters.
  2175.   ;; This should be safe enough even for really wierd shells.
  2176.   (let ((result "") (start 0) end)
  2177.     (while (string-match "[^---0-9a-zA-Z_./]" filename start)
  2178.       (setq end (match-beginning 0)
  2179.         result (concat result (substring filename start end)
  2180.                "\\" (substring filename end (1+ end)))
  2181.         start (1+ end)))
  2182.     (concat result (substring filename start))))
  2183.  
  2184. (defun dired-read-shell-command (prompt arg files)
  2185. ;;  "Read a dired shell command prompting with PROMPT (using read-string).
  2186. ;;ARG is the prefix arg and may be used to indicate in the prompt which
  2187. ;;  files are affected.
  2188. ;;This is an extra function so that you can redefine it, e.g., to use gmhist."
  2189.   (dired-mark-pop-up
  2190.    nil 'shell files
  2191.    (function read-string) (format prompt (dired-mark-prompt arg files))))
  2192.  
  2193. ;; The in-background argument is only needed in Emacs 18 where
  2194. ;; shell-command doesn't understand an appended ampersand `&'.
  2195. (defun dired-do-shell-command (&optional arg in-background)
  2196.   "Run a shell command on the marked files.
  2197. If there is output, it goes to a separate buffer.
  2198. The list of marked files is appended to the command string unless asterisks
  2199.   `*' indicate the place(s) where the list should go.
  2200. If no files are marked or a specific numeric prefix arg is given, uses
  2201.   next ARG files.  As always, a raw arg (\\[universal-argument]) means the current file.
  2202.   The prompt mentions the file(s) or the marker, as appropriate.
  2203. With a zero argument, run command on each marked file separately: `cmd *
  2204.   foo' results in `cmd F1 foo; ...; cmd Fn foo'.
  2205. No automatic redisplay is attempted, as the file names may have
  2206.   changed.  Type \\[dired-do-redisplay] to redisplay the marked files.
  2207. The shell command has the top level directory as working directory, so
  2208.   output files usually are created there instead of in a subdir."
  2209. ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
  2210. ;;actual work and can be redefined for customization.
  2211.   (interactive "P")
  2212.   (let* ((on-each (equal arg 0))
  2213.      (prompt (concat (if in-background "& on " "! on ")
  2214.              (if on-each "each " "")
  2215.              "%s: "))
  2216.      (file-list (dired-mark-get-files t (if on-each nil arg)))
  2217.      ;; Want to give feedback whether this file or marked files are used:
  2218.      (command (dired-read-shell-command
  2219.            prompt (if on-each nil arg) file-list))
  2220.      (result
  2221.       (dired-shell-stuff-it command file-list on-each arg)))
  2222.     ;; execute the shell command
  2223.     (dired-run-shell-command result in-background)))
  2224.  
  2225. ;; Might use {,} for bash or csh:
  2226. (defvar dired-mark-prefix ""
  2227.   "Prepended to marked files in dired shell commands.")
  2228. (defvar dired-mark-postfix ""
  2229.   "Appended to marked files in dired shell commands.")
  2230. (defvar dired-mark-separator " "
  2231.   "Separates marked files in dired shell commands.")
  2232.  
  2233. (defun dired-shell-stuff-it (command file-list on-each &optional raw-arg)
  2234. ;; "Make up a shell command line from COMMAND and FILE-LIST.
  2235. ;; If ON-EACH is t, COMMAND should be applied to each file, else
  2236. ;; simply concat all files and apply COMMAND to this.
  2237. ;; FILE-LIST's elements will be quoted for the shell."
  2238. ;; Might be redefined for smarter things and could then use RAW-ARG
  2239. ;; (coming from interactive P and currently ignored) to decide what to do.
  2240. ;; Smart would be a way to access basename or extension of file names.
  2241. ;; See dired-trns.el for an approach to this.
  2242.   ;; Bug: There is no way to quote a *
  2243.   ;; On the other hand, you can never accidentally get a * into your cmd.
  2244.   (let ((stuff-it
  2245.      (if (string-match "\\*" command)
  2246.          (function (lambda (x)
  2247.              (dired-replace-in-string "\\*" x command)))
  2248.        (function (lambda (x) (concat command " " x))))))
  2249.     (if on-each
  2250.     (mapconcat stuff-it (mapcar (function shell-quote) file-list) ";")
  2251.       (let ((fns (mapconcat (function shell-quote)
  2252.                 file-list dired-mark-separator)))
  2253.     (if (> (length file-list) 1)
  2254.         (setq fns (concat dired-mark-prefix fns dired-mark-postfix)))
  2255.     (funcall stuff-it fns)))))
  2256.  
  2257. ;; This is an extra function so that it can be redefined by ange-ftp.
  2258. (defun dired-run-shell-command (command &optional in-background)
  2259.   (if (and in-background (not (string-match "&[ \t]*$" command)))
  2260.       (setq command (concat command " &")))
  2261.   (shell-command command))
  2262.  
  2263. (defun dired-do-print (&optional arg)
  2264.   "Print the marked (or next ARG) files.
  2265. Uses the shell command coming from variables `lpr-command' and
  2266. `lpr-switches' as default."
  2267.   (interactive "P")
  2268.   (or (listp lpr-switches)
  2269.       (error "lpr-switches must be a *list* of strings"))
  2270.   (let* ((file-list (dired-mark-get-files t arg))
  2271.      (switches (mapconcat (function identity) lpr-switches " "))
  2272.      (command (dired-mark-read-string
  2273.            "Print %s with: "
  2274.            (concat lpr-command " " switches)
  2275.            'print arg file-list)))
  2276.     (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
  2277.  
  2278.  
  2279. ;;; 10K
  2280. ;;;###begin dired-cp.el
  2281. ;;; Copy, move/rename, making hard and symbolic links
  2282.  
  2283. (defvar dired-backup-if-overwrite nil
  2284.   "*Non-nil if Dired should ask about making backups before overwriting files.
  2285. Special value 'always suppresses confirmation.")
  2286.  
  2287. (defun dired-handle-overwrite (to)
  2288.   ;; Save old version of a to be overwritten file TO.
  2289.   ;; `overwrite-confirmed' and `overwrite-backup-query' are fluid vars
  2290.   ;; from dired-create-files.
  2291.   (if (and dired-backup-if-overwrite
  2292.        overwrite-confirmed
  2293.        (or (eq 'always dired-backup-if-overwrite)
  2294.            (dired-query 'overwrite-backup-query
  2295.             (format "Make backup for existing file `%s'? " to))))
  2296.       (let ((backup (car (find-backup-file-name to))))
  2297.     (rename-file to backup 0)    ; confirm overwrite of old backup
  2298.     (dired-relist-entry backup))))
  2299.  
  2300. (defun dired-copy-file (from to ok-flag)
  2301.   (dired-handle-overwrite to)
  2302.   (copy-file from to ok-flag dired-copy-preserve-time))
  2303.  
  2304. (defun dired-rename-file (from to ok-flag)
  2305.   (dired-handle-overwrite to)
  2306.   (rename-file from to ok-flag)        ; error is caught in -create-files
  2307.   ;; Silently rename the visited file of any buffer visiting this file.
  2308.   (and (get-file-buffer from)
  2309.        (save-excursion
  2310.      (set-buffer (get-file-buffer from))
  2311.      (let ((modflag (buffer-modified-p)))
  2312.        (set-visited-file-name to)    ; kills write-file-hooks
  2313.        (set-buffer-modified-p modflag))))
  2314.   (dired-remove-file from)
  2315.   ;; See if it's an inserted subdir, and rename that, too.
  2316.   (dired-rename-subdir from to))
  2317.  
  2318. (defun dired-rename-subdir (from-dir to-dir)
  2319.   (setq from-dir (file-name-as-directory from-dir)
  2320.     to-dir (file-name-as-directory to-dir))
  2321.   (dired-fun-in-all-buffers from-dir
  2322.                 (function dired-rename-subdir-1) from-dir to-dir)
  2323.   ;; Update visited file name of all affected buffers
  2324.   (let ((blist (buffer-list)))
  2325.     (while blist
  2326.       (save-excursion
  2327.         (set-buffer (car blist))
  2328.     (if (and buffer-file-name
  2329.          (dired-in-this-tree buffer-file-name from-dir))
  2330.         (let ((modflag (buffer-modified-p))
  2331.           (to-file (dired-replace-in-string
  2332.                 (concat "^" (regexp-quote from-dir))
  2333.                 to-dir
  2334.                 buffer-file-name)))
  2335.           (set-visited-file-name to-file)
  2336.           (set-buffer-modified-p modflag))))
  2337.       (setq blist (cdr blist)))))
  2338.  
  2339. (defun dired-rename-subdir-1 (dir to)
  2340.   ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
  2341.   ;; one of its subdirectories is expanded in this buffer.
  2342.   (let ((alist dired-subdir-alist)
  2343.     (elt nil))
  2344.     (while alist
  2345.       (setq elt (car alist)
  2346.         alist (cdr alist))
  2347.       (if (dired-in-this-tree (car elt) dir)
  2348.       ;; ELT's subdir is affected by the rename
  2349.       (dired-rename-subdir-2 elt dir to)))
  2350.     (if (equal dir default-directory)
  2351.     ;; if top level directory was renamed, lots of things have to be
  2352.     ;; updated:
  2353.     (progn
  2354.       (dired-unadvertise dir)    ; we no longer dired DIR...
  2355.       (setq default-directory to
  2356.         dired-directory (expand-file-name;; this is correct
  2357.                  ;; with and without wildcards
  2358.                  (file-name-nondirectory dired-directory)
  2359.                  to))
  2360.       (let ((new-name (file-name-nondirectory
  2361.                (directory-file-name dired-directory))))
  2362.         ;; try to rename buffer, but just leave old name if new
  2363.         ;; name would already exist (don't try appending "<%d>")
  2364.         (or (get-buffer new-name)
  2365.         (rename-buffer new-name)))
  2366.       ;; ... we dired TO now:
  2367.       (dired-advertise)))))
  2368.  
  2369. (defun dired-rename-subdir-2 (elt dir to)
  2370.   ;; Update the headerline and dired-subdir-alist element of directory
  2371.   ;; described by alist-element ELT to reflect the moving of DIR to TO.
  2372.   ;; Thus, ELT describes either DIR itself or a subdir of DIR.
  2373.  
  2374.   ;; Bug: If TO is not longer part of the same dired tree as DIR was,
  2375.   ;; updating the headerline is actually not the right thing---it
  2376.   ;; should be removed in that case and a completely new entry be
  2377.   ;; added for TO.  Actually, removing and adding anew would always be
  2378.   ;; the right (but slow) way of doing it.
  2379.  
  2380.   ;; The consequences are pretty harmless though (no updates since
  2381.   ;; dired-buffers-for-dir will not suspect it to be in this dired
  2382.   ;; buffer).
  2383.  
  2384.   (save-excursion
  2385.     (let ((regexp (regexp-quote (directory-file-name dir)))
  2386.       (newtext (directory-file-name to))
  2387.       buffer-read-only)
  2388.       (goto-char (dired-get-subdir-min elt))
  2389.       ;; Update subdir headerline in buffer
  2390.       (if (not (looking-at dired-subdir-regexp))
  2391.       (error "%s not found where expected - dired-subdir-alist broken?"
  2392.          dir)
  2393.     (goto-char (match-beginning 1))
  2394.     (if (re-search-forward regexp (match-end 1) t)
  2395.         (replace-match newtext t t)
  2396.       (error "Expected to find `%s' in headerline of %s" dir (car elt))))
  2397.       ;; Update buffer-local dired-subdir-alist
  2398.       (setcar elt
  2399.           (dired-normalize-subdir
  2400.            (dired-replace-in-string regexp newtext (car elt)))))))
  2401.  
  2402. ;; Cloning replace-match to work on strings instead of in buffer:
  2403. ;; The FIXEDCASE parameter of replace-match is not implemented.
  2404. (defun dired-string-replace-match (regexp string newtext
  2405.                       &optional literal global)
  2406.   "Replace first match of REGEXP in STRING with NEWTEXT.
  2407. If it does not match, nil is returned instead of the new string.
  2408. Optional arg LITERAL means to take NEWTEXT literally.
  2409. Optional arg GLOBAL means to replace all matches."
  2410.   (if global
  2411.         (let ((result "") (start 0) mb me)
  2412.       (while (string-match regexp string start)
  2413.         (setq mb (match-beginning 0)
  2414.           me (match-end 0)
  2415.           result (concat result
  2416.                  (substring string start mb)
  2417.                  (if literal
  2418.                      newtext
  2419.                    (dired-expand-newtext string newtext)))
  2420.           start me))
  2421.       (if mb            ; matched at least once
  2422.           (concat result (substring string start))
  2423.         nil))
  2424.     ;; not GLOBAL
  2425.     (if (not (string-match regexp string 0))
  2426.     nil
  2427.       (concat (substring string 0 (match-beginning 0))
  2428.           (if literal newtext (dired-expand-newtext string newtext))
  2429.           (substring string (match-end 0))))))
  2430.  
  2431. (defun dired-expand-newtext (string newtext)
  2432.   ;; Expand \& and \1..\9 (referring to STRING) in NEWTEXT, using match data.
  2433.   ;; Note that in Emacs 18 match data are clipped to current buffer
  2434.   ;; size...so the buffer should better not be smaller than STRING.
  2435.   (let ((pos 0)
  2436.     (len (length newtext))
  2437.     (expanded-newtext ""))
  2438.     (while (< pos len)
  2439.       (setq expanded-newtext
  2440.         (concat expanded-newtext
  2441.             (let ((c (aref newtext pos)))
  2442.               (if (= ?\\ c)
  2443.               (cond ((= ?\& (setq c
  2444.                           (aref newtext
  2445.                             (setq pos (1+ pos)))))
  2446.                  (substring string
  2447.                         (match-beginning 0)
  2448.                         (match-end 0)))
  2449.                 ((and (>= c ?1) (<= c ?9))
  2450.                  ;; return empty string if N'th
  2451.                  ;; sub-regexp did not match:
  2452.                  (let ((n (- c ?0)))
  2453.                    (if (match-beginning n)
  2454.                        (substring string
  2455.                           (match-beginning n)
  2456.                           (match-end n))
  2457.                      "")))
  2458.                 (t
  2459.                  (char-to-string c)))
  2460.             (char-to-string c)))))
  2461.       (setq pos (1+ pos)))
  2462.     expanded-newtext))
  2463.  
  2464. ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
  2465. (defun dired-create-files (file-creator operation fn-list name-constructor
  2466.                     &optional marker-char)
  2467.  
  2468. ;; Create a new file for each from a list of existing files.  The user
  2469. ;; is queried, dired buffers are updated, and at the end a success or
  2470. ;; failure message is displayed
  2471.  
  2472. ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
  2473.  
  2474. ;; It is called for each file and must create newfile, the entry of
  2475. ;; which will be added.  The user will be queried if the file already
  2476. ;; exists.  If oldfile is removed by FILE-CREATOR (i.e, it is a
  2477. ;; rename), it is FILE-CREATOR's responsibility to update dired
  2478. ;; buffers.  FILE-CREATOR must abort by signalling a file-error if it
  2479. ;; could not create newfile.  The error is caught and logged.
  2480.  
  2481. ;; OPERATION (a capitalized string, e.g. `Copy') describes the
  2482. ;; operation performed.  It is used for error logging.
  2483.  
  2484. ;; FN-LIST is the list of files to copy (full absolute pathnames).
  2485.  
  2486. ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
  2487. ;; skip.  If it skips files for other reasons than a direct user
  2488. ;; query, it is supposed to tell why (using dired-log).
  2489.  
  2490. ;; Optional MARKER-CHAR is a character with which to mark every
  2491. ;; newfile's entry, or t to use the current marker character if the
  2492. ;; oldfile was marked.
  2493.  
  2494.   (let (failures skipped (success-count 0) (total (length fn-list)))
  2495.     (let (to overwrite-query
  2496.          overwrite-backup-query)    ; for dired-handle-overwrite
  2497.       (mapcar
  2498.        (function
  2499.     (lambda (from)
  2500.       (setq to (funcall name-constructor from))
  2501.       (if (equal to from)
  2502.           (progn
  2503.         (setq to nil)
  2504.         (dired-log "Cannot %s to same file: %s\n"
  2505.                (downcase operation) from)))
  2506.       (if (not to)
  2507.           (setq skipped (cons (dired-make-relative from) skipped))
  2508.         (let* ((overwrite (file-exists-p to))
  2509.            (overwrite-confirmed    ; for dired-handle-overwrite
  2510.             (and overwrite
  2511.              (let ((help-form '(format "\
  2512. Type SPC or `y' to overwrite file `%s',
  2513. DEL or `n' to skip to next,
  2514. ESC or `q' to not overwrite any of the remaining files,
  2515. `!' to overwrite all remaining files with no more questions." to)))
  2516.                (dired-query 'overwrite-query
  2517.                     "Overwrite `%s'?" to))))
  2518.            ;; must determine if FROM is marked before file-creator
  2519.            ;; gets a chance to delete it (in case of a move).
  2520.            (actual-marker-char
  2521.             (cond  ((integerp marker-char) marker-char)
  2522.                (marker-char (dired-file-marker from)) ; slow
  2523.                (t nil))))
  2524.           (condition-case err
  2525.           (progn
  2526.             (funcall file-creator from to overwrite-confirmed)
  2527.             (if overwrite
  2528.             ;; If we get here, file-creator hasn't been aborted
  2529.             ;; and the old entry (if any) has to be deleted
  2530.             ;; before adding the new entry.
  2531.             (dired-remove-file to))
  2532.             (setq success-count (1+ success-count))
  2533.             (message "%s: %d of %d" operation success-count total)
  2534.             (dired-add-file to actual-marker-char))
  2535.         (file-error        ; FILE-CREATOR aborted
  2536.          (progn
  2537.            (setq failures (cons (dired-make-relative from) failures))
  2538.            (dired-log "%s `%s' to `%s' failed:\n%s\n"
  2539.                   operation from to err))))))))
  2540.        fn-list))
  2541.     (cond
  2542.      (failures
  2543.       (dired-log-summary
  2544.        (message "%s failed for %d of %d file%s %s"
  2545.         operation (length failures) total
  2546.         (dired-plural-s total) failures)))
  2547.      (skipped
  2548.       (dired-log-summary
  2549.        (message "%s: %d of %d file%s skipped %s"
  2550.         operation (length skipped) total
  2551.         (dired-plural-s total) skipped)))
  2552.      (t
  2553.       (message "%s: %s file%s."
  2554.            operation success-count (dired-plural-s success-count)))))
  2555.   (dired-move-to-filename))
  2556.  
  2557. (defun dired-do-create-files (op-symbol file-creator operation arg
  2558.                          &optional marker-char op1
  2559.                          how-to)
  2560.   ;; Create a new file for each marked file.
  2561.   ;; Prompts user for target, which is a directory in which to create
  2562.   ;;   the new files.  Target may be a plain file if only one marked
  2563.   ;;   file exists.
  2564.   ;; OP-SYMBOL is the symbol for the operation.  Function `dired-mark-pop-up'
  2565.   ;;   will determine wether pop-ups are appropriate for this OP-SYMBOL.
  2566.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2567.   ;; ARG as in dired-mark-get-files.
  2568.   ;; Optional arg OP1 is an alternate form for OPERATION if there is
  2569.   ;;   only one file.
  2570.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2571.   ;; Optional arg HOW-TO determines how to treat target:
  2572.   ;;   If HOW-TO is not given (or nil), and target is a directory, the
  2573.   ;;     file(s) are created inside the target directory.  If target
  2574.   ;;     is not a directory, there must be exactly one marked file,
  2575.   ;;     else error.
  2576.   ;;   If HOW-TO is t, then target is not modified.  There must be
  2577.   ;;     exactly one marked file, else error.
  2578.   ;; Else HOW-TO is assumed to be a function of one argument, target,
  2579.   ;;     that looks at target and returns a value for the into-dir
  2580.   ;;     variable.  The function dired-into-dir-with-symlinks is provided
  2581.   ;;     for the case (common when creating symlinks) that symbolic
  2582.   ;;     links to directories are not to be considered as directories
  2583.   ;;     (as file-directory-p would if HOW-TO had been nil).
  2584.   (or op1 (setq op1 operation))
  2585.   (let* ((fn-list (dired-mark-get-files nil arg))
  2586.      (fn-count (length fn-list))
  2587.      (target (expand-file-name
  2588.            (dired-mark-read-file-name
  2589.             (concat (if (= 1 fn-count) op1 operation) " %s to: ")
  2590.             (dired-dwim-target-directory)
  2591.             op-symbol arg (mapcar (function dired-make-relative) fn-list))))
  2592.      (into-dir (cond ((null how-to) (file-directory-p target))
  2593.              ((eq how-to t) nil)
  2594.              (t (funcall how-to target)))))
  2595.     (if (and (> fn-count 1)
  2596.          (not into-dir))
  2597.     (error "Marked %s: target must be a directory: %s" operation target))
  2598.     ;; rename-file bombs when moving directories unless we do this:
  2599.     (or into-dir (setq target (directory-file-name target)))
  2600.     (dired-create-files
  2601.      file-creator operation fn-list
  2602.      (if into-dir            ; target is a directory
  2603.      ;; This function uses fluid vars into-dir and target when called
  2604.      ;; inside dired-create-files:
  2605.      (function (lambda (from)
  2606.              (expand-file-name (file-name-nondirectory from) target)))
  2607.        (function (lambda (from) target)))
  2608.      marker-char)))
  2609.  
  2610. (defun dired-dwim-target-directory ()
  2611.   ;; Try to guess which target directory the user may want.
  2612.   ;; If there is a dired buffer displayed in the next window, use
  2613.   ;; its current subdir, else use current subdir of this dired buffer.
  2614.   (let ((this-dir (and (eq major-mode 'dired-mode)
  2615.                (dired-current-directory))))
  2616.     ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
  2617.     (if dired-dwim-target
  2618.     (let* ((other-buf (window-buffer (next-window)))
  2619.            (other-dir (save-excursion
  2620.                 (set-buffer other-buf)
  2621.                 (and (eq major-mode 'dired-mode)
  2622.                  (dired-current-directory)))))
  2623.       (or other-dir this-dir))
  2624.       this-dir)))
  2625.  
  2626. (defun dired-into-dir-with-symlinks (target)
  2627.   (and (file-directory-p target)
  2628.        (not (file-symlink-p target))))
  2629. ;; This may not always be what you want, especially if target is your
  2630. ;; home directory and it happens to be a symbolic link, as is often the
  2631. ;; case with NFS and automounters.  Or if you want to make symlinks
  2632. ;; into directories that themselves are only symlinks, also quite
  2633. ;; common.
  2634.  
  2635. ;; So we don't use this function as value for HOW-TO in
  2636. ;; dired-do-symlink, which has the minor disadvantage of
  2637. ;; making links *into* a symlinked-dir, when you really wanted to
  2638. ;; *overwrite* that symlink.  In that (rare, I guess) case, you'll
  2639. ;; just have to remove that symlink by hand before making your marked
  2640. ;; symlinks.
  2641.  
  2642. (defun dired-do-copy (&optional arg)
  2643.   "Copy all marked (or next ARG) files, or copy the current file.
  2644. Thus, a zero prefix argument copies nothing.  But it toggles the
  2645. variable `dired-copy-preserve-time' (which see)."
  2646.   (interactive "P")
  2647.   (if (not (zerop (prefix-numeric-value arg)))
  2648.       (dired-do-create-files 'copy (function dired-copy-file)
  2649.                    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2650.                    arg dired-keep-marker-copy)
  2651.     (setq dired-copy-preserve-time (not dired-copy-preserve-time))
  2652.     (if dired-copy-preserve-time
  2653.     (message "Copy will preserve time.")
  2654.       (message "Copied files will get current date."))))
  2655.  
  2656. (defun dired-do-symlink (&optional arg)
  2657.    "Symlink all marked (or next ARG) files into a directory,
  2658. or make a symbolic link to the current file."
  2659.   (interactive "P")
  2660.   (dired-do-create-files 'symlink (function make-symbolic-link)
  2661.                "SymLink" arg dired-keep-marker-symlink))
  2662.  
  2663. (defun dired-do-hardlink (&optional arg)
  2664.    "Hard-link all marked (or next ARG) files into a directory,
  2665. or make a hard link to the current file."
  2666.   (interactive "P")
  2667.   (dired-do-create-files 'hardlink (function add-name-to-file)
  2668.                "HardLink" arg dired-keep-marker-hardlink))
  2669.  
  2670. (defun dired-do-move (&optional arg)
  2671.   "Move all marked (or next ARG) files into a directory,
  2672. or rename the current file.
  2673. A zero ARG moves no files but toggles `dired-dwim-target' (which see)."
  2674.   (interactive "P")
  2675.   (if (not (zerop (prefix-numeric-value arg)))
  2676.       (dired-do-create-files 'move (function dired-rename-file)
  2677.                    "Move" arg dired-keep-marker-move "Rename")
  2678.     (setq dired-dwim-target (not dired-dwim-target))
  2679.     (message "dired-dwim-target is %s." (if dired-dwim-target "ON" "OFF"))))
  2680.  
  2681. ;;;###end dired-cp.el
  2682.  
  2683. ;;; 5K
  2684. ;;;###begin dired-re.el
  2685. (defun dired-do-create-files-regexp
  2686.   (file-creator operation arg regexp newname &optional whole-path marker-char)
  2687.   ;; Create a new file for each marked file using regexps.
  2688.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2689.   ;; ARG as in dired-mark-get-files.
  2690.   ;; Matches each marked file against REGEXP and constructs the new
  2691.   ;;   filename from NEWNAME (like in function replace-match).
  2692.   ;; Optional arg WHOLE-PATH means match/replace the whole pathname
  2693.   ;;   instead of only the non-directory part of the file.
  2694.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2695.   (let* ((fn-list (dired-mark-get-files nil arg))
  2696.      (fn-count (length fn-list))
  2697.      (operation-prompt (concat operation " `%s' to `%s'?"))
  2698.      (rename-regexp-help-form (format "\
  2699. Type SPC or `y' to %s one match, DEL or `n' to skip to next,
  2700. `!' to %s all remaining matches with no more questions."
  2701.                       (downcase operation)
  2702.                       (downcase operation)))
  2703.      (regexp-name-constructor
  2704.       ;; Function to construct new filename using REGEXP and NEWNAME:
  2705.       (if whole-path        ; easy (but rare) case
  2706.           (function
  2707.            (lambda (from)
  2708.          (let ((to (dired-string-replace-match regexp from newname))
  2709.                ;; must bind help-form directly around call to
  2710.                ;; dired-query
  2711.                (help-form rename-regexp-help-form))
  2712.            (if to
  2713.                (and (dired-query 'rename-regexp-query
  2714.                      operation-prompt
  2715.                      from
  2716.                      to)
  2717.                 to)
  2718.              (dired-log "%s: %s did not match regexp %s\n"
  2719.                 operation from regexp)))))
  2720.         ;; not whole-path, replace non-directory part only
  2721.         (function
  2722.          (lambda (from)
  2723.            (let* ((new (dired-string-replace-match
  2724.                 regexp (file-name-nondirectory from) newname))
  2725.               (to (and new    ; nil means there was no match
  2726.                    (expand-file-name new
  2727.                          (file-name-directory from))))
  2728.               (help-form rename-regexp-help-form))
  2729.          (if to
  2730.              (and (dired-query 'rename-regexp-query
  2731.                        operation-prompt
  2732.                        (dired-make-relative from)
  2733.                        (dired-make-relative to))
  2734.               to)
  2735.            (dired-log "%s: %s did not match regexp %s\n"
  2736.                   operation (file-name-nondirectory from) regexp)))))))
  2737.      rename-regexp-query)
  2738.     (dired-create-files
  2739.      file-creator operation fn-list regexp-name-constructor marker-char)))
  2740.  
  2741. (defun dired-mark-read-regexp (operation)
  2742.   ;; Prompt user about performing OPERATION.
  2743.   ;; Read and return list of: regexp newname arg whole-path.
  2744.   (let* ((whole-path
  2745.       (equal 0 (prefix-numeric-value current-prefix-arg)))
  2746.      (arg
  2747.       (if whole-path nil current-prefix-arg))
  2748.      (regexp
  2749.       (dired-read-regexp
  2750.        (concat (if whole-path "Path " "") operation " from (regexp): ")
  2751.        dired-flagging-regexp))
  2752.      (newname
  2753.       (read-string
  2754.        (concat (if whole-path "Path " "") operation " " regexp " to: "))))
  2755.     (list regexp newname arg whole-path)))
  2756.  
  2757. (defun dired-do-rename-regexp (regexp newname &optional arg whole-path)
  2758.   "Rename marked files containing REGEXP to NEWNAME.
  2759. As each match is found, the user must type a character saying
  2760.   what to do with it.  For directions, type \\[help-command] at that time.
  2761. NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
  2762. REGEXP defaults to the last regexp used.
  2763. With a zero prefix arg, renaming by regexp affects the complete
  2764.   pathname - usually only the non-directory part of file names is used
  2765.   and changed."
  2766.   (interactive (dired-mark-read-regexp "Rename"))
  2767.   (dired-do-create-files-regexp
  2768.    (function dired-rename-file)
  2769.    "Rename" arg regexp newname whole-path dired-keep-marker-move))
  2770.  
  2771. (defun dired-do-copy-regexp (regexp newname &optional arg whole-path)
  2772.   "Copy all marked files containing REGEXP to NEWNAME.
  2773. See function `dired-rename-regexp' for more info."
  2774.   (interactive (dired-mark-read-regexp "Copy"))
  2775.   (dired-do-create-files-regexp
  2776.    (function dired-copy-file)
  2777.    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2778.    arg regexp newname whole-path dired-keep-marker-copy))
  2779.  
  2780. (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-path)
  2781.   "Hardlink all marked files containing REGEXP to NEWNAME.
  2782. See function `dired-rename-regexp' for more info."
  2783.   (interactive (dired-mark-read-regexp "HardLink"))
  2784.   (dired-do-create-files-regexp
  2785.    (function add-name-to-file)
  2786.    "HardLink" arg regexp newname whole-path dired-keep-marker-hardlink))
  2787.  
  2788. (defun dired-do-symlink-regexp (regexp newname &optional arg whole-path)
  2789.   "Symlink all marked files containing REGEXP to NEWNAME.
  2790. See function `dired-rename-regexp' for more info."
  2791.   (interactive (dired-mark-read-regexp "SymLink"))
  2792.   (dired-do-create-files-regexp
  2793.    (function make-symbolic-link)
  2794.    "SymLink" arg regexp newname whole-path dired-keep-marker-symlink))
  2795.  
  2796. (defun dired-create-files-non-directory
  2797.   (file-creator basename-constructor operation arg)
  2798.   ;; Perform FILE-CREATOR on the non-directory part of marked files
  2799.   ;; using function BASENAME-CONSTRUCTOR, with query for each file.
  2800.   ;; OPERATION like in dired-create-files, ARG like in dired-mark-get-files.
  2801.   (let (rename-non-directory-query)
  2802.     (dired-create-files
  2803.      file-creator
  2804.      operation
  2805.      (dired-mark-get-files nil arg)
  2806.      (function
  2807.       (lambda (from)
  2808.     (let ((to (concat (file-name-directory from)
  2809.               (funcall basename-constructor
  2810.                    (file-name-nondirectory from)))))
  2811.       (and (let ((help-form (format "\
  2812. Type SPC or `y' to %s one file, DEL or `n' to skip to next,
  2813. `!' to %s all remaining matches with no more questions."
  2814.                     (downcase operation)
  2815.                     (downcase operation))))
  2816.          (dired-query 'rename-non-directory-query
  2817.                   (concat operation " `%s' to `%s'")
  2818.                   (dired-make-relative from)
  2819.                   (dired-make-relative to)))
  2820.            to))))
  2821.      dired-keep-marker-move)))
  2822.  
  2823. (defun dired-rename-non-directory (basename-constructor operation arg)
  2824.   (dired-create-files-non-directory
  2825.    (function dired-rename-file)
  2826.    basename-constructor operation arg))
  2827.  
  2828. (defun dired-upcase (&optional arg)
  2829.   "Rename all marked (or next ARG) files to upper case."
  2830.   (interactive "P")
  2831.   (dired-rename-non-directory (function upcase) "Rename upcase" arg))
  2832.  
  2833. (defun dired-downcase (&optional arg)
  2834.   "Rename all marked (or next ARG) files to lower case."
  2835.   (interactive "P")
  2836.   (dired-rename-non-directory (function downcase) "Rename downcase" arg))
  2837.  
  2838. ;;;###end dired-re.el
  2839.  
  2840.  
  2841. ;; Tree Dired
  2842.  
  2843. ;;; utility functions
  2844.  
  2845. (defun dired-in-this-tree (file dir)
  2846.   ;;"Is FILE part of the directory tree starting at DIR?"
  2847.   (let (case-fold-search)
  2848.     (string-match (concat "^" (regexp-quote dir)) file)))
  2849.  
  2850. (defun dired-make-absolute (file &optional dir)
  2851.   ;;"Convert FILE (a pathname relative to DIR) to an absolute pathname."
  2852.   ;; We can't always use expand-file-name as this would get rid of `.'
  2853.   ;; or expand in / instead default-directory if DIR=="".
  2854.   ;; This should be good enough for ange-ftp, but might easily be
  2855.   ;; redefined (for VMS?).
  2856.   ;; It should be reasonably fast, though, as it is called in
  2857.   ;; dired-get-filename.
  2858.   (concat (or dir default-directory) file))
  2859.  
  2860. (defun dired-make-relative (file &optional dir no-error)
  2861.   ;;"Convert FILE (an absolute pathname) to a pathname relative to DIR.
  2862.   ;; Else error (unless NO-ERROR is non-nil, then FILE is returned unchanged)
  2863.   ;;DIR defaults to default-directory."
  2864.   ;; DIR must be file-name-as-directory, as with all directory args in
  2865.   ;; elisp code.
  2866.   (or dir (setq dir default-directory))
  2867.   (if (string-match (concat "^" (regexp-quote dir)) file)
  2868.       (substring file (match-end 0))
  2869.     (if no-error
  2870.     file
  2871.       (error  "%s: not in directory tree growing at %s" file dir))))
  2872.  
  2873. (defun dired-normalize-subdir (dir)
  2874.   ;; Prepend default-directory to DIR if relative path name.
  2875.   ;; dired-get-filename must be able to make a valid filename from a
  2876.   ;; file and its directory DIR.
  2877.   (file-name-as-directory
  2878.    (if (file-name-absolute-p dir)
  2879.        dir
  2880.      (expand-file-name dir default-directory))))
  2881.  
  2882. (defun dired-between-files ()
  2883.   ;; Point must be at beginning of line
  2884.   ;; Should be equivalent to (save-excursion (not (dired-move-to-filename)))
  2885.   ;; but is about 1.5..2.0 times as fast. (Actually that's not worth it)
  2886.   (or (looking-at "^$\\|^. *$\\|^. total\\|^. wildcard")
  2887.       (looking-at dired-subdir-regexp)))
  2888.  
  2889. (defun dired-get-subdir ()
  2890.   ;;"Return the subdir name on this line, or nil if not on a headerline."
  2891.   ;; Look up in the alist whether this is a headerline.
  2892.   (save-excursion
  2893.     (let ((cur-dir (dired-current-directory)))
  2894.       (beginning-of-line)        ; alist stores b-o-l positions
  2895.       (and (zerop (- (point)
  2896.              (dired-get-subdir-min (assoc cur-dir
  2897.                           dired-subdir-alist))))
  2898.        cur-dir))))
  2899.  
  2900. ;(defun dired-get-subdir-min (elt)
  2901. ;  (cdr elt))
  2902. ;; can't use macro,  must be redefinable for other alist format in dired-nstd.
  2903. (fset 'dired-get-subdir-min 'cdr)
  2904.  
  2905. (defun dired-get-subdir-max (elt)
  2906.   (save-excursion
  2907.     (goto-char (dired-get-subdir-min elt))
  2908.     (dired-subdir-max)))
  2909.  
  2910. (defun dired-clear-alist ()
  2911.   (while dired-subdir-alist
  2912.     (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
  2913.     (setq dired-subdir-alist (cdr dired-subdir-alist))))
  2914.  
  2915. (defun dired-simple-subdir-alist ()
  2916.   ;; Build and return `dired-subdir-alist' assuming just the top level
  2917.   ;; directory to be inserted.  Don't parse the buffer.
  2918.   (set (make-local-variable 'dired-subdir-alist)
  2919.        (list (cons default-directory (point-min-marker)))))
  2920.  
  2921. (defun dired-build-subdir-alist ()
  2922.   "Build `dired-subdir-alist' by parsing the buffer and return it's new value."
  2923.   (interactive)
  2924.   (dired-clear-alist)
  2925.   (save-excursion
  2926.     (let ((count 0))
  2927.       (goto-char (point-min))
  2928.       (setq dired-subdir-alist nil)
  2929.       (while (re-search-forward dired-subdir-regexp nil t)
  2930.     (setq count (1+ count))
  2931.     (dired-alist-add-1 (buffer-substring (match-beginning 1)
  2932.                          (match-end 1))
  2933.              ;; Put subdir boundary between lines:
  2934.              (save-excursion
  2935.                (goto-char (match-beginning 0))
  2936.                (beginning-of-line)
  2937.                (point-marker)))
  2938.     (message "%d" count))
  2939.       (message "%d director%s." count (if (= 1 count) "y" "ies"))
  2940.       ;; We don't need to sort it because it is in buffer order per
  2941.       ;; constructionem.  Return new alist:
  2942.       dired-subdir-alist)))
  2943.  
  2944. (defun dired-alist-add (dir new-marker)
  2945.   ;; Add new DIR at NEW-MARKER.  Sort alist.
  2946.   (dired-alist-add-1 dir new-marker)
  2947.   (dired-alist-sort))
  2948.  
  2949. (defun dired-alist-add-1 (dir new-marker)
  2950.   ;; Add new DIR at NEW-MARKER.  Don't sort.
  2951.   (setq dired-subdir-alist
  2952.     (cons (cons (dired-normalize-subdir dir) new-marker)
  2953.           dired-subdir-alist)))
  2954.  
  2955. (defun dired-alist-sort ()
  2956.   ;; Keep the alist sorted on buffer position.
  2957.   (setq dired-subdir-alist
  2958.     (sort dired-subdir-alist
  2959.           (function (lambda (elt1 elt2)
  2960.               (> (dired-get-subdir-min elt1)
  2961.                  (dired-get-subdir-min elt2)))))))
  2962.  
  2963. (defun dired-unsubdir (dir)
  2964.   ;; Remove DIR from the alist
  2965.   (setq dired-subdir-alist
  2966.     (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
  2967.  
  2968. (defun dired-goto-next-nontrivial-file ()
  2969.   ;; Position point on first nontrivial file after point.
  2970.   (dired-goto-next-file);; so there is a file to compare with
  2971.   (if (stringp dired-trivial-filenames)
  2972.       (while (and (not (eobp))
  2973.           (string-match dired-trivial-filenames
  2974.                 (file-name-nondirectory
  2975.                  (or (dired-get-filename nil t) ""))))
  2976.     (forward-line 1)
  2977.     (dired-move-to-filename))))
  2978.  
  2979. (defun dired-goto-next-file ()
  2980.   (let ((max (1- (dired-subdir-max))))
  2981.     (while (and (not (dired-move-to-filename)) (< (point) max))
  2982.       (forward-line 1))))
  2983.  
  2984. (defun dired-goto-subdir (dir)
  2985.   "Goto end of header line of DIR in this dired buffer.
  2986. Return value of point on success, otherwise return nil.
  2987. The next char is either \\n, or \\r if DIR is hidden."
  2988.   (interactive
  2989.    (prog1                ; let push-mark display its message
  2990.        (list (expand-file-name
  2991.           (completing-read "Goto in situ directory: " ; prompt
  2992.                    dired-subdir-alist ; table
  2993.                    nil    ; predicate
  2994.                    t    ; require-match
  2995.                    (dired-current-directory))))
  2996.      (push-mark)))
  2997.   (setq dir (file-name-as-directory dir))
  2998.   (let ((elt (assoc dir dired-subdir-alist)))
  2999.     (and elt
  3000.      (goto-char (dired-get-subdir-min elt))
  3001.      ;; dired-subdir-hidden-p and dired-add-entry depend on point being
  3002.      ;; at either \r or \n after this function succeeds.
  3003.      (progn (skip-chars-forward "^\r\n")
  3004.         (point)))))
  3005.  
  3006. (defun dired-goto-file (file)
  3007.   "Goto file line of FILE in this dired buffer."
  3008.   ;; Return value of point on success, else nil.
  3009.   ;; FILE must be an absolute pathname.
  3010.   ;; Loses if FILE contains control chars like "\007" for which ls
  3011.   ;; either inserts "?" or "\\007" into the buffer, so we won't find
  3012.   ;; it in the buffer.
  3013.   (interactive
  3014.    (prog1                ; let push-mark display its message
  3015.        (list (expand-file-name
  3016.           (read-file-name "Goto file: "
  3017.                   (dired-current-directory))))
  3018.      (push-mark)))
  3019.   (setq file (directory-file-name file)) ; does no harm if no directory
  3020.   (let (found case-fold-search)
  3021.     (save-excursion
  3022.       (if (dired-goto-subdir (or (file-name-directory file)
  3023.                  (error "Need absolute pathname for %s" file)))
  3024.       (let ((base (file-name-nondirectory file))
  3025.         (boundary (dired-subdir-max)))
  3026.         (while (and (not found)
  3027.             ;; filenames are preceded by SPC, this makes
  3028.             ;; the search faster (e.g. for the filename "-"!).
  3029.             (search-forward (concat " " base) boundary 'move))
  3030.           ;; Match could have BASE just as initial substring or
  3031.           ;; or in permission bits or date or
  3032.           ;; not be a proper filename at all:
  3033.           (if (equal base (dired-get-filename 'no-dir t))
  3034.             ;; Must move to filename since an (actually
  3035.             ;; correct) match could have been elsewhere on the
  3036.             ;; ;; line (e.g. "-" would match somewhere in the
  3037.             ;; permission bits).
  3038.           (setq found (dired-move-to-filename)))))))
  3039.     (and found
  3040.      ;; return value of point (i.e., FOUND):
  3041.      (goto-char found))))
  3042.  
  3043. (defun dired-initial-position (dirname)
  3044.   ;; Where point should go in a new listing of DIRNAME.
  3045.   ;; Point assumed at beginning of new subdir line.
  3046.   ;; You may redefine this function as you wish, e.g. like in dired-x.el.
  3047.   (end-of-line)
  3048.   (if dired-trivial-filenames (dired-goto-next-nontrivial-file)))
  3049.  
  3050. ;;; moving by subdirectories
  3051.  
  3052. (defun dired-subdir-index (dir)
  3053.   ;; Return an index into alist for use with nth
  3054.   ;; for the sake of subdir moving commands.
  3055.   (let (found (index 0) (alist dired-subdir-alist))
  3056.     (while alist
  3057.       (if (string= dir (car (car alist)))
  3058.       (setq alist nil found t)
  3059.     (setq alist (cdr alist) index (1+ index))))
  3060.     (if found index nil)))
  3061.  
  3062. (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
  3063.   "Go to next subdirectory, regardless of level."
  3064.   ;; Use 0 arg to go to this directory's header line.
  3065.   ;; NO-SKIP prevents moving to end of header line, returning whatever
  3066.   ;; position was found in dired-subdir-alist.
  3067.   (interactive "p")
  3068.   (let ((this-dir (dired-current-directory))
  3069.     pos index)
  3070.     ;; nth with negative arg does not return nil but the first element
  3071.     (setq index (- (dired-subdir-index this-dir) arg))
  3072.     (setq pos (if (>= index 0)
  3073.           (dired-get-subdir-min (nth index dired-subdir-alist))))
  3074.     (if pos
  3075.     (progn
  3076.       (goto-char pos)
  3077.       (or no-skip (skip-chars-forward "^\n\r"))
  3078.       (point))
  3079.       (if no-error-if-not-found
  3080.       nil                ; return nil if not found
  3081.     (error "%s directory" (if (> arg 0) "Last" "First"))))))
  3082.  
  3083. (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
  3084.   "Go to previous subdirectory, regardless of level.
  3085. When called interactively and not on a subdir line, go to this subdir's line."
  3086.   ;;(interactive "p")
  3087.   (interactive
  3088.    (list (if current-prefix-arg
  3089.          (prefix-numeric-value current-prefix-arg)
  3090.        ;; if on subdir start already, don't stay there!
  3091.        (if (dired-get-subdir) 1 0))))
  3092.   (dired-next-subdir (- arg) no-error-if-not-found no-skip))
  3093.  
  3094. (defun dired-tree-up (arg)
  3095.   "Go up ARG levels in the dired tree."
  3096.   (interactive "p")
  3097.   (let ((dir (dired-current-directory)))
  3098.     (while (>= arg 1)
  3099.       (setq arg (1- arg)
  3100.         dir (file-name-directory (directory-file-name dir))))
  3101.     ;;(setq dir (expand-file-name dir))
  3102.     (or (dired-goto-subdir dir)
  3103.     (error "Cannot go up to %s - not in this tree." dir))))
  3104.  
  3105. (defun dired-tree-down ()
  3106.   "Go down in the dired tree."
  3107.   (interactive)
  3108.   (let ((dir (dired-current-directory)) ; has slash
  3109.     pos case-fold-search)        ; filenames are case sensitive
  3110.     (let ((rest (reverse dired-subdir-alist)) elt)
  3111.       (while rest
  3112.     (setq elt (car rest)
  3113.           rest (cdr rest))
  3114.     (if (dired-in-this-tree (directory-file-name (car elt)) dir)
  3115.         (setq rest nil
  3116.           pos (dired-goto-subdir (car elt))))))
  3117.     (if pos
  3118.     (goto-char pos)
  3119.       (error "At the bottom"))))
  3120.  
  3121. ;;; hiding
  3122.  
  3123. (defun dired-subdir-hidden-p (dir)
  3124.   (and selective-display
  3125.        (save-excursion
  3126.      (dired-goto-subdir dir)
  3127.      (looking-at "\r"))))
  3128.  
  3129. (defun dired-unhide-subdir ()
  3130.   (let (buffer-read-only)
  3131.     (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
  3132.  
  3133. (defun dired-hide-check ()
  3134.   (or selective-display
  3135.       (error "selective-display must be t for subdir hiding to work!")))
  3136.  
  3137. (defun dired-hide-subdir (arg)
  3138.   "Hide or unhide the current subdirectory and move to next directory.
  3139. Optional prefix arg is a repeat factor.
  3140. Use \\[dired-hide-all] to (un)hide all directories."
  3141.   (interactive "p")
  3142.   (dired-hide-check)
  3143.   (while (>=  (setq arg (1- arg)) 0)
  3144.     (let* ((cur-dir (dired-current-directory))
  3145.        (hidden-p (dired-subdir-hidden-p cur-dir))
  3146.        (elt (assoc cur-dir dired-subdir-alist))
  3147.        (end-pos (1- (dired-get-subdir-max elt)))
  3148.        buffer-read-only)
  3149.       ;; keep header line visible, hide rest
  3150.       (goto-char (dired-get-subdir-min elt))
  3151.       (skip-chars-forward "^\n\r")
  3152.       (if hidden-p
  3153.       (subst-char-in-region (point) end-pos ?\r ?\n)
  3154.     (subst-char-in-region (point) end-pos ?\n ?\r)))
  3155.     (dired-next-subdir 1 t)))
  3156.  
  3157. (defun dired-hide-all (arg)
  3158.   "Hide all subdirectories, leaving only their header lines.
  3159. If there is already something hidden, make everything visible again.
  3160. Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
  3161.   (interactive "P")
  3162.   (dired-hide-check)
  3163.   (let (buffer-read-only)
  3164.     (if (save-excursion
  3165.       (goto-char (point-min))
  3166.       (search-forward "\r" nil t))
  3167.     ;; unhide - bombs on \r in filenames
  3168.     (subst-char-in-region (point-min) (point-max) ?\r ?\n)
  3169.       ;; hide
  3170.       (let ((pos (point-max))        ; pos of end of last directory
  3171.         (alist dired-subdir-alist))
  3172.     (while alist            ; while there are dirs before pos
  3173.       (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
  3174.                 (save-excursion
  3175.                   (goto-char pos) ; current dir
  3176.                   ;; we're somewhere on current dir's line
  3177.                   (forward-line -1)
  3178.                   (point))
  3179.                 ?\n ?\r)
  3180.       (setq pos (dired-get-subdir-min (car alist)))    ; prev dir gets current dir
  3181.       (setq alist (cdr alist)))))))
  3182.  
  3183.  
  3184. ;; This function is the heart of tree dired.
  3185. ;; It is called for each retrieved filename.
  3186. ;; It could stand to be faster, though it's mostly function call
  3187. ;; overhead.  Avoiding to funcall seems to save about 10% in
  3188. ;; dired-get-filename.  Make it a defsubst?
  3189. (defun dired-current-directory (&optional localp)
  3190.   "Return the name of the subdirectory to which this line belongs.
  3191. This returns a string with trailing slash, like `default-directory'.
  3192. Optional argument means return a file name relative to `default-directory'."
  3193.   (let ((here (point))
  3194.     (alist (or dired-subdir-alist
  3195.            ;; probably because called in a non-dired buffer
  3196.            (error "No subdir-alist in %s" (current-buffer))))
  3197.     elt dir)
  3198.     (while alist
  3199.       (setq elt (car alist)
  3200.         dir (car elt)
  3201.         ;; use `<=' (not `<') as subdir line is part of subdir
  3202.         alist (if (<= (dired-get-subdir-min elt) here)
  3203.               nil        ; found
  3204.             (cdr alist))))
  3205.     (if localp
  3206.     (dired-make-relative dir default-directory)
  3207.       dir)))
  3208.  
  3209. ;; Subdirs start at the beginning of their header lines and end just
  3210. ;; before the beginning of the next header line (or end of buffer).
  3211.  
  3212. (defun dired-subdir-min ()
  3213.   (save-excursion
  3214.     (if (not (dired-prev-subdir 0 t t))
  3215.     (error "Not in a subdir!")
  3216.       (point))))
  3217.  
  3218. (defun dired-subdir-max ()
  3219.   (save-excursion
  3220.     (if (not (dired-next-subdir 1 t t))
  3221.     (point-max)
  3222.       (point))))
  3223.  
  3224. (defun dired-kill-line-or-subdir (&optional arg)
  3225.   "Kill this line (but not this file).
  3226. Optional prefix argument is a repeat factor.
  3227. If file is displayed as in situ subdir, kill that as well.
  3228. If on a subdir headerline, kill whole subdir."
  3229.   (interactive "p")
  3230.   (if (dired-get-subdir)
  3231.       (dired-kill-subdir)
  3232.     (dired-kill-line arg)))
  3233.  
  3234. (defun dired-kill-line (&optional arg)
  3235.   (interactive "P")
  3236.   (setq arg (prefix-numeric-value arg))
  3237.   (let (buffer-read-only file)
  3238.     (while (/= 0 arg)
  3239.       (setq file (dired-get-filename nil t))
  3240.       (if (not file)
  3241.       (error "Can only kill file lines.")
  3242.     (save-excursion (and file
  3243.                  (dired-goto-subdir file)
  3244.                  (dired-kill-subdir)))
  3245.     (delete-region (progn (beginning-of-line) (point))
  3246.                (progn (forward-line 1) (point)))
  3247.     (if (> arg 0)
  3248.         (setq arg (1- arg))
  3249.       (setq arg (1+ arg))
  3250.       (forward-line -1))))
  3251.     (dired-move-to-filename)))
  3252.  
  3253. (defun dired-kill-subdir (&optional remember-marks)
  3254.   "Remove all lines of current subdirectory.
  3255. Lower levels are unaffected."
  3256.   ;; With optional REMEMBER-MARKS, return a mark-alist.
  3257.   (interactive)
  3258.   (let ((beg (dired-subdir-min))
  3259.     (end (dired-subdir-max))
  3260.     buffer-read-only cur-dir)
  3261.     (setq cur-dir (dired-current-directory))
  3262.     (if (equal cur-dir default-directory)
  3263.     (error "Attempt to kill top level directory"))
  3264.     (prog1
  3265.     (if remember-marks (dired-remember-marks beg end))
  3266.       (delete-region beg end)
  3267.       (if (eobp)            ; don't leave final blank line
  3268.       (delete-char -1))
  3269.       (dired-unsubdir cur-dir))))
  3270.  
  3271. (defun dired-do-kill (&optional arg fmt)
  3272.   "Kill all marked lines (not files).
  3273. With a prefix arg, kill all lines not marked or flagged."
  3274.   ;; Returns count of killed lines.  FMT="" suppresses message.
  3275.   (interactive "P")
  3276.   (save-excursion
  3277.     (goto-char (point-min))
  3278.     (let (buffer-read-only (count 0))
  3279.       (if (not arg)            ; kill marked lines
  3280.       (let ((regexp (dired-marker-regexp)))
  3281.         (while (and (not (eobp))
  3282.             (re-search-forward regexp nil t))
  3283.           (setq count (1+ count))
  3284.           (delete-region (progn (beginning-of-line) (point))
  3285.                  (progn (forward-line 1) (point)))))
  3286.     ;; else kill unmarked lines
  3287.     (while (not (eobp))
  3288.       (if (or (dired-between-files)
  3289.           (not (looking-at "^  ")))
  3290.           (forward-line 1)
  3291.         (setq count (1+ count))
  3292.         (delete-region (point) (save-excursion
  3293.                      (forward-line 1)
  3294.                      (point))))))
  3295.       (or (equal "" fmt)
  3296.       (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
  3297.       count)))
  3298.  
  3299. (defun dired-do-redisplay (&optional arg test-for-subdir)
  3300.   "Redisplay all marked (or next ARG) files.
  3301.  
  3302. If on a subdir line, redisplay that subdirectory.  In that case,
  3303. a prefix arg lets you edit the ls switches used for the new listing."
  3304.   ;; Moves point if the next ARG files are redisplayed.
  3305.   (interactive "P\np")
  3306.   (if (and test-for-subdir (dired-get-subdir))
  3307.       (dired-insert-subdir
  3308.        (dired-get-subdir)
  3309.        (if arg (read-string "Switches for listing: " dired-actual-switches)))
  3310.     (message "Redisplaying...")
  3311.     ;; message instead of making dired-mark-map show-progress is much faster
  3312.     (dired-mark-map (let ((fname (dired-get-filename)))
  3313.               (message "Redisplaying... %s" fname)
  3314.               (dired-update-file-line fname))
  3315.             arg)
  3316.     (dired-move-to-filename)
  3317.     (message "Redisplaying...done")))
  3318.  
  3319. (defun dired-mark-files-in-region (start end)
  3320.   (let (buffer-read-only)
  3321.     (if (> start end)
  3322.     (error "start > end"))
  3323.     (goto-char start)            ; assumed at beginning of line
  3324.     (while (< (point) end)
  3325.       ;; Skip subdir line and following garbage like the `total' line:
  3326.       (while (and (< (point) end) (dired-between-files))
  3327.     (forward-line 1))
  3328.       (if (and (not (looking-at dired-re-dot))
  3329.            (dired-get-filename nil t))
  3330.       (progn
  3331.         (delete-char 1)
  3332.         (insert dired-marker-char)))
  3333.       (forward-line 1))))
  3334.  
  3335. (defun dired-mark-subdir-files ()
  3336.   "Mark all files except `.' and `..'."
  3337.   (interactive "P")
  3338.   (let ((p-min (dired-subdir-min)))
  3339.     (dired-mark-files-in-region p-min (dired-subdir-max))))
  3340.  
  3341. (defun dired-mark-subdir-or-file (arg)
  3342.   "Mark the current (or next ARG) files.
  3343. If on a subdir headerline, mark all its files except `.' and `..'.
  3344.  
  3345. Use \\[dired-unflag-all-files] to remove all marks
  3346. and \\[dired-unmark-subdir-or-file] on a subdir to remove the marks in
  3347. this subdir."
  3348.   (interactive "P")
  3349.   (if (dired-get-subdir)
  3350.       (save-excursion (dired-mark-subdir-files))
  3351.     (dired-mark-file (prefix-numeric-value arg))))
  3352.  
  3353. (defun dired-unmark-subdir-or-file (arg)
  3354.   "Unmark the current (or next ARG) files.
  3355. If looking at a subdir, unmark all its files except `.' and `..'."
  3356.   (interactive "P")
  3357.   (let ((dired-marker-char ?\040))
  3358.     (dired-mark-subdir-or-file arg)))
  3359.  
  3360. ;;; 5K
  3361. ;;;###begin dired-ins.el
  3362.  
  3363. (defun dired-maybe-insert-subdir (dirname &optional
  3364.                       switches no-error-if-not-dir-p)
  3365.   "Insert this subdirectory into the same dired buffer.
  3366. If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
  3367.   else inserts it at its natural place (as ls -lR would have done).
  3368. With a prefix arg, you may edit the ls switches used for this listing.
  3369.   You can add `R' to the switches to expand the whole tree starting at
  3370.   this subdirectory.
  3371. This function takes some pains to conform to ls -lR output."
  3372.   (interactive
  3373.    (list (dired-get-filename)
  3374.      (if current-prefix-arg
  3375.          (read-string "Switches for listing: " dired-actual-switches))))
  3376.   (let ((opoint (point)))
  3377.     ;; We don't need a marker for opoint as the subdir is always
  3378.     ;; inserted *after* opoint.
  3379.     (setq dirname (file-name-as-directory dirname))
  3380.     (or (and (not switches)
  3381.          (dired-goto-subdir dirname))
  3382.     (dired-insert-subdir dirname switches no-error-if-not-dir-p))
  3383.     ;; Push mark so that it's easy to find back.  Do this after the
  3384.     ;; insert message so that the user sees the `Mark set' message.
  3385.     (push-mark opoint)))
  3386.  
  3387. (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
  3388.   "Insert this subdirectory into the same dired buffer.
  3389. If it is already present, overwrites previous entry,
  3390.   else inserts it at its natural place (as ls -lR would have done).
  3391. With a prefix arg, you may edit the ls switches used for this listing.
  3392.   You can add `R' to the switches to expand the whole tree starting at
  3393.   this subdirectory.
  3394. This function takes some pains to conform to ls -lR output."
  3395.   ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
  3396.   ;; Prospero where dired-ls does the right thing, but
  3397.   ;; file-directory-p has not been redefined.
  3398.   (interactive
  3399.    (list (dired-get-filename)
  3400.      (if current-prefix-arg
  3401.          (read-string "Switches for listing: " dired-actual-switches))))
  3402.   (setq dirname (file-name-as-directory (expand-file-name dirname)))
  3403.   (dired-insert-subdir-validate dirname switches)
  3404.   (or no-error-if-not-dir-p
  3405.       (file-directory-p dirname)
  3406.       (error  "Attempt to insert a non-directory: %s" dirname))
  3407.   (let ((elt (assoc dirname dired-subdir-alist))
  3408.      switches-have-R mark-alist case-fold-search buffer-read-only)
  3409.     ;; case-fold-search is nil now, so we can test for capital `R':
  3410.     (if (setq switches-have-R (and switches (string-match "R" switches)))
  3411.     ;; avoid duplicated subdirs
  3412.     (setq mark-alist (dired-kill-tree dirname t)))
  3413.     (if elt
  3414.     ;; If subdir is already present, remove it and remember its marks
  3415.     (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
  3416.       (dired-insert-subdir-newpos dirname)) ; else compute new position
  3417.     (dired-insert-subdir-doupdate
  3418.      dirname elt (dired-insert-subdir-doinsert dirname switches))
  3419.     (if switches-have-R (dired-build-subdir-alist))
  3420.     (dired-initial-position dirname)
  3421.     (save-excursion (dired-mark-remembered mark-alist))))
  3422.  
  3423. ;; This is a separate function for dired-vms.
  3424. (defun dired-insert-subdir-validate (dirname &optional switches)
  3425.   ;; Check that it is valid to insert DIRNAME with SWITCHES.
  3426.   ;; Signal an error if invalid (e.g. user typed `i' on `..').
  3427.   (or (dired-in-this-tree dirname default-directory)
  3428.       (error  "%s: not in this directory tree" dirname))
  3429.   (if switches
  3430.       (let (case-fold-search)
  3431.     (mapcar
  3432.      (function
  3433.       (lambda (x)
  3434.         (or (eq (null (string-match x switches))
  3435.             (null (string-match x dired-actual-switches)))
  3436.         (error "Can't have dirs with and without -%s switches together"
  3437.                x))))
  3438.      ;; all switches that make a difference to dired-get-filename:
  3439.      '("F" "b")))))
  3440.  
  3441. (defun dired-kill-tree (dirname &optional remember-marks)
  3442.   ;;"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
  3443.   ;; With optional arg REMEMBER-MARKS, return an alist of marked files."
  3444.   (interactive "DKill tree below directory: ")
  3445.   (let ((s-alist dired-subdir-alist) dir m-alist)
  3446.     (while s-alist
  3447.       (setq dir (car (car s-alist))
  3448.         s-alist (cdr s-alist))
  3449.       (if (and (not (string-equal dir dirname))
  3450.            (dired-in-this-tree dir dirname)
  3451.            (dired-goto-subdir dir))
  3452.       (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
  3453.     m-alist))
  3454.  
  3455. (defun dired-insert-subdir-newpos (new-dir)
  3456.   ;; Find pos for new subdir, according to tree order.
  3457.   (let ((alist dired-subdir-alist) elt dir pos new-pos)
  3458.     (while alist
  3459.       (setq elt (car alist)
  3460.         alist (cdr alist)
  3461.         dir (car elt)
  3462.         pos (dired-get-subdir-min elt))
  3463.       (if (dired-tree-lessp dir new-dir)
  3464.       ;; Insert NEW-DIR after DIR
  3465.       (setq new-pos (dired-get-subdir-max elt)
  3466.         alist nil)))
  3467.     (goto-char new-pos))
  3468.   ;; want a separating newline between subdirs
  3469.   (or (eobp)
  3470.       (forward-line -1))
  3471.   (insert "\n")
  3472.   (point))
  3473.  
  3474. (defun dired-insert-subdir-del (element)
  3475.   ;; Erase an already present subdir (given by ELEMENT) from buffer.
  3476.   ;; Move to that buffer position.  Return a mark-alist.
  3477.   (let ((begin-marker (dired-get-subdir-min element)))
  3478.     (goto-char begin-marker)
  3479.     ;; Are at beginning of subdir (and inside it!).  Now determine its end:
  3480.     (goto-char (dired-subdir-max))
  3481.     (or (eobp);; want a separating newline _between_ subdirs:
  3482.     (forward-char -1))
  3483.     (prog1
  3484.     (dired-remember-marks begin-marker (point))
  3485.       (delete-region begin-marker (point)))))
  3486.  
  3487. (defun dired-insert-subdir-doinsert (dirname switches)
  3488.   ;; Insert ls output after point and put point on the correct
  3489.   ;; position for the subdir alist.
  3490.   ;; Return the boundary of the inserted text (as list of BEG and END).
  3491.   (let ((begin (point)) end)
  3492.     (message "Reading directory %s..." dirname)
  3493.     (let ((dired-actual-switches
  3494.        (or switches
  3495.            (dired-replace-in-string "R" "" dired-actual-switches))))
  3496.       (if (equal dirname (car (car (reverse dired-subdir-alist))))
  3497.       ;; top level directory may contain wildcards:
  3498.       (dired-readin-insert dired-directory)
  3499.     (dired-ls dirname dired-actual-switches nil t)))
  3500.     (message "Reading directory %s...done" dirname)
  3501.     (setq end (point-marker))
  3502.     (indent-rigidly begin end 2)
  3503.     ;;  call dired-insert-headerline afterwards, as under VMS dired-ls
  3504.     ;;  does insert the headerline itself and the insert function just
  3505.     ;;  moves point.
  3506.     ;;  Need a marker for END as this inserts text.
  3507.     (goto-char begin)
  3508.     (dired-insert-headerline dirname)
  3509.     ;; point is now like in dired-build-subdir-alist
  3510.     (prog1
  3511.     (list begin (marker-position end))
  3512.       (set-marker end nil))))
  3513.  
  3514. (defun dired-insert-subdir-doupdate (dirname elt beg-end)
  3515.   ;; Point is at the correct subdir alist position for ELT,
  3516.   ;; BEG-END is the subdir-region (as list of begin and end).
  3517.   (if elt                ; subdir was already present
  3518.       ;; update its position (should actually be unchanged)
  3519.       (set-marker (dired-get-subdir-min elt) (point-marker))
  3520.     (dired-alist-add dirname (point-marker)))
  3521.   ;; The hook may depend on the subdir-alist containing the just
  3522.   ;; inserted subdir, so run it after dired-alist-add:
  3523.   (if dired-after-readin-hook
  3524.       (save-excursion
  3525.     (let ((begin (nth 0 beg-end))
  3526.           (end (nth 1 beg-end)))
  3527.       (goto-char begin)
  3528.       (save-restriction
  3529.         (narrow-to-region begin end)
  3530.         ;; hook may add or delete lines, but the subdir boundary
  3531.         ;; marker floats
  3532.         (run-hooks 'dired-after-readin-hook))))))
  3533.  
  3534. (defun dired-tree-lessp (dir1 dir2)
  3535.   ;; Lexicographic order on pathname components, like `ls -lR':
  3536.   ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
  3537.   ;;   i.e., iff DIR1 is a (grand)parent dir of DIR2,
  3538.   ;;   or DIR1 and DIR2 are in the same parentdir and their last
  3539.   ;;   components are string-lessp.
  3540.   ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
  3541.   ;; string-lessp could arguably be replaced by file-newer-than-file-p
  3542.   ;;   if dired-actual-switches contained `t'.
  3543.   (setq dir1 (file-name-as-directory dir1)
  3544.     dir2 (file-name-as-directory dir2))
  3545.   (let ((components-1 (dired-split "/" dir1))
  3546.     (components-2 (dired-split "/" dir2)))
  3547.     (while (and components-1
  3548.         components-2
  3549.         (equal (car components-1) (car components-2)))
  3550.       (setq components-1 (cdr components-1)
  3551.         components-2 (cdr components-2)))
  3552.     (let ((c1 (car components-1))
  3553.       (c2 (car components-2)))
  3554.  
  3555.       (cond ((and c1 c2)
  3556.          (string-lessp c1 c2))
  3557.         ((and (null c1) (null c2))
  3558.          nil)            ; they are equal, not lessp
  3559.         ((null c1)            ; c2 is a subdir of c1: c1<c2
  3560.          t)
  3561.         ((null c2)            ; c1 is a subdir of c2: c1>c2
  3562.          nil)
  3563.         (t (error "This can't happen"))))))
  3564.  
  3565. ;; There should be a builtin split function - inverse to mapconcat.
  3566. (defun dired-split (pat str &optional limit)
  3567.   "Splitting on regexp PAT, turn string STR into a list of substrings.
  3568. Optional third arg LIMIT (>= 1) is a limit to the length of the
  3569. resulting list.
  3570. Thus, if SEP is a regexp that only matches itself,
  3571.  
  3572.    (mapconcat 'identity (dired-split SEP STRING) SEP)
  3573.  
  3574. is always equal to STRING."
  3575.   (let* ((start (string-match pat str))
  3576.      (result (list (substring str 0 start)))
  3577.      (count 1)
  3578.      (end (if start (match-end 0))))
  3579.     (if end                ; else nothing left
  3580.     (while (and (or (not (integerp limit))
  3581.             (< count limit))
  3582.             (string-match pat str end))
  3583.       (setq start (match-beginning 0)
  3584.         count (1+ count)
  3585.         result (cons (substring str end start) result)
  3586.         end (match-end 0)
  3587.         start end)
  3588.       ))
  3589.     (if (and (or (not (integerp limit))
  3590.          (< count limit))
  3591.          end)            ; else nothing left
  3592.     (setq result
  3593.           (cons (substring str end) result)))
  3594.     (nreverse result)))
  3595.  
  3596. ;;;###end dired-ins.el
  3597.  
  3598.  
  3599. ;;; Sorting
  3600.  
  3601. ;; Most ls can only sort by name or by date (with -t), nothing else.
  3602. ;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
  3603. ;; So anything that does not contain these is sort "by name".
  3604.  
  3605. (defvar dired-ls-sorting-switches "SXU"
  3606.   "String of ls switches (single letters) except `t' that influence sorting.")
  3607.  
  3608. (defvar dired-sort-by-date-regexp
  3609.   (concat "^-[^" dired-ls-sorting-switches
  3610.       "]*t[^" dired-ls-sorting-switches "]*$")
  3611.   "Regexp recognized by dired to set `by date' mode.")
  3612.  
  3613. (defvar dired-sort-by-name-regexp
  3614.   (concat "^-[^t" dired-ls-sorting-switches "]+$")
  3615.   "Regexp recognized by dired to set `by name' mode.")
  3616.  
  3617. (defvar dired-sort-mode nil
  3618.   "Whether Dired sorts by name, date etc. (buffer-local).")
  3619. ;; This is nil outside dired buffers so it can be used in the modeline
  3620.  
  3621. (defun dired-sort-set-modeline ()
  3622.   ;; Set modeline display according to dired-actual-switches.
  3623.   ;; Modeline display of "by name" or "by date" guarantees the user a
  3624.   ;; match with the corresponding regexps.  Non-matching switches are
  3625.   ;; shown literally.
  3626.   (setq dired-sort-mode
  3627.     (let (case-fold-search)
  3628.       (cond ((string-match dired-sort-by-name-regexp dired-actual-switches)
  3629.          " by name")
  3630.         ((string-match dired-sort-by-date-regexp dired-actual-switches)
  3631.          " by date")
  3632.         (t
  3633.          (concat " " dired-actual-switches)))))
  3634.   ;; update mode line:
  3635.   (set-buffer-modified-p (buffer-modified-p)))
  3636.  
  3637. (defun dired-sort-toggle-or-edit (&optional arg)
  3638.   "Toggle between sort by date/name and refresh the dired buffer.
  3639. With a prefix argument you can edit the current listing switches instead."
  3640.   (interactive "P")
  3641.   (if arg
  3642.       (dired-sort-other
  3643.        (read-string "ls switches (must contain -l): " dired-actual-switches))
  3644.     (dired-sort-toggle)))
  3645.  
  3646. (defun dired-sort-toggle ()
  3647.   ;; Toggle between sort by date/name.  Reverts the buffer.
  3648.   (setq dired-actual-switches
  3649.     (let (case-fold-search)
  3650.       (concat
  3651.        "-l"
  3652.        (dired-replace-in-string (concat "[---lt"
  3653.                         dired-ls-sorting-switches "]")
  3654.                     ""
  3655.                     dired-actual-switches)
  3656.        (if (string-match (concat "[t" dired-ls-sorting-switches "]")
  3657.                  dired-actual-switches)
  3658.            ""
  3659.          "t"))))
  3660.   (dired-sort-set-modeline)
  3661.   (revert-buffer))
  3662.  
  3663. (defun dired-sort-other (switches &optional no-revert)
  3664.   ;; Specify new ls SWITCHES for current dired buffer.  Values matching
  3665.   ;; `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp' set the
  3666.   ;; minor mode accordingly, others appear literally in the mode line.
  3667.   ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
  3668.   (setq dired-actual-switches switches)
  3669.   (dired-sort-set-modeline)
  3670.   (or no-revert (revert-buffer)))
  3671.  
  3672. (if (eq system-type 'vax-vms)
  3673.     (load "dired-vms"))
  3674.  
  3675. (run-hooks 'dired-load-hook)        ; for your customizations
  3676.