1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2019 Free Software
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/>. */
37 #include <stat-time.h>
46 #include "msdos.h" /* for fstatat */
50 extern int is_slow_fs (const char *);
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. */
59 dirent_namelen (struct dirent
*dp
)
61 #ifdef _D_EXACT_NAMLEN
62 return _D_EXACT_NAMLEN (dp
);
64 return strlen (dp
->d_name
);
68 #ifndef HAVE_STRUCT_DIRENT_D_TYPE
69 enum { DT_UNKNOWN
, DT_DIR
, DT_LNK
};
72 /* Return the file type of DP. */
74 dirent_type (struct dirent
*dp
)
76 #ifdef HAVE_STRUCT_DIRENT_D_TYPE
84 open_directory (Lisp_Object dirname
, int *fdp
)
86 char *name
= SSDATA (dirname
);
88 int fd
, opendir_errno
;
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. */
96 opendir_errno
= errno
;
98 fd
= emacs_open (name
, O_RDONLY
| O_DIRECTORY
, 0);
101 opendir_errno
= errno
;
107 opendir_errno
= errno
;
114 report_file_errno ("Opening directory", dirname
, opendir_errno
);
121 directory_files_internal_w32_unwind (Lisp_Object arg
)
123 Vw32_get_true_file_attributes
= arg
;
128 directory_files_internal_unwind (void *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
)
143 struct dirent
*dp
= readdir (dir
);
144 if (dp
|| errno
== 0)
146 if (! (errno
== EAGAIN
|| errno
== EINTR
))
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
);
156 report_file_error ("Reading directory", dirname
);
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. */
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
;
176 ptrdiff_t count
= SPECPDL_INDEX ();
178 Lisp_Object w32_save
= Qnil
;
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
);
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. */
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
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! */
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
);
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
;
240 Vw32_get_true_file_attributes
= Qt
;
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)))
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,
262 name
= DECODE_FILE (name
);
265 /* Now that we have unwind_protect in place, we might as well
266 allow matching to be interrupted. */
269 bool wanted
= (NILP (match
)
270 || re_search (bufp
, SSDATA (name
), len
, 0, len
, 0) >= 0);
276 Lisp_Object fullname
;
277 ptrdiff_t nbytes
= len
+ directory_nbytes
+ needsep
;
280 fullname
= make_uninit_multibyte_string (nbytes
, nbytes
);
281 memcpy (SDATA (fullname
), SDATA (directory
),
285 SSET (fullname
, directory_nbytes
, DIRECTORY_SEP
);
287 memcpy (SDATA (fullname
) + directory_nbytes
+ needsep
,
290 nchars
= multibyte_chars_in_text (SDATA (fullname
), nbytes
);
292 /* Some bug somewhere. */
296 STRING_SET_CHARS (fullname
, nchars
);
297 if (nchars
== nbytes
)
298 STRING_SET_UNIBYTE (fullname
);
300 finalname
= fullname
;
307 Lisp_Object fileattrs
308 = file_attributes (fd
, dp
->d_name
, directory
, name
, id_format
);
309 list
= Fcons (Fcons (finalname
, fileattrs
), list
);
312 list
= Fcons (finalname
, list
);
319 Vw32_get_true_file_attributes
= w32_save
;
322 /* Discard the unwind protect. */
323 specpdl_ptr
= specpdl
+ count
;
326 list
= Fsort (Fnreverse (list
),
327 attrs
? Qfile_attributes_lessp
: Qstring_lessp
);
329 (void) directory_volatile
;
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
)
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
);
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 Value is a list of the form:
363 ((FILE1 FILE1-ATTRS) (FILE2 FILE2-ATTRS) ...)
365 where each FILEn-ATTRS is the attributes of FILEn as returned
366 by `file-attributes'.
368 This function accepts four optional arguments:
369 If FULL is non-nil, return absolute file names. Otherwise return names
370 that are relative to the specified directory.
371 If MATCH is non-nil, mention only file names that match the regexp MATCH.
372 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
373 NOSORT is useful if you plan to sort the result yourself.
374 ID-FORMAT specifies the preferred format of attributes uid and gid, see
375 `file-attributes' for further documentation.
376 On MS-Windows, performance depends on `w32-get-true-file-attributes',
378 (Lisp_Object directory
, Lisp_Object full
, Lisp_Object match
, Lisp_Object nosort
, Lisp_Object id_format
)
381 directory
= Fexpand_file_name (directory
, Qnil
);
383 /* If the file name has special constructs in it,
384 call the corresponding file handler. */
385 handler
= Ffind_file_name_handler (directory
, Qdirectory_files_and_attributes
);
387 return call6 (handler
, Qdirectory_files_and_attributes
,
388 directory
, full
, match
, nosort
, id_format
);
390 return directory_files_internal (directory
, full
, match
, nosort
,
395 static Lisp_Object
file_name_completion (Lisp_Object
, Lisp_Object
, bool,
398 DEFUN ("file-name-completion", Ffile_name_completion
, Sfile_name_completion
,
400 doc
: /* Complete file name FILE in directory DIRECTORY.
401 Returns the longest string
402 common to all file names in DIRECTORY that start with FILE.
403 If there is only one and FILE matches it exactly, returns t.
404 Returns nil if DIRECTORY contains no name starting with FILE.
406 If PREDICATE is non-nil, call PREDICATE with each possible
407 completion (in absolute form) and ignore it if PREDICATE returns nil.
409 This function ignores some of the possible completions as determined
410 by the variables `completion-regexp-list' and
411 `completion-ignored-extensions', which see. `completion-regexp-list'
412 is matched against file and directory names relative to DIRECTORY. */)
413 (Lisp_Object file
, Lisp_Object directory
, Lisp_Object predicate
)
416 directory
= Fexpand_file_name (directory
, Qnil
);
418 /* If the directory name has special constructs in it,
419 call the corresponding file handler. */
420 handler
= Ffind_file_name_handler (directory
, Qfile_name_completion
);
422 return call4 (handler
, Qfile_name_completion
, file
, directory
, predicate
);
424 /* If the file name has special constructs in it,
425 call the corresponding file handler. */
426 handler
= Ffind_file_name_handler (file
, Qfile_name_completion
);
428 return call4 (handler
, Qfile_name_completion
, file
, directory
, predicate
);
430 return file_name_completion (file
, directory
, 0, predicate
);
433 DEFUN ("file-name-all-completions", Ffile_name_all_completions
,
434 Sfile_name_all_completions
, 2, 2, 0,
435 doc
: /* Return a list of all completions of file name FILE in directory DIRECTORY.
436 These are all file names in directory DIRECTORY which begin with FILE.
438 This function ignores some of the possible completions as determined
439 by `completion-regexp-list', which see. `completion-regexp-list'
440 is matched against file and directory names relative to DIRECTORY. */)
441 (Lisp_Object file
, Lisp_Object directory
)
444 directory
= Fexpand_file_name (directory
, Qnil
);
446 /* If the directory name has special constructs in it,
447 call the corresponding file handler. */
448 handler
= Ffind_file_name_handler (directory
, Qfile_name_all_completions
);
450 return call3 (handler
, Qfile_name_all_completions
, file
, directory
);
452 /* If the file name has special constructs in it,
453 call the corresponding file handler. */
454 handler
= Ffind_file_name_handler (file
, Qfile_name_all_completions
);
456 return call3 (handler
, Qfile_name_all_completions
, file
, directory
);
458 return file_name_completion (file
, directory
, 1, Qnil
);
461 static bool file_name_completion_dirp (int, struct dirent
*, ptrdiff_t);
464 file_name_completion (Lisp_Object file
, Lisp_Object dirname
, bool all_flag
,
465 Lisp_Object predicate
)
467 ptrdiff_t bestmatchsize
= 0;
469 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
470 If ALL_FLAG is 0, BESTMATCH is either nil
471 or the best match so far, not decoded. */
472 Lisp_Object bestmatch
, tem
, elt
, name
;
473 Lisp_Object encoded_file
;
474 Lisp_Object encoded_dir
;
476 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
477 well as "." and "..". Until shown otherwise, assume we can't exclude
480 bool check_decoded
= false;
481 ptrdiff_t count
= SPECPDL_INDEX ();
488 encoded_file
= encoded_dir
= Qnil
;
489 specbind (Qdefault_directory
, dirname
);
491 /* Do completion on the encoded file name
492 because the other names in the directory are (we presume)
493 encoded likewise. We decode the completed string at the end. */
494 /* Actually, this is not quite true any more: we do most of the completion
495 work with decoded file names, but we still do some filtering based
496 on the encoded file name. */
497 encoded_file
= ENCODE_FILE (file
);
498 encoded_dir
= ENCODE_FILE (Fdirectory_file_name (dirname
));
500 Lisp_Object file_encoding
= Vfile_name_coding_system
;
501 if (NILP (Vfile_name_coding_system
))
502 file_encoding
= Vdefault_file_name_coding_system
;
503 /* If the file-name encoding decomposes characters, as we do for
504 HFS+ filesystems, we need to make an additional comparison of
505 decoded names in order to filter false positives, such as "a"
506 falsely matching "a-ring". */
507 if (!NILP (file_encoding
)
508 && !NILP (Fplist_get (Fcoding_system_plist (file_encoding
),
509 Qdecomposed_characters
)))
511 check_decoded
= true;
512 if (STRING_MULTIBYTE (file
))
514 /* Recompute FILE to make sure any decomposed characters in
515 it are re-composed by the post-read-conversion.
516 Otherwise, any decomposed characters will be rejected by
517 the additional check below. */
518 file
= DECODE_FILE (encoded_file
);
522 DIR *d
= open_directory (encoded_dir
, &fd
);
523 record_unwind_protect_ptr (directory_files_internal_unwind
, d
);
525 /* Loop reading directory entries. */
526 for (struct dirent
*dp
; (dp
= read_dirent (d
, dirname
)); )
528 ptrdiff_t len
= dirent_namelen (dp
);
532 if (len
< SCHARS (encoded_file
)
533 || (scmp (dp
->d_name
, SSDATA (encoded_file
),
534 SCHARS (encoded_file
))
538 switch (dirent_type (dp
))
544 case DT_LNK
: case DT_UNKNOWN
:
545 directoryp
= file_name_completion_dirp (fd
, dp
, len
);
554 /* If all_flag is set, always include all.
555 It would not actually be helpful to the user to ignore any possible
556 completions when making a list of them. */
561 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
562 /* If this entry matches the current bestmatch, the only
563 thing it can do is increase matchcount, so don't bother
564 investigating it any further. */
565 if (!completion_ignore_case
566 /* The return result depends on whether it's the sole match. */
568 && !includeall
/* This match may allow includeall to 0. */
569 && len
>= bestmatchsize
570 && 0 > scmp (dp
->d_name
, SSDATA (bestmatch
), bestmatchsize
))
576 #ifndef TRIVIAL_DIRECTORY_ENTRY
577 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
579 /* "." and ".." are never interesting as completions, and are
580 actually in the way in a directory with only one file. */
581 if (TRIVIAL_DIRECTORY_ENTRY (dp
->d_name
))
583 else if (len
> SCHARS (encoded_file
))
584 /* Ignore directories if they match an element of
585 completion-ignored-extensions which ends in a slash. */
586 for (tem
= Vcompletion_ignored_extensions
;
587 CONSP (tem
); tem
= XCDR (tem
))
595 /* Need to encode ELT, since scmp compares unibyte
597 elt
= ENCODE_FILE (elt
);
598 elt_len
= SCHARS (elt
) - 1; /* -1 for trailing / */
602 if (p1
[elt_len
] != '/')
604 skip
= len
- elt_len
;
608 if (scmp (dp
->d_name
+ skip
, p1
, elt_len
) >= 0)
615 /* Compare extensions-to-be-ignored against end of this file name */
616 /* if name is not an exact match against specified string */
617 if (len
> SCHARS (encoded_file
))
618 /* and exit this for loop if a match is found */
619 for (tem
= Vcompletion_ignored_extensions
;
620 CONSP (tem
); tem
= XCDR (tem
))
623 if (!STRINGP (elt
)) continue;
624 /* Need to encode ELT, since scmp compares unibyte
626 elt
= ENCODE_FILE (elt
);
627 skip
= len
- SCHARS (elt
);
628 if (skip
< 0) continue;
630 if (scmp (dp
->d_name
+ skip
, SSDATA (elt
), SCHARS (elt
))
637 /* If an ignored-extensions match was found,
638 don't process this name as a completion. */
642 if (!includeall
&& canexclude
)
643 /* We're not including all files and this file can be excluded. */
646 if (includeall
&& !canexclude
)
647 { /* If we have one non-excludable file, we want to exclude the
650 /* Throw away any previous excludable match found. */
656 /* FIXME: If we move this `decode' earlier we can eliminate
657 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
658 name
= make_unibyte_string (dp
->d_name
, len
);
659 name
= DECODE_FILE (name
);
662 Lisp_Object regexps
, table
= (completion_ignore_case
663 ? Vascii_canon_table
: Qnil
);
665 /* Ignore this element if it fails to match all the regexps. */
666 for (regexps
= Vcompletion_regexp_list
; CONSP (regexps
);
667 regexps
= XCDR (regexps
))
668 if (fast_string_match_internal (XCAR (regexps
), name
, table
) < 0)
675 /* This is a possible completion */
677 /* This completion is a directory; make it end with '/'. */
678 name
= Ffile_name_as_directory (name
);
680 /* Test the predicate, if any. */
681 if (!NILP (predicate
) && NILP (call1 (predicate
, name
)))
684 /* Reject entries where the encoded strings match, but the
685 decoded don't. For example, "a" should not match "a-ring" on
686 file systems that store decomposed characters. */
687 Lisp_Object zero
= make_number (0);
689 if (check_decoded
&& SCHARS (file
) <= SCHARS (name
))
691 /* FIXME: This is a copy of the code below. */
692 ptrdiff_t compare
= SCHARS (file
);
694 = Fcompare_strings (name
, zero
, make_number (compare
),
695 file
, zero
, make_number (compare
),
696 completion_ignore_case
? Qt
: Qnil
);
701 /* Suitably record this match. */
703 matchcount
+= matchcount
<= 1;
706 bestmatch
= Fcons (name
, bestmatch
);
707 else if (NILP (bestmatch
))
710 bestmatchsize
= SCHARS (name
);
714 /* FIXME: This is a copy of the code in Ftry_completion. */
715 ptrdiff_t compare
= min (bestmatchsize
, SCHARS (name
));
717 = Fcompare_strings (bestmatch
, zero
, make_number (compare
),
718 name
, zero
, 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
736 /* If there is more than one exact match aside from
737 case, and one of them is exact including case,
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
)),
750 && (cmp
= Fcompare_strings (bestmatch
, zero
,
751 make_number (SCHARS (file
)),
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. */
776 /* This closes the directory. */
777 bestmatch
= unbind_to (count
, bestmatch
);
779 if (all_flag
|| NILP (bestmatch
))
781 /* Return t if the supplied string is an exact match (counting case);
782 it does not require any change to be made. */
783 if (matchcount
== 1 && !NILP (Fequal (bestmatch
, file
)))
785 bestmatch
= Fsubstring (bestmatch
, make_number (0),
786 make_number (bestmatchsize
));
790 /* Compare exactly LEN chars of strings at S1 and S2,
791 ignoring case if appropriate.
792 Return -1 if strings match,
793 else number of chars that match at the beginning. */
796 scmp (const char *s1
, const char *s2
, ptrdiff_t len
)
798 register ptrdiff_t l
= len
;
800 if (completion_ignore_case
)
803 && (downcase ((unsigned char) *s1
++)
804 == downcase ((unsigned char) *s2
++)))
809 while (l
&& *s1
++ == *s2
++)
818 /* Return true if in the directory FD the directory entry DP, whose
819 string length is LEN, is that of a subdirectory that can be searched. */
821 file_name_completion_dirp (int fd
, struct dirent
*dp
, ptrdiff_t len
)
824 char *subdir_name
= SAFE_ALLOCA (len
+ 2);
825 memcpy (subdir_name
, dp
->d_name
, len
);
826 strcpy (subdir_name
+ len
, "/");
827 bool dirp
= faccessat (fd
, subdir_name
, F_OK
, AT_EACCESS
) == 0;
833 stat_uname (struct stat
*st
)
838 struct passwd
*pw
= getpwuid (st
->st_uid
);
848 stat_gname (struct stat
*st
)
853 struct group
*gr
= getgrgid (st
->st_gid
);
862 DEFUN ("file-attributes", Ffile_attributes
, Sfile_attributes
, 1, 2, 0,
863 doc
: /* Return a list of attributes of file FILENAME.
864 Value is nil if specified file cannot be opened.
866 ID-FORMAT specifies the preferred format of attributes uid and gid (see
867 below) - valid values are `string' and `integer'. The latter is the
868 default, but we plan to change that, so you should specify a non-nil value
869 for ID-FORMAT if you use the returned uid or gid.
871 To access the elements returned, the following access functions are
872 provided: `file-attribute-type', `file-attribute-link-number',
873 `file-attribute-user-id', `file-attribute-group-id',
874 `file-attribute-access-time', `file-attribute-modification-time',
875 `file-attribute-status-change-time', `file-attribute-size',
876 `file-attribute-modes', `file-attribute-inode-number', and
877 `file-attribute-device-number'.
879 Elements of the attribute list are:
880 0. t for directory, string (name linked to) for symbolic link, or nil.
881 1. Number of links to file.
882 2. File uid as a string or a number. If a string value cannot be
883 looked up, a numeric value, either an integer or a float, is returned.
884 3. File gid, likewise.
885 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
886 same style as (current-time).
887 (See a note below about access time on FAT-based filesystems.)
888 5. Last modification time, likewise. This is the time of the last
889 change to the file's contents.
890 6. Last status change time, likewise. This is the time of last change
891 to the file's attributes: owner and group, access mode bits, etc.
893 This is a floating point number if the size is too large for an integer.
894 8. File modes, as a string of ten letters or dashes as in ls -l.
895 9. An unspecified value, present only for backward compatibility.
896 10. inode number. If it is larger than what an Emacs integer can hold,
897 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
898 If even HIGH is too large for an Emacs integer, this is instead of the form
899 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
900 and finally the low 16 bits.
901 11. Filesystem device number. If it is larger than what the Emacs
902 integer can hold, this is a cons cell, similar to the inode number.
904 On most filesystems, the combination of the inode and the device
905 number uniquely identifies the file.
907 On MS-Windows, performance depends on `w32-get-true-file-attributes',
910 On some FAT-based filesystems, only the date of last access is recorded,
911 so last access time will always be midnight of that day. */)
912 (Lisp_Object filename
, Lisp_Object id_format
)
917 filename
= internal_condition_case_2 (Fexpand_file_name
, filename
, Qnil
,
919 if (!STRINGP (filename
))
922 /* If the file name has special constructs in it,
923 call the corresponding file handler. */
924 handler
= Ffind_file_name_handler (filename
, Qfile_attributes
);
926 { /* Only pass the extra arg if it is used to help backward compatibility
927 with old file handlers which do not implement the new arg. --Stef */
928 if (NILP (id_format
))
929 return call2 (handler
, Qfile_attributes
, filename
);
931 return call3 (handler
, Qfile_attributes
, filename
, id_format
);
934 encoded
= ENCODE_FILE (filename
);
935 return file_attributes (AT_FDCWD
, SSDATA (encoded
), Qnil
, filename
,
940 file_attributes (int fd
, char const *name
,
941 Lisp_Object dirname
, Lisp_Object filename
,
942 Lisp_Object id_format
)
944 ptrdiff_t count
= SPECPDL_INDEX ();
947 /* An array to hold the mode string generated by filemodestring,
948 including its terminating space and null byte. */
949 char modes
[sizeof "-rwxr-xr-x "];
951 char *uname
= NULL
, *gname
= NULL
;
956 int namefd
= openat (fd
, name
, O_PATH
| O_CLOEXEC
| O_NOFOLLOW
);
961 record_unwind_protect_int (close_file_unwind
, namefd
);
962 if (fstat (namefd
, &s
) != 0)
965 /* The Linux kernel before version 3.6 does not support
966 fstat on O_PATH file descriptors. Handle this error like
967 missing support for O_PATH. */
983 /* We usually don't request accurate owner and group info,
984 because it can be expensive on Windows to get that, and most
985 callers of 'lstat' don't need that. But here we do want that
986 information to be accurate. */
987 w32_stat_get_owner_group
= 1;
989 if (fstatat (fd
, name
, &s
, AT_SYMLINK_NOFOLLOW
) == 0)
992 w32_stat_get_owner_group
= 0;
997 return unbind_to (count
, Qnil
);
999 Lisp_Object file_type
;
1000 if (S_ISLNK (s
.st_mode
))
1002 /* On systems lacking O_PATH support there is a race if the
1003 symlink is replaced between the call to fstatat and the call
1004 to emacs_readlinkat. Detect this race unless the replacement
1005 is also a symlink. */
1006 file_type
= emacs_readlinkat (fd
, name
);
1007 if (NILP (file_type
))
1008 return unbind_to (count
, Qnil
);
1011 file_type
= S_ISDIR (s
.st_mode
) ? Qt
: Qnil
;
1013 unbind_to (count
, Qnil
);
1015 if (!(NILP (id_format
) || EQ (id_format
, Qinteger
)))
1017 uname
= stat_uname (&s
);
1018 gname
= stat_gname (&s
);
1021 filemodestring (&s
, modes
);
1023 return CALLN (Flist
,
1025 make_number (s
.st_nlink
),
1027 ? DECODE_SYSTEM (build_unibyte_string (uname
))
1028 : make_fixnum_or_float (s
.st_uid
)),
1030 ? DECODE_SYSTEM (build_unibyte_string (gname
))
1031 : make_fixnum_or_float (s
.st_gid
)),
1032 make_lisp_time (get_stat_atime (&s
)),
1033 make_lisp_time (get_stat_mtime (&s
)),
1034 make_lisp_time (get_stat_ctime (&s
)),
1036 /* If the file size is a 4-byte type, assume that
1037 files of sizes in the 2-4 GiB range wrap around to
1038 negative values, as this is a common bug on older
1039 32-bit platforms. */
1040 make_fixnum_or_float (sizeof (s
.st_size
) == 4
1041 ? s
.st_size
& 0xffffffffu
1044 make_string (modes
, 10),
1046 INTEGER_TO_CONS (s
.st_ino
),
1047 INTEGER_TO_CONS (s
.st_dev
));
1050 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp
, Sfile_attributes_lessp
, 2, 2, 0,
1051 doc
: /* Return t if first arg file attributes list is less than second.
1052 Comparison is in lexicographic order and case is significant. */)
1053 (Lisp_Object f1
, Lisp_Object f2
)
1055 return Fstring_lessp (Fcar (f1
), Fcar (f2
));
1059 DEFUN ("system-users", Fsystem_users
, Ssystem_users
, 0, 0, 0,
1060 doc
: /* Return a list of user names currently registered in the system.
1061 If we don't know how to determine that on this platform, just
1062 return a list with one element, taken from `user-real-login-name'. */)
1065 Lisp_Object users
= Qnil
;
1066 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
1069 while ((pw
= getpwent ()))
1070 users
= Fcons (DECODE_SYSTEM (build_string (pw
->pw_name
)), users
);
1074 if (EQ (users
, Qnil
))
1075 /* At least current user is always known. */
1076 users
= list1 (Vuser_real_login_name
);
1080 DEFUN ("system-groups", Fsystem_groups
, Ssystem_groups
, 0, 0, 0,
1081 doc
: /* Return a list of user group names currently registered in the system.
1082 The value may be nil if not supported on this platform. */)
1085 Lisp_Object groups
= Qnil
;
1086 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1089 while ((gr
= getgrent ()))
1090 groups
= Fcons (DECODE_SYSTEM (build_string (gr
->gr_name
)), groups
);
1098 syms_of_dired (void)
1100 DEFSYM (Qdirectory_files
, "directory-files");
1101 DEFSYM (Qdirectory_files_and_attributes
, "directory-files-and-attributes");
1102 DEFSYM (Qfile_name_completion
, "file-name-completion");
1103 DEFSYM (Qfile_name_all_completions
, "file-name-all-completions");
1104 DEFSYM (Qfile_attributes
, "file-attributes");
1105 DEFSYM (Qfile_attributes_lessp
, "file-attributes-lessp");
1106 DEFSYM (Qdefault_directory
, "default-directory");
1107 DEFSYM (Qdecomposed_characters
, "decomposed-characters");
1109 defsubr (&Sdirectory_files
);
1110 defsubr (&Sdirectory_files_and_attributes
);
1111 defsubr (&Sfile_name_completion
);
1112 defsubr (&Sfile_name_all_completions
);
1113 defsubr (&Sfile_attributes
);
1114 defsubr (&Sfile_attributes_lessp
);
1115 defsubr (&Ssystem_users
);
1116 defsubr (&Ssystem_groups
);
1118 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions
,
1119 doc
: /* Completion ignores file names ending in any string in this list.
1120 It does not ignore them if all possible completions end in one of
1121 these strings or when displaying a list of completions.
1122 It ignores directory names if they match any string in this list which
1123 ends in a slash. */);
1124 Vcompletion_ignored_extensions
= Qnil
;