Backport the :end-of-capability fix
[emacs.git] / src / dired.c
blob43cb8373a6d55199a5815423f352f7a17de5ecac
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2015 Free Software
3 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>
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30 #include <grp.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <unistd.h>
36 #include <dirent.h>
37 #include <filemode.h>
38 #include <stat-time.h>
40 #include "lisp.h"
41 #include "systime.h"
42 #include "character.h"
43 #include "buffer.h"
44 #include "commands.h"
45 #include "charset.h"
46 #include "coding.h"
47 #include "regex.h"
48 #include "blockinput.h"
50 #ifdef MSDOS
51 #include "msdos.h" /* for fstatat */
52 #endif
54 static Lisp_Object Qdirectory_files;
55 static Lisp_Object Qdirectory_files_and_attributes;
56 static Lisp_Object Qfile_name_completion;
57 static Lisp_Object Qfile_name_all_completions;
58 static Lisp_Object Qfile_attributes;
59 static Lisp_Object Qfile_attributes_lessp;
61 static ptrdiff_t scmp (const char *, const char *, ptrdiff_t);
62 static Lisp_Object file_attributes (int, char const *, Lisp_Object);
64 /* Return the number of bytes in DP's name. */
65 static ptrdiff_t
66 dirent_namelen (struct dirent *dp)
68 #ifdef _D_EXACT_NAMLEN
69 return _D_EXACT_NAMLEN (dp);
70 #else
71 return strlen (dp->d_name);
72 #endif
75 static DIR *
76 open_directory (char const *name, int *fdp)
78 DIR *d;
79 int fd, opendir_errno;
81 block_input ();
83 #ifdef DOS_NT
84 /* Directories cannot be opened. The emulation assumes that any
85 file descriptor other than AT_FDCWD corresponds to the most
86 recently opened directory. This hack is good enough for Emacs. */
87 fd = 0;
88 d = opendir (name);
89 opendir_errno = errno;
90 #else
91 fd = emacs_open (name, O_RDONLY | O_DIRECTORY, 0);
92 if (fd < 0)
94 opendir_errno = errno;
95 d = 0;
97 else
99 d = fdopendir (fd);
100 opendir_errno = errno;
101 if (! d)
102 emacs_close (fd);
104 #endif
106 unblock_input ();
108 *fdp = fd;
109 errno = opendir_errno;
110 return d;
113 #ifdef WINDOWSNT
114 void
115 directory_files_internal_w32_unwind (Lisp_Object arg)
117 Vw32_get_true_file_attributes = arg;
119 #endif
121 static void
122 directory_files_internal_unwind (void *dh)
124 DIR *d = dh;
125 block_input ();
126 closedir (d);
127 unblock_input ();
130 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
131 If not ATTRS, return a list of directory filenames;
132 if ATTRS, return a list of directory filenames and their attributes.
133 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
135 Lisp_Object
136 directory_files_internal (Lisp_Object directory, Lisp_Object full,
137 Lisp_Object match, Lisp_Object nosort, bool attrs,
138 Lisp_Object id_format)
140 DIR *d;
141 int fd;
142 ptrdiff_t directory_nbytes;
143 Lisp_Object list, dirfilename, encoded_directory;
144 struct re_pattern_buffer *bufp = NULL;
145 bool needsep = 0;
146 ptrdiff_t count = SPECPDL_INDEX ();
147 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
148 struct dirent *dp;
149 #ifdef WINDOWSNT
150 Lisp_Object w32_save = Qnil;
151 #endif
153 /* Don't let the compiler optimize away all copies of DIRECTORY,
154 which would break GC; see Bug#16986. Although this is required
155 only in the common case where GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS,
156 it shouldn't break anything in the other cases. */
157 Lisp_Object volatile directory_volatile = directory;
159 /* Because of file name handlers, these functions might call
160 Ffuncall, and cause a GC. */
161 list = encoded_directory = dirfilename = Qnil;
162 GCPRO5 (match, directory, list, dirfilename, encoded_directory);
163 dirfilename = Fdirectory_file_name (directory);
165 if (!NILP (match))
167 CHECK_STRING (match);
169 /* MATCH might be a flawed regular expression. Rather than
170 catching and signaling our own errors, we just call
171 compile_pattern to do the work for us. */
172 /* Pass 1 for the MULTIBYTE arg
173 because we do make multibyte strings if the contents warrant. */
174 # ifdef WINDOWSNT
175 /* Windows users want case-insensitive wildcards. */
176 bufp = compile_pattern (match, 0,
177 BVAR (&buffer_defaults, case_canon_table), 0, 1);
178 # else /* !WINDOWSNT */
179 bufp = compile_pattern (match, 0, Qnil, 0, 1);
180 # endif /* !WINDOWSNT */
183 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
184 run_pre_post_conversion_on_str which calls Lisp directly and
185 indirectly. */
186 if (STRING_MULTIBYTE (dirfilename))
187 dirfilename = ENCODE_FILE (dirfilename);
188 encoded_directory = (STRING_MULTIBYTE (directory)
189 ? ENCODE_FILE (directory) : directory);
191 /* Now *bufp is the compiled form of MATCH; don't call anything
192 which might compile a new regexp until we're done with the loop! */
194 d = open_directory (SSDATA (dirfilename), &fd);
195 if (d == NULL)
196 report_file_error ("Opening directory", directory);
198 /* Unfortunately, we can now invoke expand-file-name and
199 file-attributes on filenames, both of which can throw, so we must
200 do a proper unwind-protect. */
201 record_unwind_protect_ptr (directory_files_internal_unwind, d);
203 #ifdef WINDOWSNT
204 if (attrs)
206 extern int is_slow_fs (const char *);
208 /* Do this only once to avoid doing it (in w32.c:stat) for each
209 file in the directory, when we call Ffile_attributes below. */
210 record_unwind_protect (directory_files_internal_w32_unwind,
211 Vw32_get_true_file_attributes);
212 w32_save = Vw32_get_true_file_attributes;
213 if (EQ (Vw32_get_true_file_attributes, Qlocal))
215 /* w32.c:stat will notice these bindings and avoid calling
216 GetDriveType for each file. */
217 if (is_slow_fs (SDATA (dirfilename)))
218 Vw32_get_true_file_attributes = Qnil;
219 else
220 Vw32_get_true_file_attributes = Qt;
223 #endif
225 directory_nbytes = SBYTES (directory);
226 re_match_object = Qt;
228 /* Decide whether we need to add a directory separator. */
229 if (directory_nbytes == 0
230 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
231 needsep = 1;
233 /* Loop reading blocks until EOF or error. */
234 for (;;)
236 ptrdiff_t len;
237 bool wanted = 0;
238 Lisp_Object name, finalname;
239 struct gcpro gcpro1, gcpro2;
241 errno = 0;
242 dp = readdir (d);
243 if (!dp)
245 if (errno == EAGAIN || errno == EINTR)
247 QUIT;
248 continue;
250 #ifdef WINDOWSNT
251 /* The MS-Windows implementation of 'opendir' doesn't
252 actually open a directory until the first call to
253 'readdir'. If 'readdir' fails to open the directory, it
254 sets errno to ENOENT or EACCES, see w32.c. */
255 if (errno)
256 report_file_error ("Opening directory", directory);
257 #endif
258 break;
261 len = dirent_namelen (dp);
262 name = finalname = make_unibyte_string (dp->d_name, len);
263 GCPRO2 (finalname, name);
265 /* Note: DECODE_FILE can GC; it should protect its argument,
266 though. */
267 name = DECODE_FILE (name);
268 len = SBYTES (name);
270 /* Now that we have unwind_protect in place, we might as well
271 allow matching to be interrupted. */
272 immediate_quit = 1;
273 QUIT;
275 if (NILP (match)
276 || re_search (bufp, SSDATA (name), len, 0, len, 0) >= 0)
277 wanted = 1;
279 immediate_quit = 0;
281 if (wanted)
283 if (!NILP (full))
285 Lisp_Object fullname;
286 ptrdiff_t nbytes = len + directory_nbytes + needsep;
287 ptrdiff_t nchars;
289 fullname = make_uninit_multibyte_string (nbytes, nbytes);
290 memcpy (SDATA (fullname), SDATA (directory),
291 directory_nbytes);
293 if (needsep)
294 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
296 memcpy (SDATA (fullname) + directory_nbytes + needsep,
297 SDATA (name), len);
299 nchars = multibyte_chars_in_text (SDATA (fullname), nbytes);
301 /* Some bug somewhere. */
302 if (nchars > nbytes)
303 emacs_abort ();
305 STRING_SET_CHARS (fullname, nchars);
306 if (nchars == nbytes)
307 STRING_SET_UNIBYTE (fullname);
309 finalname = fullname;
311 else
312 finalname = name;
314 if (attrs)
316 Lisp_Object fileattrs
317 = file_attributes (fd, dp->d_name, id_format);
318 list = Fcons (Fcons (finalname, fileattrs), list);
320 else
321 list = Fcons (finalname, list);
324 UNGCPRO;
327 block_input ();
328 closedir (d);
329 unblock_input ();
330 #ifdef WINDOWSNT
331 if (attrs)
332 Vw32_get_true_file_attributes = w32_save;
333 #endif
335 /* Discard the unwind protect. */
336 specpdl_ptr = specpdl + count;
338 if (NILP (nosort))
339 list = Fsort (Fnreverse (list),
340 attrs ? Qfile_attributes_lessp : Qstring_lessp);
342 (void) directory_volatile;
343 RETURN_UNGCPRO (list);
347 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
348 doc: /* Return a list of names of files in DIRECTORY.
349 There are three optional arguments:
350 If FULL is non-nil, return absolute file names. Otherwise return names
351 that are relative to the specified directory.
352 If MATCH is non-nil, mention only file names that match the regexp MATCH.
353 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
354 Otherwise, the list returned is sorted with `string-lessp'.
355 NOSORT is useful if you plan to sort the result yourself. */)
356 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
358 Lisp_Object handler;
359 directory = Fexpand_file_name (directory, Qnil);
361 /* If the file name has special constructs in it,
362 call the corresponding file handler. */
363 handler = Ffind_file_name_handler (directory, Qdirectory_files);
364 if (!NILP (handler))
365 return call5 (handler, Qdirectory_files, directory,
366 full, match, nosort);
368 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
371 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
372 Sdirectory_files_and_attributes, 1, 5, 0,
373 doc: /* Return a list of names of files and their attributes in DIRECTORY.
374 There are four optional arguments:
375 If FULL is non-nil, return absolute file names. Otherwise return names
376 that are relative to the specified directory.
377 If MATCH is non-nil, mention only file names that match the regexp MATCH.
378 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
379 NOSORT is useful if you plan to sort the result yourself.
380 ID-FORMAT specifies the preferred format of attributes uid and gid, see
381 `file-attributes' for further documentation.
382 On MS-Windows, performance depends on `w32-get-true-file-attributes',
383 which see. */)
384 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
386 Lisp_Object handler;
387 directory = Fexpand_file_name (directory, Qnil);
389 /* If the file name has special constructs in it,
390 call the corresponding file handler. */
391 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
392 if (!NILP (handler))
393 return call6 (handler, Qdirectory_files_and_attributes,
394 directory, full, match, nosort, id_format);
396 return directory_files_internal (directory, full, match, nosort, 1, id_format);
400 static Lisp_Object file_name_completion (Lisp_Object, Lisp_Object, bool,
401 Lisp_Object);
403 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
404 2, 3, 0,
405 doc: /* Complete file name FILE in directory DIRECTORY.
406 Returns the longest string
407 common to all file names in DIRECTORY that start with FILE.
408 If there is only one and FILE matches it exactly, returns t.
409 Returns nil if DIRECTORY contains no name starting with FILE.
411 If PREDICATE is non-nil, call PREDICATE with each possible
412 completion (in absolute form) and ignore it if PREDICATE returns nil.
414 This function ignores some of the possible completions as
415 determined by the variable `completion-ignored-extensions', which see. */)
416 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
418 Lisp_Object handler;
419 directory = Fexpand_file_name (directory, Qnil);
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, 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;
443 directory = Fexpand_file_name (directory, Qnil);
445 /* If the directory name has special constructs in it,
446 call the corresponding file handler. */
447 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
448 if (!NILP (handler))
449 return call3 (handler, Qfile_name_all_completions, file, directory);
451 /* If the file name has special constructs in it,
452 call the corresponding file handler. */
453 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
454 if (!NILP (handler))
455 return call3 (handler, Qfile_name_all_completions, file, directory);
457 return file_name_completion (file, directory, 1, Qnil);
460 static int file_name_completion_stat (int, struct dirent *, struct stat *);
461 static Lisp_Object Qdefault_directory;
463 static Lisp_Object
464 file_name_completion (Lisp_Object file, Lisp_Object dirname, bool all_flag,
465 Lisp_Object predicate)
467 DIR *d;
468 int fd;
469 ptrdiff_t bestmatchsize = 0;
470 int matchcount = 0;
471 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
472 If ALL_FLAG is 0, BESTMATCH is either nil
473 or the best match so far, not decoded. */
474 Lisp_Object bestmatch, tem, elt, name;
475 Lisp_Object encoded_file;
476 Lisp_Object encoded_dir;
477 struct stat st;
478 bool directoryp;
479 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
480 well as "." and "..". Until shown otherwise, assume we can't exclude
481 anything. */
482 bool includeall = 1;
483 ptrdiff_t count = SPECPDL_INDEX ();
484 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
486 elt = Qnil;
488 CHECK_STRING (file);
490 bestmatch = Qnil;
491 encoded_file = encoded_dir = Qnil;
492 GCPRO5 (file, dirname, bestmatch, encoded_file, encoded_dir);
493 specbind (Qdefault_directory, dirname);
495 /* Do completion on the encoded file name
496 because the other names in the directory are (we presume)
497 encoded likewise. We decode the completed string at the end. */
498 /* Actually, this is not quite true any more: we do most of the completion
499 work with decoded file names, but we still do some filtering based
500 on the encoded file name. */
501 encoded_file = STRING_MULTIBYTE (file) ? ENCODE_FILE (file) : file;
503 encoded_dir = ENCODE_FILE (Fdirectory_file_name (dirname));
505 d = open_directory (SSDATA (encoded_dir), &fd);
506 if (!d)
507 report_file_error ("Opening directory", dirname);
509 record_unwind_protect_ptr (directory_files_internal_unwind, d);
511 /* Loop reading blocks */
512 /* (att3b compiler bug requires do a null comparison this way) */
513 while (1)
515 struct dirent *dp;
516 ptrdiff_t len;
517 bool canexclude = 0;
519 errno = 0;
520 dp = readdir (d);
521 if (!dp)
523 if (errno == EAGAIN || errno == EINTR)
525 QUIT;
526 continue;
528 #ifdef WINDOWSNT
529 if (errno)
530 report_file_error ("Opening directory", dirname);
531 #endif
532 break;
535 len = dirent_namelen (dp);
537 QUIT;
538 if (len < SCHARS (encoded_file)
539 || (scmp (dp->d_name, SSDATA (encoded_file),
540 SCHARS (encoded_file))
541 >= 0))
542 continue;
544 if (file_name_completion_stat (fd, dp, &st) < 0)
545 continue;
547 directoryp = S_ISDIR (st.st_mode) != 0;
548 tem = Qnil;
549 /* If all_flag is set, always include all.
550 It would not actually be helpful to the user to ignore any possible
551 completions when making a list of them. */
552 if (!all_flag)
554 ptrdiff_t skip;
556 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
557 /* If this entry matches the current bestmatch, the only
558 thing it can do is increase matchcount, so don't bother
559 investigating it any further. */
560 if (!completion_ignore_case
561 /* The return result depends on whether it's the sole match. */
562 && matchcount > 1
563 && !includeall /* This match may allow includeall to 0. */
564 && len >= bestmatchsize
565 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
566 continue;
567 #endif
569 if (directoryp)
571 #ifndef TRIVIAL_DIRECTORY_ENTRY
572 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
573 #endif
574 /* "." and ".." are never interesting as completions, and are
575 actually in the way in a directory with only one file. */
576 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
577 canexclude = 1;
578 else if (len > SCHARS (encoded_file))
579 /* Ignore directories if they match an element of
580 completion-ignored-extensions which ends in a slash. */
581 for (tem = Vcompletion_ignored_extensions;
582 CONSP (tem); tem = XCDR (tem))
584 ptrdiff_t elt_len;
585 char *p1;
587 elt = XCAR (tem);
588 if (!STRINGP (elt))
589 continue;
590 /* Need to encode ELT, since scmp compares unibyte
591 strings only. */
592 elt = ENCODE_FILE (elt);
593 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
594 if (elt_len <= 0)
595 continue;
596 p1 = SSDATA (elt);
597 if (p1[elt_len] != '/')
598 continue;
599 skip = len - elt_len;
600 if (skip < 0)
601 continue;
603 if (scmp (dp->d_name + skip, p1, elt_len) >= 0)
604 continue;
605 break;
608 else
610 /* Compare extensions-to-be-ignored against end of this file name */
611 /* if name is not an exact match against specified string */
612 if (len > SCHARS (encoded_file))
613 /* and exit this for loop if a match is found */
614 for (tem = Vcompletion_ignored_extensions;
615 CONSP (tem); tem = XCDR (tem))
617 elt = XCAR (tem);
618 if (!STRINGP (elt)) continue;
619 /* Need to encode ELT, since scmp compares unibyte
620 strings only. */
621 elt = ENCODE_FILE (elt);
622 skip = len - SCHARS (elt);
623 if (skip < 0) continue;
625 if (scmp (dp->d_name + skip, SSDATA (elt), SCHARS (elt))
626 >= 0)
627 continue;
628 break;
632 /* If an ignored-extensions match was found,
633 don't process this name as a completion. */
634 if (CONSP (tem))
635 canexclude = 1;
637 if (!includeall && canexclude)
638 /* We're not including all files and this file can be excluded. */
639 continue;
641 if (includeall && !canexclude)
642 { /* If we have one non-excludable file, we want to exclude the
643 excludable files. */
644 includeall = 0;
645 /* Throw away any previous excludable match found. */
646 bestmatch = Qnil;
647 bestmatchsize = 0;
648 matchcount = 0;
651 /* FIXME: If we move this `decode' earlier we can eliminate
652 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
653 name = make_unibyte_string (dp->d_name, len);
654 name = DECODE_FILE (name);
657 Lisp_Object regexps;
659 /* Ignore this element if it fails to match all the regexps. */
660 if (completion_ignore_case)
662 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
663 regexps = XCDR (regexps))
664 if (fast_string_match_ignore_case (XCAR (regexps), name) < 0)
665 break;
667 else
669 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
670 regexps = XCDR (regexps))
671 if (fast_string_match (XCAR (regexps), name) < 0)
672 break;
675 if (CONSP (regexps))
676 continue;
679 /* This is a possible completion */
680 if (directoryp)
681 /* This completion is a directory; make it end with '/'. */
682 name = Ffile_name_as_directory (name);
684 /* Test the predicate, if any. */
685 if (!NILP (predicate))
687 Lisp_Object val;
688 struct gcpro gcpro1;
690 GCPRO1 (name);
691 val = call1 (predicate, name);
692 UNGCPRO;
694 if (NILP (val))
695 continue;
698 /* Suitably record this match. */
700 matchcount += matchcount <= 1;
702 if (all_flag)
703 bestmatch = Fcons (name, bestmatch);
704 else if (NILP (bestmatch))
706 bestmatch = name;
707 bestmatchsize = SCHARS (name);
709 else
711 Lisp_Object zero = make_number (0);
712 /* FIXME: This is a copy of the code in Ftry_completion. */
713 ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
714 Lisp_Object cmp
715 = Fcompare_strings (bestmatch, zero,
716 make_number (compare),
717 name, zero,
718 make_number (compare),
719 completion_ignore_case ? Qt : Qnil);
720 ptrdiff_t matchsize = EQ (cmp, Qt) ? compare : eabs (XINT (cmp)) - 1;
722 if (completion_ignore_case)
724 /* If this is an exact match except for case,
725 use it as the best match rather than one that is not
726 an exact match. This way, we get the case pattern
727 of the actual match. */
728 /* This tests that the current file is an exact match
729 but BESTMATCH is not (it is too long). */
730 if ((matchsize == SCHARS (name)
731 && matchsize + directoryp < SCHARS (bestmatch))
733 /* If there is no exact match ignoring case,
734 prefer a match that does not change the case
735 of the input. */
736 /* If there is more than one exact match aside from
737 case, and one of them is exact including case,
738 prefer that one. */
739 /* This == checks that, of current file and BESTMATCH,
740 either both or neither are exact. */
741 (((matchsize == SCHARS (name))
743 (matchsize + directoryp == SCHARS (bestmatch)))
744 && (cmp = Fcompare_strings (name, zero,
745 make_number (SCHARS (file)),
746 file, zero,
747 Qnil,
748 Qnil),
749 EQ (Qt, cmp))
750 && (cmp = Fcompare_strings (bestmatch, zero,
751 make_number (SCHARS (file)),
752 file, zero,
753 Qnil,
754 Qnil),
755 ! EQ (Qt, cmp))))
756 bestmatch = name;
758 bestmatchsize = matchsize;
760 /* If the best completion so far is reduced to the string
761 we're trying to complete, then we already know there's no
762 other completion, so there's no point looking any further. */
763 if (matchsize <= SCHARS (file)
764 && !includeall /* A future match may allow includeall to 0. */
765 /* If completion-ignore-case is non-nil, don't
766 short-circuit because we want to find the best
767 possible match *including* case differences. */
768 && (!completion_ignore_case || matchsize == 0)
769 /* The return value depends on whether it's the sole match. */
770 && matchcount > 1)
771 break;
776 UNGCPRO;
777 /* This closes the directory. */
778 bestmatch = unbind_to (count, bestmatch);
780 if (all_flag || NILP (bestmatch))
781 return bestmatch;
782 /* Return t if the supplied string is an exact match (counting case);
783 it does not require any change to be made. */
784 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
785 return Qt;
786 bestmatch = Fsubstring (bestmatch, make_number (0),
787 make_number (bestmatchsize));
788 return bestmatch;
791 /* Compare exactly LEN chars of strings at S1 and S2,
792 ignoring case if appropriate.
793 Return -1 if strings match,
794 else number of chars that match at the beginning. */
796 static ptrdiff_t
797 scmp (const char *s1, const char *s2, ptrdiff_t len)
799 register ptrdiff_t l = len;
801 if (completion_ignore_case)
803 while (l
804 && (downcase ((unsigned char) *s1++)
805 == downcase ((unsigned char) *s2++)))
806 l--;
808 else
810 while (l && *s1++ == *s2++)
811 l--;
813 if (l == 0)
814 return -1;
815 else
816 return len - l;
819 static int
820 file_name_completion_stat (int fd, struct dirent *dp, struct stat *st_addr)
822 int value;
824 #ifdef MSDOS
825 /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
826 but aren't required here. Avoid computing the following fields:
827 st_inode, st_size and st_nlink for directories, and the execute bits
828 in st_mode for non-directory files with non-standard extensions. */
830 unsigned short save_djstat_flags = _djstat_flags;
832 _djstat_flags = _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
833 #endif /* MSDOS */
835 /* We want to return success if a link points to a nonexistent file,
836 but we want to return the status for what the link points to,
837 in case it is a directory. */
838 value = fstatat (fd, dp->d_name, st_addr, AT_SYMLINK_NOFOLLOW);
839 if (value == 0 && S_ISLNK (st_addr->st_mode))
840 fstatat (fd, dp->d_name, st_addr, 0);
841 #ifdef MSDOS
842 _djstat_flags = save_djstat_flags;
843 #endif /* MSDOS */
844 return value;
847 static char *
848 stat_uname (struct stat *st)
850 #ifdef WINDOWSNT
851 return st->st_uname;
852 #else
853 struct passwd *pw = getpwuid (st->st_uid);
855 if (pw)
856 return pw->pw_name;
857 else
858 return NULL;
859 #endif
862 static char *
863 stat_gname (struct stat *st)
865 #ifdef WINDOWSNT
866 return st->st_gname;
867 #else
868 struct group *gr = getgrgid (st->st_gid);
870 if (gr)
871 return gr->gr_name;
872 else
873 return NULL;
874 #endif
877 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
878 doc: /* Return a list of attributes of file FILENAME.
879 Value is nil if specified file cannot be opened.
881 ID-FORMAT specifies the preferred format of attributes uid and gid (see
882 below) - valid values are 'string and 'integer. The latter is the
883 default, but we plan to change that, so you should specify a non-nil value
884 for ID-FORMAT if you use the returned uid or gid.
886 Elements of the attribute list are:
887 0. t for directory, string (name linked to) for symbolic link, or nil.
888 1. Number of links to file.
889 2. File uid as a string or a number. If a string value cannot be
890 looked up, a numeric value, either an integer or a float, is returned.
891 3. File gid, likewise.
892 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
893 same style as (current-time).
894 (See a note below about access time on FAT-based filesystems.)
895 5. Last modification time, likewise. This is the time of the last
896 change to the file's contents.
897 6. Last status change time, likewise. This is the time of last change
898 to the file's attributes: owner and group, access mode bits, etc.
899 7. Size in bytes.
900 This is a floating point number if the size is too large for an integer.
901 8. File modes, as a string of ten letters or dashes as in ls -l.
902 9. An unspecified value, present only for backward compatibility.
903 10. inode number. If it is larger than what an Emacs integer can hold,
904 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
905 If even HIGH is too large for an Emacs integer, this is instead of the form
906 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
907 and finally the low 16 bits.
908 11. Filesystem device number. If it is larger than what the Emacs
909 integer can hold, this is a cons cell, similar to the inode number.
911 On most filesystems, the combination of the inode and the device
912 number uniquely identifies the file.
914 On MS-Windows, performance depends on `w32-get-true-file-attributes',
915 which see.
917 On some FAT-based filesystems, only the date of last access is recorded,
918 so last access time will always be midnight of that day. */)
919 (Lisp_Object filename, Lisp_Object id_format)
921 Lisp_Object encoded;
922 Lisp_Object handler;
924 filename = internal_condition_case_2 (Fexpand_file_name, filename, Qnil,
925 Qt, Fidentity);
926 if (!STRINGP (filename))
927 return Qnil;
929 /* If the file name has special constructs in it,
930 call the corresponding file handler. */
931 handler = Ffind_file_name_handler (filename, Qfile_attributes);
932 if (!NILP (handler))
933 { /* Only pass the extra arg if it is used to help backward compatibility
934 with old file handlers which do not implement the new arg. --Stef */
935 if (NILP (id_format))
936 return call2 (handler, Qfile_attributes, filename);
937 else
938 return call3 (handler, Qfile_attributes, filename, id_format);
941 encoded = ENCODE_FILE (filename);
942 return file_attributes (AT_FDCWD, SSDATA (encoded), id_format);
945 static Lisp_Object
946 file_attributes (int fd, char const *name, Lisp_Object id_format)
948 Lisp_Object values[12];
949 struct stat s;
950 int lstat_result;
952 /* An array to hold the mode string generated by filemodestring,
953 including its terminating space and null byte. */
954 char modes[sizeof "-rwxr-xr-x "];
956 char *uname = NULL, *gname = NULL;
958 #ifdef WINDOWSNT
959 /* We usually don't request accurate owner and group info, because
960 it can be very expensive on Windows to get that, and most callers
961 of 'lstat' don't need that. But here we do want that information
962 to be accurate. */
963 w32_stat_get_owner_group = 1;
964 #endif
966 lstat_result = fstatat (fd, name, &s, AT_SYMLINK_NOFOLLOW);
968 #ifdef WINDOWSNT
969 w32_stat_get_owner_group = 0;
970 #endif
972 if (lstat_result < 0)
973 return Qnil;
975 values[0] = (S_ISLNK (s.st_mode) ? emacs_readlinkat (fd, name)
976 : S_ISDIR (s.st_mode) ? Qt : Qnil);
977 values[1] = make_number (s.st_nlink);
979 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
981 block_input ();
982 uname = stat_uname (&s);
983 gname = stat_gname (&s);
984 unblock_input ();
986 if (uname)
987 values[2] = DECODE_SYSTEM (build_unibyte_string (uname));
988 else
989 values[2] = make_fixnum_or_float (s.st_uid);
990 if (gname)
991 values[3] = DECODE_SYSTEM (build_unibyte_string (gname));
992 else
993 values[3] = make_fixnum_or_float (s.st_gid);
995 values[4] = make_lisp_time (get_stat_atime (&s));
996 values[5] = make_lisp_time (get_stat_mtime (&s));
997 values[6] = make_lisp_time (get_stat_ctime (&s));
999 /* If the file size is a 4-byte type, assume that files of sizes in
1000 the 2-4 GiB range wrap around to negative values, as this is a
1001 common bug on older 32-bit platforms. */
1002 if (sizeof (s.st_size) == 4)
1003 values[7] = make_fixnum_or_float (s.st_size & 0xffffffffu);
1004 else
1005 values[7] = make_fixnum_or_float (s.st_size);
1007 filemodestring (&s, modes);
1008 values[8] = make_string (modes, 10);
1009 values[9] = Qt;
1010 values[10] = INTEGER_TO_CONS (s.st_ino);
1011 values[11] = INTEGER_TO_CONS (s.st_dev);
1013 return Flist (sizeof (values) / sizeof (values[0]), values);
1016 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
1017 doc: /* Return t if first arg file attributes list is less than second.
1018 Comparison is in lexicographic order and case is significant. */)
1019 (Lisp_Object f1, Lisp_Object f2)
1021 return Fstring_lessp (Fcar (f1), Fcar (f2));
1025 DEFUN ("system-users", Fsystem_users, Ssystem_users, 0, 0, 0,
1026 doc: /* Return a list of user names currently registered in the system.
1027 If we don't know how to determine that on this platform, just
1028 return a list with one element, taken from `user-real-login-name'. */)
1029 (void)
1031 Lisp_Object users = Qnil;
1032 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
1033 struct passwd *pw;
1035 while ((pw = getpwent ()))
1036 users = Fcons (DECODE_SYSTEM (build_string (pw->pw_name)), users);
1038 endpwent ();
1039 #endif
1040 if (EQ (users, Qnil))
1041 /* At least current user is always known. */
1042 users = list1 (Vuser_real_login_name);
1043 return users;
1046 DEFUN ("system-groups", Fsystem_groups, Ssystem_groups, 0, 0, 0,
1047 doc: /* Return a list of user group names currently registered in the system.
1048 The value may be nil if not supported on this platform. */)
1049 (void)
1051 Lisp_Object groups = Qnil;
1052 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1053 struct group *gr;
1055 while ((gr = getgrent ()))
1056 groups = Fcons (DECODE_SYSTEM (build_string (gr->gr_name)), groups);
1058 endgrent ();
1059 #endif
1060 return groups;
1063 void
1064 syms_of_dired (void)
1066 DEFSYM (Qdirectory_files, "directory-files");
1067 DEFSYM (Qdirectory_files_and_attributes, "directory-files-and-attributes");
1068 DEFSYM (Qfile_name_completion, "file-name-completion");
1069 DEFSYM (Qfile_name_all_completions, "file-name-all-completions");
1070 DEFSYM (Qfile_attributes, "file-attributes");
1071 DEFSYM (Qfile_attributes_lessp, "file-attributes-lessp");
1072 DEFSYM (Qdefault_directory, "default-directory");
1074 defsubr (&Sdirectory_files);
1075 defsubr (&Sdirectory_files_and_attributes);
1076 defsubr (&Sfile_name_completion);
1077 defsubr (&Sfile_name_all_completions);
1078 defsubr (&Sfile_attributes);
1079 defsubr (&Sfile_attributes_lessp);
1080 defsubr (&Ssystem_users);
1081 defsubr (&Ssystem_groups);
1083 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1084 doc: /* Completion ignores file names ending in any string in this list.
1085 It does not ignore them if all possible completions end in one of
1086 these strings or when displaying a list of completions.
1087 It ignores directory names if they match any string in this list which
1088 ends in a slash. */);
1089 Vcompletion_ignored_extensions = Qnil;