Amend to fontify /regexp/s in actions correctly.
[emacs.git] / src / dired.c
bloba4c8621e9c03ce8024424769581ad0d607dc5f2f
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2013 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30 #include <grp.h>
32 #include <errno.h>
33 #include <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 "character.h"
42 #include "buffer.h"
43 #include "commands.h"
44 #include "charset.h"
45 #include "coding.h"
46 #include "regex.h"
47 #include "blockinput.h"
49 static Lisp_Object Qdirectory_files;
50 static Lisp_Object Qdirectory_files_and_attributes;
51 static Lisp_Object Qfile_name_completion;
52 static Lisp_Object Qfile_name_all_completions;
53 static Lisp_Object Qfile_attributes;
54 static Lisp_Object Qfile_attributes_lessp;
56 static ptrdiff_t scmp (const char *, const char *, ptrdiff_t);
58 /* Return the number of bytes in DP's name. */
59 static ptrdiff_t
60 dirent_namelen (struct dirent *dp)
62 #ifdef _D_EXACT_NAMLEN
63 return _D_EXACT_NAMLEN (dp);
64 #else
65 return strlen (dp->d_name);
66 #endif
69 #ifdef WINDOWSNT
70 Lisp_Object
71 directory_files_internal_w32_unwind (Lisp_Object arg)
73 Vw32_get_true_file_attributes = arg;
74 return Qnil;
76 #endif
78 static Lisp_Object
79 directory_files_internal_unwind (Lisp_Object dh)
81 DIR *d = XSAVE_POINTER (dh, 0);
82 block_input ();
83 closedir (d);
84 unblock_input ();
85 return Qnil;
88 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
89 If not ATTRS, return a list of directory filenames;
90 if ATTRS, return a list of directory filenames and their attributes.
91 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
93 Lisp_Object
94 directory_files_internal (Lisp_Object directory, Lisp_Object full,
95 Lisp_Object match, Lisp_Object nosort, bool attrs,
96 Lisp_Object id_format)
98 DIR *d;
99 ptrdiff_t directory_nbytes;
100 Lisp_Object list, dirfilename, encoded_directory;
101 struct re_pattern_buffer *bufp = NULL;
102 bool needsep = 0;
103 ptrdiff_t count = SPECPDL_INDEX ();
104 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
105 struct dirent *dp;
106 #ifdef WINDOWSNT
107 Lisp_Object w32_save = Qnil;
108 #endif
110 /* Because of file name handlers, these functions might call
111 Ffuncall, and cause a GC. */
112 list = encoded_directory = dirfilename = Qnil;
113 GCPRO5 (match, directory, list, dirfilename, encoded_directory);
114 dirfilename = Fdirectory_file_name (directory);
116 if (!NILP (match))
118 CHECK_STRING (match);
120 /* MATCH might be a flawed regular expression. Rather than
121 catching and signaling our own errors, we just call
122 compile_pattern to do the work for us. */
123 /* Pass 1 for the MULTIBYTE arg
124 because we do make multibyte strings if the contents warrant. */
125 # ifdef WINDOWSNT
126 /* Windows users want case-insensitive wildcards. */
127 bufp = compile_pattern (match, 0,
128 BVAR (&buffer_defaults, case_canon_table), 0, 1);
129 # else /* !WINDOWSNT */
130 bufp = compile_pattern (match, 0, Qnil, 0, 1);
131 # endif /* !WINDOWSNT */
134 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
135 run_pre_post_conversion_on_str which calls Lisp directly and
136 indirectly. */
137 if (STRING_MULTIBYTE (dirfilename))
138 dirfilename = ENCODE_FILE (dirfilename);
139 encoded_directory = (STRING_MULTIBYTE (directory)
140 ? ENCODE_FILE (directory) : directory);
142 /* Now *bufp is the compiled form of MATCH; don't call anything
143 which might compile a new regexp until we're done with the loop! */
145 block_input ();
146 d = opendir (SSDATA (dirfilename));
147 unblock_input ();
148 if (d == NULL)
149 report_file_error ("Opening directory", Fcons (directory, Qnil));
151 /* Unfortunately, we can now invoke expand-file-name and
152 file-attributes on filenames, both of which can throw, so we must
153 do a proper unwind-protect. */
154 record_unwind_protect (directory_files_internal_unwind,
155 make_save_pointer (d));
157 #ifdef WINDOWSNT
158 if (attrs)
160 extern int is_slow_fs (const char *);
162 /* Do this only once to avoid doing it (in w32.c:stat) for each
163 file in the directory, when we call Ffile_attributes below. */
164 record_unwind_protect (directory_files_internal_w32_unwind,
165 Vw32_get_true_file_attributes);
166 w32_save = Vw32_get_true_file_attributes;
167 if (EQ (Vw32_get_true_file_attributes, Qlocal))
169 /* w32.c:stat will notice these bindings and avoid calling
170 GetDriveType for each file. */
171 if (is_slow_fs (SDATA (dirfilename)))
172 Vw32_get_true_file_attributes = Qnil;
173 else
174 Vw32_get_true_file_attributes = Qt;
177 #endif
179 directory_nbytes = SBYTES (directory);
180 re_match_object = Qt;
182 /* Decide whether we need to add a directory separator. */
183 if (directory_nbytes == 0
184 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
185 needsep = 1;
187 /* Loop reading blocks until EOF or error. */
188 for (;;)
190 ptrdiff_t len;
191 bool wanted = 0;
192 Lisp_Object name, finalname;
193 struct gcpro gcpro1, gcpro2;
195 errno = 0;
196 dp = readdir (d);
197 if (!dp)
199 if (errno == EAGAIN || errno == EINTR)
201 QUIT;
202 continue;
204 break;
207 len = dirent_namelen (dp);
208 name = finalname = make_unibyte_string (dp->d_name, len);
209 GCPRO2 (finalname, name);
211 /* Note: DECODE_FILE can GC; it should protect its argument,
212 though. */
213 name = DECODE_FILE (name);
214 len = SBYTES (name);
216 /* Now that we have unwind_protect in place, we might as well
217 allow matching to be interrupted. */
218 immediate_quit = 1;
219 QUIT;
221 if (NILP (match)
222 || (0 <= re_search (bufp, SSDATA (name), len, 0, len, 0)))
223 wanted = 1;
225 immediate_quit = 0;
227 if (wanted)
229 if (!NILP (full))
231 Lisp_Object fullname;
232 ptrdiff_t nbytes = len + directory_nbytes + needsep;
233 ptrdiff_t nchars;
235 fullname = make_uninit_multibyte_string (nbytes, nbytes);
236 memcpy (SDATA (fullname), SDATA (directory),
237 directory_nbytes);
239 if (needsep)
240 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
242 memcpy (SDATA (fullname) + directory_nbytes + needsep,
243 SDATA (name), len);
245 nchars = chars_in_text (SDATA (fullname), nbytes);
247 /* Some bug somewhere. */
248 if (nchars > nbytes)
249 emacs_abort ();
251 STRING_SET_CHARS (fullname, nchars);
252 if (nchars == nbytes)
253 STRING_SET_UNIBYTE (fullname);
255 finalname = fullname;
257 else
258 finalname = name;
260 if (attrs)
262 /* Construct an expanded filename for the directory entry.
263 Use the decoded names for input to Ffile_attributes. */
264 Lisp_Object decoded_fullname, fileattrs;
265 struct gcpro gcpro1, gcpro2;
267 decoded_fullname = fileattrs = Qnil;
268 GCPRO2 (decoded_fullname, fileattrs);
270 /* Both Fexpand_file_name and Ffile_attributes can GC. */
271 decoded_fullname = Fexpand_file_name (name, directory);
272 fileattrs = Ffile_attributes (decoded_fullname, id_format);
274 list = Fcons (Fcons (finalname, fileattrs), list);
275 UNGCPRO;
277 else
278 list = Fcons (finalname, list);
281 UNGCPRO;
284 block_input ();
285 closedir (d);
286 unblock_input ();
287 #ifdef WINDOWSNT
288 if (attrs)
289 Vw32_get_true_file_attributes = w32_save;
290 #endif
292 /* Discard the unwind protect. */
293 specpdl_ptr = specpdl + count;
295 if (NILP (nosort))
296 list = Fsort (Fnreverse (list),
297 attrs ? Qfile_attributes_lessp : Qstring_lessp);
299 RETURN_UNGCPRO (list);
303 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
304 doc: /* Return a list of names of files in DIRECTORY.
305 There are three optional arguments:
306 If FULL is non-nil, return absolute file names. Otherwise return names
307 that are relative to the specified directory.
308 If MATCH is non-nil, mention only file names that match the regexp MATCH.
309 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
310 Otherwise, the list returned is sorted with `string-lessp'.
311 NOSORT is useful if you plan to sort the result yourself. */)
312 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
314 Lisp_Object handler;
315 directory = Fexpand_file_name (directory, Qnil);
317 /* If the file name has special constructs in it,
318 call the corresponding file handler. */
319 handler = Ffind_file_name_handler (directory, Qdirectory_files);
320 if (!NILP (handler))
321 return call5 (handler, Qdirectory_files, directory,
322 full, match, nosort);
324 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
327 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
328 Sdirectory_files_and_attributes, 1, 5, 0,
329 doc: /* Return a list of names of files and their attributes in DIRECTORY.
330 There are four optional arguments:
331 If FULL is non-nil, return absolute file names. Otherwise return names
332 that are relative to the specified directory.
333 If MATCH is non-nil, mention only file names that match the regexp MATCH.
334 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
335 NOSORT is useful if you plan to sort the result yourself.
336 ID-FORMAT specifies the preferred format of attributes uid and gid, see
337 `file-attributes' for further documentation.
338 On MS-Windows, performance depends on `w32-get-true-file-attributes',
339 which see. */)
340 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
342 Lisp_Object handler;
343 directory = Fexpand_file_name (directory, Qnil);
345 /* If the file name has special constructs in it,
346 call the corresponding file handler. */
347 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
348 if (!NILP (handler))
349 return call6 (handler, Qdirectory_files_and_attributes,
350 directory, full, match, nosort, id_format);
352 return directory_files_internal (directory, full, match, nosort, 1, id_format);
356 static Lisp_Object file_name_completion (Lisp_Object, Lisp_Object, bool,
357 Lisp_Object);
359 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
360 2, 3, 0,
361 doc: /* Complete file name FILE in directory DIRECTORY.
362 Returns the longest string
363 common to all file names in DIRECTORY that start with FILE.
364 If there is only one and FILE matches it exactly, returns t.
365 Returns nil if DIRECTORY contains no name starting with FILE.
367 If PREDICATE is non-nil, call PREDICATE with each possible
368 completion (in absolute form) and ignore it if PREDICATE returns nil.
370 This function ignores some of the possible completions as
371 determined by the variable `completion-ignored-extensions', which see. */)
372 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
374 Lisp_Object handler;
375 directory = Fexpand_file_name (directory, Qnil);
377 /* If the directory name has special constructs in it,
378 call the corresponding file handler. */
379 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
380 if (!NILP (handler))
381 return call4 (handler, Qfile_name_completion, file, directory, predicate);
383 /* If the file name has special constructs in it,
384 call the corresponding file handler. */
385 handler = Ffind_file_name_handler (file, Qfile_name_completion);
386 if (!NILP (handler))
387 return call4 (handler, Qfile_name_completion, file, directory, predicate);
389 return file_name_completion (file, directory, 0, predicate);
392 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
393 Sfile_name_all_completions, 2, 2, 0,
394 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
395 These are all file names in directory DIRECTORY which begin with FILE. */)
396 (Lisp_Object file, Lisp_Object directory)
398 Lisp_Object handler;
399 directory = Fexpand_file_name (directory, Qnil);
401 /* If the directory name has special constructs in it,
402 call the corresponding file handler. */
403 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
404 if (!NILP (handler))
405 return call3 (handler, Qfile_name_all_completions, file, directory);
407 /* If the file name has special constructs in it,
408 call the corresponding file handler. */
409 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
410 if (!NILP (handler))
411 return call3 (handler, Qfile_name_all_completions, file, directory);
413 return file_name_completion (file, directory, 1, Qnil);
416 static int file_name_completion_stat (Lisp_Object dirname, struct dirent *dp,
417 struct stat *st_addr);
418 static Lisp_Object Qdefault_directory;
420 static Lisp_Object
421 file_name_completion (Lisp_Object file, Lisp_Object dirname, bool all_flag,
422 Lisp_Object predicate)
424 DIR *d;
425 ptrdiff_t bestmatchsize = 0;
426 int matchcount = 0;
427 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
428 If ALL_FLAG is 0, BESTMATCH is either nil
429 or the best match so far, not decoded. */
430 Lisp_Object bestmatch, tem, elt, name;
431 Lisp_Object encoded_file;
432 Lisp_Object encoded_dir;
433 struct stat st;
434 bool directoryp;
435 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
436 well as "." and "..". Until shown otherwise, assume we can't exclude
437 anything. */
438 bool includeall = 1;
439 ptrdiff_t count = SPECPDL_INDEX ();
440 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
442 elt = Qnil;
444 CHECK_STRING (file);
446 bestmatch = Qnil;
447 encoded_file = encoded_dir = Qnil;
448 GCPRO5 (file, dirname, bestmatch, encoded_file, encoded_dir);
449 specbind (Qdefault_directory, dirname);
451 /* Do completion on the encoded file name
452 because the other names in the directory are (we presume)
453 encoded likewise. We decode the completed string at the end. */
454 /* Actually, this is not quite true any more: we do most of the completion
455 work with decoded file names, but we still do some filtering based
456 on the encoded file name. */
457 encoded_file = STRING_MULTIBYTE (file) ? ENCODE_FILE (file) : file;
459 encoded_dir = ENCODE_FILE (dirname);
461 block_input ();
462 d = opendir (SSDATA (Fdirectory_file_name (encoded_dir)));
463 unblock_input ();
464 if (!d)
465 report_file_error ("Opening directory", Fcons (dirname, Qnil));
467 record_unwind_protect (directory_files_internal_unwind,
468 make_save_pointer (d));
470 /* Loop reading blocks */
471 /* (att3b compiler bug requires do a null comparison this way) */
472 while (1)
474 struct dirent *dp;
475 ptrdiff_t len;
476 bool canexclude = 0;
478 errno = 0;
479 dp = readdir (d);
480 if (!dp)
482 if (errno == EAGAIN || errno == EINTR)
484 QUIT;
485 continue;
487 break;
490 len = dirent_namelen (dp);
492 QUIT;
493 if (len < SCHARS (encoded_file)
494 || 0 <= scmp (dp->d_name, SSDATA (encoded_file),
495 SCHARS (encoded_file)))
496 continue;
498 if (file_name_completion_stat (encoded_dir, dp, &st) < 0)
499 continue;
501 directoryp = S_ISDIR (st.st_mode) != 0;
502 tem = Qnil;
503 /* If all_flag is set, always include all.
504 It would not actually be helpful to the user to ignore any possible
505 completions when making a list of them. */
506 if (!all_flag)
508 ptrdiff_t skip;
510 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
511 /* If this entry matches the current bestmatch, the only
512 thing it can do is increase matchcount, so don't bother
513 investigating it any further. */
514 if (!completion_ignore_case
515 /* The return result depends on whether it's the sole match. */
516 && matchcount > 1
517 && !includeall /* This match may allow includeall to 0. */
518 && len >= bestmatchsize
519 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
520 continue;
521 #endif
523 if (directoryp)
525 #ifndef TRIVIAL_DIRECTORY_ENTRY
526 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
527 #endif
528 /* "." and ".." are never interesting as completions, and are
529 actually in the way in a directory with only one file. */
530 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
531 canexclude = 1;
532 else if (len > SCHARS (encoded_file))
533 /* Ignore directories if they match an element of
534 completion-ignored-extensions which ends in a slash. */
535 for (tem = Vcompletion_ignored_extensions;
536 CONSP (tem); tem = XCDR (tem))
538 ptrdiff_t elt_len;
539 char *p1;
541 elt = XCAR (tem);
542 if (!STRINGP (elt))
543 continue;
544 /* Need to encode ELT, since scmp compares unibyte
545 strings only. */
546 elt = ENCODE_FILE (elt);
547 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
548 if (elt_len <= 0)
549 continue;
550 p1 = SSDATA (elt);
551 if (p1[elt_len] != '/')
552 continue;
553 skip = len - elt_len;
554 if (skip < 0)
555 continue;
557 if (0 <= scmp (dp->d_name + skip, p1, elt_len))
558 continue;
559 break;
562 else
564 /* Compare extensions-to-be-ignored against end of this file name */
565 /* if name is not an exact match against specified string */
566 if (len > SCHARS (encoded_file))
567 /* and exit this for loop if a match is found */
568 for (tem = Vcompletion_ignored_extensions;
569 CONSP (tem); tem = XCDR (tem))
571 elt = XCAR (tem);
572 if (!STRINGP (elt)) continue;
573 /* Need to encode ELT, since scmp compares unibyte
574 strings only. */
575 elt = ENCODE_FILE (elt);
576 skip = len - SCHARS (elt);
577 if (skip < 0) continue;
579 if (0 <= scmp (dp->d_name + skip,
580 SSDATA (elt),
581 SCHARS (elt)))
582 continue;
583 break;
587 /* If an ignored-extensions match was found,
588 don't process this name as a completion. */
589 if (CONSP (tem))
590 canexclude = 1;
592 if (!includeall && canexclude)
593 /* We're not including all files and this file can be excluded. */
594 continue;
596 if (includeall && !canexclude)
597 { /* If we have one non-excludable file, we want to exclude the
598 excludable files. */
599 includeall = 0;
600 /* Throw away any previous excludable match found. */
601 bestmatch = Qnil;
602 bestmatchsize = 0;
603 matchcount = 0;
606 /* FIXME: If we move this `decode' earlier we can eliminate
607 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
608 name = make_unibyte_string (dp->d_name, len);
609 name = DECODE_FILE (name);
612 Lisp_Object regexps;
614 /* Ignore this element if it fails to match all the regexps. */
615 if (completion_ignore_case)
617 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
618 regexps = XCDR (regexps))
619 if (fast_string_match_ignore_case (XCAR (regexps), name) < 0)
620 break;
622 else
624 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
625 regexps = XCDR (regexps))
626 if (fast_string_match (XCAR (regexps), name) < 0)
627 break;
630 if (CONSP (regexps))
631 continue;
634 /* This is a possible completion */
635 if (directoryp)
636 /* This completion is a directory; make it end with '/'. */
637 name = Ffile_name_as_directory (name);
639 /* Test the predicate, if any. */
640 if (!NILP (predicate))
642 Lisp_Object val;
643 struct gcpro gcpro1;
645 GCPRO1 (name);
646 val = call1 (predicate, name);
647 UNGCPRO;
649 if (NILP (val))
650 continue;
653 /* Suitably record this match. */
655 matchcount += matchcount <= 1;
657 if (all_flag)
658 bestmatch = Fcons (name, bestmatch);
659 else if (NILP (bestmatch))
661 bestmatch = name;
662 bestmatchsize = SCHARS (name);
664 else
666 Lisp_Object zero = make_number (0);
667 /* FIXME: This is a copy of the code in Ftry_completion. */
668 ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
669 Lisp_Object cmp
670 = Fcompare_strings (bestmatch, zero,
671 make_number (compare),
672 name, zero,
673 make_number (compare),
674 completion_ignore_case ? Qt : Qnil);
675 ptrdiff_t matchsize = EQ (cmp, Qt) ? compare : eabs (XINT (cmp)) - 1;
677 if (completion_ignore_case)
679 /* If this is an exact match except for case,
680 use it as the best match rather than one that is not
681 an exact match. This way, we get the case pattern
682 of the actual match. */
683 /* This tests that the current file is an exact match
684 but BESTMATCH is not (it is too long). */
685 if ((matchsize == SCHARS (name)
686 && matchsize + directoryp < SCHARS (bestmatch))
688 /* If there is no exact match ignoring case,
689 prefer a match that does not change the case
690 of the input. */
691 /* If there is more than one exact match aside from
692 case, and one of them is exact including case,
693 prefer that one. */
694 /* This == checks that, of current file and BESTMATCH,
695 either both or neither are exact. */
696 (((matchsize == SCHARS (name))
698 (matchsize + directoryp == SCHARS (bestmatch)))
699 && (cmp = Fcompare_strings (name, zero,
700 make_number (SCHARS (file)),
701 file, zero,
702 Qnil,
703 Qnil),
704 EQ (Qt, cmp))
705 && (cmp = Fcompare_strings (bestmatch, zero,
706 make_number (SCHARS (file)),
707 file, zero,
708 Qnil,
709 Qnil),
710 ! EQ (Qt, cmp))))
711 bestmatch = name;
713 bestmatchsize = matchsize;
715 /* If the best completion so far is reduced to the string
716 we're trying to complete, then we already know there's no
717 other completion, so there's no point looking any further. */
718 if (matchsize <= SCHARS (file)
719 && !includeall /* A future match may allow includeall to 0. */
720 /* If completion-ignore-case is non-nil, don't
721 short-circuit because we want to find the best
722 possible match *including* case differences. */
723 && (!completion_ignore_case || matchsize == 0)
724 /* The return value depends on whether it's the sole match. */
725 && matchcount > 1)
726 break;
731 UNGCPRO;
732 /* This closes the directory. */
733 bestmatch = unbind_to (count, bestmatch);
735 if (all_flag || NILP (bestmatch))
736 return bestmatch;
737 /* Return t if the supplied string is an exact match (counting case);
738 it does not require any change to be made. */
739 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
740 return Qt;
741 bestmatch = Fsubstring (bestmatch, make_number (0),
742 make_number (bestmatchsize));
743 return bestmatch;
746 /* Compare exactly LEN chars of strings at S1 and S2,
747 ignoring case if appropriate.
748 Return -1 if strings match,
749 else number of chars that match at the beginning. */
751 static ptrdiff_t
752 scmp (const char *s1, const char *s2, ptrdiff_t len)
754 register ptrdiff_t l = len;
756 if (completion_ignore_case)
758 while (l
759 && (downcase ((unsigned char) *s1++)
760 == downcase ((unsigned char) *s2++)))
761 l--;
763 else
765 while (l && *s1++ == *s2++)
766 l--;
768 if (l == 0)
769 return -1;
770 else
771 return len - l;
774 static int
775 file_name_completion_stat (Lisp_Object dirname, struct dirent *dp,
776 struct stat *st_addr)
778 ptrdiff_t len = dirent_namelen (dp);
779 ptrdiff_t pos = SCHARS (dirname);
780 int value;
781 USE_SAFE_ALLOCA;
782 char *fullname = SAFE_ALLOCA (len + pos + 2);
784 #ifdef MSDOS
785 /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
786 but aren't required here. Avoid computing the following fields:
787 st_inode, st_size and st_nlink for directories, and the execute bits
788 in st_mode for non-directory files with non-standard extensions. */
790 unsigned short save_djstat_flags = _djstat_flags;
792 _djstat_flags = _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
793 #endif /* MSDOS */
795 memcpy (fullname, SDATA (dirname), pos);
796 if (!IS_DIRECTORY_SEP (fullname[pos - 1]))
797 fullname[pos++] = DIRECTORY_SEP;
799 memcpy (fullname + pos, dp->d_name, len);
800 fullname[pos + len] = 0;
802 /* We want to return success if a link points to a nonexistent file,
803 but we want to return the status for what the link points to,
804 in case it is a directory. */
805 value = lstat (fullname, st_addr);
806 if (value == 0 && S_ISLNK (st_addr->st_mode))
807 stat (fullname, st_addr);
808 #ifdef MSDOS
809 _djstat_flags = save_djstat_flags;
810 #endif /* MSDOS */
811 SAFE_FREE ();
812 return value;
815 static char *
816 stat_uname (struct stat *st)
818 #ifdef WINDOWSNT
819 return st->st_uname;
820 #else
821 struct passwd *pw = getpwuid (st->st_uid);
823 if (pw)
824 return pw->pw_name;
825 else
826 return NULL;
827 #endif
830 static char *
831 stat_gname (struct stat *st)
833 #ifdef WINDOWSNT
834 return st->st_gname;
835 #else
836 struct group *gr = getgrgid (st->st_gid);
838 if (gr)
839 return gr->gr_name;
840 else
841 return NULL;
842 #endif
845 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
846 doc: /* Return a list of attributes of file FILENAME.
847 Value is nil if specified file cannot be opened.
849 ID-FORMAT specifies the preferred format of attributes uid and gid (see
850 below) - valid values are 'string and 'integer. The latter is the
851 default, but we plan to change that, so you should specify a non-nil value
852 for ID-FORMAT if you use the returned uid or gid.
854 Elements of the attribute list are:
855 0. t for directory, string (name linked to) for symbolic link, or nil.
856 1. Number of links to file.
857 2. File uid as a string or a number. If a string value cannot be
858 looked up, a numeric value, either an integer or a float, is returned.
859 3. File gid, likewise.
860 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
861 same style as (current-time).
862 (See a note below about access time on FAT-based filesystems.)
863 5. Last modification time, likewise. This is the time of the last
864 change to the file's contents.
865 6. Last status change time, likewise. This is the time of last change
866 to the file's attributes: owner and group, access mode bits, etc.
867 7. Size in bytes.
868 This is a floating point number if the size is too large for an integer.
869 8. File modes, as a string of ten letters or dashes as in ls -l.
870 9. An unspecified value, present only for backward compatibility.
871 10. inode number. If it is larger than what an Emacs integer can hold,
872 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
873 If even HIGH is too large for an Emacs integer, this is instead of the form
874 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
875 and finally the low 16 bits.
876 11. Filesystem device number. If it is larger than what the Emacs
877 integer can hold, this is a cons cell, similar to the inode number.
879 On most filesystems, the combination of the inode and the device
880 number uniquely identifies the file.
882 On MS-Windows, performance depends on `w32-get-true-file-attributes',
883 which see.
885 On some FAT-based filesystems, only the date of last access is recorded,
886 so last access time will always be midnight of that day. */)
887 (Lisp_Object filename, Lisp_Object id_format)
889 Lisp_Object values[12];
890 Lisp_Object encoded;
891 struct stat s;
892 int lstat_result;
894 /* An array to hold the mode string generated by filemodestring,
895 including its terminating space and null byte. */
896 char modes[sizeof "-rwxr-xr-x "];
898 Lisp_Object handler;
899 struct gcpro gcpro1;
900 char *uname = NULL, *gname = NULL;
902 filename = Fexpand_file_name (filename, Qnil);
904 /* If the file name has special constructs in it,
905 call the corresponding file handler. */
906 handler = Ffind_file_name_handler (filename, Qfile_attributes);
907 if (!NILP (handler))
908 { /* Only pass the extra arg if it is used to help backward compatibility
909 with old file handlers which do not implement the new arg. --Stef */
910 if (NILP (id_format))
911 return call2 (handler, Qfile_attributes, filename);
912 else
913 return call3 (handler, Qfile_attributes, filename, id_format);
916 GCPRO1 (filename);
917 encoded = ENCODE_FILE (filename);
918 UNGCPRO;
920 #ifdef WINDOWSNT
921 /* We usually don't request accurate owner and group info, because
922 it can be very expensive on Windows to get that, and most callers
923 of 'lstat' don't need that. But here we do want that information
924 to be accurate. */
925 w32_stat_get_owner_group = 1;
926 #endif
928 lstat_result = lstat (SSDATA (encoded), &s);
930 #ifdef WINDOWSNT
931 w32_stat_get_owner_group = 0;
932 #endif
934 if (lstat_result < 0)
935 return Qnil;
937 values[0] = (S_ISLNK (s.st_mode) ? Ffile_symlink_p (filename)
938 : S_ISDIR (s.st_mode) ? Qt : Qnil);
939 values[1] = make_number (s.st_nlink);
941 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
943 block_input ();
944 uname = stat_uname (&s);
945 gname = stat_gname (&s);
946 unblock_input ();
948 if (uname)
949 values[2] = DECODE_SYSTEM (build_string (uname));
950 else
951 values[2] = make_fixnum_or_float (s.st_uid);
952 if (gname)
953 values[3] = DECODE_SYSTEM (build_string (gname));
954 else
955 values[3] = make_fixnum_or_float (s.st_gid);
957 values[4] = make_lisp_time (get_stat_atime (&s));
958 values[5] = make_lisp_time (get_stat_mtime (&s));
959 values[6] = make_lisp_time (get_stat_ctime (&s));
961 /* If the file size is a 4-byte type, assume that files of sizes in
962 the 2-4 GiB range wrap around to negative values, as this is a
963 common bug on older 32-bit platforms. */
964 if (sizeof (s.st_size) == 4)
965 values[7] = make_fixnum_or_float (s.st_size & 0xffffffffu);
966 else
967 values[7] = make_fixnum_or_float (s.st_size);
969 filemodestring (&s, modes);
970 values[8] = make_string (modes, 10);
971 values[9] = Qt;
972 values[10] = INTEGER_TO_CONS (s.st_ino);
973 values[11] = INTEGER_TO_CONS (s.st_dev);
975 return Flist (sizeof (values) / sizeof (values[0]), values);
978 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
979 doc: /* Return t if first arg file attributes list is less than second.
980 Comparison is in lexicographic order and case is significant. */)
981 (Lisp_Object f1, Lisp_Object f2)
983 return Fstring_lessp (Fcar (f1), Fcar (f2));
987 DEFUN ("system-users", Fsystem_users, Ssystem_users, 0, 0, 0,
988 doc: /* Return a list of user names currently registered in the system.
989 If we don't know how to determine that on this platform, just
990 return a list with one element, taken from `user-real-login-name'. */)
991 (void)
993 Lisp_Object users = Qnil;
994 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
995 struct passwd *pw;
997 while ((pw = getpwent ()))
998 users = Fcons (DECODE_SYSTEM (build_string (pw->pw_name)), users);
1000 endpwent ();
1001 #endif
1002 if (EQ (users, Qnil))
1003 /* At least current user is always known. */
1004 users = Fcons (Vuser_real_login_name, Qnil);
1005 return users;
1008 DEFUN ("system-groups", Fsystem_groups, Ssystem_groups, 0, 0, 0,
1009 doc: /* Return a list of user group names currently registered in the system.
1010 The value may be nil if not supported on this platform. */)
1011 (void)
1013 Lisp_Object groups = Qnil;
1014 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1015 struct group *gr;
1017 while ((gr = getgrent ()))
1018 groups = Fcons (DECODE_SYSTEM (build_string (gr->gr_name)), groups);
1020 endgrent ();
1021 #endif
1022 return groups;
1025 void
1026 syms_of_dired (void)
1028 DEFSYM (Qdirectory_files, "directory-files");
1029 DEFSYM (Qdirectory_files_and_attributes, "directory-files-and-attributes");
1030 DEFSYM (Qfile_name_completion, "file-name-completion");
1031 DEFSYM (Qfile_name_all_completions, "file-name-all-completions");
1032 DEFSYM (Qfile_attributes, "file-attributes");
1033 DEFSYM (Qfile_attributes_lessp, "file-attributes-lessp");
1034 DEFSYM (Qdefault_directory, "default-directory");
1036 defsubr (&Sdirectory_files);
1037 defsubr (&Sdirectory_files_and_attributes);
1038 defsubr (&Sfile_name_completion);
1039 defsubr (&Sfile_name_all_completions);
1040 defsubr (&Sfile_attributes);
1041 defsubr (&Sfile_attributes_lessp);
1042 defsubr (&Ssystem_users);
1043 defsubr (&Ssystem_groups);
1045 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1046 doc: /* Completion ignores file names ending in any string in this list.
1047 It does not ignore them if all possible completions end in one of
1048 these strings or when displaying a list of completions.
1049 It ignores directory names if they match any string in this list which
1050 ends in a slash. */);
1051 Vcompletion_ignored_extensions = Qnil;