;;; dired-aux.el --- less commonly used parts of dired -*-byte-compile-dynamic: t;-*-;; Copyright (C) 1985, 1986, 1992, 1994 Free Software Foundation, Inc.;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>.;; This file is part of GNU Emacs.;; GNU Emacs is free software; you can redistribute it and/or modify;; it under the terms of the GNU General Public License as published by;; the Free Software Foundation; either version 2, or (at your option);; any later version.;; GNU Emacs is distributed in the hope that it will be useful,;; but WITHOUT ANY WARRANTY; without even the implied warranty of;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the;; GNU General Public License for more details.;; You should have received a copy of the GNU General Public License;; along with GNU Emacs; see the file COPYING. If not, write to the;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,;; Boston, MA 02111-1307, USA.;;; Commentary:;; The parts of dired mode not normally used. This is a space-saving hack;; to avoid having to load a large mode when all that's wanted are a few;; functions.;; Rewritten in 1990/1991 to add tree features, file marking and;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.;; Finished up by rms in 1992.;;; Code:;; We need macros in dired.el to compile properly.(eval-when-compile(require'dired));;; 15K;;;###begin dired-cmd.el;; Diffing and compressing;;;###autoload(defundired-diff(file&optionalswitches)"Compare file at point with file FILE using `diff'.FILE defaults to the file at the mark.The prompted-for file is the first file given to `diff'.With prefix arg, prompt for second argument SWITCHES, which is options for `diff'."(interactive(let((default(if(markt)(save-excursion(goto-char(markt))(dired-get-filenamett)))))(require'diff)(list(read-file-name(format"Diff %s with: %s"(dired-get-filenamet)(ifdefault(concat"(default "default") ")""))(dired-current-directory)defaultt)(ifcurrent-prefix-arg(read-string"Options for diff: "(if(stringpdiff-switches)diff-switches(mapconcat'identitydiff-switches" ")))))))(difffile(dired-get-filenamet)switches));;;###autoload(defundired-backup-diff(&optionalswitches)"Diff this file with its backup file or vice versa.Uses the latest backup, if there are several numerical backups.If this file is a backup, diff it with its original.The backup file is the first file given to `diff'.With prefix arg, prompt for argument SWITCHES which is options for `diff'."(interactive(ifcurrent-prefix-arg(list(read-string"Options for diff: "(if(stringpdiff-switches)diff-switches(mapconcat'identitydiff-switches" "))))nil))(diff-backup(dired-get-filename)switches))(defundired-do-chxxx(attribute-nameprogramop-symbolarg);; Change file attributes (mode, group, owner) of marked files and;; refresh their file lines.;; ATTRIBUTE-NAME is a string describing the attribute to the user.;; PROGRAM is the program used to change the attribute.;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).;; ARG describes which files to use, as in dired-get-marked-files.(let*((files(dired-get-marked-filestarg))(new-attribute(dired-mark-read-string(concat"Change "attribute-name" of %s to: ")nilop-symbolargfiles))(operation(concatprogram" "new-attribute))failures)(setqfailures(dired-bunch-files10000(functiondired-check-process)(listoperationprogramnew-attribute)files))(dired-do-redisplayarg);; moves point if ARG is an integer(iffailures(dired-log-summary(format"%s: error"operation)nil))));;;###autoload(defundired-do-chmod(&optionalarg)"Change the mode of the marked (or next ARG) files.This calls chmod, thus symbolic modes like `g+w' are allowed."(interactive"P")(dired-do-chxxx"Mode"dired-chmod-program'chmodarg));;;###autoload(defundired-do-chgrp(&optionalarg)"Change the group of the marked (or next ARG) files."(interactive"P")(if(memqsystem-type'(ms-doswindows-nt))(error"chgrp not supported on this system."))(dired-do-chxxx"Group""chgrp"'chgrparg));;;###autoload(defundired-do-chown(&optionalarg)"Change the owner of the marked (or next ARG) files."(interactive"P")(if(memqsystem-type'(ms-doswindows-nt))(error"chown not supported on this system."))(dired-do-chxxx"Owner"dired-chown-program'chownarg));; Process all the files in FILES in batches of a convenient size,;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).;; Batches are chosen to need less than MAX chars for the file names,;; allowing 3 extra characters of separator per file name.(defundired-bunch-files(maxfunctionargsfiles)(let(pending(pending-length0)failures);; Accumulate files as long as they fit in MAX chars,;; then process the ones accumulated so far.(whilefiles(let*((thisfile(carfiles))(thislength(+(lengththisfile)3))(rest(cdrfiles)));; If we have at least 1 pending file;; and this file won't fit in the length limit, process now.(if(andpending(>(+thislengthpending-length)max))(setqfailures(nconc(applyfunction(appendargspending))failures)pendingnilpending-length0));; Do (setq pending (cons thisfile pending));; but reuse the cons that was in `files'.(setcdrfilespending)(setqpendingfiles)(setqpending-length(+thislengthpending-length))(setqfilesrest)))(nconc(applyfunction(appendargspending))failures)));;;###autoload(defundired-do-print(&optionalarg)"Print the marked (or next ARG) files.Uses the shell command coming from variables `lpr-command' and`lpr-switches' as default."(interactive"P")(let*((file-list(dired-get-marked-filestarg))(command(dired-mark-read-string"Print %s with: "(mapconcat'identity(conslpr-command(if(stringplpr-switches)(listlpr-switches)lpr-switches))" ")'printargfile-list)))(dired-run-shell-command(dired-shell-stuff-itcommandfile-listnil))));; Read arguments for a marked-files command that wants a string;; that is not a file name,;; perhaps popping up the list of marked files.;; ARG is the prefix arg and indicates whether the files came from;; marks (ARG=nil) or a repeat factor (integerp ARG).;; If the current file was used, the list has but one element and ARG;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).(defundired-mark-read-string(promptinitialop-symbolargfiles);; PROMPT for a string, with INITIAL input.;; Other args are used to give user feedback and pop-up:;; OP-SYMBOL of command, prefix ARG, marked FILES.(dired-mark-pop-upnilop-symbolfiles(functionread-string)(formatprompt(dired-mark-promptargfiles))initial));;; Cleaning a directory: flagging some backups for deletion.(defvardired-file-version-alist)(defundired-clean-directory(keep)"Flag numerical backups for deletion.Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.Positive prefix arg KEEP overrides `dired-kept-versions';Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.To clear the flags on these files, you can use \\[dired-flag-backup-files]with a prefix argument."(interactive"P")(setqkeep(ifkeep(prefix-numeric-valuekeep)dired-kept-versions))(let((early-retention(if(<keep0)(-keep)kept-old-versions))(late-retention(if(<=keep0)dired-kept-versionskeep))(dired-file-version-alist()))(message"Cleaning numerical backups (keeping %d late, %d old)..."late-retentionearly-retention);; Look at each file.;; If the file has numeric backup versions,;; put on dired-file-version-alist an element of the form;; (FILENAME . VERSION-NUMBER-LIST)(dired-map-dired-file-lines(functiondired-collect-file-versions));; Sort each VERSION-NUMBER-LIST,;; and remove the versions not to be deleted.(let((fvaldired-file-version-alist))(whilefval(let*((sorted-v-list(cons'q(sort(cdr(carfval))'<)))(v-count(lengthsorted-v-list)))(if(>v-count(+early-retentionlate-retention))(rplacd(nthcdrearly-retentionsorted-v-list)(nthcdr(-v-countlate-retention)sorted-v-list)))(rplacd(carfval)(cdrsorted-v-list)))(setqfval(cdrfval))));; Look at each file. If it is a numeric backup file,;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.(dired-map-dired-file-lines(functiondired-trample-file-versions))(message"Cleaning numerical backups...done")));;; Subroutines of dired-clean-directory.(defundired-map-dired-file-lines(fun);; Perform FUN with point at the end of each non-directory line.;; FUN takes one argument, the filename (complete pathname).(save-excursion(let(filebuffer-read-only)(goto-char(point-min))(while(not(eobp))(save-excursion(and(not(looking-atdired-re-dir))(not(eolp))(setqfile(dired-get-filenamenilt)); nil on non-file(progn(end-of-line)(funcallfunfile))))(forward-line1)))))(defundired-collect-file-versions(fn)(let((fn(file-name-sans-versionsfn)));; Only do work if this file is not already in the alist.(if(assocfndired-file-version-alist)nil;; If it looks like file FN has versions, return a list of the versions.;;That is a list of strings which are file names.;;The caller may want to flag some of these files for deletion.(let*((base-versions(concat(file-name-nondirectoryfn)".~"))(bv-length(lengthbase-versions))(possibilities(file-name-all-completionsbase-versions(file-name-directoryfn)))(versions(mapcar'backup-extract-versionpossibilities)))(ifversions(setqdired-file-version-alist(cons(consfnversions)dired-file-version-alist)))))))(defundired-trample-file-versions(fn)(let*((start-vn(string-match"\\.~[0-9]+~$"fn))base-version-list)(andstart-vn(setqbase-version-list; there was a base version to which(assoc(substringfn0start-vn); this looks like adired-file-version-alist)); subversion(not(memq(string-to-int(substringfn(+2start-vn)))base-version-list)); this one doesn't make the cut(progn(beginning-of-line)(delete-char1)(insertdired-del-marker)))));;; Shell commands;;>>> install (move this function into simple.el)(defundired-shell-quote(filename)"Quote a file name for inferior shell (see variable `shell-file-name').";; Quote everything except POSIX filename characters.;; This should be safe enough even for really weird shells.(let((result"")(start0)end)(while(string-match"[^-0-9a-zA-Z_./]"filenamestart)(setqend(match-beginning0)result(concatresult(substringfilenamestartend)"\\"(substringfilenameend(1+end)))start(1+end)))(concatresult(substringfilenamestart))))(defundired-read-shell-command(promptargfiles);; "Read a dired shell command prompting with PROMPT (using read-string).;;ARG is the prefix arg and may be used to indicate in the prompt which;; files are affected.;;This is an extra function so that you can redefine it, e.g., to use gmhist."(dired-mark-pop-upnil'shellfiles(functionread-string)(formatprompt(dired-mark-promptargfiles))nil'shell-command-history));; The in-background argument is only needed in Emacs 18 where;; shell-command doesn't understand an appended ampersand `&'.;;;###autoload(defundired-do-shell-command(command&optionalarg)"Run a shell command COMMAND on the marked files.If no files are marked or a specific numeric prefix arg is given,the next ARG files are used. Just \\[universal-argument] means the current file.The prompt mentions the file(s) or the marker, as appropriate.If there is output, it goes to a separate buffer.Normally the command is run on each file individually.However, if there is a `*' in the command then it is runjust once with the entire file list substituted there.No automatic redisplay of dired buffers is attempted, as there's notelling what files the command may have changed. Type\\[dired-do-redisplay] to redisplay the marked files.The shell command has the top level directory as working directory, sooutput files usually are created there instead of in a subdir.";;Functions dired-run-shell-command and dired-shell-stuff-it do the;;actual work and can be redefined for customization.(interactive(list;; Want to give feedback whether this file or marked files are used:(dired-read-shell-command(concat"! on ""%s: ")current-prefix-arg(dired-get-marked-filestcurrent-prefix-arg))current-prefix-arg))(let*((on-each(not(string-match"\\*"command)))(file-list(dired-get-marked-filestarg)))(ifon-each(dired-bunch-files(-10000(lengthcommand))(function(lambda(&restfiles)(dired-run-shell-command(dired-shell-stuff-itcommandfilestarg))))nilfile-list);; execute the shell command(dired-run-shell-command(dired-shell-stuff-itcommandfile-listnilarg)))));; Might use {,} for bash or csh:(defvardired-mark-prefix"""Prepended to marked files in dired shell commands.")(defvardired-mark-postfix"""Appended to marked files in dired shell commands.")(defvardired-mark-separator" ""Separates marked files in dired shell commands.")(defundired-shell-stuff-it(commandfile-liston-each&optionalraw-arg);; "Make up a shell command line from COMMAND and FILE-LIST.;; If ON-EACH is t, COMMAND should be applied to each file, else;; simply concat all files and apply COMMAND to this.;; FILE-LIST's elements will be quoted for the shell.";; Might be redefined for smarter things and could then use RAW-ARG;; (coming from interactive P and currently ignored) to decide what to do.;; Smart would be a way to access basename or extension of file names.;; See dired-trns.el for an approach to this.;; Bug: There is no way to quote a *;; On the other hand, you can never accidentally get a * into your cmd.(let((stuff-it(if(string-match"\\*"command)(function(lambda(x)(dired-replace-in-string"\\*"xcommand)))(function(lambda(x)(concatcommand" "x))))))(ifon-each(mapconcatstuff-it(mapcar'dired-shell-quotefile-list)";")(let((fns(mapconcat'dired-shell-quotefile-listdired-mark-separator)))(if(>(lengthfile-list)1)(setqfns(concatdired-mark-prefixfnsdired-mark-postfix)))(funcallstuff-itfns)))));; This is an extra function so that it can be redefined by ange-ftp.(defundired-run-shell-command(command)(shell-commandcommand);; Return nil for sake of nconc in dired-bunch-files.nil);; In Emacs 19 this will return program's exit status.;; This is a separate function so that ange-ftp can redefine it.(defundired-call-process(programdiscard&restarguments); "Run PROGRAM with output to current buffer unless DISCARD is t.;Remaining arguments are strings passed as command arguments to PROGRAM.";; Look for a handler for default-directory in case it is a remote file name.(let((handler(find-file-name-handler(directory-file-namedefault-directory)'dired-call-process)))(ifhandler(applyhandler'dired-call-processprogramdiscardarguments)(apply'call-processprogramnil(notdiscard)nilarguments))))(defundired-check-process(msgprogram&restarguments); "Display MSG while running PROGRAM, and check for output.;Remaining arguments are strings passed as command arguments to PROGRAM.; On error, insert output; in a log buffer and return the offending ARGUMENTS or PROGRAM.; Caller can cons up a list of failed args.;Else returns nil for success."(let(err-buffererr(dirdefault-directory))(message"%s..."msg)(save-excursion;; Get a clean buffer for error output:(setqerr-buffer(get-buffer-create" *dired-check-process output*"))(set-buffererr-buffer)(erase-buffer)(setqdefault-directorydir; caller's default-directoryerr(/=0(apply(functiondired-call-process)programnilarguments)))(iferr(progn(dired-log(concatprogram" "(prin1-to-stringarguments)"\n"))(dired-logerr-buffer)(orargumentsprogramt))(kill-buffererr-buffer)(message"%s...done"msg)nil))));; Commands that delete or redisplay part of the dired buffer.(defundired-kill-line(&optionalarg)(interactive"P")(setqarg(prefix-numeric-valuearg))(let(buffer-read-onlyfile)(while(/=0arg)(setqfile(dired-get-filenamenilt))(if(notfile)(error"Can only kill file lines.")(save-excursion(andfile(dired-goto-subdirfile)(dired-kill-subdir)))(delete-region(progn(beginning-of-line)(point))(progn(forward-line1)(point)))(if(>arg0)(setqarg(1-arg))(setqarg(1+arg))(forward-line-1))))(dired-move-to-filename)));;;###autoload(defundired-do-kill-lines(&optionalargfmt)"Kill all marked lines (not the files).With a prefix argument, kill that many lines starting with the current line.\(A negative argument kills lines before the current line.)To kill an entire subdirectory, go to its directory header lineand use this command with a prefix argument (the value does not matter).";; Returns count of killed lines. FMT="" suppresses message.(interactive"P")(ifarg(if(dired-get-subdir)(dired-kill-subdir)(dired-kill-linearg))(save-excursion(goto-char(point-min))(let(buffer-read-only(count0))(if(notarg); kill marked lines(let((regexp(dired-marker-regexp)))(while(and(not(eobp))(re-search-forwardregexpnilt))(setqcount(1+count))(delete-region(progn(beginning-of-line)(point))(progn(forward-line1)(point)))));; else kill unmarked lines(while(not(eobp))(if(or(dired-between-files)(not(looking-at"^ ")))(forward-line1)(setqcount(1+count))(delete-region(point)(save-excursion(forward-line1)(point))))))(or(equal""fmt)(message(orfmt"Killed %d line%s.")count(dired-plural-scount)))count))));;;###end dired-cmd.el;;; 30K;;;###begin dired-cp.el(defundired-compress();; Compress or uncompress the current file.;; Return nil for success, offending filename else.(let*(buffer-read-only(from-file(dired-get-filename))(new-file(dired-compress-filefrom-file)))(ifnew-file(let((start(point)));; Remove any preexisting entry for the name NEW-FILE.(condition-casenil(dired-remove-entrynew-file)(errornil))(goto-charstart);; Now replace the current line with an entry for NEW-FILE.(dired-update-file-linenew-file)nil)(dired-log(concat"Failed to compress"from-file))from-file)))(defvardired-compress-file-suffixes'(("\\.gz\\'""""gunzip")("\\.tgz\\'"".tar""gunzip")("\\.Z\\'""""uncompress");; For .z, try gunzip. It might be an old gzip file,;; or it might be from compact? pack? (which?) but gunzip handles both.("\\.z\\'""""gunzip");; This item controls naming for compression.("\\.tar\\'"".tgz"nil))"Control changes in file name suffixes for compression and uncompression.Each element specifies one transformation rule, and has the form: (REGEXP NEW-SUFFIX PROGRAM)The rule applies when the old file name matches REGEXP.The new file name is computed by deleting the part that matches REGEXP (as well as anything after that), then adding NEW-SUFFIX in its place.If PROGRAM is non-nil, the rule is an uncompression rule,and uncompression is done by running PROGRAM.Otherwise, the rule is a compression rule, and compression is done with gzip.");;;###autoload(defundired-compress-file(file);; Compress or uncompress FILE.;; Return the name of the compressed or uncompressed file.;; Return nil if no change in files.(let((handler(find-file-name-handlerfile'dired-compress-file))suffixnewname(suffixesdired-compress-file-suffixes));; See if any suffix rule matches this file name.(whilesuffixes(let(case-fold-search)(if(string-match(car(carsuffixes))file)(setqsuffix(carsuffixes)suffixesnil))(setqsuffixes(cdrsuffixes))));; If so, compute desired new name.(ifsuffix(setqnewname(concat(substringfile0(match-beginning0))(nth1suffix))))(cond(handler(funcallhandler'dired-compress-filefile))((file-symlink-pfile)nil)((andsuffix(nth2suffix));; We found an uncompression rule.(if(not(dired-check-process(concat"Uncompressing "file)(nth2suffix)file))newname))(t;;; We don't recognize the file as compressed, so compress it.;;; Try gzip; if we don't have that, use compress.(condition-casenil(if(not(dired-check-process(concat"Compressing "file)"gzip""-f"file))(let((out-name(if(file-exists-p(concatfile".gz"))(concatfile".gz")(concatfile".z"))));; Rename the compressed file to NEWNAME;; if it hasn't got that name already.(if(andnewname(not(equalnewnameout-name)))(progn(rename-fileout-namenewnamet)newname)out-name)))(file-error(if(not(dired-check-process(concat"Compressing "file)"compress""-f"file));; Don't use NEWNAME with `compress'.(concatfile".Z"))))))))(defundired-mark-confirm(op-symbolarg);; Request confirmation from the user that the operation described;; by OP-SYMBOL is to be performed on the marked files.;; Confirmation consists in a y-or-n question with a file list;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.;; The files used are determined by ARG (as in dired-get-marked-files).(or(memqop-symboldired-no-confirm)(let((files(dired-get-marked-filestarg))(string(if(eqop-symbol'compress)"Compress or uncompress"(capitalize(symbol-nameop-symbol)))))(dired-mark-pop-upnilop-symbolfiles(functiony-or-n-p)(concatstring" "(dired-mark-promptargfiles)"? ")))))(defundired-map-over-marks-check(funargop-symbol&optionalshow-progress); "Map FUN over marked files (with second ARG like in dired-map-over-marks); and display failures.; FUN takes zero args. It returns non-nil (the offending object, e.g.; the short form of the filename) for a failure and probably logs a; detailed error explanation using function `dired-log'.; OP-SYMBOL is a symbol describing the operation performed (e.g.; `compress'). It is used with `dired-mark-pop-up' to prompt the user; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.; `Failed to compress 1 of 2 files - type W to see why ("foo")'); SHOW-PROGRESS if non-nil means redisplay dired after each file."(if(dired-mark-confirmop-symbolarg)(let*((total-list;; all of FUN's return values(dired-map-over-marks(funcallfun)argshow-progress))(total(lengthtotal-list))(failures(delqniltotal-list))(count(lengthfailures))(string(if(eqop-symbol'compress)"Compress or uncompress"(capitalize(symbol-nameop-symbol)))))(if(notfailures)(message"%s: %d file%s."stringtotal(dired-plural-stotal));; end this bunch of errors:(dired-log-summary(format"Failed to %s %d of %d file%s"(downcasestring)counttotal(dired-plural-stotal))failures)))))(defvardired-query-alist'((?\y.y)(?\040.y); `y' or SPC means accept once(?n.n)(?\177.n); `n' or DEL skips once(?!.yes); `!' accepts rest(?q.no)(?\e.no); `q' or ESC skips rest;; None of these keys quit - use C-g for that.))(defundired-query(qs-varqs-prompt&restqs-args);; Query user and return nil or t.;; Store answer in symbol VAR (which must initially be bound to nil).;; Format PROMPT with ARGS.;; Binding variable help-form will help the user who types the help key.(let*((char(symbol-valueqs-var))(action(cdr(assocchardired-query-alist))))(cond((eq'yesaction)t); accept, and don't ask again((eq'noaction)nil); skip, and don't ask again(t;; no lasting effects from last time we asked - ask now(let((qprompt(concatqs-prompt(ifhelp-form(format" [Type yn!q or %s] "(key-description(char-to-stringhelp-char)))" [Type y, n, q or !] ")))resultelt);; Actually it looks nicer without cursor-in-echo-area - you can;; look at the dired buffer instead of at the prompt to decide.(apply'messageqpromptqs-args)(setqchar(setqs-var(read-char)))(while(not(setqelt(assocchardired-query-alist)))(message"Invalid char - type %c for help."help-char)(ding)(sit-for1)(apply'messageqpromptqs-args)(setqchar(setqs-var(read-char))))(memq(cdrelt)'(tyyes)))))));;;###autoload(defundired-do-compress(&optionalarg)"Compress or uncompress marked (or next ARG) files."(interactive"P")(dired-map-over-marks-check(functiondired-compress)arg'compresst));; Commands for Emacs Lisp files - load and byte compile(defundired-byte-compile();; Return nil for success, offending file name else.(let*((filename(dired-get-filename))elc-filebuffer-read-onlyfailure)(condition-caseerr(save-excursion(byte-compile-filefilename))(error(setqfailureerr)))(setqelc-file(byte-compile-dest-filefilename))(or(file-exists-pelc-file)(setqfailuret))(iffailure(progn(dired-log"Byte compile error for %s:\n%s\n"filenamefailure)(dired-make-relativefilename))(dired-remove-fileelc-file)(forward-line); insert .elc after its .el file(dired-add-fileelc-file)nil)));;;###autoload(defundired-do-byte-compile(&optionalarg)"Byte compile marked (or next ARG) Emacs Lisp files."(interactive"P")(dired-map-over-marks-check(functiondired-byte-compile)arg'byte-compilet))(defundired-load();; Return nil for success, offending file name else.(let((file(dired-get-filename))failure)(condition-caseerr(loadfilenilnilt)(error(setqfailureerr)))(if(notfailure)nil(dired-log"Load error for %s:\n%s\n"filefailure)(dired-make-relativefile))));;;###autoload(defundired-do-load(&optionalarg)"Load the marked (or next ARG) Emacs Lisp files."(interactive"P")(dired-map-over-marks-check(functiondired-load)arg'loadt));;;###autoload(defundired-do-redisplay(&optionalargtest-for-subdir)"Redisplay all marked (or next ARG) files.If on a subdir line, redisplay that subdirectory. In that case,a prefix arg lets you edit the `ls' switches used for the new listing.";; Moves point if the next ARG files are redisplayed.(interactive"P\np")(if(andtest-for-subdir(dired-get-subdir))(dired-insert-subdir(dired-get-subdir)(ifarg(read-string"Switches for listing: "dired-actual-switches)))(message"Redisplaying...");; message much faster than making dired-map-over-marks show progress(dired-uncache(if(conspdired-directory)(cardired-directory)dired-directory))(dired-map-over-marks(let((fname(dired-get-filename)))(message"Redisplaying... %s"fname)(dired-update-file-linefname))arg)(dired-move-to-filename)(message"Redisplaying...done")))(defundired-update-file-line(file);; Delete the current line, and insert an entry for FILE.;; If FILE is nil, then just delete the current line.;; Keeps any marks that may be present in column one (doing this;; here is faster than with dired-add-entry's optional arg).;; Does not update other dired buffers. Use dired-relist-entry for that.(beginning-of-line)(let((char(following-char))(opoint(point))(buffer-read-only))(delete-region(point)(progn(forward-line1)(point)))(iffile(progn(dired-add-entryfile);; Replace space by old marker without moving point.;; Faster than goto+insdel inside a save-excursion?(subst-char-in-regionopoint(1+opoint)?\040char))))(dired-move-to-filename))(defundired-fun-in-all-buffers(directoryfun&restargs);; In all buffers dired'ing DIRECTORY, run FUN with ARGS.;; Return list of buffers where FUN succeeded (i.e., returned non-nil).(let((buf-list(dired-buffers-for-dir(expand-file-namedirectory)))(obuf(current-buffer))bufsuccess-list)(whilebuf-list(setqbuf(carbuf-list)buf-list(cdrbuf-list))(unwind-protect(progn(set-bufferbuf)(if(applyfunargs)(setqsuccess-list(cons(buffer-namebuf)success-list))))(set-bufferobuf)))success-list));;;###autoload(defundired-add-file(filename&optionalmarker-char)(dired-fun-in-all-buffers(file-name-directoryfilename)(functiondired-add-entry)filenamemarker-char))(defundired-add-entry(filename&optionalmarker-char);; Add a new entry for FILENAME, optionally marking it;; with MARKER-CHAR (a character, else dired-marker-char is used).;; Note that this adds the entry `out of order' if files sorted by;; time, etc.;; At least this version inserts in the right subdirectory (if present).;; And it skips "." or ".." (see `dired-trivial-filenames').;; Hidden subdirs are exposed if a file is added there.(setqfilename(directory-file-namefilename));; Entry is always for files, even if they happen to also be directories(let((opoint(point))(cur-dir(dired-current-directory))(orig-file-namefilename)(directory(file-name-directoryfilename))reason)(setqfilename(file-name-nondirectoryfilename)reason(catch'not-found(if(string=directorycur-dir)(progn(skip-chars-forward"^\r\n")(if(eq(following-char)?\r)(dired-unhide-subdir));; We are already where we should be, except when;; point is before the subdir line or its total line.(let((p(dired-after-subdir-garbagecur-dir)))(if(<(point)p)(goto-charp))));; else try to find correct place to insert(if(dired-goto-subdirdirectory)(progn;; unhide if necessary(if(looking-at"\r");; point is at end of subdir line(dired-unhide-subdir));; found - skip subdir and `total' line;; and uninteresting files like . and ..;; This better not moves into the next subdir!(dired-goto-next-nontrivial-file));; not found(throw'not-found"Subdir not found")))(let(buffer-read-onlyopoint)(beginning-of-line)(setqopoint(point))(dired-add-entry-do-indentationmarker-char);; don't expand `.'. Show just the file name within directory.(let((default-directorydirectory))(insert-directoryfilename(concatdired-actual-switches"d")));; Compensate for a bug in ange-ftp.;; It inserts the file's absolute name, rather than;; the relative one. That may be hard to fix since it;; is probably controlled by something in ftp.(goto-charopoint)(let((inserted-name(dired-get-filename'no-dir)))(if(file-name-directoryinserted-name)(progn(end-of-line)(delete-char(-(lengthinserted-name)))(insertfilename)(forward-char1))(forward-line1)));; Give each line a text property recording info about it.(dired-insert-set-propertiesopoint(point))(forward-line-1)(ifdired-after-readin-hook;; the subdir-alist is not affected...(save-excursion;; ...so we can run it right now:(save-restriction(beginning-of-line)(narrow-to-region(point)(save-excursion(forward-line1)(point)))(run-hooks'dired-after-readin-hook))))(dired-move-to-filename));; return nil if all went wellnil))(ifreason; don't move away on failure(goto-charopoint))(notreason))); return t on success, nil else;; This is a separate function for the sake of nested dired format.(defundired-add-entry-do-indentation(marker-char);; two spaces or a marker plus a space:(insert(ifmarker-char(if(integerpmarker-char)marker-chardired-marker-char)?\040)?\040))(defundired-after-subdir-garbage(dir);; Return pos of first file line of DIR, skipping header and total;; or wildcard lines.;; Important: never moves into the next subdir.;; DIR is assumed to be unhidden.;; Will probably be redefined for VMS etc.(save-excursion(or(dired-goto-subdirdir)(error"This cannot happen"))(forward-line1)(while(and(not(eolp)); don't cross subdir boundary(not(dired-move-to-filename)))(forward-line1))(point)));;;###autoload(defundired-remove-file(file)(dired-fun-in-all-buffers(file-name-directoryfile)(functiondired-remove-entry)file))(defundired-remove-entry(file)(save-excursion(and(dired-goto-filefile)(let(buffer-read-only)(delete-region(progn(beginning-of-line)(point))(save-excursion(forward-line1)(point)))))));;;###autoload(defundired-relist-file(file)(dired-fun-in-all-buffers(file-name-directoryfile)(functiondired-relist-entry)file))(defundired-relist-entry(file);; Relist the line for FILE, or just add it if it did not exist.;; FILE must be an absolute pathname.(let(buffer-read-onlymarker);; If cursor is already on FILE's line delete-region will cause;; save-excursion to fail because of floating makers,;; moving point to beginning of line. Sigh.(save-excursion(and(dired-goto-filefile)(delete-region(progn(beginning-of-line)(setqmarker(following-char))(point))(save-excursion(forward-line1)(point))))(setqfile(directory-file-namefile))(dired-add-entryfile(if(eq?\040marker)nilmarker)))));;; Copy, move/rename, making hard and symbolic links(defvardired-backup-overwritenil"*Non-nil if Dired should ask about making backups before overwriting files.Special value `always' suppresses confirmation.")(defvardired-overwrite-confirmed)(defundired-handle-overwrite(to);; Save old version of a to be overwritten file TO.;; `dired-overwrite-confirmed' and `overwrite-backup-query' are fluid vars;; from dired-create-files.(let(backup)(if(anddired-backup-overwritedired-overwrite-confirmed(setqbackup(car(find-backup-file-nameto)))(or(eq'alwaysdired-backup-overwrite)(dired-query'overwrite-backup-query(format"Make backup for existing file `%s'? "to))))(progn(rename-filetobackup0); confirm overwrite of old backup(dired-relist-entrybackup)))));;;###autoload(defundired-copy-file(fromtook-flag)(dired-handle-overwriteto)(copy-filefromtook-flagdired-copy-preserve-time));;;###autoload(defundired-rename-file(fromtook-flag)(dired-handle-overwriteto)(rename-filefromtook-flag); error is caught in -create-files;; Silently rename the visited file of any buffer visiting this file.(and(get-file-bufferfrom)(save-excursion(set-buffer(get-file-bufferfrom))(let((modflag(buffer-modified-p)))(set-visited-file-nameto)(set-buffer-modified-pmodflag))))(dired-remove-filefrom);; See if it's an inserted subdir, and rename that, too.(dired-rename-subdirfromto))(defundired-rename-subdir(from-dirto-dir)(setqfrom-dir(file-name-as-directoryfrom-dir)to-dir(file-name-as-directoryto-dir))(dired-fun-in-all-buffersfrom-dir(functiondired-rename-subdir-1)from-dirto-dir);; Update visited file name of all affected buffers(let((expanded-from-dir(expand-file-namefrom-dir))(blist(buffer-list)))(whileblist(save-excursion(set-buffer(carblist))(if(andbuffer-file-name(dired-in-this-treebuffer-file-nameexpanded-from-dir))(let((modflag(buffer-modified-p))(to-file(dired-replace-in-string(concat"^"(regexp-quotefrom-dir))to-dirbuffer-file-name)))(set-visited-file-nameto-file)(set-buffer-modified-pmodflag))))(setqblist(cdrblist)))))(defundired-rename-subdir-1(dirto);; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or;; one of its subdirectories is expanded in this buffer.(let((expanded-dir(expand-file-namedir))(alistdired-subdir-alist)(eltnil))(whilealist(setqelt(caralist)alist(cdralist))(if(dired-in-this-tree(carelt)expanded-dir);; ELT's subdir is affected by the rename(dired-rename-subdir-2eltdirto)))(if(equaldirdefault-directory);; if top level directory was renamed, lots of things have to be;; updated:(progn(dired-unadvertisedir); we no longer dired DIR...(setqdefault-directorytodired-directory(expand-file-name;; this is correct;; with and without wildcards(file-name-nondirectorydired-directory)to))(let((new-name(file-name-nondirectory(directory-file-namedired-directory))));; try to rename buffer, but just leave old name if new;; name would already exist (don't try appending "<%d>")(or(get-buffernew-name)(rename-buffernew-name)));; ... we dired TO now:(dired-advertise)))))(defundired-rename-subdir-2(eltdirto);; Update the headerline and dired-subdir-alist element of directory;; described by alist-element ELT to reflect the moving of DIR to TO.;; Thus, ELT describes either DIR itself or a subdir of DIR.(save-excursion(let((regexp(regexp-quote(directory-file-namedir)))(newtext(directory-file-nameto))buffer-read-only)(goto-char(dired-get-subdir-minelt));; Update subdir headerline in buffer(if(not(looking-atdired-subdir-regexp))(error"%s not found where expected - dired-subdir-alist broken?"dir)(goto-char(match-beginning1))(if(re-search-forwardregexp(match-end1)t)(replace-matchnewtexttt)(error"Expected to find `%s' in headerline of %s"dir(carelt))));; Update buffer-local dired-subdir-alist(setcarelt(dired-normalize-subdir(dired-replace-in-stringregexpnewtext(carelt)))))));; The basic function for half a dozen variations on cp/mv/ln/ln -s.(defundired-create-files(file-creatoroperationfn-listname-constructor&optionalmarker-char);; Create a new file for each from a list of existing files. The user;; is queried, dired buffers are updated, and at the end a success or;; failure message is displayed;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists;; It is called for each file and must create newfile, the entry of;; which will be added. The user will be queried if the file already;; exists. If oldfile is removed by FILE-CREATOR (i.e, it is a;; rename), it is FILE-CREATOR's responsibility to update dired;; buffers. FILE-CREATOR must abort by signaling a file-error if it;; could not create newfile. The error is caught and logged.;; OPERATION (a capitalized string, e.g. `Copy') describes the;; operation performed. It is used for error logging.;; FN-LIST is the list of files to copy (full absolute pathnames).;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to;; skip. If it skips files for other reasons than a direct user;; query, it is supposed to tell why (using dired-log).;; Optional MARKER-CHAR is a character with which to mark every;; newfile's entry, or t to use the current marker character if the;; oldfile was marked.(let(failuresskipped(success-count0)(total(lengthfn-list)))(let(tooverwrite-queryoverwrite-backup-query); for dired-handle-overwrite(mapcar(function(lambda(from)(setqto(funcallname-constructorfrom))(if(equaltofrom)(progn(setqtonil)(dired-log"Cannot %s to same file: %s\n"(downcaseoperation)from)))(if(notto)(setqskipped(cons(dired-make-relativefrom)skipped))(let*((overwrite(file-exists-pto))(dired-overwrite-confirmed; for dired-handle-overwrite(andoverwrite(let((help-form'(format"\Type SPC or `y' to overwrite file `%s',DEL or `n' to skip to next,ESC or `q' to not overwrite any of the remaining files,`!' to overwrite all remaining files with no more questions."to)))(dired-query'overwrite-query"Overwrite `%s'?"to))));; must determine if FROM is marked before file-creator;; gets a chance to delete it (in case of a move).(actual-marker-char(cond((integerpmarker-char)marker-char)(marker-char(dired-file-markerfrom)); slow(tnil))))(condition-caseerr(progn(funcallfile-creatorfromtodired-overwrite-confirmed)(ifoverwrite;; If we get here, file-creator hasn't been aborted;; and the old entry (if any) has to be deleted;; before adding the new entry.(dired-remove-fileto))(setqsuccess-count(1+success-count))(message"%s: %d of %d"operationsuccess-counttotal)(dired-add-filetoactual-marker-char))(file-error; FILE-CREATOR aborted(progn(setqfailures(cons(dired-make-relativefrom)failures))(dired-log"%s `%s' to `%s' failed:\n%s\n"operationfromtoerr))))))))fn-list))(cond(failures(dired-log-summary(format"%s failed for %d of %d file%s"operation(lengthfailures)total(dired-plural-stotal))failures))(skipped(dired-log-summary(format"%s: %d of %d file%s skipped"operation(lengthskipped)total(dired-plural-stotal))skipped))(t(message"%s: %s file%s"operationsuccess-count(dired-plural-ssuccess-count)))))(dired-move-to-filename))(defundired-do-create-files(op-symbolfile-creatoroperationarg&optionalmarker-charop1how-to);; Create a new file for each marked file.;; Prompts user for target, which is a directory in which to create;; the new files. Target may be a plain file if only one marked;; file exists.;; OP-SYMBOL is the symbol for the operation. Function `dired-mark-pop-up';; will determine whether pop-ups are appropriate for this OP-SYMBOL.;; FILE-CREATOR and OPERATION as in dired-create-files.;; ARG as in dired-get-marked-files.;; Optional arg OP1 is an alternate form for OPERATION if there is;; only one file.;; Optional arg MARKER-CHAR as in dired-create-files.;; Optional arg HOW-TO determines how to treat target:;; If HOW-TO is not given (or nil), and target is a directory, the;; file(s) are created inside the target directory. If target;; is not a directory, there must be exactly one marked file,;; else error.;; If HOW-TO is t, then target is not modified. There must be;; exactly one marked file, else error.;; Else HOW-TO is assumed to be a function of one argument, target,;; that looks at target and returns a value for the into-dir;; variable. The function dired-into-dir-with-symlinks is provided;; for the case (common when creating symlinks) that symbolic;; links to directories are not to be considered as directories;; (as file-directory-p would if HOW-TO had been nil).(orop1(setqop1operation))(let*((fn-list(dired-get-marked-filesnilarg))(fn-count(lengthfn-list))(target(expand-file-name(dired-mark-read-file-name(concat(if(=1fn-count)op1operation)" %s to: ")(dired-dwim-target-directory)op-symbolarg(mapcar(functiondired-make-relative)fn-list))))(into-dir(cond((nullhow-to)(file-directory-ptarget))((eqhow-tot)nil)(t(funcallhow-totarget)))))(if(and(>fn-count1)(notinto-dir))(error"Marked %s: target must be a directory: %s"operationtarget));; rename-file bombs when moving directories unless we do this:(orinto-dir(setqtarget(directory-file-nametarget)))(dired-create-filesfile-creatoroperationfn-list(ifinto-dir; target is a directory;; This function uses fluid vars into-dir and target when called;; inside dired-create-files:(function(lambda(from)(expand-file-name(file-name-nondirectoryfrom)target)))(function(lambda(from)target)))marker-char)));; Read arguments for a marked-files command that wants a file name,;; perhaps popping up the list of marked files.;; ARG is the prefix arg and indicates whether the files came from;; marks (ARG=nil) or a repeat factor (integerp ARG).;; If the current file was used, the list has but one element and ARG;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).(defundired-mark-read-file-name(promptdirop-symbolargfiles)(dired-mark-pop-upnilop-symbolfiles(functionread-file-name)(formatprompt(dired-mark-promptargfiles))dir))(defundired-dwim-target-directory();; Try to guess which target directory the user may want.;; If there is a dired buffer displayed in the next window, use;; its current subdir, else use current subdir of this dired buffer.(let((this-dir(and(eqmajor-mode'dired-mode)(dired-current-directory))));; non-dired buffer may want to profit from this function, e.g. vm-uudecode(ifdired-dwim-target(let*((other-buf(window-buffer(next-window)))(other-dir(save-excursion(set-bufferother-buf)(and(eqmajor-mode'dired-mode)(dired-current-directory)))))(orother-dirthis-dir))this-dir)));;;###autoload(defundired-create-directory(directory)"Create a directory called DIRECTORY."(interactive(list(read-file-name"Create directory: "(dired-current-directory))))(let((expanded(directory-file-name(expand-file-namedirectory))))(make-directoryexpanded)(dired-add-fileexpanded)(dired-move-to-filename)))(defundired-into-dir-with-symlinks(target)(and(file-directory-ptarget)(not(file-symlink-ptarget))));; This may not always be what you want, especially if target is your;; home directory and it happens to be a symbolic link, as is often the;; case with NFS and automounters. Or if you want to make symlinks;; into directories that themselves are only symlinks, also quite;; common.;; So we don't use this function as value for HOW-TO in;; dired-do-symlink, which has the minor disadvantage of;; making links *into* a symlinked-dir, when you really wanted to;; *overwrite* that symlink. In that (rare, I guess) case, you'll;; just have to remove that symlink by hand before making your marked;; symlinks.;;;###autoload(defundired-do-copy(&optionalarg)"Copy all marked (or next ARG) files, or copy the current file.This normally preserves the last-modified date when copying.When operating on just the current file, you specify the new name.When operating on multiple or marked files, you specify a directory,and new copies of these files are made in that directorywith the same names that the files currently have."(interactive"P")(dired-do-create-files'copy(functiondired-copy-file)(ifdired-copy-preserve-time"Copy [-p]""Copy")argdired-keep-marker-copy));;;###autoload(defundired-do-symlink(&optionalarg)"Make symbolic links to current file or all marked (or next ARG) files.When operating on just the current file, you specify the new name.When operating on multiple or marked files, you specify a directoryand new symbolic links are made in that directorywith the same names that the files currently have."(interactive"P")(dired-do-create-files'symlink(functionmake-symbolic-link)"Symlink"argdired-keep-marker-symlink));;;###autoload(defundired-do-hardlink(&optionalarg)"Add names (hard links) current file or all marked (or next ARG) files.When operating on just the current file, you specify the new name.When operating on multiple or marked files, you specify a directoryand new hard links are made in that directorywith the same names that the files currently have."(interactive"P")(dired-do-create-files'hardlink(functionadd-name-to-file)"Hardlink"argdired-keep-marker-hardlink));;;###autoload(defundired-do-rename(&optionalarg)"Rename current file or all marked (or next ARG) files.When renaming just the current file, you specify the new name.When renaming multiple or marked files, you specify a directory."(interactive"P")(dired-do-create-files'move(functiondired-rename-file)"Move"argdired-keep-marker-rename"Rename"));;;###end dired-cp.el;;; 5K;;;###begin dired-re.el(defundired-do-create-files-regexp(file-creatoroperationargregexpnewname&optionalwhole-pathmarker-char);; Create a new file for each marked file using regexps.;; FILE-CREATOR and OPERATION as in dired-create-files.;; ARG as in dired-get-marked-files.;; Matches each marked file against REGEXP and constructs the new;; filename from NEWNAME (like in function replace-match).;; Optional arg WHOLE-PATH means match/replace the whole pathname;; instead of only the non-directory part of the file.;; Optional arg MARKER-CHAR as in dired-create-files.(let*((fn-list(dired-get-marked-filesnilarg))(fn-count(lengthfn-list))(operation-prompt(concatoperation" `%s' to `%s'?"))(rename-regexp-help-form(format"\Type SPC or `y' to %s one match, DEL or `n' to skip to next,`!' to %s all remaining matches with no more questions."(downcaseoperation)(downcaseoperation)))(regexp-name-constructor;; Function to construct new filename using REGEXP and NEWNAME:(ifwhole-path; easy (but rare) case(function(lambda(from)(let((to(dired-string-replace-matchregexpfromnewname));; must bind help-form directly around call to;; dired-query(help-formrename-regexp-help-form))(ifto(and(dired-query'rename-regexp-queryoperation-promptfromto)to)(dired-log"%s: %s did not match regexp %s\n"operationfromregexp)))));; not whole-path, replace non-directory part only(function(lambda(from)(let*((new(dired-string-replace-matchregexp(file-name-nondirectoryfrom)newname))(to(andnew; nil means there was no match(expand-file-namenew(file-name-directoryfrom))))(help-formrename-regexp-help-form))(ifto(and(dired-query'rename-regexp-queryoperation-prompt(dired-make-relativefrom)(dired-make-relativeto))to)(dired-log"%s: %s did not match regexp %s\n"operation(file-name-nondirectoryfrom)regexp)))))))rename-regexp-query)(dired-create-filesfile-creatoroperationfn-listregexp-name-constructormarker-char)))(defundired-mark-read-regexp(operation);; Prompt user about performing OPERATION.;; Read and return list of: regexp newname arg whole-path.(let*((whole-path(equal0(prefix-numeric-valuecurrent-prefix-arg)))(arg(ifwhole-pathnilcurrent-prefix-arg))(regexp(dired-read-regexp(concat(ifwhole-path"Path """)operation" from (regexp): ")))(newname(read-string(concat(ifwhole-path"Path """)operation" "regexp" to: "))))(listregexpnewnameargwhole-path)));;;###autoload(defundired-do-rename-regexp(regexpnewname&optionalargwhole-path)"Rename marked files containing REGEXP to NEWNAME.As each match is found, the user must type a character saying what to do with it. For directions, type \\[help-command] at that time.NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.REGEXP defaults to the last regexp used.With a zero prefix arg, renaming by regexp affects the complete pathname - usually only the non-directory part of file names is used and changed."(interactive(dired-mark-read-regexp"Rename"))(dired-do-create-files-regexp(functiondired-rename-file)"Rename"argregexpnewnamewhole-pathdired-keep-marker-rename));;;###autoload(defundired-do-copy-regexp(regexpnewname&optionalargwhole-path)"Copy all marked files containing REGEXP to NEWNAME.See function `dired-rename-regexp' for more info."(interactive(dired-mark-read-regexp"Copy"))(dired-do-create-files-regexp(functiondired-copy-file)(ifdired-copy-preserve-time"Copy [-p]""Copy")argregexpnewnamewhole-pathdired-keep-marker-copy));;;###autoload(defundired-do-hardlink-regexp(regexpnewname&optionalargwhole-path)"Hardlink all marked files containing REGEXP to NEWNAME.See function `dired-rename-regexp' for more info."(interactive(dired-mark-read-regexp"HardLink"))(dired-do-create-files-regexp(functionadd-name-to-file)"HardLink"argregexpnewnamewhole-pathdired-keep-marker-hardlink));;;###autoload(defundired-do-symlink-regexp(regexpnewname&optionalargwhole-path)"Symlink all marked files containing REGEXP to NEWNAME.See function `dired-rename-regexp' for more info."(interactive(dired-mark-read-regexp"SymLink"))(dired-do-create-files-regexp(functionmake-symbolic-link)"SymLink"argregexpnewnamewhole-pathdired-keep-marker-symlink))(defundired-create-files-non-directory(file-creatorbasename-constructoroperationarg);; Perform FILE-CREATOR on the non-directory part of marked files;; using function BASENAME-CONSTRUCTOR, with query for each file.;; OPERATION like in dired-create-files, ARG as in dired-get-marked-files.(let(rename-non-directory-query)(dired-create-filesfile-creatoroperation(dired-get-marked-filesnilarg)(function(lambda(from)(let((to(concat(file-name-directoryfrom)(funcallbasename-constructor(file-name-nondirectoryfrom)))))(and(let((help-form(format"\Type SPC or `y' to %s one file, DEL or `n' to skip to next,`!' to %s all remaining matches with no more questions."(downcaseoperation)(downcaseoperation))))(dired-query'rename-non-directory-query(concatoperation" `%s' to `%s'")(dired-make-relativefrom)(dired-make-relativeto)))to))))dired-keep-marker-rename)))(defundired-rename-non-directory(basename-constructoroperationarg)(dired-create-files-non-directory(functiondired-rename-file)basename-constructoroperationarg));;;###autoload(defundired-upcase(&optionalarg)"Rename all marked (or next ARG) files to upper case."(interactive"P")(dired-rename-non-directory(functionupcase)"Rename upcase"arg));;;###autoload(defundired-downcase(&optionalarg)"Rename all marked (or next ARG) files to lower case."(interactive"P")(dired-rename-non-directory(functiondowncase)"Rename downcase"arg));;;###end dired-re.el;;; 13K;;;###begin dired-ins.el;;;###autoload(defundired-maybe-insert-subdir(dirname&optionalswitchesno-error-if-not-dir-p)"Insert this subdirectory into the same dired buffer.If it is already present, just move to it (type \\[dired-do-redisplay] to refresh), else inserts it at its natural place (as `ls -lR' would have done).With a prefix arg, you may edit the ls switches used for this listing. You can add `R' to the switches to expand the whole tree starting at this subdirectory.This function takes some pains to conform to `ls -lR' output."(interactive(list(dired-get-filename)(ifcurrent-prefix-arg(read-string"Switches for listing: "dired-actual-switches))))(let((opoint(point)));; We don't need a marker for opoint as the subdir is always;; inserted *after* opoint.(setqdirname(file-name-as-directorydirname))(or(and(notswitches)(dired-goto-subdirdirname))(dired-insert-subdirdirnameswitchesno-error-if-not-dir-p));; Push mark so that it's easy to find back. Do this after the;; insert message so that the user sees the `Mark set' message.(push-markopoint)))(defundired-insert-subdir(dirname&optionalswitchesno-error-if-not-dir-p)"Insert this subdirectory into the same dired buffer.If it is already present, overwrites previous entry, else inserts it at its natural place (as `ls -lR' would have done).With a prefix arg, you may edit the `ls' switches used for this listing. You can add `R' to the switches to expand the whole tree starting at this subdirectory.This function takes some pains to conform to `ls -lR' output.";; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like;; Prospero where dired-ls does the right thing, but;; file-directory-p has not been redefined.(interactive(list(dired-get-filename)(ifcurrent-prefix-arg(read-string"Switches for listing: "dired-actual-switches))))(setqdirname(file-name-as-directory(expand-file-namedirname)))(dired-insert-subdir-validatedirnameswitches)(orno-error-if-not-dir-p(file-directory-pdirname)(error"Attempt to insert a non-directory: %s"dirname))(let((elt(assocdirnamedired-subdir-alist))switches-have-Rmark-alistcase-fold-searchbuffer-read-only);; case-fold-search is nil now, so we can test for capital `R':(if(setqswitches-have-R(andswitches(string-match"R"switches)));; avoid duplicated subdirs(setqmark-alist(dired-kill-treedirnamet)))(ifelt;; If subdir is already present, remove it and remember its marks(setqmark-alist(nconc(dired-insert-subdir-delelt)mark-alist))(dired-insert-subdir-newposdirname)); else compute new position(dired-insert-subdir-doupdatedirnameelt(dired-insert-subdir-doinsertdirnameswitches))(ifswitches-have-R(dired-build-subdir-alist))(dired-initial-positiondirname)(save-excursion(dired-mark-rememberedmark-alist))));; This is a separate function for dired-vms.(defundired-insert-subdir-validate(dirname&optionalswitches);; Check that it is valid to insert DIRNAME with SWITCHES.;; Signal an error if invalid (e.g. user typed `i' on `..').(or(dired-in-this-treedirname(expand-file-namedefault-directory))(error"%s: not in this directory tree"dirname))(ifswitches(let(case-fold-search)(mapcar(function(lambda(x)(or(eq(null(string-matchxswitches))(null(string-matchxdired-actual-switches)))(error"Can't have dirs with and without -%s switches together"x))));; all switches that make a difference to dired-get-filename:'("F""b")))))(defundired-alist-add(dirnew-marker);; Add new DIR at NEW-MARKER. Sort alist.(dired-alist-add-1dirnew-marker)(dired-alist-sort))(defundired-alist-sort();; Keep the alist sorted on buffer position.(setqdired-subdir-alist(sortdired-subdir-alist(function(lambda(elt1elt2)(>(dired-get-subdir-minelt1)(dired-get-subdir-minelt2)))))))(defundired-kill-tree(dirname&optionalremember-marks);;"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.;; With optional arg REMEMBER-MARKS, return an alist of marked files."(interactive"DKill tree below directory: ")(setqdirname(expand-file-namedirname))(let((s-alistdired-subdir-alist)dirm-alist)(whiles-alist(setqdir(car(cars-alist))s-alist(cdrs-alist))(if(and(not(string-equaldirdirname))(dired-in-this-treedirdirname)(dired-goto-subdirdir))(setqm-alist(nconc(dired-kill-subdirremember-marks)m-alist))))m-alist))(defundired-insert-subdir-newpos(new-dir);; Find pos for new subdir, according to tree order.;;(goto-char (point-max))(let((alistdired-subdir-alist)eltdirposnew-pos)(whilealist(setqelt(caralist)alist(cdralist)dir(carelt)pos(dired-get-subdir-minelt))(if(dired-tree-lesspdirnew-dir);; Insert NEW-DIR after DIR(setqnew-pos(dired-get-subdir-maxelt)alistnil)))(goto-charnew-pos));; want a separating newline between subdirs(or(eobp)(forward-line-1))(insert"\n")(point))(defundired-insert-subdir-del(element);; Erase an already present subdir (given by ELEMENT) from buffer.;; Move to that buffer position. Return a mark-alist.(let((begin-marker(dired-get-subdir-minelement)))(goto-charbegin-marker);; Are at beginning of subdir (and inside it!). Now determine its end:(goto-char(dired-subdir-max))(or(eobp);; want a separating newline _between_ subdirs:(forward-char-1))(prog1(dired-remember-marksbegin-marker(point))(delete-regionbegin-marker(point)))))(defundired-insert-subdir-doinsert(dirnameswitches);; Insert ls output after point and put point on the correct;; position for the subdir alist.;; Return the boundary of the inserted text (as list of BEG and END).(let((begin(point))end)(message"Reading directory %s..."dirname)(let((dired-actual-switches(orswitches(dired-replace-in-string"R"""dired-actual-switches))))(if(equaldirname(car(car(reversedired-subdir-alist))));; top level directory may contain wildcards:(dired-readin-insertdired-directory)(let((opoint(point)))(insert-directorydirnamedired-actual-switchesnilt)(dired-insert-set-propertiesopoint(point)))))(message"Reading directory %s...done"dirname)(setqend(point-marker))(indent-rigidlybeginend2);; call dired-insert-headerline afterwards, as under VMS dired-ls;; does insert the headerline itself and the insert function just;; moves point.;; Need a marker for END as this inserts text.(goto-charbegin)(dired-insert-headerlinedirname);; point is now like in dired-build-subdir-alist(prog1(listbegin(marker-positionend))(set-markerendnil))))(defundired-insert-subdir-doupdate(dirnameeltbeg-end);; Point is at the correct subdir alist position for ELT,;; BEG-END is the subdir-region (as list of begin and end).(ifelt; subdir was already present;; update its position (should actually be unchanged)(set-marker(dired-get-subdir-minelt)(point-marker))(dired-alist-adddirname(point-marker)));; The hook may depend on the subdir-alist containing the just;; inserted subdir, so run it after dired-alist-add:(ifdired-after-readin-hook(save-excursion(let((begin(nth0beg-end))(end(nth1beg-end)))(goto-charbegin)(save-restriction(narrow-to-regionbeginend);; hook may add or delete lines, but the subdir boundary;; marker floats(run-hooks'dired-after-readin-hook))))))(defundired-tree-lessp(dir1dir2);; Lexicographic order on pathname components, like `ls -lR':;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,;; i.e., iff DIR1 is a (grand)parent dir of DIR2,;; or DIR1 and DIR2 are in the same parentdir and their last;; components are string-lessp.;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.;; string-lessp could arguably be replaced by file-newer-than-file-p;; if dired-actual-switches contained `t'.(setqdir1(file-name-as-directorydir1)dir2(file-name-as-directorydir2))(let((components-1(dired-split"/"dir1))(components-2(dired-split"/"dir2)))(while(andcomponents-1components-2(equal(carcomponents-1)(carcomponents-2)))(setqcomponents-1(cdrcomponents-1)components-2(cdrcomponents-2)))(let((c1(carcomponents-1))(c2(carcomponents-2)))(cond((andc1c2)(string-lesspc1c2))((and(nullc1)(nullc2))nil); they are equal, not lessp((nullc1); c2 is a subdir of c1: c1<c2t)((nullc2); c1 is a subdir of c2: c1>c2nil)(t(error"This can't happen"))))));; There should be a builtin split function - inverse to mapconcat.(defundired-split(patstr&optionallimit)"Splitting on regexp PAT, turn string STR into a list of substrings.Optional third arg LIMIT (>= 1) is a limit to the length of theresulting list.Thus, if SEP is a regexp that only matches itself, (mapconcat 'identity (dired-split SEP STRING) SEP)is always equal to STRING."(let*((start(string-matchpatstr))(result(list(substringstr0start)))(count1)(end(ifstart(match-end0))))(ifend; else nothing left(while(and(or(not(integerplimit))(<countlimit))(string-matchpatstrend))(setqstart(match-beginning0)count(1+count)result(cons(substringstrendstart)result)end(match-end0)startend)))(if(and(or(not(integerplimit))(<countlimit))end); else nothing left(setqresult(cons(substringstrend)result)))(nreverseresult)));;; moving by subdirectories;;;###autoload(defundired-prev-subdir(arg&optionalno-error-if-not-foundno-skip)"Go to previous subdirectory, regardless of level.When called interactively and not on a subdir line, go to this subdir's line.";;(interactive "p")(interactive(list(ifcurrent-prefix-arg(prefix-numeric-valuecurrent-prefix-arg);; if on subdir start already, don't stay there!(if(dired-get-subdir)10))))(dired-next-subdir(-arg)no-error-if-not-foundno-skip))(defundired-subdir-min()(save-excursion(if(not(dired-prev-subdir0tt))(error"Not in a subdir!")(point))));;;###autoload(defundired-goto-subdir(dir)"Go to end of header line of DIR in this dired buffer.Return value of point on success, otherwise return nil.The next char is either \\n, or \\r if DIR is hidden."(interactive(prog1; let push-mark display its message(list(expand-file-name(completing-read"Goto in situ directory: "; promptdired-subdir-alist; tablenil; predicatet; require-match(dired-current-directory))))(push-mark)))(setqdir(file-name-as-directorydir))(let((elt(assocdirdired-subdir-alist)))(andelt(goto-char(dired-get-subdir-minelt));; dired-subdir-hidden-p and dired-add-entry depend on point being;; at either \r or \n after this function succeeds.(progn(skip-chars-forward"^\r\n")(point)))));;;###autoload(defundired-mark-subdir-files()"Mark all files except `.' and `..'."(interactive)(let((p-min(dired-subdir-min)))(dired-mark-files-in-regionp-min(dired-subdir-max))));;;###autoload(defundired-kill-subdir(&optionalremember-marks)"Remove all lines of current subdirectory.Lower levels are unaffected.";; With optional REMEMBER-MARKS, return a mark-alist.(interactive)(let((beg(dired-subdir-min))(end(dired-subdir-max))buffer-read-onlycur-dir)(setqcur-dir(dired-current-directory))(if(equalcur-dirdefault-directory)(error"Attempt to kill top level directory"))(prog1(ifremember-marks(dired-remember-marksbegend))(delete-regionbegend)(if(eobp); don't leave final blank line(delete-char-1))(dired-unsubdircur-dir))))(defundired-unsubdir(dir);; Remove DIR from the alist(setqdired-subdir-alist(delq(assocdirdired-subdir-alist)dired-subdir-alist)));;;###autoload(defundired-tree-up(arg)"Go up ARG levels in the dired tree."(interactive"p")(let((dir(dired-current-directory)))(while(>=arg1)(setqarg(1-arg)dir(file-name-directory(directory-file-namedir))));;(setq dir (expand-file-name dir))(or(dired-goto-subdirdir)(error"Cannot go up to %s - not in this tree."dir))));;;###autoload(defundired-tree-down()"Go down in the dired tree."(interactive)(let((dir(dired-current-directory)); has slashposcase-fold-search); filenames are case sensitive(let((rest(reversedired-subdir-alist))elt)(whilerest(setqelt(carrest)rest(cdrrest))(if(dired-in-this-tree(directory-file-name(carelt))dir)(setqrestnilpos(dired-goto-subdir(carelt))))))(ifpos(goto-charpos)(error"At the bottom"))));;; hiding(defundired-unhide-subdir()(let(buffer-read-only)(subst-char-in-region(dired-subdir-min)(dired-subdir-max)?\r?\n)))(defundired-hide-check()(orselective-display(error"selective-display must be t for subdir hiding to work!")))(defundired-subdir-hidden-p(dir)(andselective-display(save-excursion(dired-goto-subdirdir)(looking-at"\r"))));;;###autoload(defundired-hide-subdir(arg)"Hide or unhide the current subdirectory and move to next directory.Optional prefix arg is a repeat factor.Use \\[dired-hide-all] to (un)hide all directories."(interactive"p")(dired-hide-check)(while(>=(setqarg(1-arg))0)(let*((cur-dir(dired-current-directory))(hidden-p(dired-subdir-hidden-pcur-dir))(elt(assoccur-dirdired-subdir-alist))(end-pos(1-(dired-get-subdir-maxelt)))buffer-read-only);; keep header line visible, hide rest(goto-char(dired-get-subdir-minelt))(skip-chars-forward"^\n\r")(ifhidden-p(subst-char-in-region(point)end-pos?\r?\n)(subst-char-in-region(point)end-pos?\n?\r)))(dired-next-subdir1t)));;;###autoload(defundired-hide-all(arg)"Hide all subdirectories, leaving only their header lines.If there is already something hidden, make everything visible again.Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."(interactive"P")(dired-hide-check)(let(buffer-read-only)(if(save-excursion(goto-char(point-min))(search-forward"\r"nilt));; unhide - bombs on \r in filenames(subst-char-in-region(point-min)(point-max)?\r?\n);; hide(let((pos(point-max)); pos of end of last directory(alistdired-subdir-alist))(whilealist; while there are dirs before pos(subst-char-in-region(dired-get-subdir-min(caralist)); pos of prev dir(save-excursion(goto-charpos); current dir;; we're somewhere on current dir's line(forward-line-1)(point))?\n?\r)(setqpos(dired-get-subdir-min(caralist))); prev dir gets current dir(setqalist(cdralist)))))));;;###end dired-ins.el;; Functions for searching in tags style among marked files.;;;###autoload(defundired-do-search(regexp)"Search through all marked files for a match for REGEXP.Stops when a match is found.To continue searching for next match, use command \\[tags-loop-continue]."(interactive"sSearch marked files (regexp): ")(tags-searchregexp'(dired-get-marked-files)));;;###autoload(defundired-do-query-replace(fromto&optionaldelimited)"Do `query-replace-regexp' of FROM with TO, on all marked files.Third arg DELIMITED (prefix arg) means replace only word-delimited matches.If you exit (\\[keyboard-quit] or ESC), you can resume the query replacewith the command \\[tags-loop-continue]."(interactive"sQuery replace in marked files (regexp): \nsQuery replace %s by: \nP")(tags-query-replacefromtodelimited'(dired-get-marked-files)))(provide'dired-aux);;; dired-aux.el ends here