Use 'header-line-highlight' face in proced and erc
[emacs.git] / src / dired.c
blob288ba6b1038f7660188f94bec56f137248c09838
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2017 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 (at
10 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/stat.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
29 #include <grp.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <unistd.h>
35 #include <dirent.h>
36 #include <filemode.h>
37 #include <stat-time.h>
39 #include "lisp.h"
40 #include "systime.h"
41 #include "buffer.h"
42 #include "coding.h"
43 #include "regex.h"
45 #ifdef MSDOS
46 #include "msdos.h" /* for fstatat */
47 #endif
49 #ifdef WINDOWSNT
50 extern int is_slow_fs (const char *);
51 #endif
53 static ptrdiff_t scmp (const char *, const char *, ptrdiff_t);
54 static Lisp_Object file_attributes (int, char const *, Lisp_Object);
56 /* Return the number of bytes in DP's name. */
57 static ptrdiff_t
58 dirent_namelen (struct dirent *dp)
60 #ifdef _D_EXACT_NAMLEN
61 return _D_EXACT_NAMLEN (dp);
62 #else
63 return strlen (dp->d_name);
64 #endif
67 #ifndef HAVE_STRUCT_DIRENT_D_TYPE
68 enum { DT_UNKNOWN, DT_DIR, DT_LNK };
69 #endif
71 /* Return the file type of DP. */
72 static int
73 dirent_type (struct dirent *dp)
75 #ifdef HAVE_STRUCT_DIRENT_D_TYPE
76 return dp->d_type;
77 #else
78 return DT_UNKNOWN;
79 #endif
82 static DIR *
83 open_directory (Lisp_Object dirname, int *fdp)
85 char *name = SSDATA (dirname);
86 DIR *d;
87 int fd, opendir_errno;
89 #ifdef DOS_NT
90 /* Directories cannot be opened. The emulation assumes that any
91 file descriptor other than AT_FDCWD corresponds to the most
92 recently opened directory. This hack is good enough for Emacs. */
93 fd = 0;
94 d = opendir (name);
95 opendir_errno = errno;
96 #else
97 fd = emacs_open (name, O_RDONLY | O_DIRECTORY, 0);
98 if (fd < 0)
100 opendir_errno = errno;
101 d = 0;
103 else
105 d = fdopendir (fd);
106 opendir_errno = errno;
107 if (! d)
108 emacs_close (fd);
110 #endif
112 if (!d)
113 report_file_errno ("Opening directory", dirname, opendir_errno);
114 *fdp = fd;
115 return d;
118 #ifdef WINDOWSNT
119 static void
120 directory_files_internal_w32_unwind (Lisp_Object arg)
122 Vw32_get_true_file_attributes = arg;
124 #endif
126 static void
127 directory_files_internal_unwind (void *d)
129 closedir (d);
132 /* Return the next directory entry from DIR; DIR's name is DIRNAME.
133 If there are no more directory entries, return a null pointer.
134 Signal any unrecoverable errors. */
136 static struct dirent *
137 read_dirent (DIR *dir, Lisp_Object dirname)
139 while (true)
141 errno = 0;
142 struct dirent *dp = readdir (dir);
143 if (dp || errno == 0)
144 return dp;
145 if (! (errno == EAGAIN || errno == EINTR))
147 #ifdef WINDOWSNT
148 /* The MS-Windows implementation of 'opendir' doesn't
149 actually open a directory until the first call to
150 'readdir'. If 'readdir' fails to open the directory, it
151 sets errno to ENOENT or EACCES, see w32.c. */
152 if (errno == ENOENT || errno == EACCES)
153 report_file_error ("Opening directory", dirname);
154 #endif
155 report_file_error ("Reading directory", dirname);
157 maybe_quit ();
161 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
162 If not ATTRS, return a list of directory filenames;
163 if ATTRS, return a list of directory filenames and their attributes.
164 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
166 Lisp_Object
167 directory_files_internal (Lisp_Object directory, Lisp_Object full,
168 Lisp_Object match, Lisp_Object nosort, bool attrs,
169 Lisp_Object id_format)
171 ptrdiff_t directory_nbytes;
172 Lisp_Object list, dirfilename, encoded_directory;
173 struct re_pattern_buffer *bufp = NULL;
174 bool needsep = 0;
175 ptrdiff_t count = SPECPDL_INDEX ();
176 #ifdef WINDOWSNT
177 Lisp_Object w32_save = Qnil;
178 #endif
180 /* Don't let the compiler optimize away all copies of DIRECTORY,
181 which would break GC; see Bug#16986. */
182 Lisp_Object volatile directory_volatile = directory;
184 /* Because of file name handlers, these functions might call
185 Ffuncall, and cause a GC. */
186 list = encoded_directory = dirfilename = Qnil;
187 dirfilename = Fdirectory_file_name (directory);
189 if (!NILP (match))
191 CHECK_STRING (match);
193 /* MATCH might be a flawed regular expression. Rather than
194 catching and signaling our own errors, we just call
195 compile_pattern to do the work for us. */
196 /* Pass 1 for the MULTIBYTE arg
197 because we do make multibyte strings if the contents warrant. */
198 # ifdef WINDOWSNT
199 /* Windows users want case-insensitive wildcards. */
200 bufp = compile_pattern (match, 0,
201 BVAR (&buffer_defaults, case_canon_table), 0, 1);
202 # else /* !WINDOWSNT */
203 bufp = compile_pattern (match, 0, Qnil, 0, 1);
204 # endif /* !WINDOWSNT */
207 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
208 run_pre_post_conversion_on_str which calls Lisp directly and
209 indirectly. */
210 dirfilename = ENCODE_FILE (dirfilename);
211 encoded_directory = ENCODE_FILE (directory);
213 /* Now *bufp is the compiled form of MATCH; don't call anything
214 which might compile a new regexp until we're done with the loop! */
216 int fd;
217 DIR *d = open_directory (dirfilename, &fd);
219 /* Unfortunately, we can now invoke expand-file-name and
220 file-attributes on filenames, both of which can throw, so we must
221 do a proper unwind-protect. */
222 record_unwind_protect_ptr (directory_files_internal_unwind, d);
224 #ifdef WINDOWSNT
225 if (attrs)
227 /* Do this only once to avoid doing it (in w32.c:stat) for each
228 file in the directory, when we call Ffile_attributes below. */
229 record_unwind_protect (directory_files_internal_w32_unwind,
230 Vw32_get_true_file_attributes);
231 w32_save = Vw32_get_true_file_attributes;
232 if (EQ (Vw32_get_true_file_attributes, Qlocal))
234 /* w32.c:stat will notice these bindings and avoid calling
235 GetDriveType for each file. */
236 if (is_slow_fs (SSDATA (dirfilename)))
237 Vw32_get_true_file_attributes = Qnil;
238 else
239 Vw32_get_true_file_attributes = Qt;
242 #endif
244 directory_nbytes = SBYTES (directory);
245 re_match_object = Qt;
247 /* Decide whether we need to add a directory separator. */
248 if (directory_nbytes == 0
249 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
250 needsep = 1;
252 /* Loop reading directory entries. */
253 for (struct dirent *dp; (dp = read_dirent (d, directory)); )
255 ptrdiff_t len = dirent_namelen (dp);
256 Lisp_Object name = make_unibyte_string (dp->d_name, len);
257 Lisp_Object finalname = name;
259 /* Note: DECODE_FILE can GC; it should protect its argument,
260 though. */
261 name = DECODE_FILE (name);
262 len = SBYTES (name);
264 /* Now that we have unwind_protect in place, we might as well
265 allow matching to be interrupted. */
266 maybe_quit ();
268 bool wanted = (NILP (match)
269 || re_search (bufp, SSDATA (name), len, 0, len, 0) >= 0);
271 if (wanted)
273 if (!NILP (full))
275 Lisp_Object fullname;
276 ptrdiff_t nbytes = len + directory_nbytes + needsep;
277 ptrdiff_t nchars;
279 fullname = make_uninit_multibyte_string (nbytes, nbytes);
280 memcpy (SDATA (fullname), SDATA (directory),
281 directory_nbytes);
283 if (needsep)
284 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
286 memcpy (SDATA (fullname) + directory_nbytes + needsep,
287 SDATA (name), len);
289 nchars = multibyte_chars_in_text (SDATA (fullname), nbytes);
291 /* Some bug somewhere. */
292 if (nchars > nbytes)
293 emacs_abort ();
295 STRING_SET_CHARS (fullname, nchars);
296 if (nchars == nbytes)
297 STRING_SET_UNIBYTE (fullname);
299 finalname = fullname;
301 else
302 finalname = name;
304 if (attrs)
306 Lisp_Object fileattrs
307 = file_attributes (fd, dp->d_name, id_format);
308 list = Fcons (Fcons (finalname, fileattrs), list);
310 else
311 list = Fcons (finalname, list);
315 closedir (d);
316 #ifdef WINDOWSNT
317 if (attrs)
318 Vw32_get_true_file_attributes = w32_save;
319 #endif
321 /* Discard the unwind protect. */
322 specpdl_ptr = specpdl + count;
324 if (NILP (nosort))
325 list = Fsort (Fnreverse (list),
326 attrs ? Qfile_attributes_lessp : Qstring_lessp);
328 (void) directory_volatile;
329 return list;
333 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
334 doc: /* Return a list of names of files in DIRECTORY.
335 There are three optional arguments:
336 If FULL is non-nil, return absolute file names. Otherwise return names
337 that are relative to the specified directory.
338 If MATCH is non-nil, mention only file names that match the regexp MATCH.
339 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
340 Otherwise, the list returned is sorted with `string-lessp'.
341 NOSORT is useful if you plan to sort the result yourself. */)
342 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
344 Lisp_Object handler;
345 directory = Fexpand_file_name (directory, Qnil);
347 /* If the file name has special constructs in it,
348 call the corresponding file handler. */
349 handler = Ffind_file_name_handler (directory, Qdirectory_files);
350 if (!NILP (handler))
351 return call5 (handler, Qdirectory_files, directory,
352 full, match, nosort);
354 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
357 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
358 Sdirectory_files_and_attributes, 1, 5, 0,
359 doc: /* Return a list of names of files and their attributes in DIRECTORY.
360 There are four optional arguments:
361 If FULL is non-nil, return absolute file names. Otherwise return names
362 that are relative to the specified directory.
363 If MATCH is non-nil, mention only file names that match the regexp MATCH.
364 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
365 NOSORT is useful if you plan to sort the result yourself.
366 ID-FORMAT specifies the preferred format of attributes uid and gid, see
367 `file-attributes' for further documentation.
368 On MS-Windows, performance depends on `w32-get-true-file-attributes',
369 which see. */)
370 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
372 Lisp_Object handler;
373 directory = Fexpand_file_name (directory, Qnil);
375 /* If the file name has special constructs in it,
376 call the corresponding file handler. */
377 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
378 if (!NILP (handler))
379 return call6 (handler, Qdirectory_files_and_attributes,
380 directory, full, match, nosort, id_format);
382 return directory_files_internal (directory, full, match, nosort, 1, id_format);
386 static Lisp_Object file_name_completion (Lisp_Object, Lisp_Object, bool,
387 Lisp_Object);
389 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
390 2, 3, 0,
391 doc: /* Complete file name FILE in directory DIRECTORY.
392 Returns the longest string
393 common to all file names in DIRECTORY that start with FILE.
394 If there is only one and FILE matches it exactly, returns t.
395 Returns nil if DIRECTORY contains no name starting with FILE.
397 If PREDICATE is non-nil, call PREDICATE with each possible
398 completion (in absolute form) and ignore it if PREDICATE returns nil.
400 This function ignores some of the possible completions as determined
401 by the variables `completion-regexp-list' and
402 `completion-ignored-extensions', which see. `completion-regexp-list'
403 is matched against file and directory names relative to DIRECTORY. */)
404 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
406 Lisp_Object handler;
407 directory = Fexpand_file_name (directory, Qnil);
409 /* If the directory name has special constructs in it,
410 call the corresponding file handler. */
411 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
412 if (!NILP (handler))
413 return call4 (handler, Qfile_name_completion, file, directory, predicate);
415 /* If the file name has special constructs in it,
416 call the corresponding file handler. */
417 handler = Ffind_file_name_handler (file, Qfile_name_completion);
418 if (!NILP (handler))
419 return call4 (handler, Qfile_name_completion, file, directory, predicate);
421 return file_name_completion (file, directory, 0, predicate);
424 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
425 Sfile_name_all_completions, 2, 2, 0,
426 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
427 These are all file names in directory DIRECTORY which begin with FILE.
429 This function ignores some of the possible completions as determined
430 by `completion-regexp-list', which see. `completion-regexp-list'
431 is matched against file and directory names relative to DIRECTORY. */)
432 (Lisp_Object file, Lisp_Object directory)
434 Lisp_Object handler;
435 directory = Fexpand_file_name (directory, Qnil);
437 /* If the directory name has special constructs in it,
438 call the corresponding file handler. */
439 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
440 if (!NILP (handler))
441 return call3 (handler, Qfile_name_all_completions, file, directory);
443 /* If the file name has special constructs in it,
444 call the corresponding file handler. */
445 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
446 if (!NILP (handler))
447 return call3 (handler, Qfile_name_all_completions, file, directory);
449 return file_name_completion (file, directory, 1, Qnil);
452 static bool file_name_completion_dirp (int, struct dirent *, ptrdiff_t);
454 static Lisp_Object
455 file_name_completion (Lisp_Object file, Lisp_Object dirname, bool all_flag,
456 Lisp_Object predicate)
458 ptrdiff_t bestmatchsize = 0;
459 int matchcount = 0;
460 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
461 If ALL_FLAG is 0, BESTMATCH is either nil
462 or the best match so far, not decoded. */
463 Lisp_Object bestmatch, tem, elt, name;
464 Lisp_Object encoded_file;
465 Lisp_Object encoded_dir;
466 bool directoryp;
467 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
468 well as "." and "..". Until shown otherwise, assume we can't exclude
469 anything. */
470 bool includeall = 1;
471 bool check_decoded = false;
472 ptrdiff_t count = SPECPDL_INDEX ();
474 elt = Qnil;
476 CHECK_STRING (file);
478 bestmatch = Qnil;
479 encoded_file = encoded_dir = Qnil;
480 specbind (Qdefault_directory, dirname);
482 /* Do completion on the encoded file name
483 because the other names in the directory are (we presume)
484 encoded likewise. We decode the completed string at the end. */
485 /* Actually, this is not quite true any more: we do most of the completion
486 work with decoded file names, but we still do some filtering based
487 on the encoded file name. */
488 encoded_file = ENCODE_FILE (file);
489 encoded_dir = ENCODE_FILE (Fdirectory_file_name (dirname));
491 Lisp_Object file_encoding = Vfile_name_coding_system;
492 if (NILP (Vfile_name_coding_system))
493 file_encoding = Vdefault_file_name_coding_system;
494 /* If the file-name encoding decomposes characters, as we do for
495 HFS+ filesystems, we need to make an additional comparison of
496 decoded names in order to filter false positives, such as "a"
497 falsely matching "a-ring". */
498 if (!NILP (file_encoding)
499 && !NILP (Fplist_get (Fcoding_system_plist (file_encoding),
500 Qdecomposed_characters)))
502 check_decoded = true;
503 if (STRING_MULTIBYTE (file))
505 /* Recompute FILE to make sure any decomposed characters in
506 it are re-composed by the post-read-conversion.
507 Otherwise, any decomposed characters will be rejected by
508 the additional check below. */
509 file = DECODE_FILE (encoded_file);
512 int fd;
513 DIR *d = open_directory (encoded_dir, &fd);
514 record_unwind_protect_ptr (directory_files_internal_unwind, d);
516 /* Loop reading directory entries. */
517 for (struct dirent *dp; (dp = read_dirent (d, dirname)); )
519 ptrdiff_t len = dirent_namelen (dp);
520 bool canexclude = 0;
522 maybe_quit ();
523 if (len < SCHARS (encoded_file)
524 || (scmp (dp->d_name, SSDATA (encoded_file),
525 SCHARS (encoded_file))
526 >= 0))
527 continue;
529 switch (dirent_type (dp))
531 case DT_DIR:
532 directoryp = true;
533 break;
535 case DT_LNK: case DT_UNKNOWN:
536 directoryp = file_name_completion_dirp (fd, dp, len);
537 break;
539 default:
540 directoryp = false;
541 break;
544 tem = Qnil;
545 /* If all_flag is set, always include all.
546 It would not actually be helpful to the user to ignore any possible
547 completions when making a list of them. */
548 if (!all_flag)
550 ptrdiff_t skip;
552 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
553 /* If this entry matches the current bestmatch, the only
554 thing it can do is increase matchcount, so don't bother
555 investigating it any further. */
556 if (!completion_ignore_case
557 /* The return result depends on whether it's the sole match. */
558 && matchcount > 1
559 && !includeall /* This match may allow includeall to 0. */
560 && len >= bestmatchsize
561 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
562 continue;
563 #endif
565 if (directoryp)
567 #ifndef TRIVIAL_DIRECTORY_ENTRY
568 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
569 #endif
570 /* "." and ".." are never interesting as completions, and are
571 actually in the way in a directory with only one file. */
572 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
573 canexclude = 1;
574 else if (len > SCHARS (encoded_file))
575 /* Ignore directories if they match an element of
576 completion-ignored-extensions which ends in a slash. */
577 for (tem = Vcompletion_ignored_extensions;
578 CONSP (tem); tem = XCDR (tem))
580 ptrdiff_t elt_len;
581 char *p1;
583 elt = XCAR (tem);
584 if (!STRINGP (elt))
585 continue;
586 /* Need to encode ELT, since scmp compares unibyte
587 strings only. */
588 elt = ENCODE_FILE (elt);
589 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
590 if (elt_len <= 0)
591 continue;
592 p1 = SSDATA (elt);
593 if (p1[elt_len] != '/')
594 continue;
595 skip = len - elt_len;
596 if (skip < 0)
597 continue;
599 if (scmp (dp->d_name + skip, p1, elt_len) >= 0)
600 continue;
601 break;
604 else
606 /* Compare extensions-to-be-ignored against end of this file name */
607 /* if name is not an exact match against specified string */
608 if (len > SCHARS (encoded_file))
609 /* and exit this for loop if a match is found */
610 for (tem = Vcompletion_ignored_extensions;
611 CONSP (tem); tem = XCDR (tem))
613 elt = XCAR (tem);
614 if (!STRINGP (elt)) continue;
615 /* Need to encode ELT, since scmp compares unibyte
616 strings only. */
617 elt = ENCODE_FILE (elt);
618 skip = len - SCHARS (elt);
619 if (skip < 0) continue;
621 if (scmp (dp->d_name + skip, SSDATA (elt), SCHARS (elt))
622 >= 0)
623 continue;
624 break;
628 /* If an ignored-extensions match was found,
629 don't process this name as a completion. */
630 if (CONSP (tem))
631 canexclude = 1;
633 if (!includeall && canexclude)
634 /* We're not including all files and this file can be excluded. */
635 continue;
637 if (includeall && !canexclude)
638 { /* If we have one non-excludable file, we want to exclude the
639 excludable files. */
640 includeall = 0;
641 /* Throw away any previous excludable match found. */
642 bestmatch = Qnil;
643 bestmatchsize = 0;
644 matchcount = 0;
647 /* FIXME: If we move this `decode' earlier we can eliminate
648 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
649 name = make_unibyte_string (dp->d_name, len);
650 name = DECODE_FILE (name);
653 Lisp_Object regexps, table = (completion_ignore_case
654 ? Vascii_canon_table : Qnil);
656 /* Ignore this element if it fails to match all the regexps. */
657 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
658 regexps = XCDR (regexps))
659 if (fast_string_match_internal (XCAR (regexps), name, table) < 0)
660 break;
662 if (CONSP (regexps))
663 continue;
666 /* This is a possible completion */
667 if (directoryp)
668 /* This completion is a directory; make it end with '/'. */
669 name = Ffile_name_as_directory (name);
671 /* Test the predicate, if any. */
672 if (!NILP (predicate) && NILP (call1 (predicate, name)))
673 continue;
675 /* Reject entries where the encoded strings match, but the
676 decoded don't. For example, "a" should not match "a-ring" on
677 file systems that store decomposed characters. */
678 Lisp_Object zero = make_number (0);
680 if (check_decoded && SCHARS (file) <= SCHARS (name))
682 /* FIXME: This is a copy of the code below. */
683 ptrdiff_t compare = SCHARS (file);
684 Lisp_Object cmp
685 = Fcompare_strings (name, zero, make_number (compare),
686 file, zero, make_number (compare),
687 completion_ignore_case ? Qt : Qnil);
688 if (!EQ (cmp, Qt))
689 continue;
692 /* Suitably record this match. */
694 matchcount += matchcount <= 1;
696 if (all_flag)
697 bestmatch = Fcons (name, bestmatch);
698 else if (NILP (bestmatch))
700 bestmatch = name;
701 bestmatchsize = SCHARS (name);
703 else
705 /* FIXME: This is a copy of the code in Ftry_completion. */
706 ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
707 Lisp_Object cmp
708 = Fcompare_strings (bestmatch, zero, make_number (compare),
709 name, zero, make_number (compare),
710 completion_ignore_case ? Qt : Qnil);
711 ptrdiff_t matchsize = EQ (cmp, Qt) ? compare : eabs (XINT (cmp)) - 1;
713 if (completion_ignore_case)
715 /* If this is an exact match except for case,
716 use it as the best match rather than one that is not
717 an exact match. This way, we get the case pattern
718 of the actual match. */
719 /* This tests that the current file is an exact match
720 but BESTMATCH is not (it is too long). */
721 if ((matchsize == SCHARS (name)
722 && matchsize + directoryp < SCHARS (bestmatch))
724 /* If there is no exact match ignoring case,
725 prefer a match that does not change the case
726 of the input. */
727 /* If there is more than one exact match aside from
728 case, and one of them is exact including case,
729 prefer that one. */
730 /* This == checks that, of current file and BESTMATCH,
731 either both or neither are exact. */
732 (((matchsize == SCHARS (name))
734 (matchsize + directoryp == SCHARS (bestmatch)))
735 && (cmp = Fcompare_strings (name, zero,
736 make_number (SCHARS (file)),
737 file, zero,
738 Qnil,
739 Qnil),
740 EQ (Qt, cmp))
741 && (cmp = Fcompare_strings (bestmatch, zero,
742 make_number (SCHARS (file)),
743 file, zero,
744 Qnil,
745 Qnil),
746 ! EQ (Qt, cmp))))
747 bestmatch = name;
749 bestmatchsize = matchsize;
751 /* If the best completion so far is reduced to the string
752 we're trying to complete, then we already know there's no
753 other completion, so there's no point looking any further. */
754 if (matchsize <= SCHARS (file)
755 && !includeall /* A future match may allow includeall to 0. */
756 /* If completion-ignore-case is non-nil, don't
757 short-circuit because we want to find the best
758 possible match *including* case differences. */
759 && (!completion_ignore_case || matchsize == 0)
760 /* The return value depends on whether it's the sole match. */
761 && matchcount > 1)
762 break;
767 /* This closes the directory. */
768 bestmatch = unbind_to (count, bestmatch);
770 if (all_flag || NILP (bestmatch))
771 return bestmatch;
772 /* Return t if the supplied string is an exact match (counting case);
773 it does not require any change to be made. */
774 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
775 return Qt;
776 bestmatch = Fsubstring (bestmatch, make_number (0),
777 make_number (bestmatchsize));
778 return bestmatch;
781 /* Compare exactly LEN chars of strings at S1 and S2,
782 ignoring case if appropriate.
783 Return -1 if strings match,
784 else number of chars that match at the beginning. */
786 static ptrdiff_t
787 scmp (const char *s1, const char *s2, ptrdiff_t len)
789 register ptrdiff_t l = len;
791 if (completion_ignore_case)
793 while (l
794 && (downcase ((unsigned char) *s1++)
795 == downcase ((unsigned char) *s2++)))
796 l--;
798 else
800 while (l && *s1++ == *s2++)
801 l--;
803 if (l == 0)
804 return -1;
805 else
806 return len - l;
809 /* Return true if in the directory FD the directory entry DP, whose
810 string length is LEN, is that of a subdirectory that can be searched. */
811 static bool
812 file_name_completion_dirp (int fd, struct dirent *dp, ptrdiff_t len)
814 USE_SAFE_ALLOCA;
815 char *subdir_name = SAFE_ALLOCA (len + 2);
816 memcpy (subdir_name, dp->d_name, len);
817 strcpy (subdir_name + len, "/");
818 bool dirp = faccessat (fd, subdir_name, F_OK, AT_EACCESS) == 0;
819 SAFE_FREE ();
820 return dirp;
823 static char *
824 stat_uname (struct stat *st)
826 #ifdef WINDOWSNT
827 return st->st_uname;
828 #else
829 struct passwd *pw = getpwuid (st->st_uid);
831 if (pw)
832 return pw->pw_name;
833 else
834 return NULL;
835 #endif
838 static char *
839 stat_gname (struct stat *st)
841 #ifdef WINDOWSNT
842 return st->st_gname;
843 #else
844 struct group *gr = getgrgid (st->st_gid);
846 if (gr)
847 return gr->gr_name;
848 else
849 return NULL;
850 #endif
853 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
854 doc: /* Return a list of attributes of file FILENAME.
855 Value is nil if specified file cannot be opened.
857 ID-FORMAT specifies the preferred format of attributes uid and gid (see
858 below) - valid values are `string' and `integer'. The latter is the
859 default, but we plan to change that, so you should specify a non-nil value
860 for ID-FORMAT if you use the returned uid or gid.
862 To access the elements returned, the following access functions are
863 provided: `file-attribute-type', `file-attribute-link-number',
864 `file-attribute-user-id', `file-attribute-group-id',
865 `file-attribute-access-time', `file-attribute-modification-time',
866 `file-attribute-status-change-time', `file-attribute-size',
867 `file-attribute-modes', `file-attribute-inode-number', and
868 `file-attribute-device-number'.
870 Elements of the attribute list are:
871 0. t for directory, string (name linked to) for symbolic link, or nil.
872 1. Number of links to file.
873 2. File uid as a string or a number. If a string value cannot be
874 looked up, a numeric value, either an integer or a float, is returned.
875 3. File gid, likewise.
876 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
877 same style as (current-time).
878 (See a note below about access time on FAT-based filesystems.)
879 5. Last modification time, likewise. This is the time of the last
880 change to the file's contents.
881 6. Last status change time, likewise. This is the time of last change
882 to the file's attributes: owner and group, access mode bits, etc.
883 7. Size in bytes.
884 This is a floating point number if the size is too large for an integer.
885 8. File modes, as a string of ten letters or dashes as in ls -l.
886 9. An unspecified value, present only for backward compatibility.
887 10. inode number. If it is larger than what an Emacs integer can hold,
888 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
889 If even HIGH is too large for an Emacs integer, this is instead of the form
890 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
891 and finally the low 16 bits.
892 11. Filesystem device number. If it is larger than what the Emacs
893 integer can hold, this is a cons cell, similar to the inode number.
895 On most filesystems, the combination of the inode and the device
896 number uniquely identifies the file.
898 On MS-Windows, performance depends on `w32-get-true-file-attributes',
899 which see.
901 On some FAT-based filesystems, only the date of last access is recorded,
902 so last access time will always be midnight of that day. */)
903 (Lisp_Object filename, Lisp_Object id_format)
905 Lisp_Object encoded;
906 Lisp_Object handler;
908 filename = internal_condition_case_2 (Fexpand_file_name, filename, Qnil,
909 Qt, Fidentity);
910 if (!STRINGP (filename))
911 return Qnil;
913 /* If the file name has special constructs in it,
914 call the corresponding file handler. */
915 handler = Ffind_file_name_handler (filename, Qfile_attributes);
916 if (!NILP (handler))
917 { /* Only pass the extra arg if it is used to help backward compatibility
918 with old file handlers which do not implement the new arg. --Stef */
919 if (NILP (id_format))
920 return call2 (handler, Qfile_attributes, filename);
921 else
922 return call3 (handler, Qfile_attributes, filename, id_format);
925 encoded = ENCODE_FILE (filename);
926 return file_attributes (AT_FDCWD, SSDATA (encoded), id_format);
929 static Lisp_Object
930 file_attributes (int fd, char const *name, Lisp_Object id_format)
932 struct stat s;
933 int lstat_result;
935 /* An array to hold the mode string generated by filemodestring,
936 including its terminating space and null byte. */
937 char modes[sizeof "-rwxr-xr-x "];
939 char *uname = NULL, *gname = NULL;
941 #ifdef WINDOWSNT
942 /* We usually don't request accurate owner and group info, because
943 it can be very expensive on Windows to get that, and most callers
944 of 'lstat' don't need that. But here we do want that information
945 to be accurate. */
946 w32_stat_get_owner_group = 1;
947 #endif
949 lstat_result = fstatat (fd, name, &s, AT_SYMLINK_NOFOLLOW);
951 #ifdef WINDOWSNT
952 w32_stat_get_owner_group = 0;
953 #endif
955 if (lstat_result < 0)
956 return Qnil;
958 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
960 uname = stat_uname (&s);
961 gname = stat_gname (&s);
964 filemodestring (&s, modes);
966 return CALLN (Flist,
967 (S_ISLNK (s.st_mode) ? emacs_readlinkat (fd, name)
968 : S_ISDIR (s.st_mode) ? Qt : Qnil),
969 make_number (s.st_nlink),
970 (uname
971 ? DECODE_SYSTEM (build_unibyte_string (uname))
972 : make_fixnum_or_float (s.st_uid)),
973 (gname
974 ? DECODE_SYSTEM (build_unibyte_string (gname))
975 : make_fixnum_or_float (s.st_gid)),
976 make_lisp_time (get_stat_atime (&s)),
977 make_lisp_time (get_stat_mtime (&s)),
978 make_lisp_time (get_stat_ctime (&s)),
980 /* If the file size is a 4-byte type, assume that
981 files of sizes in the 2-4 GiB range wrap around to
982 negative values, as this is a common bug on older
983 32-bit platforms. */
984 make_fixnum_or_float (sizeof (s.st_size) == 4
985 ? s.st_size & 0xffffffffu
986 : s.st_size),
988 make_string (modes, 10),
990 INTEGER_TO_CONS (s.st_ino),
991 INTEGER_TO_CONS (s.st_dev));
994 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
995 doc: /* Return t if first arg file attributes list is less than second.
996 Comparison is in lexicographic order and case is significant. */)
997 (Lisp_Object f1, Lisp_Object f2)
999 return Fstring_lessp (Fcar (f1), Fcar (f2));
1003 DEFUN ("system-users", Fsystem_users, Ssystem_users, 0, 0, 0,
1004 doc: /* Return a list of user names currently registered in the system.
1005 If we don't know how to determine that on this platform, just
1006 return a list with one element, taken from `user-real-login-name'. */)
1007 (void)
1009 Lisp_Object users = Qnil;
1010 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
1011 struct passwd *pw;
1013 while ((pw = getpwent ()))
1014 users = Fcons (DECODE_SYSTEM (build_string (pw->pw_name)), users);
1016 endpwent ();
1017 #endif
1018 if (EQ (users, Qnil))
1019 /* At least current user is always known. */
1020 users = list1 (Vuser_real_login_name);
1021 return users;
1024 DEFUN ("system-groups", Fsystem_groups, Ssystem_groups, 0, 0, 0,
1025 doc: /* Return a list of user group names currently registered in the system.
1026 The value may be nil if not supported on this platform. */)
1027 (void)
1029 Lisp_Object groups = Qnil;
1030 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1031 struct group *gr;
1033 while ((gr = getgrent ()))
1034 groups = Fcons (DECODE_SYSTEM (build_string (gr->gr_name)), groups);
1036 endgrent ();
1037 #endif
1038 return groups;
1041 void
1042 syms_of_dired (void)
1044 DEFSYM (Qdirectory_files, "directory-files");
1045 DEFSYM (Qdirectory_files_and_attributes, "directory-files-and-attributes");
1046 DEFSYM (Qfile_name_completion, "file-name-completion");
1047 DEFSYM (Qfile_name_all_completions, "file-name-all-completions");
1048 DEFSYM (Qfile_attributes, "file-attributes");
1049 DEFSYM (Qfile_attributes_lessp, "file-attributes-lessp");
1050 DEFSYM (Qdefault_directory, "default-directory");
1051 DEFSYM (Qdecomposed_characters, "decomposed-characters");
1053 defsubr (&Sdirectory_files);
1054 defsubr (&Sdirectory_files_and_attributes);
1055 defsubr (&Sfile_name_completion);
1056 defsubr (&Sfile_name_all_completions);
1057 defsubr (&Sfile_attributes);
1058 defsubr (&Sfile_attributes_lessp);
1059 defsubr (&Ssystem_users);
1060 defsubr (&Ssystem_groups);
1062 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1063 doc: /* Completion ignores file names ending in any string in this list.
1064 It does not ignore them if all possible completions end in one of
1065 these strings or when displaying a list of completions.
1066 It ignores directory names if they match any string in this list which
1067 ends in a slash. */);
1068 Vcompletion_ignored_extensions = Qnil;