Import filemode module from gnulib.
[bpt/emacs.git] / src / dired.c
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2011 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <setjmp.h>
26
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30 #include <grp.h>
31
32 #include <errno.h>
33 #include <unistd.h>
34
35 /* The d_nameln member of a struct dirent includes the '\0' character
36 on some systems, but not on others. What's worse, you can't tell
37 at compile-time which one it will be, since it really depends on
38 the sort of system providing the filesystem you're reading from,
39 not the system you are running on. Paul Eggert
40 <eggert@bi.twinsun.com> says this occurs when Emacs is running on a
41 SunOS 4.1.2 host, reading a directory that is remote-mounted from a
42 Solaris 2.1 host and is in a native Solaris 2.1 filesystem.
43
44 Since applying strlen to the name always works, we'll just do that. */
45 #define NAMLEN(p) strlen (p->d_name)
46
47 #ifdef HAVE_DIRENT_H
48
49 #include <dirent.h>
50 #define DIRENTRY struct dirent
51
52 #else /* not HAVE_DIRENT_H */
53
54 #include <sys/dir.h>
55 #include <sys/stat.h>
56
57 #include <filemode.h>
58
59 #define DIRENTRY struct direct
60
61 extern DIR *opendir (char *);
62 extern struct direct *readdir (DIR *);
63
64 #endif /* HAVE_DIRENT_H */
65
66 #ifdef MSDOS
67 #define DIRENTRY_NONEMPTY(p) ((p)->d_name[0] != 0)
68 #else
69 #define DIRENTRY_NONEMPTY(p) ((p)->d_ino)
70 #endif
71
72 #include "lisp.h"
73 #include "systime.h"
74 #include "buffer.h"
75 #include "commands.h"
76 #include "character.h"
77 #include "charset.h"
78 #include "coding.h"
79 #include "regex.h"
80 #include "blockinput.h"
81
82 /* Returns a search buffer, with a fastmap allocated and ready to go. */
83 extern struct re_pattern_buffer *compile_pattern (Lisp_Object,
84 struct re_registers *,
85 Lisp_Object, int, int);
86
87 /* if system does not have symbolic links, it does not have lstat.
88 In that case, use ordinary stat instead. */
89
90 #ifndef S_IFLNK
91 #define lstat stat
92 #endif
93
94 Lisp_Object Qdirectory_files;
95 Lisp_Object Qdirectory_files_and_attributes;
96 Lisp_Object Qfile_name_completion;
97 Lisp_Object Qfile_name_all_completions;
98 Lisp_Object Qfile_attributes;
99 Lisp_Object Qfile_attributes_lessp;
100
101 static int scmp (const char *, const char *, int);
102 \f
103 #ifdef WINDOWSNT
104 Lisp_Object
105 directory_files_internal_w32_unwind (Lisp_Object arg)
106 {
107 Vw32_get_true_file_attributes = arg;
108 return Qnil;
109 }
110 #endif
111
112 Lisp_Object
113 directory_files_internal_unwind (Lisp_Object dh)
114 {
115 DIR *d = (DIR *) XSAVE_VALUE (dh)->pointer;
116 BLOCK_INPUT;
117 closedir (d);
118 UNBLOCK_INPUT;
119 return Qnil;
120 }
121
122 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
123 When ATTRS is zero, return a list of directory filenames; when
124 non-zero, return a list of directory filenames and their attributes.
125 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
126
127 Lisp_Object
128 directory_files_internal (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, int attrs, Lisp_Object id_format)
129 {
130 DIR *d;
131 int directory_nbytes;
132 Lisp_Object list, dirfilename, encoded_directory;
133 struct re_pattern_buffer *bufp = NULL;
134 int needsep = 0;
135 int count = SPECPDL_INDEX ();
136 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
137 DIRENTRY *dp;
138 #ifdef WINDOWSNT
139 Lisp_Object w32_save = Qnil;
140 #endif
141
142 /* Because of file name handlers, these functions might call
143 Ffuncall, and cause a GC. */
144 list = encoded_directory = dirfilename = Qnil;
145 GCPRO5 (match, directory, list, dirfilename, encoded_directory);
146 dirfilename = Fdirectory_file_name (directory);
147
148 if (!NILP (match))
149 {
150 CHECK_STRING (match);
151
152 /* MATCH might be a flawed regular expression. Rather than
153 catching and signaling our own errors, we just call
154 compile_pattern to do the work for us. */
155 /* Pass 1 for the MULTIBYTE arg
156 because we do make multibyte strings if the contents warrant. */
157 # ifdef WINDOWSNT
158 /* Windows users want case-insensitive wildcards. */
159 bufp = compile_pattern (match, 0,
160 BVAR (&buffer_defaults, case_canon_table), 0, 1);
161 # else /* !WINDOWSNT */
162 bufp = compile_pattern (match, 0, Qnil, 0, 1);
163 # endif /* !WINDOWSNT */
164 }
165
166 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
167 run_pre_post_conversion_on_str which calls Lisp directly and
168 indirectly. */
169 if (STRING_MULTIBYTE (dirfilename))
170 dirfilename = ENCODE_FILE (dirfilename);
171 encoded_directory = (STRING_MULTIBYTE (directory)
172 ? ENCODE_FILE (directory) : directory);
173
174 /* Now *bufp is the compiled form of MATCH; don't call anything
175 which might compile a new regexp until we're done with the loop! */
176
177 BLOCK_INPUT;
178 d = opendir (SSDATA (dirfilename));
179 UNBLOCK_INPUT;
180 if (d == NULL)
181 report_file_error ("Opening directory", Fcons (directory, Qnil));
182
183 /* Unfortunately, we can now invoke expand-file-name and
184 file-attributes on filenames, both of which can throw, so we must
185 do a proper unwind-protect. */
186 record_unwind_protect (directory_files_internal_unwind,
187 make_save_value (d, 0));
188
189 #ifdef WINDOWSNT
190 if (attrs)
191 {
192 extern int is_slow_fs (const char *);
193
194 /* Do this only once to avoid doing it (in w32.c:stat) for each
195 file in the directory, when we call Ffile_attributes below. */
196 record_unwind_protect (directory_files_internal_w32_unwind,
197 Vw32_get_true_file_attributes);
198 w32_save = Vw32_get_true_file_attributes;
199 if (EQ (Vw32_get_true_file_attributes, Qlocal))
200 {
201 /* w32.c:stat will notice these bindings and avoid calling
202 GetDriveType for each file. */
203 if (is_slow_fs (SDATA (dirfilename)))
204 Vw32_get_true_file_attributes = Qnil;
205 else
206 Vw32_get_true_file_attributes = Qt;
207 }
208 }
209 #endif
210
211 directory_nbytes = SBYTES (directory);
212 re_match_object = Qt;
213
214 /* Decide whether we need to add a directory separator. */
215 if (directory_nbytes == 0
216 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
217 needsep = 1;
218
219 /* Loop reading blocks until EOF or error. */
220 for (;;)
221 {
222 errno = 0;
223 dp = readdir (d);
224
225 if (dp == NULL && (0
226 #ifdef EAGAIN
227 || errno == EAGAIN
228 #endif
229 #ifdef EINTR
230 || errno == EINTR
231 #endif
232 ))
233 { QUIT; continue; }
234
235 if (dp == NULL)
236 break;
237
238 if (DIRENTRY_NONEMPTY (dp))
239 {
240 int len;
241 int wanted = 0;
242 Lisp_Object name, finalname;
243 struct gcpro gcpro1, gcpro2;
244
245 len = NAMLEN (dp);
246 name = finalname = make_unibyte_string (dp->d_name, len);
247 GCPRO2 (finalname, name);
248
249 /* Note: DECODE_FILE can GC; it should protect its argument,
250 though. */
251 name = DECODE_FILE (name);
252 len = SBYTES (name);
253
254 /* Now that we have unwind_protect in place, we might as well
255 allow matching to be interrupted. */
256 immediate_quit = 1;
257 QUIT;
258
259 if (NILP (match)
260 || (0 <= re_search (bufp, SSDATA (name), len, 0, len, 0)))
261 wanted = 1;
262
263 immediate_quit = 0;
264
265 if (wanted)
266 {
267 if (!NILP (full))
268 {
269 Lisp_Object fullname;
270 int nbytes = len + directory_nbytes + needsep;
271 int nchars;
272
273 fullname = make_uninit_multibyte_string (nbytes, nbytes);
274 memcpy (SDATA (fullname), SDATA (directory),
275 directory_nbytes);
276
277 if (needsep)
278 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
279
280 memcpy (SDATA (fullname) + directory_nbytes + needsep,
281 SDATA (name), len);
282
283 nchars = chars_in_text (SDATA (fullname), nbytes);
284
285 /* Some bug somewhere. */
286 if (nchars > nbytes)
287 abort ();
288
289 STRING_SET_CHARS (fullname, nchars);
290 if (nchars == nbytes)
291 STRING_SET_UNIBYTE (fullname);
292
293 finalname = fullname;
294 }
295 else
296 finalname = name;
297
298 if (attrs)
299 {
300 /* Construct an expanded filename for the directory entry.
301 Use the decoded names for input to Ffile_attributes. */
302 Lisp_Object decoded_fullname, fileattrs;
303 struct gcpro gcpro1, gcpro2;
304
305 decoded_fullname = fileattrs = Qnil;
306 GCPRO2 (decoded_fullname, fileattrs);
307
308 /* Both Fexpand_file_name and Ffile_attributes can GC. */
309 decoded_fullname = Fexpand_file_name (name, directory);
310 fileattrs = Ffile_attributes (decoded_fullname, id_format);
311
312 list = Fcons (Fcons (finalname, fileattrs), list);
313 UNGCPRO;
314 }
315 else
316 list = Fcons (finalname, list);
317 }
318
319 UNGCPRO;
320 }
321 }
322
323 BLOCK_INPUT;
324 closedir (d);
325 UNBLOCK_INPUT;
326 #ifdef WINDOWSNT
327 if (attrs)
328 Vw32_get_true_file_attributes = w32_save;
329 #endif
330
331 /* Discard the unwind protect. */
332 specpdl_ptr = specpdl + count;
333
334 if (NILP (nosort))
335 list = Fsort (Fnreverse (list),
336 attrs ? Qfile_attributes_lessp : Qstring_lessp);
337
338 RETURN_UNGCPRO (list);
339 }
340
341
342 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
343 doc: /* Return a list of names of files in DIRECTORY.
344 There are three optional arguments:
345 If FULL is non-nil, return absolute file names. Otherwise return names
346 that are relative to the specified directory.
347 If MATCH is non-nil, mention only file names that match the regexp MATCH.
348 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
349 Otherwise, the list returned is sorted with `string-lessp'.
350 NOSORT is useful if you plan to sort the result yourself. */)
351 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
352 {
353 Lisp_Object handler;
354 directory = Fexpand_file_name (directory, Qnil);
355
356 /* If the file name has special constructs in it,
357 call the corresponding file handler. */
358 handler = Ffind_file_name_handler (directory, Qdirectory_files);
359 if (!NILP (handler))
360 return call5 (handler, Qdirectory_files, directory,
361 full, match, nosort);
362
363 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
364 }
365
366 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
367 Sdirectory_files_and_attributes, 1, 5, 0,
368 doc: /* Return a list of names of files and their attributes in DIRECTORY.
369 There are four optional arguments:
370 If FULL is non-nil, return absolute file names. Otherwise return names
371 that are relative to the specified directory.
372 If MATCH is non-nil, mention only file names that match the regexp MATCH.
373 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
374 NOSORT is useful if you plan to sort the result yourself.
375 ID-FORMAT specifies the preferred format of attributes uid and gid, see
376 `file-attributes' for further documentation.
377 On MS-Windows, performance depends on `w32-get-true-file-attributes',
378 which see. */)
379 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
380 {
381 Lisp_Object handler;
382 directory = Fexpand_file_name (directory, Qnil);
383
384 /* If the file name has special constructs in it,
385 call the corresponding file handler. */
386 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
387 if (!NILP (handler))
388 return call6 (handler, Qdirectory_files_and_attributes,
389 directory, full, match, nosort, id_format);
390
391 return directory_files_internal (directory, full, match, nosort, 1, id_format);
392 }
393
394 \f
395 Lisp_Object file_name_completion (Lisp_Object file, Lisp_Object dirname, int all_flag, int ver_flag, Lisp_Object predicate);
396
397 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
398 2, 3, 0,
399 doc: /* Complete file name FILE in directory DIRECTORY.
400 Returns the longest string
401 common to all file names in DIRECTORY that start with FILE.
402 If there is only one and FILE matches it exactly, returns t.
403 Returns nil if DIRECTORY contains no name starting with FILE.
404
405 If PREDICATE is non-nil, call PREDICATE with each possible
406 completion (in absolute form) and ignore it if PREDICATE returns nil.
407
408 This function ignores some of the possible completions as
409 determined by the variable `completion-ignored-extensions', which see. */)
410 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
411 {
412 Lisp_Object handler;
413
414 /* If the directory name has special constructs in it,
415 call the corresponding file handler. */
416 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
417 if (!NILP (handler))
418 return call4 (handler, Qfile_name_completion, file, directory, predicate);
419
420 /* If the file name has special constructs in it,
421 call the corresponding file handler. */
422 handler = Ffind_file_name_handler (file, Qfile_name_completion);
423 if (!NILP (handler))
424 return call4 (handler, Qfile_name_completion, file, directory, predicate);
425
426 return file_name_completion (file, directory, 0, 0, predicate);
427 }
428
429 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
430 Sfile_name_all_completions, 2, 2, 0,
431 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
432 These are all file names in directory DIRECTORY which begin with FILE. */)
433 (Lisp_Object file, Lisp_Object directory)
434 {
435 Lisp_Object handler;
436
437 /* If the directory name has special constructs in it,
438 call the corresponding file handler. */
439 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
440 if (!NILP (handler))
441 return call3 (handler, Qfile_name_all_completions, file, directory);
442
443 /* If the file name has special constructs in it,
444 call the corresponding file handler. */
445 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
446 if (!NILP (handler))
447 return call3 (handler, Qfile_name_all_completions, file, directory);
448
449 return file_name_completion (file, directory, 1, 0, Qnil);
450 }
451
452 static int file_name_completion_stat (Lisp_Object dirname, DIRENTRY *dp, struct stat *st_addr);
453 Lisp_Object Qdefault_directory;
454
455 Lisp_Object
456 file_name_completion (Lisp_Object file, Lisp_Object dirname, int all_flag, int ver_flag, Lisp_Object predicate)
457 {
458 DIR *d;
459 int bestmatchsize = 0;
460 int matchcount = 0;
461 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
462 If ALL_FLAG is 0, BESTMATCH is either nil
463 or the best match so far, not decoded. */
464 Lisp_Object bestmatch, tem, elt, name;
465 Lisp_Object encoded_file;
466 Lisp_Object encoded_dir;
467 struct stat st;
468 int directoryp;
469 /* If includeall is zero, exclude files in completion-ignored-extensions as
470 well as "." and "..". Until shown otherwise, assume we can't exclude
471 anything. */
472 int includeall = 1;
473 int count = SPECPDL_INDEX ();
474 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
475
476 elt = Qnil;
477
478 CHECK_STRING (file);
479
480 #ifdef FILE_SYSTEM_CASE
481 file = FILE_SYSTEM_CASE (file);
482 #endif
483 bestmatch = Qnil;
484 encoded_file = encoded_dir = Qnil;
485 GCPRO5 (file, dirname, bestmatch, encoded_file, encoded_dir);
486 dirname = Fexpand_file_name (dirname, Qnil);
487 specbind (Qdefault_directory, dirname);
488
489 /* Do completion on the encoded file name
490 because the other names in the directory are (we presume)
491 encoded likewise. We decode the completed string at the end. */
492 /* Actually, this is not quite true any more: we do most of the completion
493 work with decoded file names, but we still do some filtering based
494 on the encoded file name. */
495 encoded_file = STRING_MULTIBYTE (file) ? ENCODE_FILE (file) : file;
496
497 encoded_dir = ENCODE_FILE (dirname);
498
499 BLOCK_INPUT;
500 d = opendir (SSDATA (Fdirectory_file_name (encoded_dir)));
501 UNBLOCK_INPUT;
502 if (!d)
503 report_file_error ("Opening directory", Fcons (dirname, Qnil));
504
505 record_unwind_protect (directory_files_internal_unwind,
506 make_save_value (d, 0));
507
508 /* Loop reading blocks */
509 /* (att3b compiler bug requires do a null comparison this way) */
510 while (1)
511 {
512 DIRENTRY *dp;
513 int len;
514 int canexclude = 0;
515
516 errno = 0;
517 dp = readdir (d);
518 if (dp == NULL && (0
519 # ifdef EAGAIN
520 || errno == EAGAIN
521 # endif
522 # ifdef EINTR
523 || errno == EINTR
524 # endif
525 ))
526 { QUIT; continue; }
527
528 if (!dp) break;
529
530 len = NAMLEN (dp);
531
532 QUIT;
533 if (! DIRENTRY_NONEMPTY (dp)
534 || len < SCHARS (encoded_file)
535 || 0 <= scmp (dp->d_name, SSDATA (encoded_file),
536 SCHARS (encoded_file)))
537 continue;
538
539 if (file_name_completion_stat (encoded_dir, dp, &st) < 0)
540 continue;
541
542 directoryp = ((st.st_mode & S_IFMT) == S_IFDIR);
543 tem = Qnil;
544 /* If all_flag is set, always include all.
545 It would not actually be helpful to the user to ignore any possible
546 completions when making a list of them. */
547 if (!all_flag)
548 {
549 int skip;
550
551 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
552 /* If this entry matches the current bestmatch, the only
553 thing it can do is increase matchcount, so don't bother
554 investigating it any further. */
555 if (!completion_ignore_case
556 /* The return result depends on whether it's the sole match. */
557 && matchcount > 1
558 && !includeall /* This match may allow includeall to 0. */
559 && len >= bestmatchsize
560 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
561 continue;
562 #endif
563
564 if (directoryp)
565 {
566 #ifndef TRIVIAL_DIRECTORY_ENTRY
567 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
568 #endif
569 /* "." and ".." are never interesting as completions, and are
570 actually in the way in a directory with only one file. */
571 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
572 canexclude = 1;
573 else if (len > SCHARS (encoded_file))
574 /* Ignore directories if they match an element of
575 completion-ignored-extensions which ends in a slash. */
576 for (tem = Vcompletion_ignored_extensions;
577 CONSP (tem); tem = XCDR (tem))
578 {
579 int elt_len;
580 char *p1;
581
582 elt = XCAR (tem);
583 if (!STRINGP (elt))
584 continue;
585 /* Need to encode ELT, since scmp compares unibyte
586 strings only. */
587 elt = ENCODE_FILE (elt);
588 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
589 if (elt_len <= 0)
590 continue;
591 p1 = SSDATA (elt);
592 if (p1[elt_len] != '/')
593 continue;
594 skip = len - elt_len;
595 if (skip < 0)
596 continue;
597
598 if (0 <= scmp (dp->d_name + skip, p1, elt_len))
599 continue;
600 break;
601 }
602 }
603 else
604 {
605 /* Compare extensions-to-be-ignored against end of this file name */
606 /* if name is not an exact match against specified string */
607 if (len > SCHARS (encoded_file))
608 /* and exit this for loop if a match is found */
609 for (tem = Vcompletion_ignored_extensions;
610 CONSP (tem); tem = XCDR (tem))
611 {
612 elt = XCAR (tem);
613 if (!STRINGP (elt)) continue;
614 /* Need to encode ELT, since scmp compares unibyte
615 strings only. */
616 elt = ENCODE_FILE (elt);
617 skip = len - SCHARS (elt);
618 if (skip < 0) continue;
619
620 if (0 <= scmp (dp->d_name + skip,
621 SSDATA (elt),
622 SCHARS (elt)))
623 continue;
624 break;
625 }
626 }
627
628 /* If an ignored-extensions match was found,
629 don't process this name as a completion. */
630 if (CONSP (tem))
631 canexclude = 1;
632
633 if (!includeall && canexclude)
634 /* We're not including all files and this file can be excluded. */
635 continue;
636
637 if (includeall && !canexclude)
638 { /* If we have one non-excludable file, we want to exclude the
639 excudable files. */
640 includeall = 0;
641 /* Throw away any previous excludable match found. */
642 bestmatch = Qnil;
643 bestmatchsize = 0;
644 matchcount = 0;
645 }
646 }
647 /* FIXME: If we move this `decode' earlier we can eliminate
648 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
649 name = make_unibyte_string (dp->d_name, len);
650 name = DECODE_FILE (name);
651
652 {
653 Lisp_Object regexps;
654 Lisp_Object zero;
655 XSETFASTINT (zero, 0);
656
657 /* Ignore this element if it fails to match all the regexps. */
658 if (completion_ignore_case)
659 {
660 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
661 regexps = XCDR (regexps))
662 if (fast_string_match_ignore_case (XCAR (regexps), name) < 0)
663 break;
664 }
665 else
666 {
667 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
668 regexps = XCDR (regexps))
669 if (fast_string_match (XCAR (regexps), name) < 0)
670 break;
671 }
672
673 if (CONSP (regexps))
674 continue;
675 }
676
677 /* This is a possible completion */
678 if (directoryp)
679 /* This completion is a directory; make it end with '/'. */
680 name = Ffile_name_as_directory (name);
681
682 /* Test the predicate, if any. */
683 if (!NILP (predicate))
684 {
685 Lisp_Object val;
686 struct gcpro gcpro1;
687
688 GCPRO1 (name);
689 val = call1 (predicate, name);
690 UNGCPRO;
691
692 if (NILP (val))
693 continue;
694 }
695
696 /* Suitably record this match. */
697
698 matchcount++;
699
700 if (all_flag)
701 bestmatch = Fcons (name, bestmatch);
702 else if (NILP (bestmatch))
703 {
704 bestmatch = name;
705 bestmatchsize = SCHARS (name);
706 }
707 else
708 {
709 Lisp_Object zero = make_number (0);
710 /* FIXME: This is a copy of the code in Ftry_completion. */
711 int compare = min (bestmatchsize, SCHARS (name));
712 Lisp_Object tem
713 = Fcompare_strings (bestmatch, zero,
714 make_number (compare),
715 name, zero,
716 make_number (compare),
717 completion_ignore_case ? Qt : Qnil);
718 int matchsize
719 = (EQ (tem, Qt) ? compare
720 : XINT (tem) < 0 ? - XINT (tem) - 1
721 : XINT (tem) - 1);
722
723 if (completion_ignore_case)
724 {
725 /* If this is an exact match except for case,
726 use it as the best match rather than one that is not
727 an exact match. This way, we get the case pattern
728 of the actual match. */
729 /* This tests that the current file is an exact match
730 but BESTMATCH is not (it is too long). */
731 if ((matchsize == SCHARS (name)
732 && matchsize + !!directoryp < SCHARS (bestmatch))
733 ||
734 /* If there is no exact match ignoring case,
735 prefer a match that does not change the case
736 of the input. */
737 /* If there is more than one exact match aside from
738 case, and one of them is exact including case,
739 prefer that one. */
740 /* This == checks that, of current file and BESTMATCH,
741 either both or neither are exact. */
742 (((matchsize == SCHARS (name))
743 ==
744 (matchsize + !!directoryp == SCHARS (bestmatch)))
745 && (tem = Fcompare_strings (name, zero,
746 make_number (SCHARS (file)),
747 file, zero,
748 Qnil,
749 Qnil),
750 EQ (Qt, tem))
751 && (tem = Fcompare_strings (bestmatch, zero,
752 make_number (SCHARS (file)),
753 file, zero,
754 Qnil,
755 Qnil),
756 ! EQ (Qt, tem))))
757 bestmatch = name;
758 }
759 bestmatchsize = matchsize;
760
761 /* If the best completion so far is reduced to the string
762 we're trying to complete, then we already know there's no
763 other completion, so there's no point looking any further. */
764 if (matchsize <= SCHARS (file)
765 && !includeall /* A future match may allow includeall to 0. */
766 /* If completion-ignore-case is non-nil, don't
767 short-circuit because we want to find the best
768 possible match *including* case differences. */
769 && (!completion_ignore_case || matchsize == 0)
770 /* The return value depends on whether it's the sole match. */
771 && matchcount > 1)
772 break;
773
774 }
775 }
776
777 UNGCPRO;
778 /* This closes the directory. */
779 bestmatch = unbind_to (count, bestmatch);
780
781 if (all_flag || NILP (bestmatch))
782 return bestmatch;
783 /* Return t if the supplied string is an exact match (counting case);
784 it does not require any change to be made. */
785 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
786 return Qt;
787 bestmatch = Fsubstring (bestmatch, make_number (0),
788 make_number (bestmatchsize));
789 return bestmatch;
790 }
791
792 /* Compare exactly LEN chars of strings at S1 and S2,
793 ignoring case if appropriate.
794 Return -1 if strings match,
795 else number of chars that match at the beginning. */
796
797 static int
798 scmp (const char *s1, const char *s2, int len)
799 {
800 register int l = len;
801
802 if (completion_ignore_case)
803 {
804 while (l
805 && (DOWNCASE ((unsigned char) *s1++)
806 == DOWNCASE ((unsigned char) *s2++)))
807 l--;
808 }
809 else
810 {
811 while (l && *s1++ == *s2++)
812 l--;
813 }
814 if (l == 0)
815 return -1;
816 else
817 return len - l;
818 }
819
820 static int
821 file_name_completion_stat (Lisp_Object dirname, DIRENTRY *dp, struct stat *st_addr)
822 {
823 int len = NAMLEN (dp);
824 int pos = SCHARS (dirname);
825 int value;
826 char *fullname = (char *) alloca (len + pos + 2);
827
828 #ifdef MSDOS
829 /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
830 but aren't required here. Avoid computing the following fields:
831 st_inode, st_size and st_nlink for directories, and the execute bits
832 in st_mode for non-directory files with non-standard extensions. */
833
834 unsigned short save_djstat_flags = _djstat_flags;
835
836 _djstat_flags = _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
837 #endif /* MSDOS */
838
839 memcpy (fullname, SDATA (dirname), pos);
840 if (!IS_DIRECTORY_SEP (fullname[pos - 1]))
841 fullname[pos++] = DIRECTORY_SEP;
842
843 memcpy (fullname + pos, dp->d_name, len);
844 fullname[pos + len] = 0;
845
846 #ifdef S_IFLNK
847 /* We want to return success if a link points to a nonexistent file,
848 but we want to return the status for what the link points to,
849 in case it is a directory. */
850 value = lstat (fullname, st_addr);
851 stat (fullname, st_addr);
852 return value;
853 #else
854 value = stat (fullname, st_addr);
855 #ifdef MSDOS
856 _djstat_flags = save_djstat_flags;
857 #endif /* MSDOS */
858 return value;
859 #endif /* S_IFLNK */
860 }
861 \f
862 Lisp_Object
863 make_time (time_t time)
864 {
865 return Fcons (make_number (time >> 16),
866 Fcons (make_number (time & 0177777), Qnil));
867 }
868
869 static char *
870 stat_uname (struct stat *st)
871 {
872 #ifdef WINDOWSNT
873 return st->st_uname;
874 #else
875 struct passwd *pw = (struct passwd *) getpwuid (st->st_uid);
876
877 if (pw)
878 return pw->pw_name;
879 else
880 return NULL;
881 #endif
882 }
883
884 static char *
885 stat_gname (struct stat *st)
886 {
887 #ifdef WINDOWSNT
888 return st->st_gname;
889 #else
890 struct group *gr = (struct group *) getgrgid (st->st_gid);
891
892 if (gr)
893 return gr->gr_name;
894 else
895 return NULL;
896 #endif
897 }
898
899 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
900 doc: /* Return a list of attributes of file FILENAME.
901 Value is nil if specified file cannot be opened.
902
903 ID-FORMAT specifies the preferred format of attributes uid and gid (see
904 below) - valid values are 'string and 'integer. The latter is the
905 default, but we plan to change that, so you should specify a non-nil value
906 for ID-FORMAT if you use the returned uid or gid.
907
908 Elements of the attribute list are:
909 0. t for directory, string (name linked to) for symbolic link, or nil.
910 1. Number of links to file.
911 2. File uid as a string or a number. If a string value cannot be
912 looked up, a numeric value, either an integer or a float, is returned.
913 3. File gid, likewise.
914 4. Last access time, as a list of two integers.
915 First integer has high-order 16 bits of time, second has low 16 bits.
916 (See a note below about access time on FAT-based filesystems.)
917 5. Last modification time, likewise. This is the time of the last
918 change to the file's contents.
919 6. Last status change time, likewise. This is the time of last change
920 to the file's attributes: owner and group, access mode bits, etc.
921 7. Size in bytes.
922 This is a floating point number if the size is too large for an integer.
923 8. File modes, as a string of ten letters or dashes as in ls -l.
924 9. t if file's gid would change if file were deleted and recreated.
925 10. inode number. If inode number is larger than what Emacs integer
926 can hold, but still fits into a 32-bit number, this is a cons cell
927 containing two integers: first the high part, then the low 16 bits.
928 If the inode number is wider than 32 bits, this is of the form
929 (HIGH MIDDLE . LOW): first the high 24 bits, then middle 24 bits,
930 and finally the low 16 bits.
931 11. Filesystem device number. If it is larger than what the Emacs
932 integer can hold, this is a cons cell, similar to the inode number.
933
934 On most filesystems, the combination of the inode and the device
935 number uniquely identifies the file.
936
937 On MS-Windows, performance depends on `w32-get-true-file-attributes',
938 which see.
939
940 On some FAT-based filesystems, only the date of last access is recorded,
941 so last access time will always be midnight of that day. */)
942 (Lisp_Object filename, Lisp_Object id_format)
943 {
944 Lisp_Object values[12];
945 Lisp_Object encoded;
946 struct stat s;
947 #ifdef BSD4_2
948 Lisp_Object dirname;
949 struct stat sdir;
950 #endif /* BSD4_2 */
951 char modes[10];
952 Lisp_Object handler;
953 struct gcpro gcpro1;
954 char *uname = NULL, *gname = NULL;
955
956 filename = Fexpand_file_name (filename, Qnil);
957
958 /* If the file name has special constructs in it,
959 call the corresponding file handler. */
960 handler = Ffind_file_name_handler (filename, Qfile_attributes);
961 if (!NILP (handler))
962 { /* Only pass the extra arg if it is used to help backward compatibility
963 with old file handlers which do not implement the new arg. --Stef */
964 if (NILP (id_format))
965 return call2 (handler, Qfile_attributes, filename);
966 else
967 return call3 (handler, Qfile_attributes, filename, id_format);
968 }
969
970 GCPRO1 (filename);
971 encoded = ENCODE_FILE (filename);
972 UNGCPRO;
973
974 if (lstat (SSDATA (encoded), &s) < 0)
975 return Qnil;
976
977 switch (s.st_mode & S_IFMT)
978 {
979 default:
980 values[0] = Qnil; break;
981 case S_IFDIR:
982 values[0] = Qt; break;
983 #ifdef S_IFLNK
984 case S_IFLNK:
985 values[0] = Ffile_symlink_p (filename); break;
986 #endif
987 }
988 values[1] = make_number (s.st_nlink);
989
990 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
991 {
992 BLOCK_INPUT;
993 uname = stat_uname (&s);
994 gname = stat_gname (&s);
995 UNBLOCK_INPUT;
996 }
997 if (uname)
998 values[2] = DECODE_SYSTEM (build_string (uname));
999 else
1000 values[2] = make_fixnum_or_float (s.st_uid);
1001 if (gname)
1002 values[3] = DECODE_SYSTEM (build_string (gname));
1003 else
1004 values[3] = make_fixnum_or_float (s.st_gid);
1005
1006 values[4] = make_time (s.st_atime);
1007 values[5] = make_time (s.st_mtime);
1008 values[6] = make_time (s.st_ctime);
1009 values[7] = make_fixnum_or_float (s.st_size);
1010 /* If the size is negative, and its type is long, convert it back to
1011 positive. */
1012 if (s.st_size < 0 && sizeof (s.st_size) == sizeof (long))
1013 values[7] = make_float ((double) ((unsigned long) s.st_size));
1014
1015 filemodestring (&s, modes);
1016 values[8] = make_string (modes, 10);
1017 #ifdef BSD4_2 /* file gid will be dir gid */
1018 dirname = Ffile_name_directory (filename);
1019 if (! NILP (dirname))
1020 encoded = ENCODE_FILE (dirname);
1021 if (! NILP (dirname) && stat (SDATA (encoded), &sdir) == 0)
1022 values[9] = (sdir.st_gid != s.st_gid) ? Qt : Qnil;
1023 else /* if we can't tell, assume worst */
1024 values[9] = Qt;
1025 #else /* file gid will be egid */
1026 values[9] = (s.st_gid != getegid ()) ? Qt : Qnil;
1027 #endif /* not BSD4_2 */
1028 if (!FIXNUM_OVERFLOW_P (s.st_ino))
1029 /* Keep the most common cases as integers. */
1030 values[10] = make_number (s.st_ino);
1031 else if (!FIXNUM_OVERFLOW_P (s.st_ino >> 16))
1032 /* To allow inode numbers larger than VALBITS, separate the bottom
1033 16 bits. */
1034 values[10] = Fcons (make_number ((EMACS_INT)(s.st_ino >> 16)),
1035 make_number ((EMACS_INT)(s.st_ino & 0xffff)));
1036 else
1037 {
1038 /* To allow inode numbers beyond 32 bits, separate into 2 24-bit
1039 high parts and a 16-bit bottom part.
1040 The code on the next line avoids a compiler warning on
1041 systems where st_ino is 32 bit wide. (bug#766). */
1042 EMACS_INT high_ino = s.st_ino >> 31 >> 1;
1043 EMACS_INT low_ino = s.st_ino & 0xffffffff;
1044
1045 values[10] = Fcons (make_number (high_ino >> 8),
1046 Fcons (make_number (((high_ino & 0xff) << 16)
1047 + (low_ino >> 16)),
1048 make_number (low_ino & 0xffff)));
1049 }
1050
1051 /* Likewise for device. */
1052 if (FIXNUM_OVERFLOW_P (s.st_dev))
1053 values[11] = Fcons (make_number (s.st_dev >> 16),
1054 make_number (s.st_dev & 0xffff));
1055 else
1056 values[11] = make_number (s.st_dev);
1057
1058 return Flist (sizeof(values) / sizeof(values[0]), values);
1059 }
1060
1061 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
1062 doc: /* Return t if first arg file attributes list is less than second.
1063 Comparison is in lexicographic order and case is significant. */)
1064 (Lisp_Object f1, Lisp_Object f2)
1065 {
1066 return Fstring_lessp (Fcar (f1), Fcar (f2));
1067 }
1068 \f
1069 void
1070 syms_of_dired (void)
1071 {
1072 Qdirectory_files = intern_c_string ("directory-files");
1073 Qdirectory_files_and_attributes = intern_c_string ("directory-files-and-attributes");
1074 Qfile_name_completion = intern_c_string ("file-name-completion");
1075 Qfile_name_all_completions = intern_c_string ("file-name-all-completions");
1076 Qfile_attributes = intern_c_string ("file-attributes");
1077 Qfile_attributes_lessp = intern_c_string ("file-attributes-lessp");
1078 Qdefault_directory = intern_c_string ("default-directory");
1079
1080 staticpro (&Qdirectory_files);
1081 staticpro (&Qdirectory_files_and_attributes);
1082 staticpro (&Qfile_name_completion);
1083 staticpro (&Qfile_name_all_completions);
1084 staticpro (&Qfile_attributes);
1085 staticpro (&Qfile_attributes_lessp);
1086 staticpro (&Qdefault_directory);
1087
1088 defsubr (&Sdirectory_files);
1089 defsubr (&Sdirectory_files_and_attributes);
1090 defsubr (&Sfile_name_completion);
1091 defsubr (&Sfile_name_all_completions);
1092 defsubr (&Sfile_attributes);
1093 defsubr (&Sfile_attributes_lessp);
1094
1095 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1096 doc: /* Completion ignores file names ending in any string in this list.
1097 It does not ignore them if all possible completions end in one of
1098 these strings or when displaying a list of completions.
1099 It ignores directory names if they match any string in this list which
1100 ends in a slash. */);
1101 Vcompletion_ignored_extensions = Qnil;
1102 }