* server.el (server-start): Simplify loop.
[emacs.git] / src / dired.c
blobfc033ac7e39d8d6dc75ed2b28f3265498787b4c3
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985, 1986, 1993, 1994, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <setjmp.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
31 #include <grp.h>
33 #include <errno.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
39 /* The d_nameln member of a struct dirent includes the '\0' character
40 on some systems, but not on others. What's worse, you can't tell
41 at compile-time which one it will be, since it really depends on
42 the sort of system providing the filesystem you're reading from,
43 not the system you are running on. Paul Eggert
44 <eggert@bi.twinsun.com> says this occurs when Emacs is running on a
45 SunOS 4.1.2 host, reading a directory that is remote-mounted from a
46 Solaris 2.1 host and is in a native Solaris 2.1 filesystem.
48 Since applying strlen to the name always works, we'll just do that. */
49 #define NAMLEN(p) strlen (p->d_name)
51 #ifdef HAVE_DIRENT_H
53 #include <dirent.h>
54 #define DIRENTRY struct dirent
56 #else /* not HAVE_DIRENT_H */
58 #include <sys/dir.h>
59 #include <sys/stat.h>
61 #define DIRENTRY struct direct
63 extern DIR *opendir (char *);
64 extern struct direct *readdir (DIR *);
66 #endif /* HAVE_DIRENT_H */
68 /* Some versions of Cygwin don't have d_ino in `struct dirent'. */
69 #if defined(MSDOS) || defined(__CYGWIN__)
70 #define DIRENTRY_NONEMPTY(p) ((p)->d_name[0] != 0)
71 #else
72 #define DIRENTRY_NONEMPTY(p) ((p)->d_ino)
73 #endif
75 #include "lisp.h"
76 #include "systime.h"
77 #include "buffer.h"
78 #include "commands.h"
79 #include "character.h"
80 #include "charset.h"
81 #include "coding.h"
82 #include "regex.h"
83 #include "blockinput.h"
85 /* Returns a search buffer, with a fastmap allocated and ready to go. */
86 extern struct re_pattern_buffer *compile_pattern (Lisp_Object, struct re_registers *, Lisp_Object, int, int);
88 /* From filemode.c. Can't go in Lisp.h because of `stat'. */
89 extern void filemodestring (struct stat *, char *);
91 /* if system does not have symbolic links, it does not have lstat.
92 In that case, use ordinary stat instead. */
94 #ifndef S_IFLNK
95 #define lstat stat
96 #endif
98 extern Lisp_Object Vw32_get_true_file_attributes;
100 Lisp_Object Vcompletion_ignored_extensions;
101 Lisp_Object Qdirectory_files;
102 Lisp_Object Qdirectory_files_and_attributes;
103 Lisp_Object Qfile_name_completion;
104 Lisp_Object Qfile_name_all_completions;
105 Lisp_Object Qfile_attributes;
106 Lisp_Object Qfile_attributes_lessp;
108 static int scmp (const unsigned char *, const unsigned char *, int);
110 #ifdef WINDOWSNT
111 Lisp_Object
112 directory_files_internal_w32_unwind (Lisp_Object arg)
114 Vw32_get_true_file_attributes = arg;
115 return Qnil;
117 #endif
119 Lisp_Object
120 directory_files_internal_unwind (Lisp_Object dh)
122 DIR *d = (DIR *) XSAVE_VALUE (dh)->pointer;
123 BLOCK_INPUT;
124 closedir (d);
125 UNBLOCK_INPUT;
126 return Qnil;
129 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
130 When ATTRS is zero, return a list of directory filenames; when
131 non-zero, return a list of directory filenames and their attributes.
132 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
134 Lisp_Object
135 directory_files_internal (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, int attrs, Lisp_Object id_format)
137 DIR *d;
138 int directory_nbytes;
139 Lisp_Object list, dirfilename, encoded_directory;
140 struct re_pattern_buffer *bufp = NULL;
141 int needsep = 0;
142 int count = SPECPDL_INDEX ();
143 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
144 DIRENTRY *dp;
145 #ifdef WINDOWSNT
146 Lisp_Object w32_save = Qnil;
147 #endif
149 /* Because of file name handlers, these functions might call
150 Ffuncall, and cause a GC. */
151 list = encoded_directory = dirfilename = Qnil;
152 GCPRO5 (match, directory, list, dirfilename, encoded_directory);
153 dirfilename = Fdirectory_file_name (directory);
155 if (!NILP (match))
157 CHECK_STRING (match);
159 /* MATCH might be a flawed regular expression. Rather than
160 catching and signaling our own errors, we just call
161 compile_pattern to do the work for us. */
162 /* Pass 1 for the MULTIBYTE arg
163 because we do make multibyte strings if the contents warrant. */
164 # ifdef WINDOWSNT
165 /* Windows users want case-insensitive wildcards. */
166 bufp = compile_pattern (match, 0,
167 buffer_defaults.case_canon_table, 0, 1);
168 # else /* !WINDOWSNT */
169 bufp = compile_pattern (match, 0, Qnil, 0, 1);
170 # endif /* !WINDOWSNT */
173 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
174 run_pre_post_conversion_on_str which calls Lisp directly and
175 indirectly. */
176 if (STRING_MULTIBYTE (dirfilename))
177 dirfilename = ENCODE_FILE (dirfilename);
178 encoded_directory = (STRING_MULTIBYTE (directory)
179 ? ENCODE_FILE (directory) : directory);
181 /* Now *bufp is the compiled form of MATCH; don't call anything
182 which might compile a new regexp until we're done with the loop! */
184 BLOCK_INPUT;
185 d = opendir (SDATA (dirfilename));
186 UNBLOCK_INPUT;
187 if (d == NULL)
188 report_file_error ("Opening directory", Fcons (directory, Qnil));
190 /* Unfortunately, we can now invoke expand-file-name and
191 file-attributes on filenames, both of which can throw, so we must
192 do a proper unwind-protect. */
193 record_unwind_protect (directory_files_internal_unwind,
194 make_save_value (d, 0));
196 #ifdef WINDOWSNT
197 if (attrs)
199 extern int is_slow_fs (const char *);
201 /* Do this only once to avoid doing it (in w32.c:stat) for each
202 file in the directory, when we call Ffile_attributes below. */
203 record_unwind_protect (directory_files_internal_w32_unwind,
204 Vw32_get_true_file_attributes);
205 w32_save = Vw32_get_true_file_attributes;
206 if (EQ (Vw32_get_true_file_attributes, Qlocal))
208 /* w32.c:stat will notice these bindings and avoid calling
209 GetDriveType for each file. */
210 if (is_slow_fs (SDATA (dirfilename)))
211 Vw32_get_true_file_attributes = Qnil;
212 else
213 Vw32_get_true_file_attributes = Qt;
216 #endif
218 directory_nbytes = SBYTES (directory);
219 re_match_object = Qt;
221 /* Decide whether we need to add a directory separator. */
222 if (directory_nbytes == 0
223 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
224 needsep = 1;
226 /* Loop reading blocks until EOF or error. */
227 for (;;)
229 errno = 0;
230 dp = readdir (d);
232 if (dp == NULL && (0
233 #ifdef EAGAIN
234 || errno == EAGAIN
235 #endif
236 #ifdef EINTR
237 || errno == EINTR
238 #endif
240 { QUIT; continue; }
242 if (dp == NULL)
243 break;
245 if (DIRENTRY_NONEMPTY (dp))
247 int len;
248 int wanted = 0;
249 Lisp_Object name, finalname;
250 struct gcpro gcpro1, gcpro2;
252 len = NAMLEN (dp);
253 name = finalname = make_unibyte_string (dp->d_name, len);
254 GCPRO2 (finalname, name);
256 /* Note: DECODE_FILE can GC; it should protect its argument,
257 though. */
258 name = DECODE_FILE (name);
259 len = SBYTES (name);
261 /* Now that we have unwind_protect in place, we might as well
262 allow matching to be interrupted. */
263 immediate_quit = 1;
264 QUIT;
266 if (NILP (match)
267 || (0 <= re_search (bufp, SDATA (name), len, 0, len, 0)))
268 wanted = 1;
270 immediate_quit = 0;
272 if (wanted)
274 if (!NILP (full))
276 Lisp_Object fullname;
277 int nbytes = len + directory_nbytes + needsep;
278 int nchars;
280 fullname = make_uninit_multibyte_string (nbytes, nbytes);
281 memcpy (SDATA (fullname), SDATA (directory),
282 directory_nbytes);
284 if (needsep)
285 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
287 memcpy (SDATA (fullname) + directory_nbytes + needsep,
288 SDATA (name), len);
290 nchars = chars_in_text (SDATA (fullname), nbytes);
292 /* Some bug somewhere. */
293 if (nchars > nbytes)
294 abort ();
296 STRING_SET_CHARS (fullname, nchars);
297 if (nchars == nbytes)
298 STRING_SET_UNIBYTE (fullname);
300 finalname = fullname;
302 else
303 finalname = name;
305 if (attrs)
307 /* Construct an expanded filename for the directory entry.
308 Use the decoded names for input to Ffile_attributes. */
309 Lisp_Object decoded_fullname, fileattrs;
310 struct gcpro gcpro1, gcpro2;
312 decoded_fullname = fileattrs = Qnil;
313 GCPRO2 (decoded_fullname, fileattrs);
315 /* Both Fexpand_file_name and Ffile_attributes can GC. */
316 decoded_fullname = Fexpand_file_name (name, directory);
317 fileattrs = Ffile_attributes (decoded_fullname, id_format);
319 list = Fcons (Fcons (finalname, fileattrs), list);
320 UNGCPRO;
322 else
323 list = Fcons (finalname, list);
326 UNGCPRO;
330 BLOCK_INPUT;
331 closedir (d);
332 UNBLOCK_INPUT;
333 #ifdef WINDOWSNT
334 if (attrs)
335 Vw32_get_true_file_attributes = w32_save;
336 #endif
338 /* Discard the unwind protect. */
339 specpdl_ptr = specpdl + count;
341 if (NILP (nosort))
342 list = Fsort (Fnreverse (list),
343 attrs ? Qfile_attributes_lessp : Qstring_lessp);
345 RETURN_UNGCPRO (list);
349 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
350 doc: /* Return a list of names of files in DIRECTORY.
351 There are three optional arguments:
352 If FULL is non-nil, return absolute file names. Otherwise return names
353 that are relative to the specified directory.
354 If MATCH is non-nil, mention only file names that match the regexp MATCH.
355 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
356 Otherwise, the list returned is sorted with `string-lessp'.
357 NOSORT is useful if you plan to sort the result yourself. */)
358 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
360 Lisp_Object handler;
361 directory = Fexpand_file_name (directory, Qnil);
363 /* If the file name has special constructs in it,
364 call the corresponding file handler. */
365 handler = Ffind_file_name_handler (directory, Qdirectory_files);
366 if (!NILP (handler))
367 return call5 (handler, Qdirectory_files, directory,
368 full, match, nosort);
370 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
373 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
374 Sdirectory_files_and_attributes, 1, 5, 0,
375 doc: /* Return a list of names of files and their attributes in DIRECTORY.
376 There are four optional arguments:
377 If FULL is non-nil, return absolute file names. Otherwise return names
378 that are relative to the specified directory.
379 If MATCH is non-nil, mention only file names that match the regexp MATCH.
380 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
381 NOSORT is useful if you plan to sort the result yourself.
382 ID-FORMAT specifies the preferred format of attributes uid and gid, see
383 `file-attributes' for further documentation.
384 On MS-Windows, performance depends on `w32-get-true-file-attributes',
385 which see. */)
386 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
388 Lisp_Object handler;
389 directory = Fexpand_file_name (directory, Qnil);
391 /* If the file name has special constructs in it,
392 call the corresponding file handler. */
393 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
394 if (!NILP (handler))
395 return call6 (handler, Qdirectory_files_and_attributes,
396 directory, full, match, nosort, id_format);
398 return directory_files_internal (directory, full, match, nosort, 1, id_format);
402 Lisp_Object file_name_completion (Lisp_Object file, Lisp_Object dirname, int all_flag, int ver_flag, Lisp_Object predicate);
404 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
405 2, 3, 0,
406 doc: /* Complete file name FILE in directory DIRECTORY.
407 Returns the longest string
408 common to all file names in DIRECTORY that start with FILE.
409 If there is only one and FILE matches it exactly, returns t.
410 Returns nil if DIRECTORY contains no name starting with FILE.
412 If PREDICATE is non-nil, call PREDICATE with each possible
413 completion (in absolute form) and ignore it if PREDICATE returns nil.
415 This function ignores some of the possible completions as
416 determined by the variable `completion-ignored-extensions', which see. */)
417 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
419 Lisp_Object handler;
421 /* If the directory name has special constructs in it,
422 call the corresponding file handler. */
423 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
424 if (!NILP (handler))
425 return call4 (handler, Qfile_name_completion, file, directory, predicate);
427 /* If the file name has special constructs in it,
428 call the corresponding file handler. */
429 handler = Ffind_file_name_handler (file, Qfile_name_completion);
430 if (!NILP (handler))
431 return call4 (handler, Qfile_name_completion, file, directory, predicate);
433 return file_name_completion (file, directory, 0, 0, predicate);
436 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
437 Sfile_name_all_completions, 2, 2, 0,
438 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
439 These are all file names in directory DIRECTORY which begin with FILE. */)
440 (Lisp_Object file, Lisp_Object directory)
442 Lisp_Object handler;
444 /* If the directory name has special constructs in it,
445 call the corresponding file handler. */
446 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
447 if (!NILP (handler))
448 return call3 (handler, Qfile_name_all_completions, file, directory);
450 /* If the file name has special constructs in it,
451 call the corresponding file handler. */
452 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
453 if (!NILP (handler))
454 return call3 (handler, Qfile_name_all_completions, file, directory);
456 return file_name_completion (file, directory, 1, 0, Qnil);
459 static int file_name_completion_stat (Lisp_Object dirname, DIRENTRY *dp, struct stat *st_addr);
460 Lisp_Object Qdefault_directory;
462 Lisp_Object
463 file_name_completion (Lisp_Object file, Lisp_Object dirname, int all_flag, int ver_flag, Lisp_Object predicate)
465 DIR *d;
466 int bestmatchsize = 0;
467 int matchcount = 0;
468 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
469 If ALL_FLAG is 0, BESTMATCH is either nil
470 or the best match so far, not decoded. */
471 Lisp_Object bestmatch, tem, elt, name;
472 Lisp_Object encoded_file;
473 Lisp_Object encoded_dir;
474 struct stat st;
475 int directoryp;
476 /* If includeall is zero, exclude files in completion-ignored-extensions as
477 well as "." and "..". Until shown otherwise, assume we can't exclude
478 anything. */
479 int includeall = 1;
480 int count = SPECPDL_INDEX ();
481 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
483 elt = Qnil;
485 CHECK_STRING (file);
487 #ifdef FILE_SYSTEM_CASE
488 file = FILE_SYSTEM_CASE (file);
489 #endif
490 bestmatch = Qnil;
491 encoded_file = encoded_dir = Qnil;
492 GCPRO5 (file, dirname, bestmatch, encoded_file, encoded_dir);
493 dirname = Fexpand_file_name (dirname, Qnil);
494 specbind (Qdefault_directory, dirname);
496 /* Do completion on the encoded file name
497 because the other names in the directory are (we presume)
498 encoded likewise. We decode the completed string at the end. */
499 /* Actually, this is not quite true any more: we do most of the completion
500 work with decoded file names, but we still do some filtering based
501 on the encoded file name. */
502 encoded_file = STRING_MULTIBYTE (file) ? ENCODE_FILE (file) : file;
504 encoded_dir = ENCODE_FILE (dirname);
506 BLOCK_INPUT;
507 d = opendir (SDATA (Fdirectory_file_name (encoded_dir)));
508 UNBLOCK_INPUT;
509 if (!d)
510 report_file_error ("Opening directory", Fcons (dirname, Qnil));
512 record_unwind_protect (directory_files_internal_unwind,
513 make_save_value (d, 0));
515 /* Loop reading blocks */
516 /* (att3b compiler bug requires do a null comparison this way) */
517 while (1)
519 DIRENTRY *dp;
520 int len;
521 int canexclude = 0;
523 errno = 0;
524 dp = readdir (d);
525 if (dp == NULL && (0
526 # ifdef EAGAIN
527 || errno == EAGAIN
528 # endif
529 # ifdef EINTR
530 || errno == EINTR
531 # endif
533 { QUIT; continue; }
535 if (!dp) break;
537 len = NAMLEN (dp);
539 QUIT;
540 if (! DIRENTRY_NONEMPTY (dp)
541 || len < SCHARS (encoded_file)
542 || 0 <= scmp (dp->d_name, SDATA (encoded_file),
543 SCHARS (encoded_file)))
544 continue;
546 if (file_name_completion_stat (encoded_dir, dp, &st) < 0)
547 continue;
549 directoryp = ((st.st_mode & S_IFMT) == S_IFDIR);
550 tem = Qnil;
551 /* If all_flag is set, always include all.
552 It would not actually be helpful to the user to ignore any possible
553 completions when making a list of them. */
554 if (!all_flag)
556 int skip;
558 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
559 /* If this entry matches the current bestmatch, the only
560 thing it can do is increase matchcount, so don't bother
561 investigating it any further. */
562 if (!completion_ignore_case
563 /* The return result depends on whether it's the sole match. */
564 && matchcount > 1
565 && !includeall /* This match may allow includeall to 0. */
566 && len >= bestmatchsize
567 && 0 > scmp (dp->d_name, SDATA (bestmatch), bestmatchsize))
568 continue;
569 #endif
571 if (directoryp)
573 #ifndef TRIVIAL_DIRECTORY_ENTRY
574 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
575 #endif
576 /* "." and ".." are never interesting as completions, and are
577 actually in the way in a directory with only one file. */
578 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
579 canexclude = 1;
580 else if (len > SCHARS (encoded_file))
581 /* Ignore directories if they match an element of
582 completion-ignored-extensions which ends in a slash. */
583 for (tem = Vcompletion_ignored_extensions;
584 CONSP (tem); tem = XCDR (tem))
586 int elt_len;
587 unsigned char *p1;
589 elt = XCAR (tem);
590 if (!STRINGP (elt))
591 continue;
592 /* Need to encode ELT, since scmp compares unibyte
593 strings only. */
594 elt = ENCODE_FILE (elt);
595 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
596 if (elt_len <= 0)
597 continue;
598 p1 = SDATA (elt);
599 if (p1[elt_len] != '/')
600 continue;
601 skip = len - elt_len;
602 if (skip < 0)
603 continue;
605 if (0 <= scmp (dp->d_name + skip, p1, elt_len))
606 continue;
607 break;
610 else
612 /* Compare extensions-to-be-ignored against end of this file name */
613 /* if name is not an exact match against specified string */
614 if (len > SCHARS (encoded_file))
615 /* and exit this for loop if a match is found */
616 for (tem = Vcompletion_ignored_extensions;
617 CONSP (tem); tem = XCDR (tem))
619 elt = XCAR (tem);
620 if (!STRINGP (elt)) continue;
621 /* Need to encode ELT, since scmp compares unibyte
622 strings only. */
623 elt = ENCODE_FILE (elt);
624 skip = len - SCHARS (elt);
625 if (skip < 0) continue;
627 if (0 <= scmp (dp->d_name + skip,
628 SDATA (elt),
629 SCHARS (elt)))
630 continue;
631 break;
635 /* If an ignored-extensions match was found,
636 don't process this name as a completion. */
637 if (CONSP (tem))
638 canexclude = 1;
640 if (!includeall && canexclude)
641 /* We're not including all files and this file can be excluded. */
642 continue;
644 if (includeall && !canexclude)
645 { /* If we have one non-excludable file, we want to exclude the
646 excudable files. */
647 includeall = 0;
648 /* Throw away any previous excludable match found. */
649 bestmatch = Qnil;
650 bestmatchsize = 0;
651 matchcount = 0;
654 /* FIXME: If we move this `decode' earlier we can eliminate
655 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
656 name = make_unibyte_string (dp->d_name, len);
657 name = DECODE_FILE (name);
660 Lisp_Object regexps;
661 Lisp_Object zero;
662 XSETFASTINT (zero, 0);
664 /* Ignore this element if it fails to match all the regexps. */
665 if (completion_ignore_case)
667 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
668 regexps = XCDR (regexps))
669 if (fast_string_match_ignore_case (XCAR (regexps), name) < 0)
670 break;
672 else
674 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
675 regexps = XCDR (regexps))
676 if (fast_string_match (XCAR (regexps), name) < 0)
677 break;
680 if (CONSP (regexps))
681 continue;
684 /* This is a possible completion */
685 if (directoryp)
686 /* This completion is a directory; make it end with '/'. */
687 name = Ffile_name_as_directory (name);
689 /* Test the predicate, if any. */
690 if (!NILP (predicate))
692 Lisp_Object val;
693 struct gcpro gcpro1;
695 GCPRO1 (name);
696 val = call1 (predicate, name);
697 UNGCPRO;
699 if (NILP (val))
700 continue;
703 /* Suitably record this match. */
705 matchcount++;
707 if (all_flag)
708 bestmatch = Fcons (name, bestmatch);
709 else if (NILP (bestmatch))
711 bestmatch = name;
712 bestmatchsize = SCHARS (name);
714 else
716 Lisp_Object zero = make_number (0);
717 /* FIXME: This is a copy of the code in Ftry_completion. */
718 int compare = min (bestmatchsize, SCHARS (name));
719 Lisp_Object tem
720 = Fcompare_strings (bestmatch, zero,
721 make_number (compare),
722 name, zero,
723 make_number (compare),
724 completion_ignore_case ? Qt : Qnil);
725 int matchsize
726 = (EQ (tem, Qt) ? compare
727 : XINT (tem) < 0 ? - XINT (tem) - 1
728 : XINT (tem) - 1);
730 if (completion_ignore_case)
732 /* If this is an exact match except for case,
733 use it as the best match rather than one that is not
734 an exact match. This way, we get the case pattern
735 of the actual match. */
736 /* This tests that the current file is an exact match
737 but BESTMATCH is not (it is too long). */
738 if ((matchsize == SCHARS (name)
739 && matchsize + !!directoryp < SCHARS (bestmatch))
741 /* If there is no exact match ignoring case,
742 prefer a match that does not change the case
743 of the input. */
744 /* If there is more than one exact match aside from
745 case, and one of them is exact including case,
746 prefer that one. */
747 /* This == checks that, of current file and BESTMATCH,
748 either both or neither are exact. */
749 (((matchsize == SCHARS (name))
751 (matchsize + !!directoryp == SCHARS (bestmatch)))
752 && (tem = Fcompare_strings (name, zero,
753 make_number (SCHARS (file)),
754 file, zero,
755 Qnil,
756 Qnil),
757 EQ (Qt, tem))
758 && (tem = Fcompare_strings (bestmatch, zero,
759 make_number (SCHARS (file)),
760 file, zero,
761 Qnil,
762 Qnil),
763 ! EQ (Qt, tem))))
764 bestmatch = name;
766 bestmatchsize = matchsize;
768 /* If the best completion so far is reduced to the string
769 we're trying to complete, then we already know there's no
770 other completion, so there's no point looking any further. */
771 if (matchsize <= SCHARS (file)
772 && !includeall /* A future match may allow includeall to 0. */
773 /* If completion-ignore-case is non-nil, don't
774 short-circuit because we want to find the best
775 possible match *including* case differences. */
776 && (!completion_ignore_case || matchsize == 0)
777 /* The return value depends on whether it's the sole match. */
778 && matchcount > 1)
779 break;
784 UNGCPRO;
785 /* This closes the directory. */
786 bestmatch = unbind_to (count, bestmatch);
788 if (all_flag || NILP (bestmatch))
789 return bestmatch;
790 /* Return t if the supplied string is an exact match (counting case);
791 it does not require any change to be made. */
792 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
793 return Qt;
794 bestmatch = Fsubstring (bestmatch, make_number (0),
795 make_number (bestmatchsize));
796 return bestmatch;
799 /* Compare exactly LEN chars of strings at S1 and S2,
800 ignoring case if appropriate.
801 Return -1 if strings match,
802 else number of chars that match at the beginning. */
804 static int
805 scmp (const unsigned char *s1, const unsigned char *s2, int len)
807 register int l = len;
809 if (completion_ignore_case)
811 while (l && DOWNCASE (*s1++) == DOWNCASE (*s2++))
812 l--;
814 else
816 while (l && *s1++ == *s2++)
817 l--;
819 if (l == 0)
820 return -1;
821 else
822 return len - l;
825 static int
826 file_name_completion_stat (Lisp_Object dirname, DIRENTRY *dp, struct stat *st_addr)
828 int len = NAMLEN (dp);
829 int pos = SCHARS (dirname);
830 int value;
831 char *fullname = (char *) alloca (len + pos + 2);
833 #ifdef MSDOS
834 /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
835 but aren't required here. Avoid computing the following fields:
836 st_inode, st_size and st_nlink for directories, and the execute bits
837 in st_mode for non-directory files with non-standard extensions. */
839 unsigned short save_djstat_flags = _djstat_flags;
841 _djstat_flags = _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
842 #endif /* MSDOS */
844 memcpy (fullname, SDATA (dirname), pos);
845 if (!IS_DIRECTORY_SEP (fullname[pos - 1]))
846 fullname[pos++] = DIRECTORY_SEP;
848 memcpy (fullname + pos, dp->d_name, len);
849 fullname[pos + len] = 0;
851 #ifdef S_IFLNK
852 /* We want to return success if a link points to a nonexistent file,
853 but we want to return the status for what the link points to,
854 in case it is a directory. */
855 value = lstat (fullname, st_addr);
856 stat (fullname, st_addr);
857 return value;
858 #else
859 value = stat (fullname, st_addr);
860 #ifdef MSDOS
861 _djstat_flags = save_djstat_flags;
862 #endif /* MSDOS */
863 return value;
864 #endif /* S_IFLNK */
867 Lisp_Object
868 make_time (time_t time)
870 return Fcons (make_number (time >> 16),
871 Fcons (make_number (time & 0177777), Qnil));
874 static char *
875 stat_uname (struct stat *st)
877 #ifdef WINDOWSNT
878 return st->st_uname;
879 #else
880 struct passwd *pw = (struct passwd *) getpwuid (st->st_uid);
882 if (pw)
883 return pw->pw_name;
884 else
885 return NULL;
886 #endif
889 static char *
890 stat_gname (struct stat *st)
892 #ifdef WINDOWSNT
893 return st->st_gname;
894 #else
895 struct group *gr = (struct group *) getgrgid (st->st_gid);
897 if (gr)
898 return gr->gr_name;
899 else
900 return NULL;
901 #endif
904 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
905 doc: /* Return a list of attributes of file FILENAME.
906 Value is nil if specified file cannot be opened.
908 ID-FORMAT specifies the preferred format of attributes uid and gid (see
909 below) - valid values are 'string and 'integer. The latter is the
910 default, but we plan to change that, so you should specify a non-nil value
911 for ID-FORMAT if you use the returned uid or gid.
913 Elements of the attribute list are:
914 0. t for directory, string (name linked to) for symbolic link, or nil.
915 1. Number of links to file.
916 2. File uid as a string or a number. If a string value cannot be
917 looked up, a numeric value, either an integer or a float, is returned.
918 3. File gid, likewise.
919 4. Last access time, as a list of two integers.
920 First integer has high-order 16 bits of time, second has low 16 bits.
921 (See a note below about access time on FAT-based filesystems.)
922 5. Last modification time, likewise. This is the time of the last
923 change to the file's contents.
924 6. Last status change time, likewise. This is the time of last change
925 to the file's attributes: owner and group, access mode bits, etc.
926 7. Size in bytes.
927 This is a floating point number if the size is too large for an integer.
928 8. File modes, as a string of ten letters or dashes as in ls -l.
929 9. t if file's gid would change if file were deleted and recreated.
930 10. inode number. If inode number is larger than what Emacs integer
931 can hold, but still fits into a 32-bit number, this is a cons cell
932 containing two integers: first the high part, then the low 16 bits.
933 If the inode number is wider than 32 bits, this is of the form
934 (HIGH MIDDLE . LOW): first the high 24 bits, then middle 24 bits,
935 and finally the low 16 bits.
936 11. Filesystem device number. If it is larger than what the Emacs
937 integer can hold, this is a cons cell, similar to the inode number.
939 On most filesystems, the combination of the inode and the device
940 number uniquely identifies the file.
942 On MS-Windows, performance depends on `w32-get-true-file-attributes',
943 which see.
945 On some FAT-based filesystems, only the date of last access is recorded,
946 so last access time will always be midnight of that day. */)
947 (Lisp_Object filename, Lisp_Object id_format)
949 Lisp_Object values[12];
950 Lisp_Object encoded;
951 struct stat s;
952 #ifdef BSD4_2
953 Lisp_Object dirname;
954 struct stat sdir;
955 #endif /* BSD4_2 */
956 char modes[10];
957 Lisp_Object handler;
958 struct gcpro gcpro1;
959 char *uname = NULL, *gname = NULL;
961 filename = Fexpand_file_name (filename, Qnil);
963 /* If the file name has special constructs in it,
964 call the corresponding file handler. */
965 handler = Ffind_file_name_handler (filename, Qfile_attributes);
966 if (!NILP (handler))
967 { /* Only pass the extra arg if it is used to help backward compatibility
968 with old file handlers which do not implement the new arg. --Stef */
969 if (NILP (id_format))
970 return call2 (handler, Qfile_attributes, filename);
971 else
972 return call3 (handler, Qfile_attributes, filename, id_format);
975 GCPRO1 (filename);
976 encoded = ENCODE_FILE (filename);
977 UNGCPRO;
979 if (lstat (SDATA (encoded), &s) < 0)
980 return Qnil;
982 switch (s.st_mode & S_IFMT)
984 default:
985 values[0] = Qnil; break;
986 case S_IFDIR:
987 values[0] = Qt; break;
988 #ifdef S_IFLNK
989 case S_IFLNK:
990 values[0] = Ffile_symlink_p (filename); break;
991 #endif
993 values[1] = make_number (s.st_nlink);
995 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
997 BLOCK_INPUT;
998 uname = stat_uname (&s);
999 gname = stat_gname (&s);
1000 UNBLOCK_INPUT;
1002 if (uname)
1003 values[2] = DECODE_SYSTEM (build_string (uname));
1004 else
1005 values[2] = make_fixnum_or_float (s.st_uid);
1006 if (gname)
1007 values[3] = DECODE_SYSTEM (build_string (gname));
1008 else
1009 values[3] = make_fixnum_or_float (s.st_gid);
1011 values[4] = make_time (s.st_atime);
1012 values[5] = make_time (s.st_mtime);
1013 values[6] = make_time (s.st_ctime);
1014 values[7] = make_fixnum_or_float (s.st_size);
1015 /* If the size is negative, and its type is long, convert it back to
1016 positive. */
1017 if (s.st_size < 0 && sizeof (s.st_size) == sizeof (long))
1018 values[7] = make_float ((double) ((unsigned long) s.st_size));
1020 filemodestring (&s, modes);
1021 values[8] = make_string (modes, 10);
1022 #ifdef BSD4_2 /* file gid will be dir gid */
1023 dirname = Ffile_name_directory (filename);
1024 if (! NILP (dirname))
1025 encoded = ENCODE_FILE (dirname);
1026 if (! NILP (dirname) && stat (SDATA (encoded), &sdir) == 0)
1027 values[9] = (sdir.st_gid != s.st_gid) ? Qt : Qnil;
1028 else /* if we can't tell, assume worst */
1029 values[9] = Qt;
1030 #else /* file gid will be egid */
1031 values[9] = (s.st_gid != getegid ()) ? Qt : Qnil;
1032 #endif /* not BSD4_2 */
1033 if (!FIXNUM_OVERFLOW_P (s.st_ino))
1034 /* Keep the most common cases as integers. */
1035 values[10] = make_number (s.st_ino);
1036 else if (!FIXNUM_OVERFLOW_P (s.st_ino >> 16))
1037 /* To allow inode numbers larger than VALBITS, separate the bottom
1038 16 bits. */
1039 values[10] = Fcons (make_number ((EMACS_INT)(s.st_ino >> 16)),
1040 make_number ((EMACS_INT)(s.st_ino & 0xffff)));
1041 else
1043 /* To allow inode numbers beyond 32 bits, separate into 2 24-bit
1044 high parts and a 16-bit bottom part.
1045 The code on the next line avoids a compiler warning on
1046 systems where st_ino is 32 bit wide. (bug#766). */
1047 EMACS_INT high_ino = s.st_ino >> 31 >> 1;
1048 EMACS_INT low_ino = s.st_ino & 0xffffffff;
1050 values[10] = Fcons (make_number (high_ino >> 8),
1051 Fcons (make_number (((high_ino & 0xff) << 16)
1052 + (low_ino >> 16)),
1053 make_number (low_ino & 0xffff)));
1056 /* Likewise for device. */
1057 if (FIXNUM_OVERFLOW_P (s.st_dev))
1058 values[11] = Fcons (make_number (s.st_dev >> 16),
1059 make_number (s.st_dev & 0xffff));
1060 else
1061 values[11] = make_number (s.st_dev);
1063 return Flist (sizeof(values) / sizeof(values[0]), values);
1066 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
1067 doc: /* Return t if first arg file attributes list is less than second.
1068 Comparison is in lexicographic order and case is significant. */)
1069 (Lisp_Object f1, Lisp_Object f2)
1071 return Fstring_lessp (Fcar (f1), Fcar (f2));
1074 void
1075 syms_of_dired (void)
1077 Qdirectory_files = intern_c_string ("directory-files");
1078 Qdirectory_files_and_attributes = intern_c_string ("directory-files-and-attributes");
1079 Qfile_name_completion = intern_c_string ("file-name-completion");
1080 Qfile_name_all_completions = intern_c_string ("file-name-all-completions");
1081 Qfile_attributes = intern_c_string ("file-attributes");
1082 Qfile_attributes_lessp = intern_c_string ("file-attributes-lessp");
1083 Qdefault_directory = intern_c_string ("default-directory");
1085 staticpro (&Qdirectory_files);
1086 staticpro (&Qdirectory_files_and_attributes);
1087 staticpro (&Qfile_name_completion);
1088 staticpro (&Qfile_name_all_completions);
1089 staticpro (&Qfile_attributes);
1090 staticpro (&Qfile_attributes_lessp);
1091 staticpro (&Qdefault_directory);
1093 defsubr (&Sdirectory_files);
1094 defsubr (&Sdirectory_files_and_attributes);
1095 defsubr (&Sfile_name_completion);
1096 defsubr (&Sfile_name_all_completions);
1097 defsubr (&Sfile_attributes);
1098 defsubr (&Sfile_attributes_lessp);
1100 DEFVAR_LISP ("completion-ignored-extensions", &Vcompletion_ignored_extensions,
1101 doc: /* Completion ignores file names ending in any string in this list.
1102 It does not ignore them if all possible completions end in one of
1103 these strings or when displaying a list of completions.
1104 It ignores directory names if they match any string in this list which
1105 ends in a slash. */);
1106 Vcompletion_ignored_extensions = Qnil;
1109 /* arch-tag: 1ac8deca-4d8f-4d41-ade9-089154d98c03
1110 (do not change this comment) */