Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / src / dired.c
blobc446223a0bcab80c0e45a46e55a5a5082c6bf328
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2018 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 <https://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,
55 Lisp_Object, Lisp_Object);
57 /* Return the number of bytes in DP's name. */
58 static ptrdiff_t
59 dirent_namelen (struct dirent *dp)
61 #ifdef _D_EXACT_NAMLEN
62 return _D_EXACT_NAMLEN (dp);
63 #else
64 return strlen (dp->d_name);
65 #endif
68 #ifndef HAVE_STRUCT_DIRENT_D_TYPE
69 enum { DT_UNKNOWN, DT_DIR, DT_LNK };
70 #endif
72 /* Return the file type of DP. */
73 static int
74 dirent_type (struct dirent *dp)
76 #ifdef HAVE_STRUCT_DIRENT_D_TYPE
77 return dp->d_type;
78 #else
79 return DT_UNKNOWN;
80 #endif
83 static DIR *
84 open_directory (Lisp_Object dirname, int *fdp)
86 char *name = SSDATA (dirname);
87 DIR *d;
88 int fd, opendir_errno;
90 #ifdef DOS_NT
91 /* Directories cannot be opened. The emulation assumes that any
92 file descriptor other than AT_FDCWD corresponds to the most
93 recently opened directory. This hack is good enough for Emacs. */
94 fd = 0;
95 d = opendir (name);
96 opendir_errno = errno;
97 #else
98 fd = emacs_open (name, O_RDONLY | O_DIRECTORY, 0);
99 if (fd < 0)
101 opendir_errno = errno;
102 d = 0;
104 else
106 d = fdopendir (fd);
107 opendir_errno = errno;
108 if (! d)
109 emacs_close (fd);
111 #endif
113 if (!d)
114 report_file_errno ("Opening directory", dirname, opendir_errno);
115 *fdp = fd;
116 return d;
119 #ifdef WINDOWSNT
120 static void
121 directory_files_internal_w32_unwind (Lisp_Object arg)
123 Vw32_get_true_file_attributes = arg;
125 #endif
127 static void
128 directory_files_internal_unwind (void *d)
130 closedir (d);
133 /* Return the next directory entry from DIR; DIR's name is DIRNAME.
134 If there are no more directory entries, return a null pointer.
135 Signal any unrecoverable errors. */
137 static struct dirent *
138 read_dirent (DIR *dir, Lisp_Object dirname)
140 while (true)
142 errno = 0;
143 struct dirent *dp = readdir (dir);
144 if (dp || errno == 0)
145 return dp;
146 if (! (errno == EAGAIN || errno == EINTR))
148 #ifdef WINDOWSNT
149 /* The MS-Windows implementation of 'opendir' doesn't
150 actually open a directory until the first call to
151 'readdir'. If 'readdir' fails to open the directory, it
152 sets errno to ENOENT or EACCES, see w32.c. */
153 if (errno == ENOENT || errno == EACCES)
154 report_file_error ("Opening directory", dirname);
155 #endif
156 report_file_error ("Reading directory", dirname);
158 maybe_quit ();
162 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
163 If not ATTRS, return a list of directory filenames;
164 if ATTRS, return a list of directory filenames and their attributes.
165 In the latter case, pass ID_FORMAT to file_attributes. */
167 Lisp_Object
168 directory_files_internal (Lisp_Object directory, Lisp_Object full,
169 Lisp_Object match, Lisp_Object nosort, bool attrs,
170 Lisp_Object id_format)
172 ptrdiff_t directory_nbytes;
173 Lisp_Object list, dirfilename, encoded_directory;
174 struct re_pattern_buffer *bufp = NULL;
175 bool needsep = 0;
176 ptrdiff_t count = SPECPDL_INDEX ();
177 #ifdef WINDOWSNT
178 Lisp_Object w32_save = Qnil;
179 #endif
181 /* Don't let the compiler optimize away all copies of DIRECTORY,
182 which would break GC; see Bug#16986. */
183 Lisp_Object volatile directory_volatile = directory;
185 /* Because of file name handlers, these functions might call
186 Ffuncall, and cause a GC. */
187 list = encoded_directory = dirfilename = Qnil;
188 dirfilename = Fdirectory_file_name (directory);
190 if (!NILP (match))
192 CHECK_STRING (match);
194 /* MATCH might be a flawed regular expression. Rather than
195 catching and signaling our own errors, we just call
196 compile_pattern to do the work for us. */
197 /* Pass 1 for the MULTIBYTE arg
198 because we do make multibyte strings if the contents warrant. */
199 # ifdef WINDOWSNT
200 /* Windows users want case-insensitive wildcards. */
201 bufp = compile_pattern (match, 0,
202 BVAR (&buffer_defaults, case_canon_table), 0, 1);
203 # else /* !WINDOWSNT */
204 bufp = compile_pattern (match, 0, Qnil, 0, 1);
205 # endif /* !WINDOWSNT */
208 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
209 run_pre_post_conversion_on_str which calls Lisp directly and
210 indirectly. */
211 dirfilename = ENCODE_FILE (dirfilename);
212 encoded_directory = ENCODE_FILE (directory);
214 /* Now *bufp is the compiled form of MATCH; don't call anything
215 which might compile a new regexp until we're done with the loop! */
217 int fd;
218 DIR *d = open_directory (dirfilename, &fd);
220 /* Unfortunately, we can now invoke expand-file-name and
221 file-attributes on filenames, both of which can throw, so we must
222 do a proper unwind-protect. */
223 record_unwind_protect_ptr (directory_files_internal_unwind, d);
225 #ifdef WINDOWSNT
226 if (attrs)
228 /* Do this only once to avoid doing it (in w32.c:stat) for each
229 file in the directory, when we call file_attributes below. */
230 record_unwind_protect (directory_files_internal_w32_unwind,
231 Vw32_get_true_file_attributes);
232 w32_save = Vw32_get_true_file_attributes;
233 if (EQ (Vw32_get_true_file_attributes, Qlocal))
235 /* w32.c:stat will notice these bindings and avoid calling
236 GetDriveType for each file. */
237 if (is_slow_fs (SSDATA (dirfilename)))
238 Vw32_get_true_file_attributes = Qnil;
239 else
240 Vw32_get_true_file_attributes = Qt;
243 #endif
245 directory_nbytes = SBYTES (directory);
246 re_match_object = Qt;
248 /* Decide whether we need to add a directory separator. */
249 if (directory_nbytes == 0
250 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
251 needsep = 1;
253 /* Loop reading directory entries. */
254 for (struct dirent *dp; (dp = read_dirent (d, directory)); )
256 ptrdiff_t len = dirent_namelen (dp);
257 Lisp_Object name = make_unibyte_string (dp->d_name, len);
258 Lisp_Object finalname = name;
260 /* Note: DECODE_FILE can GC; it should protect its argument,
261 though. */
262 name = DECODE_FILE (name);
263 len = SBYTES (name);
265 /* Now that we have unwind_protect in place, we might as well
266 allow matching to be interrupted. */
267 maybe_quit ();
269 bool wanted = (NILP (match)
270 || re_search (bufp, SSDATA (name), len, 0, len, 0) >= 0);
272 if (wanted)
274 if (!NILP (full))
276 Lisp_Object fullname;
277 ptrdiff_t nbytes = len + directory_nbytes + needsep;
278 ptrdiff_t 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 = multibyte_chars_in_text (SDATA (fullname), nbytes);
292 /* Some bug somewhere. */
293 if (nchars > nbytes)
294 emacs_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 Lisp_Object fileattrs
308 = file_attributes (fd, dp->d_name, directory, name, id_format);
309 list = Fcons (Fcons (finalname, fileattrs), list);
311 else
312 list = Fcons (finalname, list);
316 closedir (d);
317 #ifdef WINDOWSNT
318 if (attrs)
319 Vw32_get_true_file_attributes = w32_save;
320 #endif
322 /* Discard the unwind protect. */
323 specpdl_ptr = specpdl + count;
325 if (NILP (nosort))
326 list = Fsort (Fnreverse (list),
327 attrs ? Qfile_attributes_lessp : Qstring_lessp);
329 (void) directory_volatile;
330 return list;
334 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
335 doc: /* Return a list of names of files in DIRECTORY.
336 There are three optional arguments:
337 If FULL is non-nil, return absolute file names. Otherwise return names
338 that are relative to the specified directory.
339 If MATCH is non-nil, mention only file names that match the regexp MATCH.
340 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
341 Otherwise, the list returned is sorted with `string-lessp'.
342 NOSORT is useful if you plan to sort the result yourself. */)
343 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
345 Lisp_Object handler;
346 directory = Fexpand_file_name (directory, Qnil);
348 /* If the file name has special constructs in it,
349 call the corresponding file handler. */
350 handler = Ffind_file_name_handler (directory, Qdirectory_files);
351 if (!NILP (handler))
352 return call5 (handler, Qdirectory_files, directory,
353 full, match, nosort);
355 return directory_files_internal (directory, full, match, nosort, false, Qnil);
358 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
359 Sdirectory_files_and_attributes, 1, 5, 0,
360 doc: /* Return a list of names of files and their attributes in DIRECTORY.
361 There are four optional arguments:
362 If FULL is non-nil, return absolute file names. Otherwise return names
363 that are relative to the specified directory.
364 If MATCH is non-nil, mention only file names that match the regexp MATCH.
365 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
366 NOSORT is useful if you plan to sort the result yourself.
367 ID-FORMAT specifies the preferred format of attributes uid and gid, see
368 `file-attributes' for further documentation.
369 On MS-Windows, performance depends on `w32-get-true-file-attributes',
370 which see. */)
371 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
373 Lisp_Object handler;
374 directory = Fexpand_file_name (directory, Qnil);
376 /* If the file name has special constructs in it,
377 call the corresponding file handler. */
378 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
379 if (!NILP (handler))
380 return call6 (handler, Qdirectory_files_and_attributes,
381 directory, full, match, nosort, id_format);
383 return directory_files_internal (directory, full, match, nosort,
384 true, id_format);
388 static Lisp_Object file_name_completion (Lisp_Object, Lisp_Object, bool,
389 Lisp_Object);
391 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
392 2, 3, 0,
393 doc: /* Complete file name FILE in directory DIRECTORY.
394 Returns the longest string
395 common to all file names in DIRECTORY that start with FILE.
396 If there is only one and FILE matches it exactly, returns t.
397 Returns nil if DIRECTORY contains no name starting with FILE.
399 If PREDICATE is non-nil, call PREDICATE with each possible
400 completion (in absolute form) and ignore it if PREDICATE returns nil.
402 This function ignores some of the possible completions as determined
403 by the variables `completion-regexp-list' and
404 `completion-ignored-extensions', which see. `completion-regexp-list'
405 is matched against file and directory names relative to DIRECTORY. */)
406 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
408 Lisp_Object handler;
409 directory = Fexpand_file_name (directory, Qnil);
411 /* If the directory name has special constructs in it,
412 call the corresponding file handler. */
413 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
414 if (!NILP (handler))
415 return call4 (handler, Qfile_name_completion, file, directory, predicate);
417 /* If the file name has special constructs in it,
418 call the corresponding file handler. */
419 handler = Ffind_file_name_handler (file, Qfile_name_completion);
420 if (!NILP (handler))
421 return call4 (handler, Qfile_name_completion, file, directory, predicate);
423 return file_name_completion (file, directory, 0, predicate);
426 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
427 Sfile_name_all_completions, 2, 2, 0,
428 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
429 These are all file names in directory DIRECTORY which begin with FILE.
431 This function ignores some of the possible completions as determined
432 by `completion-regexp-list', which see. `completion-regexp-list'
433 is matched against file and directory names relative to DIRECTORY. */)
434 (Lisp_Object file, Lisp_Object directory)
436 Lisp_Object handler;
437 directory = Fexpand_file_name (directory, Qnil);
439 /* If the directory name has special constructs in it,
440 call the corresponding file handler. */
441 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
442 if (!NILP (handler))
443 return call3 (handler, Qfile_name_all_completions, file, directory);
445 /* If the file name has special constructs in it,
446 call the corresponding file handler. */
447 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
448 if (!NILP (handler))
449 return call3 (handler, Qfile_name_all_completions, file, directory);
451 return file_name_completion (file, directory, 1, Qnil);
454 static bool file_name_completion_dirp (int, struct dirent *, ptrdiff_t);
456 static Lisp_Object
457 file_name_completion (Lisp_Object file, Lisp_Object dirname, bool all_flag,
458 Lisp_Object predicate)
460 ptrdiff_t bestmatchsize = 0;
461 int matchcount = 0;
462 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
463 If ALL_FLAG is 0, BESTMATCH is either nil
464 or the best match so far, not decoded. */
465 Lisp_Object bestmatch, tem, elt, name;
466 Lisp_Object encoded_file;
467 Lisp_Object encoded_dir;
468 bool directoryp;
469 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
470 well as "." and "..". Until shown otherwise, assume we can't exclude
471 anything. */
472 bool includeall = 1;
473 bool check_decoded = false;
474 ptrdiff_t count = SPECPDL_INDEX ();
476 elt = Qnil;
478 CHECK_STRING (file);
480 bestmatch = Qnil;
481 encoded_file = encoded_dir = Qnil;
482 specbind (Qdefault_directory, dirname);
484 /* Do completion on the encoded file name
485 because the other names in the directory are (we presume)
486 encoded likewise. We decode the completed string at the end. */
487 /* Actually, this is not quite true any more: we do most of the completion
488 work with decoded file names, but we still do some filtering based
489 on the encoded file name. */
490 encoded_file = ENCODE_FILE (file);
491 encoded_dir = ENCODE_FILE (Fdirectory_file_name (dirname));
493 Lisp_Object file_encoding = Vfile_name_coding_system;
494 if (NILP (Vfile_name_coding_system))
495 file_encoding = Vdefault_file_name_coding_system;
496 /* If the file-name encoding decomposes characters, as we do for
497 HFS+ filesystems, we need to make an additional comparison of
498 decoded names in order to filter false positives, such as "a"
499 falsely matching "a-ring". */
500 if (!NILP (file_encoding)
501 && !NILP (Fplist_get (Fcoding_system_plist (file_encoding),
502 Qdecomposed_characters)))
504 check_decoded = true;
505 if (STRING_MULTIBYTE (file))
507 /* Recompute FILE to make sure any decomposed characters in
508 it are re-composed by the post-read-conversion.
509 Otherwise, any decomposed characters will be rejected by
510 the additional check below. */
511 file = DECODE_FILE (encoded_file);
514 int fd;
515 DIR *d = open_directory (encoded_dir, &fd);
516 record_unwind_protect_ptr (directory_files_internal_unwind, d);
518 /* Loop reading directory entries. */
519 for (struct dirent *dp; (dp = read_dirent (d, dirname)); )
521 ptrdiff_t len = dirent_namelen (dp);
522 bool canexclude = 0;
524 maybe_quit ();
525 if (len < SCHARS (encoded_file)
526 || (scmp (dp->d_name, SSDATA (encoded_file),
527 SCHARS (encoded_file))
528 >= 0))
529 continue;
531 switch (dirent_type (dp))
533 case DT_DIR:
534 directoryp = true;
535 break;
537 case DT_LNK: case DT_UNKNOWN:
538 directoryp = file_name_completion_dirp (fd, dp, len);
539 break;
541 default:
542 directoryp = false;
543 break;
546 tem = Qnil;
547 /* If all_flag is set, always include all.
548 It would not actually be helpful to the user to ignore any possible
549 completions when making a list of them. */
550 if (!all_flag)
552 ptrdiff_t skip;
554 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
555 /* If this entry matches the current bestmatch, the only
556 thing it can do is increase matchcount, so don't bother
557 investigating it any further. */
558 if (!completion_ignore_case
559 /* The return result depends on whether it's the sole match. */
560 && matchcount > 1
561 && !includeall /* This match may allow includeall to 0. */
562 && len >= bestmatchsize
563 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
564 continue;
565 #endif
567 if (directoryp)
569 #ifndef TRIVIAL_DIRECTORY_ENTRY
570 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
571 #endif
572 /* "." and ".." are never interesting as completions, and are
573 actually in the way in a directory with only one file. */
574 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
575 canexclude = 1;
576 else if (len > SCHARS (encoded_file))
577 /* Ignore directories if they match an element of
578 completion-ignored-extensions which ends in a slash. */
579 for (tem = Vcompletion_ignored_extensions;
580 CONSP (tem); tem = XCDR (tem))
582 ptrdiff_t elt_len;
583 char *p1;
585 elt = XCAR (tem);
586 if (!STRINGP (elt))
587 continue;
588 /* Need to encode ELT, since scmp compares unibyte
589 strings only. */
590 elt = ENCODE_FILE (elt);
591 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
592 if (elt_len <= 0)
593 continue;
594 p1 = SSDATA (elt);
595 if (p1[elt_len] != '/')
596 continue;
597 skip = len - elt_len;
598 if (skip < 0)
599 continue;
601 if (scmp (dp->d_name + skip, p1, elt_len) >= 0)
602 continue;
603 break;
606 else
608 /* Compare extensions-to-be-ignored against end of this file name */
609 /* if name is not an exact match against specified string */
610 if (len > SCHARS (encoded_file))
611 /* and exit this for loop if a match is found */
612 for (tem = Vcompletion_ignored_extensions;
613 CONSP (tem); tem = XCDR (tem))
615 elt = XCAR (tem);
616 if (!STRINGP (elt)) continue;
617 /* Need to encode ELT, since scmp compares unibyte
618 strings only. */
619 elt = ENCODE_FILE (elt);
620 skip = len - SCHARS (elt);
621 if (skip < 0) continue;
623 if (scmp (dp->d_name + skip, SSDATA (elt), SCHARS (elt))
624 >= 0)
625 continue;
626 break;
630 /* If an ignored-extensions match was found,
631 don't process this name as a completion. */
632 if (CONSP (tem))
633 canexclude = 1;
635 if (!includeall && canexclude)
636 /* We're not including all files and this file can be excluded. */
637 continue;
639 if (includeall && !canexclude)
640 { /* If we have one non-excludable file, we want to exclude the
641 excludable files. */
642 includeall = 0;
643 /* Throw away any previous excludable match found. */
644 bestmatch = Qnil;
645 bestmatchsize = 0;
646 matchcount = 0;
649 /* FIXME: If we move this `decode' earlier we can eliminate
650 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
651 name = make_unibyte_string (dp->d_name, len);
652 name = DECODE_FILE (name);
655 Lisp_Object regexps, table = (completion_ignore_case
656 ? Vascii_canon_table : Qnil);
658 /* Ignore this element if it fails to match all the regexps. */
659 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
660 regexps = XCDR (regexps))
661 if (fast_string_match_internal (XCAR (regexps), name, table) < 0)
662 break;
664 if (CONSP (regexps))
665 continue;
668 /* This is a possible completion */
669 if (directoryp)
670 /* This completion is a directory; make it end with '/'. */
671 name = Ffile_name_as_directory (name);
673 /* Test the predicate, if any. */
674 if (!NILP (predicate) && NILP (call1 (predicate, name)))
675 continue;
677 /* Reject entries where the encoded strings match, but the
678 decoded don't. For example, "a" should not match "a-ring" on
679 file systems that store decomposed characters. */
680 Lisp_Object zero = make_number (0);
682 if (check_decoded && SCHARS (file) <= SCHARS (name))
684 /* FIXME: This is a copy of the code below. */
685 ptrdiff_t compare = SCHARS (file);
686 Lisp_Object cmp
687 = Fcompare_strings (name, zero, make_number (compare),
688 file, zero, make_number (compare),
689 completion_ignore_case ? Qt : Qnil);
690 if (!EQ (cmp, Qt))
691 continue;
694 /* Suitably record this match. */
696 matchcount += matchcount <= 1;
698 if (all_flag)
699 bestmatch = Fcons (name, bestmatch);
700 else if (NILP (bestmatch))
702 bestmatch = name;
703 bestmatchsize = SCHARS (name);
705 else
707 /* FIXME: This is a copy of the code in Ftry_completion. */
708 ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
709 Lisp_Object cmp
710 = Fcompare_strings (bestmatch, zero, make_number (compare),
711 name, zero, make_number (compare),
712 completion_ignore_case ? Qt : Qnil);
713 ptrdiff_t matchsize = EQ (cmp, Qt) ? compare : eabs (XINT (cmp)) - 1;
715 if (completion_ignore_case)
717 /* If this is an exact match except for case,
718 use it as the best match rather than one that is not
719 an exact match. This way, we get the case pattern
720 of the actual match. */
721 /* This tests that the current file is an exact match
722 but BESTMATCH is not (it is too long). */
723 if ((matchsize == SCHARS (name)
724 && matchsize + directoryp < SCHARS (bestmatch))
726 /* If there is no exact match ignoring case,
727 prefer a match that does not change the case
728 of the input. */
729 /* If there is more than one exact match aside from
730 case, and one of them is exact including case,
731 prefer that one. */
732 /* This == checks that, of current file and BESTMATCH,
733 either both or neither are exact. */
734 (((matchsize == SCHARS (name))
736 (matchsize + directoryp == SCHARS (bestmatch)))
737 && (cmp = Fcompare_strings (name, zero,
738 make_number (SCHARS (file)),
739 file, zero,
740 Qnil,
741 Qnil),
742 EQ (Qt, cmp))
743 && (cmp = Fcompare_strings (bestmatch, zero,
744 make_number (SCHARS (file)),
745 file, zero,
746 Qnil,
747 Qnil),
748 ! EQ (Qt, cmp))))
749 bestmatch = name;
751 bestmatchsize = matchsize;
753 /* If the best completion so far is reduced to the string
754 we're trying to complete, then we already know there's no
755 other completion, so there's no point looking any further. */
756 if (matchsize <= SCHARS (file)
757 && !includeall /* A future match may allow includeall to 0. */
758 /* If completion-ignore-case is non-nil, don't
759 short-circuit because we want to find the best
760 possible match *including* case differences. */
761 && (!completion_ignore_case || matchsize == 0)
762 /* The return value depends on whether it's the sole match. */
763 && matchcount > 1)
764 break;
769 /* This closes the directory. */
770 bestmatch = unbind_to (count, bestmatch);
772 if (all_flag || NILP (bestmatch))
773 return bestmatch;
774 /* Return t if the supplied string is an exact match (counting case);
775 it does not require any change to be made. */
776 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
777 return Qt;
778 bestmatch = Fsubstring (bestmatch, make_number (0),
779 make_number (bestmatchsize));
780 return bestmatch;
783 /* Compare exactly LEN chars of strings at S1 and S2,
784 ignoring case if appropriate.
785 Return -1 if strings match,
786 else number of chars that match at the beginning. */
788 static ptrdiff_t
789 scmp (const char *s1, const char *s2, ptrdiff_t len)
791 register ptrdiff_t l = len;
793 if (completion_ignore_case)
795 while (l
796 && (downcase ((unsigned char) *s1++)
797 == downcase ((unsigned char) *s2++)))
798 l--;
800 else
802 while (l && *s1++ == *s2++)
803 l--;
805 if (l == 0)
806 return -1;
807 else
808 return len - l;
811 /* Return true if in the directory FD the directory entry DP, whose
812 string length is LEN, is that of a subdirectory that can be searched. */
813 static bool
814 file_name_completion_dirp (int fd, struct dirent *dp, ptrdiff_t len)
816 USE_SAFE_ALLOCA;
817 char *subdir_name = SAFE_ALLOCA (len + 2);
818 memcpy (subdir_name, dp->d_name, len);
819 strcpy (subdir_name + len, "/");
820 bool dirp = faccessat (fd, subdir_name, F_OK, AT_EACCESS) == 0;
821 SAFE_FREE ();
822 return dirp;
825 static char *
826 stat_uname (struct stat *st)
828 #ifdef WINDOWSNT
829 return st->st_uname;
830 #else
831 struct passwd *pw = getpwuid (st->st_uid);
833 if (pw)
834 return pw->pw_name;
835 else
836 return NULL;
837 #endif
840 static char *
841 stat_gname (struct stat *st)
843 #ifdef WINDOWSNT
844 return st->st_gname;
845 #else
846 struct group *gr = getgrgid (st->st_gid);
848 if (gr)
849 return gr->gr_name;
850 else
851 return NULL;
852 #endif
855 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
856 doc: /* Return a list of attributes of file FILENAME.
857 Value is nil if specified file cannot be opened.
859 ID-FORMAT specifies the preferred format of attributes uid and gid (see
860 below) - valid values are `string' and `integer'. The latter is the
861 default, but we plan to change that, so you should specify a non-nil value
862 for ID-FORMAT if you use the returned uid or gid.
864 To access the elements returned, the following access functions are
865 provided: `file-attribute-type', `file-attribute-link-number',
866 `file-attribute-user-id', `file-attribute-group-id',
867 `file-attribute-access-time', `file-attribute-modification-time',
868 `file-attribute-status-change-time', `file-attribute-size',
869 `file-attribute-modes', `file-attribute-inode-number', and
870 `file-attribute-device-number'.
872 Elements of the attribute list are:
873 0. t for directory, string (name linked to) for symbolic link, or nil.
874 1. Number of links to file.
875 2. File uid as a string or a number. If a string value cannot be
876 looked up, a numeric value, either an integer or a float, is returned.
877 3. File gid, likewise.
878 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
879 same style as (current-time).
880 (See a note below about access time on FAT-based filesystems.)
881 5. Last modification time, likewise. This is the time of the last
882 change to the file's contents.
883 6. Last status change time, likewise. This is the time of last change
884 to the file's attributes: owner and group, access mode bits, etc.
885 7. Size in bytes.
886 This is a floating point number if the size is too large for an integer.
887 8. File modes, as a string of ten letters or dashes as in ls -l.
888 9. An unspecified value, present only for backward compatibility.
889 10. inode number. If it is larger than what an Emacs integer can hold,
890 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
891 If even HIGH is too large for an Emacs integer, this is instead of the form
892 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
893 and finally the low 16 bits.
894 11. Filesystem device number. If it is larger than what the Emacs
895 integer can hold, this is a cons cell, similar to the inode number.
897 On most filesystems, the combination of the inode and the device
898 number uniquely identifies the file.
900 On MS-Windows, performance depends on `w32-get-true-file-attributes',
901 which see.
903 On some FAT-based filesystems, only the date of last access is recorded,
904 so last access time will always be midnight of that day. */)
905 (Lisp_Object filename, Lisp_Object id_format)
907 Lisp_Object encoded;
908 Lisp_Object handler;
910 filename = internal_condition_case_2 (Fexpand_file_name, filename, Qnil,
911 Qt, Fidentity);
912 if (!STRINGP (filename))
913 return Qnil;
915 /* If the file name has special constructs in it,
916 call the corresponding file handler. */
917 handler = Ffind_file_name_handler (filename, Qfile_attributes);
918 if (!NILP (handler))
919 { /* Only pass the extra arg if it is used to help backward compatibility
920 with old file handlers which do not implement the new arg. --Stef */
921 if (NILP (id_format))
922 return call2 (handler, Qfile_attributes, filename);
923 else
924 return call3 (handler, Qfile_attributes, filename, id_format);
927 encoded = ENCODE_FILE (filename);
928 return file_attributes (AT_FDCWD, SSDATA (encoded), Qnil, filename,
929 id_format);
932 static Lisp_Object
933 file_attributes (int fd, char const *name,
934 Lisp_Object dirname, Lisp_Object filename,
935 Lisp_Object id_format)
937 ptrdiff_t count = SPECPDL_INDEX ();
938 struct stat s;
940 /* An array to hold the mode string generated by filemodestring,
941 including its terminating space and null byte. */
942 char modes[sizeof "-rwxr-xr-x "];
944 char *uname = NULL, *gname = NULL;
946 int err = EINVAL;
948 #ifdef O_PATH
949 int namefd = openat (fd, name, O_PATH | O_CLOEXEC | O_NOFOLLOW);
950 if (namefd < 0)
951 err = errno;
952 else
954 record_unwind_protect_int (close_file_unwind, namefd);
955 if (fstat (namefd, &s) != 0)
957 err = errno;
958 /* The Linux kernel before version 3.6 does not support
959 fstat on O_PATH file descriptors. Handle this error like
960 missing support for O_PATH. */
961 if (err == EBADF)
962 err = EINVAL;
964 else
966 err = 0;
967 fd = namefd;
968 name = "";
971 #endif
973 if (err == EINVAL)
975 #ifdef WINDOWSNT
976 /* We usually don't request accurate owner and group info,
977 because it can be expensive on Windows to get that, and most
978 callers of 'lstat' don't need that. But here we do want that
979 information to be accurate. */
980 w32_stat_get_owner_group = 1;
981 #endif
982 if (fstatat (fd, name, &s, AT_SYMLINK_NOFOLLOW) == 0)
983 err = 0;
984 #ifdef WINDOWSNT
985 w32_stat_get_owner_group = 0;
986 #endif
989 if (err != 0)
990 return unbind_to (count, Qnil);
992 Lisp_Object file_type;
993 if (S_ISLNK (s.st_mode))
995 /* On systems lacking O_PATH support there is a race if the
996 symlink is replaced between the call to fstatat and the call
997 to emacs_readlinkat. Detect this race unless the replacement
998 is also a symlink. */
999 file_type = emacs_readlinkat (fd, name);
1000 if (NILP (file_type))
1001 return unbind_to (count, Qnil);
1003 else
1004 file_type = S_ISDIR (s.st_mode) ? Qt : Qnil;
1006 unbind_to (count, Qnil);
1008 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
1010 uname = stat_uname (&s);
1011 gname = stat_gname (&s);
1014 filemodestring (&s, modes);
1016 return CALLN (Flist,
1017 file_type,
1018 make_number (s.st_nlink),
1019 (uname
1020 ? DECODE_SYSTEM (build_unibyte_string (uname))
1021 : make_fixnum_or_float (s.st_uid)),
1022 (gname
1023 ? DECODE_SYSTEM (build_unibyte_string (gname))
1024 : make_fixnum_or_float (s.st_gid)),
1025 make_lisp_time (get_stat_atime (&s)),
1026 make_lisp_time (get_stat_mtime (&s)),
1027 make_lisp_time (get_stat_ctime (&s)),
1029 /* If the file size is a 4-byte type, assume that
1030 files of sizes in the 2-4 GiB range wrap around to
1031 negative values, as this is a common bug on older
1032 32-bit platforms. */
1033 make_fixnum_or_float (sizeof (s.st_size) == 4
1034 ? s.st_size & 0xffffffffu
1035 : s.st_size),
1037 make_string (modes, 10),
1039 INTEGER_TO_CONS (s.st_ino),
1040 INTEGER_TO_CONS (s.st_dev));
1043 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
1044 doc: /* Return t if first arg file attributes list is less than second.
1045 Comparison is in lexicographic order and case is significant. */)
1046 (Lisp_Object f1, Lisp_Object f2)
1048 return Fstring_lessp (Fcar (f1), Fcar (f2));
1052 DEFUN ("system-users", Fsystem_users, Ssystem_users, 0, 0, 0,
1053 doc: /* Return a list of user names currently registered in the system.
1054 If we don't know how to determine that on this platform, just
1055 return a list with one element, taken from `user-real-login-name'. */)
1056 (void)
1058 Lisp_Object users = Qnil;
1059 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
1060 struct passwd *pw;
1062 while ((pw = getpwent ()))
1063 users = Fcons (DECODE_SYSTEM (build_string (pw->pw_name)), users);
1065 endpwent ();
1066 #endif
1067 if (EQ (users, Qnil))
1068 /* At least current user is always known. */
1069 users = list1 (Vuser_real_login_name);
1070 return users;
1073 DEFUN ("system-groups", Fsystem_groups, Ssystem_groups, 0, 0, 0,
1074 doc: /* Return a list of user group names currently registered in the system.
1075 The value may be nil if not supported on this platform. */)
1076 (void)
1078 Lisp_Object groups = Qnil;
1079 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1080 struct group *gr;
1082 while ((gr = getgrent ()))
1083 groups = Fcons (DECODE_SYSTEM (build_string (gr->gr_name)), groups);
1085 endgrent ();
1086 #endif
1087 return groups;
1090 void
1091 syms_of_dired (void)
1093 DEFSYM (Qdirectory_files, "directory-files");
1094 DEFSYM (Qdirectory_files_and_attributes, "directory-files-and-attributes");
1095 DEFSYM (Qfile_name_completion, "file-name-completion");
1096 DEFSYM (Qfile_name_all_completions, "file-name-all-completions");
1097 DEFSYM (Qfile_attributes, "file-attributes");
1098 DEFSYM (Qfile_attributes_lessp, "file-attributes-lessp");
1099 DEFSYM (Qdefault_directory, "default-directory");
1100 DEFSYM (Qdecomposed_characters, "decomposed-characters");
1102 defsubr (&Sdirectory_files);
1103 defsubr (&Sdirectory_files_and_attributes);
1104 defsubr (&Sfile_name_completion);
1105 defsubr (&Sfile_name_all_completions);
1106 defsubr (&Sfile_attributes);
1107 defsubr (&Sfile_attributes_lessp);
1108 defsubr (&Ssystem_users);
1109 defsubr (&Ssystem_groups);
1111 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1112 doc: /* Completion ignores file names ending in any string in this list.
1113 It does not ignore them if all possible completions end in one of
1114 these strings or when displaying a list of completions.
1115 It ignores directory names if they match any string in this list which
1116 ends in a slash. */);
1117 Vcompletion_ignored_extensions = Qnil;