(memcasecmp): Declare local I to be unsigned to avoid warning from gcc -Wall.
[coreutils.git] / src / ls.c
blobbed1cf831ccac2a19b02f6837b05cc7f4135ef9d
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 1985, 1988, 1990, 1991, 1995 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* If the macro MULTI_COL is defined,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If the macro LONG_FORMAT is defined,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
28 If neither is defined,
29 the output format depends on whether the output
30 device is a terminal.
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 #ifdef _AIX
36 #pragma alloca
37 #endif
39 #include <config.h>
40 #include <sys/types.h>
42 #if HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
44 #endif
46 #include <stdio.h>
47 #include <grp.h>
48 #include <pwd.h>
49 #include <getopt.h>
51 #if HAVE_LIMITS_H
52 /* limits.h must come before system.h because limits.h on some systems
53 undefs PATH_MAX, whereas system.h includes pathmax.h which sets
54 PATH_MAX. */
55 #include <limits.h>
56 #endif
58 #include "system.h"
59 #include <fnmatch.h>
61 #include "obstack.h"
62 #include "ls.h"
63 #include "version.h"
64 #include "error.h"
65 #include "argmatch.h"
67 #define obstack_chunk_alloc xmalloc
68 #define obstack_chunk_free free
70 #ifndef INT_MAX
71 #define INT_MAX 2147483647
72 #endif
74 /* Return an int indicating the result of comparing two longs. */
75 #if (INT_MAX <= 65535)
76 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
77 #else
78 #define longdiff(a, b) ((a) - (b))
79 #endif
81 /* The maximum number of digits required to print an inode number
82 in an unsigned format. */
83 #ifndef INODE_DIGITS
84 #define INODE_DIGITS 7
85 #endif
87 enum filetype
89 symbolic_link,
90 directory,
91 arg_directory, /* Directory given as command line arg. */
92 normal /* All others. */
95 struct fileinfo
97 /* The file name. */
98 char *name;
100 struct stat stat;
102 /* For symbolic link, name of the file linked to, otherwise zero. */
103 char *linkname;
105 /* For symbolic link and long listing, st_mode of file linked to, otherwise
106 zero. */
107 unsigned int linkmode;
109 enum filetype filetype;
112 #ifndef STDC_HEADERS
113 char *ctime ();
114 time_t time ();
115 void free ();
116 #endif
118 void mode_string ();
120 char *stpcpy ();
121 char *xstrdup ();
122 char *getgroup ();
123 char *getuser ();
124 char *xmalloc ();
125 char *xrealloc ();
126 void invalid_arg ();
128 static char *make_link_path __P ((char *path, char *linkname));
129 static int compare_atime __P ((struct fileinfo *file1,
130 struct fileinfo *file2));
131 static int rev_cmp_atime __P ((struct fileinfo *file2,
132 struct fileinfo *file1));
133 static int compare_ctime __P ((struct fileinfo *file1,
134 struct fileinfo *file2));
135 static int rev_cmp_ctime __P ((struct fileinfo *file2,
136 struct fileinfo *file1));
137 static int compare_mtime __P ((struct fileinfo *file1,
138 struct fileinfo *file2));
139 static int rev_cmp_mtime __P ((struct fileinfo *file2,
140 struct fileinfo *file1));
141 static int compare_size __P ((struct fileinfo *file1,
142 struct fileinfo *file2));
143 static int rev_cmp_size __P ((struct fileinfo *file2,
144 struct fileinfo *file1));
145 static int compare_name __P ((struct fileinfo *file1,
146 struct fileinfo *file2));
147 static int rev_cmp_name __P ((struct fileinfo *file2,
148 struct fileinfo *file1));
149 static int compare_extension __P ((struct fileinfo *file1,
150 struct fileinfo *file2));
151 static int rev_cmp_extension __P ((struct fileinfo *file2,
152 struct fileinfo *file1));
153 static int decode_switches __P ((int argc, char **argv));
154 static void parse_ls_color __P ((void));
155 static int file_interesting __P ((register struct dirent *next));
156 static int gobble_file __P ((const char *name, int explicit_arg,
157 const char *dirname));
158 static int is_not_dot_or_dotdot __P ((char *name));
159 static int length_of_file_name_and_frills __P ((struct fileinfo *f));
160 static void add_ignore_pattern __P ((char *pattern));
161 static void attach __P ((char *dest, const char *dirname, const char *name));
162 static void clear_files __P ((void));
163 static void extract_dirs_from_files __P ((const char *dirname, int recursive));
164 static void get_link_name __P ((char *filename, struct fileinfo *f));
165 static void indent __P ((int from, int to));
166 static void print_current_files __P ((void));
167 static void print_dir __P ((const char *name, const char *realname));
168 static void print_file_name_and_frills __P ((struct fileinfo *f));
169 static void print_horizontal __P ((void));
170 static void print_long_format __P ((struct fileinfo *f));
171 static void print_many_per_line __P ((void));
172 static void print_name_with_quoting __P ((register char *p));
173 static void print_type_indicator __P ((unsigned int mode));
174 static void print_color_indicator __P ((unsigned int mode));
175 static void put_indicator __P ((int n));
176 static void print_with_commas __P ((void));
177 static void queue_directory __P ((char *name, char *realname));
178 static void sort_files __P ((void));
179 static void usage __P ((int status));
181 /* The name the program was run with, stripped of any leading path. */
182 char *program_name;
184 /* The table of files in the current directory:
186 `files' points to a vector of `struct fileinfo', one per file.
187 `nfiles' is the number of elements space has been allocated for.
188 `files_index' is the number actually in use. */
190 /* Address of block containing the files that are described. */
192 static struct fileinfo *files;
194 /* Length of block that `files' points to, measured in files. */
196 static int nfiles;
198 /* Index of first unused in `files'. */
200 static int files_index;
202 /* Record of one pending directory waiting to be listed. */
204 struct pending
206 char *name;
207 /* If the directory is actually the file pointed to by a symbolic link we
208 were told to list, `realname' will contain the name of the symbolic
209 link, otherwise zero. */
210 char *realname;
211 struct pending *next;
214 static struct pending *pending_dirs;
216 /* Current time (seconds since 1970). When we are printing a file's time,
217 include the year if it is more than 6 months before this time. */
219 static time_t current_time;
221 /* The number of digits to use for block sizes.
222 4, or more if needed for bigger numbers. */
224 static int block_size_size;
226 /* Option flags */
228 /* long_format for lots of info, one per line.
229 one_per_line for just names, one per line.
230 many_per_line for just names, many per line, sorted vertically.
231 horizontal for just names, many per line, sorted horizontally.
232 with_commas for just names, many per line, separated by commas.
234 -l, -1, -C, -x and -m control this parameter. */
236 enum format
238 long_format, /* -l */
239 one_per_line, /* -1 */
240 many_per_line, /* -C */
241 horizontal, /* -x */
242 with_commas /* -m */
245 static enum format format;
247 /* Type of time to print or sort by. Controlled by -c and -u. */
249 enum time_type
251 time_mtime, /* default */
252 time_ctime, /* -c */
253 time_atime /* -u */
256 static enum time_type time_type;
258 /* print the full time, otherwise the standard unix heuristics. */
260 int full_time;
262 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X. */
264 enum sort_type
266 sort_none, /* -U */
267 sort_name, /* default */
268 sort_extension, /* -X */
269 sort_time, /* -t */
270 sort_size /* -S */
273 static enum sort_type sort_type;
275 /* Direction of sort.
276 0 means highest first if numeric,
277 lowest first if alphabetic;
278 these are the defaults.
279 1 means the opposite order in each case. -r */
281 static int sort_reverse;
283 /* Nonzero means to NOT display group information. -G */
285 int inhibit_group;
287 /* Nonzero means print the user and group id's as numbers rather
288 than as names. -n */
290 static int numeric_users;
292 /* Nonzero means mention the size in 512 byte blocks of each file. -s */
294 static int print_block_size;
296 /* Nonzero means show file sizes in kilobytes instead of blocks
297 (the size of which is system-dependent). -k */
299 static int kilobyte_blocks;
301 /* Precede each line of long output (per file) with a string like `m,n:'
302 where M is the number of characters after the `:' and before the
303 filename and N is the length of the filename. Using this format,
304 Emacs' dired mode starts up twice as fast, and can handle all
305 strange characters in file names. */
306 static int dired;
308 /* none means don't mention the type of files.
309 all means mention the types of all files.
310 not_programs means do so except for executables.
312 Controlled by -F and -p. */
314 enum indicator_style
316 none, /* default */
317 all, /* -F */
318 not_programs /* -p */
321 static enum indicator_style indicator_style;
323 /* Nonzero means use colors to mark types. Also define the different
324 colors as well as the stuff for the LS_COLORS environment variable.
325 The LS_COLORS variable is now in a termcap-like format. -o or
326 --color-if-tty. */
328 static int print_with_color;
330 enum color_type
332 color_no, /* 0: default or --color=no */
333 color_yes, /* 1: -o or --color=yes */
334 color_if_tty /* 2: --color=tty */
337 /* Note that color_no and color_yes equals boolean values; they will
338 be assigned to print_with_color which is a boolean variable */
340 #define MAXCOLORLEN 16 /* Max # of characters in a color sequence */
342 enum indicator_no
344 C_LEFT, C_RIGHT, C_END, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
345 C_BLK, C_CHR, C_EXEC
348 const char *const indicator_name[] =
350 "lc", "rc", "ec", "fi", "di", "ln", "pi", "so", "bd", "cd", "ex", NULL
353 struct indicator_type
355 int len;
356 char string[MAXCOLORLEN];
359 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
361 static struct indicator_type color_indicator[] =
363 {LEN_STR_PAIR ("\033[")}, /* lc: Left of color sequence */
364 {LEN_STR_PAIR ("m")}, /* rc: Right of color sequence */
365 {LEN_STR_PAIR ("\033[0m")}, /* ec: End color */
366 {LEN_STR_PAIR ("0")}, /* fi: File: default */
367 {LEN_STR_PAIR ("32")}, /* di: Directory: green */
368 {LEN_STR_PAIR ("36")}, /* ln: Symlink: cyan */
369 {LEN_STR_PAIR ("31")}, /* pi: Pipe: red */
370 {LEN_STR_PAIR ("33")}, /* so: Socket: yellow/brown */
371 {LEN_STR_PAIR ("44;37")}, /* bd: Block device: white on blue */
372 {LEN_STR_PAIR ("44;37")}, /* cd: Char device: white on blue */
373 {LEN_STR_PAIR ("35")}, /* ex: Executable: purple */
376 /* Nonzero means print using ISO 8859 characters. The default is specified
377 here as well. -8 enables, -7 disables. */
379 static int print_iso8859;
380 #ifndef DEFAULT_ISO8859
381 #define DEFAULT_ISO8859 1
382 #endif
384 /* Nonzero means mention the inode number of each file. -i */
386 static int print_inode;
388 /* Nonzero means when a symbolic link is found, display info on
389 the file linked to. -L */
391 static int trace_links;
393 /* Nonzero means when a directory is found, display info on its
394 contents. -R */
396 static int trace_dirs;
398 /* Nonzero means when an argument is a directory name, display info
399 on it itself. -d */
401 static int immediate_dirs;
403 /* Nonzero means don't omit files whose names start with `.'. -A */
405 static int all_files;
407 /* Nonzero means don't omit files `.' and `..'
408 This flag implies `all_files'. -a */
410 static int really_all_files;
412 /* A linked list of shell-style globbing patterns. If a non-argument
413 file name matches any of these patterns, it is omitted.
414 Controlled by -I. Multiple -I options accumulate.
415 The -B option adds `*~' and `.*~' to this list. */
417 struct ignore_pattern
419 char *pattern;
420 struct ignore_pattern *next;
423 static struct ignore_pattern *ignore_patterns;
425 /* Nonzero means quote nongraphic chars in file names. -b */
427 static int quote_funny_chars;
429 /* Nonzero means output nongraphic chars in file names as `?'. -q */
431 static int qmark_funny_chars;
433 /* Nonzero means output each file name using C syntax for a string.
434 Always accompanied by `quote_funny_chars'.
435 This mode, together with -x or -C or -m,
436 and without such frills as -F or -s,
437 is guaranteed to make it possible for a program receiving
438 the output to tell exactly what file names are present. -Q */
440 static int quote_as_string;
442 /* The number of chars per hardware tab stop. -T */
443 static int tabsize;
445 /* Nonzero means we are listing the working directory because no
446 non-option arguments were given. */
448 static int dir_defaulted;
450 /* Nonzero means print each directory name before listing it. */
452 static int print_dir_name;
454 /* The line length to use for breaking lines in many-per-line format.
455 Can be set with -w. */
457 static int line_length;
459 /* If nonzero, the file listing format requires that stat be called on
460 each file. */
462 static int format_needs_stat;
464 /* The exit status to use if we don't get any fatal errors. */
466 static int exit_status;
468 /* If nonzero, display usage information and exit. */
469 static int show_help;
471 /* If nonzero, print the version on standard output and exit. */
472 static int show_version;
474 static struct option const long_options[] =
476 {"all", no_argument, 0, 'a'},
477 {"escape", no_argument, 0, 'b'},
478 {"directory", no_argument, 0, 'd'},
479 {"dired", no_argument, 0, 'D'},
480 {"full-time", no_argument, &full_time, 1},
481 {"inode", no_argument, 0, 'i'},
482 {"kilobytes", no_argument, 0, 'k'},
483 {"numeric-uid-gid", no_argument, 0, 'n'},
484 {"no-group", no_argument, 0, 'G'},
485 {"hide-control-chars", no_argument, 0, 'q'},
486 {"reverse", no_argument, 0, 'r'},
487 {"size", no_argument, 0, 's'},
488 {"width", required_argument, 0, 'w'},
489 {"almost-all", no_argument, 0, 'A'},
490 {"ignore-backups", no_argument, 0, 'B'},
491 {"classify", no_argument, 0, 'F'},
492 {"file-type", no_argument, 0, 'F'},
493 {"ignore", required_argument, 0, 'I'},
494 {"dereference", no_argument, 0, 'L'},
495 {"literal", no_argument, 0, 'N'},
496 {"quote-name", no_argument, 0, 'Q'},
497 {"recursive", no_argument, 0, 'R'},
498 {"format", required_argument, 0, 12},
499 {"sort", required_argument, 0, 10},
500 {"tabsize", required_argument, 0, 'T'},
501 {"time", required_argument, 0, 11},
502 {"help", no_argument, &show_help, 1},
503 {"version", no_argument, &show_version, 1},
504 {"color", optional_argument, 0, 13},
505 {"7bit", no_argument, 0, '7'},
506 {"8bit", no_argument, 0, '8'},
507 {0, 0, 0, 0}
510 static char const *const format_args[] =
512 "verbose", "long", "commas", "horizontal", "across",
513 "vertical", "single-column", 0
516 static enum format const formats[] =
518 long_format, long_format, with_commas, horizontal, horizontal,
519 many_per_line, one_per_line
522 static char const *const sort_args[] =
524 "none", "time", "size", "extension", 0
527 static enum sort_type const sort_types[] =
529 sort_none, sort_time, sort_size, sort_extension
532 static char const *const time_args[] =
534 "atime", "access", "use", "ctime", "status", 0
537 /* This zero-based index is used solely with the --dired option.
538 When that option is in effect, this counter is incremented for each
539 character of output generated by this program so that the beginning
540 and ending indices (in that output) of every file name can be recorded
541 and later output themselves. */
542 static size_t dired_pos;
544 #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
546 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
547 #define FPUTS(s, stream, s_len) \
548 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
550 /* Like FPUTS, but for use when S is a literal string. */
551 #define FPUTS_LITERAL(s, stream) \
552 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
554 #define DIRED_INDENT() \
555 do \
557 /* FIXME: remove the `&& format == long_format' clause. */ \
558 if (dired && format == long_format) \
559 FPUTS_LITERAL (" ", stdout); \
561 while (0)
563 /* With --dired, store pairs of beginning and ending indices of filenames. */
564 static struct obstack dired_obstack;
566 /* With --dired, store pairs of beginning and ending indices of any
567 directory names that appear as headers (just before `total' line)
568 for lists of directory entries. Such directory names are seen when
569 listing hierarchies using -R and when a directory is listed with at
570 least one other command line argument. */
571 static struct obstack subdired_obstack;
573 /* Save the current index on the specified obstack, OBS. */
574 #define PUSH_CURRENT_DIRED_POS(obs) \
575 do \
577 /* FIXME: remove the `&& format == long_format' clause. */ \
578 if (dired && format == long_format) \
579 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
581 while (0)
583 static enum time_type const time_types[] =
585 time_atime, time_atime, time_atime, time_ctime, time_ctime
588 static char const *const color_args[] =
590 /* Note: "no" is a prefix of "none" so we don't include it */
591 "yes", "force", "none", "tty", "if-tty"
594 static enum color_type const color_types[] =
596 color_yes, color_yes, color_no, color_if_tty, color_if_tty
599 /* Write to standard output the string PREFIX followed by a space-separated
600 list of the integers stored in OS all on one line. */
602 static void
603 dired_dump_obstack (const char *prefix, struct obstack *os)
605 int n_pos;
607 n_pos = obstack_object_size (os) / sizeof (size_t);
608 if (n_pos > 0)
610 int i;
611 size_t *pos;
613 pos = (size_t *) obstack_finish (os);
614 fputs (prefix, stdout);
615 for (i = 0; i < n_pos; i++)
616 printf (" %d", (int) pos[i]);
617 fputs ("\n", stdout);
621 void
622 main (int argc, char **argv)
624 register int i;
625 register struct pending *thispend;
627 exit_status = 0;
628 dir_defaulted = 1;
629 print_dir_name = 1;
630 pending_dirs = 0;
631 current_time = time ((time_t *) 0);
633 program_name = argv[0];
634 i = decode_switches (argc, argv);
636 if (show_version)
638 printf ("ls - %s\n", version_string);
639 exit (0);
642 if (show_help)
643 usage (0);
645 format_needs_stat = sort_type == sort_time || sort_type == sort_size
646 || format == long_format
647 || trace_links || trace_dirs || indicator_style != none
648 || print_block_size || print_inode || print_with_color;
650 if (dired && format == long_format)
652 obstack_init (&dired_obstack);
653 obstack_init (&subdired_obstack);
656 nfiles = 100;
657 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
658 files_index = 0;
660 clear_files ();
662 if (i < argc)
663 dir_defaulted = 0;
664 for (; i < argc; i++)
665 gobble_file (argv[i], 1, "");
667 if (dir_defaulted)
669 if (immediate_dirs)
670 gobble_file (".", 1, "");
671 else
672 queue_directory (".", 0);
675 if (files_index)
677 sort_files ();
678 if (!immediate_dirs)
679 extract_dirs_from_files ("", 0);
680 /* `files_index' might be zero now. */
682 if (files_index)
684 print_current_files ();
685 if (pending_dirs)
686 PUTCHAR ('\n');
688 else if (pending_dirs && pending_dirs->next == 0)
689 print_dir_name = 0;
691 while (pending_dirs)
693 thispend = pending_dirs;
694 pending_dirs = pending_dirs->next;
695 print_dir (thispend->name, thispend->realname);
696 free (thispend->name);
697 if (thispend->realname)
698 free (thispend->realname);
699 free (thispend);
700 print_dir_name = 1;
703 if (dired && format == long_format)
705 /* No need to free these since we're about to exit. */
706 dired_dump_obstack ("//DIRED//", &dired_obstack);
707 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
710 exit (exit_status);
713 /* Set all the option flags according to the switches specified.
714 Return the index of the first non-option argument. */
716 static int
717 decode_switches (int argc, char **argv)
719 register char *p;
720 int c;
721 int i;
723 qmark_funny_chars = 0;
724 quote_funny_chars = 0;
726 /* initialize all switches to default settings */
728 switch (ls_mode)
730 case LS_MULTI_COL:
731 /* This is for the `dir' program. */
732 format = many_per_line;
733 quote_funny_chars = 1;
734 break;
736 case LS_LONG_FORMAT:
737 /* This is for the `vdir' program. */
738 format = long_format;
739 quote_funny_chars = 1;
740 break;
742 case LS_LS:
743 /* This is for the `ls' program. */
744 if (isatty (1))
746 format = many_per_line;
747 qmark_funny_chars = 1;
749 else
751 format = one_per_line;
752 qmark_funny_chars = 0;
754 break;
756 default:
757 abort ();
760 time_type = time_mtime;
761 full_time = 0;
762 sort_type = sort_name;
763 sort_reverse = 0;
764 numeric_users = 0;
765 print_block_size = 0;
766 kilobyte_blocks = getenv ("POSIXLY_CORRECT") == 0;
767 indicator_style = none;
768 print_inode = 0;
769 trace_links = 0;
770 trace_dirs = 0;
771 immediate_dirs = 0;
772 all_files = 0;
773 really_all_files = 0;
774 ignore_patterns = 0;
775 quote_as_string = 0;
776 print_with_color = 0;
777 print_iso8859 = DEFAULT_ISO8859;
779 p = getenv ("COLUMNS");
780 line_length = p ? atoi (p) : 80;
782 #ifdef TIOCGWINSZ
784 struct winsize ws;
786 if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
787 line_length = ws.ws_col;
789 #endif
791 /* FIXME: reference TABSIZE iff !posix_pedantic. */
792 p = getenv ("TABSIZE");
793 /* FIXME: use strtol here! */
794 tabsize = p ? atoi (p) : 8;
795 if (tabsize < 1)
797 error (0, 0,
798 _("ignoring invalid tab size in enironment variable TABSIZE: %s"),
799 optarg);
800 tabsize = 8;
803 while ((c = getopt_long (argc, argv,
804 "abcdfgiklmnopqrstuw:xABCDFGI:LNQRST:UX178",
805 long_options, (int *) 0)) != EOF)
807 switch (c)
809 case 0:
810 break;
812 case 'a':
813 all_files = 1;
814 really_all_files = 1;
815 break;
817 case 'b':
818 quote_funny_chars = 1;
819 qmark_funny_chars = 0;
820 break;
822 case 'c':
823 time_type = time_ctime;
824 sort_type = sort_time;
825 break;
827 case 'd':
828 immediate_dirs = 1;
829 break;
831 case 'f':
832 /* Same as enabling -a -U and disabling -l -s. */
833 all_files = 1;
834 really_all_files = 1;
835 sort_type = sort_none;
836 /* disable -l */
837 if (format == long_format)
838 format = (isatty (1) ? many_per_line : one_per_line);
839 print_block_size = 0; /* disable -s */
840 break;
842 case 'g':
843 /* No effect. For BSD compatibility. */
844 break;
846 case 'i':
847 print_inode = 1;
848 break;
850 case 'k':
851 kilobyte_blocks = 1;
852 break;
854 case 'l':
855 format = long_format;
856 break;
858 case 'm':
859 format = with_commas;
860 break;
862 case 'n':
863 numeric_users = 1;
864 break;
866 case 'o': /* Just like -l, but don't display group info. */
867 format = long_format;
868 inhibit_group = 1;
869 break;
871 case 13: /* --color */
872 if (optarg)
874 i = argmatch (optarg, color_args);
875 if (i < 0)
877 invalid_arg (_("colorization criterion"), optarg, i);
878 usage (1);
880 i = color_types[i];
882 else
883 i = color_yes; /* --color -> do colorize */
885 if (i == color_if_tty)
886 print_with_color = isatty (1) ? 1 : 0;
887 else
888 print_with_color = i;
890 if (print_with_color)
892 /* Don't use TAB characters in output. Some terminal
893 emulators can't handle the combination of tabs and
894 color codes on the same line. */
895 tabsize = line_length;
897 break;
899 case 'p':
900 indicator_style = not_programs;
901 break;
903 case 'q':
904 qmark_funny_chars = 1;
905 quote_funny_chars = 0;
906 break;
908 case 'r':
909 sort_reverse = 1;
910 break;
912 case 's':
913 print_block_size = 1;
914 break;
916 case 't':
917 sort_type = sort_time;
918 break;
920 case 'u':
921 time_type = time_atime;
922 break;
924 case 'w':
925 line_length = atoi (optarg);
926 if (line_length < 1)
927 error (1, 0, _("invalid line width: %s"), optarg);
928 break;
930 case 'x':
931 format = horizontal;
932 break;
934 case 'A':
935 all_files = 1;
936 break;
938 case 'B':
939 add_ignore_pattern ("*~");
940 add_ignore_pattern (".*~");
941 break;
943 case 'C':
944 format = many_per_line;
945 break;
947 case 'D':
948 dired = 1;
949 break;
951 case 'F':
952 indicator_style = all;
953 break;
955 case 'G': /* inhibit display of group info */
956 inhibit_group = 1;
957 break;
959 case 'I':
960 add_ignore_pattern (optarg);
961 break;
963 case 'L':
964 trace_links = 1;
965 break;
967 case 'N':
968 quote_funny_chars = 0;
969 qmark_funny_chars = 0;
970 break;
972 case 'Q':
973 quote_as_string = 1;
974 quote_funny_chars = 1;
975 qmark_funny_chars = 0;
976 break;
978 case 'R':
979 trace_dirs = 1;
980 break;
982 case 'S':
983 sort_type = sort_size;
984 break;
986 case 'T':
987 tabsize = atoi (optarg);
988 if (tabsize < 1)
989 error (1, 0, _("invalid tab size: %s"), optarg);
990 break;
992 case 'U':
993 sort_type = sort_none;
994 break;
996 case 'X':
997 sort_type = sort_extension;
998 break;
1000 case '1':
1001 format = one_per_line;
1002 break;
1004 case '7':
1005 print_iso8859 = 0;
1006 break;
1008 case '8':
1009 print_iso8859 = 1;
1010 break;
1012 case 10: /* --sort */
1013 i = argmatch (optarg, sort_args);
1014 if (i < 0)
1016 invalid_arg (_("sort type"), optarg, i);
1017 usage (1);
1019 sort_type = sort_types[i];
1020 break;
1022 case 11: /* --time */
1023 i = argmatch (optarg, time_args);
1024 if (i < 0)
1026 invalid_arg (_("time type"), optarg, i);
1027 usage (1);
1029 time_type = time_types[i];
1030 break;
1032 case 12: /* --format */
1033 i = argmatch (optarg, format_args);
1034 if (i < 0)
1036 invalid_arg (_("format type"), optarg, i);
1037 usage (1);
1039 format = formats[i];
1040 break;
1042 default:
1043 usage (1);
1047 if (print_with_color)
1049 parse_ls_color ();
1052 return optind;
1055 /* Parse the LS_COLORS/LS_COLOURS variable */
1057 static void
1058 parse_ls_color (void)
1060 register char *p; /* Pointer to character being parsed */
1061 char *whichvar; /* LS_COLORS or LS_COLOURS? */
1062 int state; /* State of parser */
1063 int ind_no; /* Indicator number */
1064 int ccount; /* Character count */
1065 int num; /* Escape char numeral */
1066 char label[3]; /* Indicator label */
1068 strcpy (label, "??");
1069 if ((p = getenv (whichvar = "LS_COLORS")) ||
1070 (p = getenv (whichvar = "LS_COLOURS")))
1072 state = 1;
1073 while (state > 0)
1075 switch (state)
1077 case 1: /* First label character */
1078 if (*p)
1080 label[0] = *(p++);
1081 state = 2;
1083 else
1084 state = 0; /* Done */
1085 break;
1087 case 2: /* Second label character */
1088 if (*p)
1090 label[1] = *(p++);
1091 state = 3;
1093 else
1094 state = -1; /* Error */
1095 break;
1097 case 3: /* Should be equal sign */
1098 if (*(p++) != '=')
1099 state = -1; /* Error state */
1100 else
1102 ind_no = 0;
1103 state = -1; /* In case we fail */
1104 while (indicator_name[ind_no] != NULL)
1106 if (strcmp (label, indicator_name[ind_no]) == 0)
1108 state = 4; /* We found it */
1109 ccount = 0; /* Nothing stored yet */
1110 break;
1112 else
1113 ind_no++;
1116 break;
1118 case 4: /* Character to store */
1119 switch (*p)
1121 case ':':
1122 color_indicator[ind_no].len = ccount;
1123 state = 1;
1124 break;
1125 case '\\':
1126 /* The escape sequence will always generate a character,
1127 so enter error state if the buffer is full */
1128 state = (ccount >= MAXCOLORLEN) ? -1 : 5;
1129 break;
1130 case '^':
1131 /* Control character in the ^X notation */
1132 state = (ccount >= MAXCOLORLEN) ? -1 : 8;
1133 break;
1134 case '\0':
1135 color_indicator[ind_no].len = ccount;
1136 state = 0; /* Done */
1137 break;
1138 default:
1139 if (ccount >= MAXCOLORLEN)
1140 state = -1; /* Too long */
1141 else
1142 color_indicator[ind_no].string[ccount++] = *p;
1144 p++;
1145 break;
1147 case 5: /* Escape character */
1148 num = -1;
1149 switch (*p)
1151 case '0':
1152 case '1':
1153 case '2':
1154 case '3':
1155 case '4':
1156 case '5':
1157 case '6':
1158 case '7':
1159 state = 6; /* Octal numeral */
1160 num = *p - '0';
1161 break;
1162 case 'x':
1163 case 'X':
1164 state = 7; /* Hex numeral */
1165 num = 0;
1166 break;
1167 case 'a': /* Bell */
1168 num = 7;
1169 break;
1170 case 'b': /* Backspace */
1171 num = '\b';
1172 break;
1173 case 'e': /* Escape */
1174 num = 27;
1175 break;
1176 case 'f': /* Formfeed */
1177 num = '\f';
1178 break;
1179 case 'n': /* Newline */
1180 num = '\n';
1181 break;
1182 case 'r': /* Return */
1183 num = '\r';
1184 break;
1185 case 't': /* Tab */
1186 num = '\t';
1187 break;
1188 case 'v': /* Vtab */
1189 num = '\v';
1190 break;
1191 case '?': /* Delete */
1192 num = 127;
1193 break;
1194 case '\0': /* End of string */
1195 state = -1; /* Error */
1196 break;
1197 default: /* Escaped character */
1198 num = *p;
1199 break;
1201 if (state == 5)
1203 color_indicator[ind_no].string[ccount++] = num;
1204 state = 4;
1206 p++;
1207 break;
1209 case 6: /* Octal numeral */
1210 switch (*p)
1212 case ':':
1213 case '\0':
1214 color_indicator[ind_no].string[ccount++] = num;
1215 color_indicator[ind_no].len = ccount;
1216 state = (*(p++) == ':') ? 1 : 0;
1217 p++;
1218 break;
1219 case '0':
1220 case '1':
1221 case '2':
1222 case '3':
1223 case '4':
1224 case '5':
1225 case '6':
1226 case '7':
1227 num = (num << 3) + (*(p++) - '0');
1228 break;
1229 default:
1230 color_indicator[ind_no].string[ccount++] = num;
1231 state = 4;
1232 break;
1234 break;
1236 case 7: /* Hex numeral */
1237 switch (*p)
1239 case ':':
1240 case '\0':
1241 color_indicator[ind_no].string[ccount++] = num;
1242 color_indicator[ind_no].len = ccount;
1243 state = (*(p++) == ':') ? 1 : 0;
1244 break;
1245 case '0':
1246 case '1':
1247 case '2':
1248 case '3':
1249 case '4':
1250 case '5':
1251 case '6':
1252 case '7':
1253 case '8':
1254 case '9':
1255 num = (num << 4) + (*(p++) - '0');
1256 break;
1257 case 'A':
1258 case 'B':
1259 case 'C':
1260 case 'D':
1261 case 'E':
1262 case 'F':
1263 num = (num << 4) + (*(p++) - 'A' + 10);
1264 break;
1265 case 'a':
1266 case 'b':
1267 case 'c':
1268 case 'd':
1269 case 'e':
1270 case 'f':
1271 num = (num << 4) + (*(p++) - 'a' + 10);
1272 break;
1273 default:
1274 color_indicator[ind_no].string[ccount++] = num;
1275 state = 4;
1276 break;
1278 break;
1280 case 8: /* ^ notation */
1281 state = 4; /* Usually the next state */
1282 if (*p >= '@' && *p <= '~')
1283 color_indicator[ind_no].string[ccount++] = *p & 037;
1284 else if (*p == '?')
1285 color_indicator[ind_no].string[ccount++] = 127;
1286 else
1287 state = -1; /* Error */
1288 p++;
1289 break;
1293 if (state < 0)
1295 error (0, 0, _("bad %s variable\n"), whichvar);
1296 print_with_color = 0;
1301 /* Request that the directory named `name' have its contents listed later.
1302 If `realname' is nonzero, it will be used instead of `name' when the
1303 directory name is printed. This allows symbolic links to directories
1304 to be treated as regular directories but still be listed under their
1305 real names. */
1307 static void
1308 queue_directory (char *name, char *realname)
1310 struct pending *new;
1312 new = (struct pending *) xmalloc (sizeof (struct pending));
1313 new->next = pending_dirs;
1314 pending_dirs = new;
1315 new->name = xstrdup (name);
1316 if (realname)
1317 new->realname = xstrdup (realname);
1318 else
1319 new->realname = 0;
1322 /* Read directory `name', and list the files in it.
1323 If `realname' is nonzero, print its name instead of `name';
1324 this is used for symbolic links to directories. */
1326 static void
1327 print_dir (const char *name, const char *realname)
1329 register DIR *reading;
1330 register struct dirent *next;
1331 register int total_blocks = 0;
1333 errno = 0;
1334 reading = opendir (name);
1335 if (!reading)
1337 error (0, errno, "%s", name);
1338 exit_status = 1;
1339 return;
1342 /* Read the directory entries, and insert the subfiles into the `files'
1343 table. */
1345 clear_files ();
1347 while ((next = readdir (reading)) != NULL)
1348 if (file_interesting (next))
1349 total_blocks += gobble_file (next->d_name, 0, name);
1351 if (CLOSEDIR (reading))
1353 error (0, errno, "%s", name);
1354 exit_status = 1;
1355 /* Don't return; print whatever we got. */
1358 /* Sort the directory contents. */
1359 sort_files ();
1361 /* If any member files are subdirectories, perhaps they should have their
1362 contents listed rather than being mentioned here as files. */
1364 if (trace_dirs)
1365 extract_dirs_from_files (name, 1);
1367 if (print_dir_name)
1369 const char *dir;
1371 DIRED_INDENT ();
1372 dir = (realname ? realname : name);
1373 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1374 FPUTS (dir, stdout, strlen (dir));
1375 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1376 FPUTS_LITERAL (":\n", stdout);
1379 if (format == long_format || print_block_size)
1381 char buf[6 + 20 + 1 + 1];
1383 DIRED_INDENT ();
1384 sprintf (buf, "total %u\n", total_blocks);
1385 FPUTS (buf, stdout, strlen (buf));
1388 if (files_index)
1389 print_current_files ();
1391 if (pending_dirs)
1392 PUTCHAR ('\n');
1395 /* Add `pattern' to the list of patterns for which files that match are
1396 not listed. */
1398 static void
1399 add_ignore_pattern (char *pattern)
1401 register struct ignore_pattern *ignore;
1403 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1404 ignore->pattern = pattern;
1405 /* Add it to the head of the linked list. */
1406 ignore->next = ignore_patterns;
1407 ignore_patterns = ignore;
1410 /* Return nonzero if the file in `next' should be listed. */
1412 static int
1413 file_interesting (register struct dirent *next)
1415 register struct ignore_pattern *ignore;
1417 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1418 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1419 return 0;
1421 if (really_all_files
1422 || next->d_name[0] != '.'
1423 || (all_files
1424 && next->d_name[1] != '\0'
1425 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1426 return 1;
1428 return 0;
1431 /* Enter and remove entries in the table `files'. */
1433 /* Empty the table of files. */
1435 static void
1436 clear_files (void)
1438 register int i;
1440 for (i = 0; i < files_index; i++)
1442 free (files[i].name);
1443 if (files[i].linkname)
1444 free (files[i].linkname);
1447 files_index = 0;
1448 block_size_size = 4;
1451 /* Add a file to the current table of files.
1452 Verify that the file exists, and print an error message if it does not.
1453 Return the number of blocks that the file occupies. */
1455 static int
1456 gobble_file (const char *name, int explicit_arg, const char *dirname)
1458 register int blocks;
1459 register int val;
1460 register char *path;
1462 if (files_index == nfiles)
1464 nfiles *= 2;
1465 files = (struct fileinfo *) xrealloc (files, sizeof (*files) * nfiles);
1468 files[files_index].linkname = 0;
1469 files[files_index].linkmode = 0;
1471 if (explicit_arg || format_needs_stat)
1473 /* `path' is the absolute pathname of this file. */
1475 if (name[0] == '/' || dirname[0] == 0)
1476 path = (char *) name;
1477 else
1479 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1480 attach (path, dirname, name);
1483 if (trace_links)
1485 val = stat (path, &files[files_index].stat);
1486 if (val < 0)
1487 /* Perhaps a symbolically-linked to file doesn't exist; stat
1488 the link instead. */
1489 val = lstat (path, &files[files_index].stat);
1491 else
1492 val = lstat (path, &files[files_index].stat);
1493 if (val < 0)
1495 error (0, errno, "%s", path);
1496 exit_status = 1;
1497 return 0;
1500 #ifdef S_ISLNK
1501 if (S_ISLNK (files[files_index].stat.st_mode)
1502 && (explicit_arg || format == long_format))
1504 char *linkpath;
1505 struct stat linkstats;
1507 get_link_name (path, &files[files_index]);
1508 linkpath = make_link_path (path, files[files_index].linkname);
1510 /* Avoid following symbolic links when possible, ie, when
1511 they won't be traced and when no indicator is needed. */
1512 if (linkpath
1513 && ((explicit_arg && format != long_format)
1514 || indicator_style != none || print_with_color)
1515 && stat (linkpath, &linkstats) == 0)
1517 /* Symbolic links to directories that are mentioned on the
1518 command line are automatically traced if not being
1519 listed as files. */
1520 if (explicit_arg && format != long_format
1521 && S_ISDIR (linkstats.st_mode))
1523 /* Substitute the linked-to directory's name, but
1524 save the real name in `linkname' for printing. */
1525 if (!immediate_dirs)
1527 const char *tempname = name;
1528 name = linkpath;
1529 linkpath = files[files_index].linkname;
1530 files[files_index].linkname = (char *) tempname;
1532 files[files_index].stat = linkstats;
1534 else
1535 /* Get the linked-to file's mode for the filetype indicator
1536 in long listings. */
1537 files[files_index].linkmode = linkstats.st_mode;
1539 if (linkpath)
1540 free (linkpath);
1542 #endif
1544 #ifdef S_ISLNK
1545 if (S_ISLNK (files[files_index].stat.st_mode))
1546 files[files_index].filetype = symbolic_link;
1547 else
1548 #endif
1549 if (S_ISDIR (files[files_index].stat.st_mode))
1551 if (explicit_arg && !immediate_dirs)
1552 files[files_index].filetype = arg_directory;
1553 else
1554 files[files_index].filetype = directory;
1556 else
1557 files[files_index].filetype = normal;
1559 blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
1560 kilobyte_blocks);
1561 if (blocks >= 10000 && block_size_size < 5)
1562 block_size_size = 5;
1563 if (blocks >= 100000 && block_size_size < 6)
1564 block_size_size = 6;
1565 if (blocks >= 1000000 && block_size_size < 7)
1566 block_size_size = 7;
1568 else
1569 blocks = 0;
1571 files[files_index].name = xstrdup (name);
1572 files_index++;
1574 return blocks;
1577 #ifdef S_ISLNK
1579 /* Put the name of the file that `filename' is a symbolic link to
1580 into the `linkname' field of `f'. */
1582 static void
1583 get_link_name (char *filename, struct fileinfo *f)
1585 char *linkbuf;
1586 register int linksize;
1588 linkbuf = (char *) alloca (PATH_MAX + 2);
1589 /* Some automounters give incorrect st_size for mount points.
1590 I can't think of a good workaround for it, though. */
1591 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1592 if (linksize < 0)
1594 error (0, errno, "%s", filename);
1595 exit_status = 1;
1597 else
1599 linkbuf[linksize] = '\0';
1600 f->linkname = xstrdup (linkbuf);
1604 /* If `linkname' is a relative path and `path' contains one or more
1605 leading directories, return `linkname' with those directories
1606 prepended; otherwise, return a copy of `linkname'.
1607 If `linkname' is zero, return zero. */
1609 static char *
1610 make_link_path (char *path, char *linkname)
1612 char *linkbuf;
1613 int bufsiz;
1615 if (linkname == 0)
1616 return 0;
1618 if (*linkname == '/')
1619 return xstrdup (linkname);
1621 /* The link is to a relative path. Prepend any leading path
1622 in `path' to the link name. */
1623 linkbuf = strrchr (path, '/');
1624 if (linkbuf == 0)
1625 return xstrdup (linkname);
1627 bufsiz = linkbuf - path + 1;
1628 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1629 strncpy (linkbuf, path, bufsiz);
1630 strcpy (linkbuf + bufsiz, linkname);
1631 return linkbuf;
1633 #endif
1635 /* Remove any entries from `files' that are for directories,
1636 and queue them to be listed as directories instead.
1637 `dirname' is the prefix to prepend to each dirname
1638 to make it correct relative to ls's working dir.
1639 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1640 This is desirable when processing directories recursively. */
1642 static void
1643 extract_dirs_from_files (const char *dirname, int recursive)
1645 register int i, j;
1646 register char *path;
1647 int dirlen;
1649 dirlen = strlen (dirname) + 2;
1650 /* Queue the directories last one first, because queueing reverses the
1651 order. */
1652 for (i = files_index - 1; i >= 0; i--)
1653 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1654 && (!recursive || is_not_dot_or_dotdot (files[i].name)))
1656 if (files[i].name[0] == '/' || dirname[0] == 0)
1658 queue_directory (files[i].name, files[i].linkname);
1660 else
1662 path = (char *) xmalloc (strlen (files[i].name) + dirlen);
1663 attach (path, dirname, files[i].name);
1664 queue_directory (path, files[i].linkname);
1665 free (path);
1667 if (files[i].filetype == arg_directory)
1668 free (files[i].name);
1671 /* Now delete the directories from the table, compacting all the remaining
1672 entries. */
1674 for (i = 0, j = 0; i < files_index; i++)
1675 if (files[i].filetype != arg_directory)
1676 files[j++] = files[i];
1677 files_index = j;
1680 /* Return nonzero if `name' doesn't end in `.' or `..'
1681 This is so we don't try to recurse on `././././. ...' */
1683 static int
1684 is_not_dot_or_dotdot (char *name)
1686 char *t;
1688 t = strrchr (name, '/');
1689 if (t)
1690 name = t + 1;
1692 if (name[0] == '.'
1693 && (name[1] == '\0'
1694 || (name[1] == '.' && name[2] == '\0')))
1695 return 0;
1697 return 1;
1700 /* Sort the files now in the table. */
1702 static void
1703 sort_files (void)
1705 int (*func) ();
1707 switch (sort_type)
1709 case sort_none:
1710 return;
1711 case sort_time:
1712 switch (time_type)
1714 case time_ctime:
1715 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1716 break;
1717 case time_mtime:
1718 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1719 break;
1720 case time_atime:
1721 func = sort_reverse ? rev_cmp_atime : compare_atime;
1722 break;
1723 default:
1724 abort ();
1726 break;
1727 case sort_name:
1728 func = sort_reverse ? rev_cmp_name : compare_name;
1729 break;
1730 case sort_extension:
1731 func = sort_reverse ? rev_cmp_extension : compare_extension;
1732 break;
1733 case sort_size:
1734 func = sort_reverse ? rev_cmp_size : compare_size;
1735 break;
1736 default:
1737 abort ();
1740 qsort (files, files_index, sizeof (struct fileinfo), func);
1743 /* Comparison routines for sorting the files. */
1745 static int
1746 compare_ctime (struct fileinfo *file1, struct fileinfo *file2)
1748 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1751 static int
1752 rev_cmp_ctime (struct fileinfo *file2, struct fileinfo *file1)
1754 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1757 static int
1758 compare_mtime (struct fileinfo *file1, struct fileinfo *file2)
1760 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1763 static int
1764 rev_cmp_mtime (struct fileinfo *file2, struct fileinfo *file1)
1766 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1769 static int
1770 compare_atime (struct fileinfo *file1, struct fileinfo *file2)
1772 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1775 static int
1776 rev_cmp_atime (struct fileinfo *file2, struct fileinfo *file1)
1778 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1781 static int
1782 compare_size (struct fileinfo *file1, struct fileinfo *file2)
1784 return longdiff (file2->stat.st_size, file1->stat.st_size);
1787 static int
1788 rev_cmp_size (struct fileinfo *file2, struct fileinfo *file1)
1790 return longdiff (file2->stat.st_size, file1->stat.st_size);
1793 static int
1794 compare_name (struct fileinfo *file1, struct fileinfo *file2)
1796 return strcmp (file1->name, file2->name);
1799 static int
1800 rev_cmp_name (struct fileinfo *file2, struct fileinfo *file1)
1802 return strcmp (file1->name, file2->name);
1805 /* Compare file extensions. Files with no extension are `smallest'.
1806 If extensions are the same, compare by filenames instead. */
1808 static int
1809 compare_extension (struct fileinfo *file1, struct fileinfo *file2)
1811 register char *base1, *base2;
1812 register int cmp;
1814 base1 = strrchr (file1->name, '.');
1815 base2 = strrchr (file2->name, '.');
1816 if (base1 == 0 && base2 == 0)
1817 return strcmp (file1->name, file2->name);
1818 if (base1 == 0)
1819 return -1;
1820 if (base2 == 0)
1821 return 1;
1822 cmp = strcmp (base1, base2);
1823 if (cmp == 0)
1824 return strcmp (file1->name, file2->name);
1825 return cmp;
1828 static int
1829 rev_cmp_extension (struct fileinfo *file2, struct fileinfo *file1)
1831 register char *base1, *base2;
1832 register int cmp;
1834 base1 = strrchr (file1->name, '.');
1835 base2 = strrchr (file2->name, '.');
1836 if (base1 == 0 && base2 == 0)
1837 return strcmp (file1->name, file2->name);
1838 if (base1 == 0)
1839 return -1;
1840 if (base2 == 0)
1841 return 1;
1842 cmp = strcmp (base1, base2);
1843 if (cmp == 0)
1844 return strcmp (file1->name, file2->name);
1845 return cmp;
1848 /* List all the files now in the table. */
1850 static void
1851 print_current_files (void)
1853 register int i;
1855 switch (format)
1857 case one_per_line:
1858 for (i = 0; i < files_index; i++)
1860 print_file_name_and_frills (files + i);
1861 putchar ('\n');
1863 break;
1865 case many_per_line:
1866 print_many_per_line ();
1867 break;
1869 case horizontal:
1870 print_horizontal ();
1871 break;
1873 case with_commas:
1874 print_with_commas ();
1875 break;
1877 case long_format:
1878 for (i = 0; i < files_index; i++)
1880 print_long_format (files + i);
1881 PUTCHAR ('\n');
1883 break;
1887 static void
1888 print_long_format (struct fileinfo *f)
1890 char modebuf[20];
1891 char timebuf[40];
1893 /* 7 fields that may (worst case be 64-bit integral values) require 20 bytes,
1894 10 character mode field,
1895 24 characters for the time,
1896 9 spaces following each of these fields,
1897 and 1 trailing NUL byte. */
1898 char bigbuf[7 * 20 + 10 + 24 + 9 + 1];
1899 char *p;
1900 time_t when;
1902 mode_string (f->stat.st_mode, modebuf);
1903 modebuf[10] = '\0';
1905 switch (time_type)
1907 case time_ctime:
1908 when = f->stat.st_ctime;
1909 break;
1910 case time_mtime:
1911 when = f->stat.st_mtime;
1912 break;
1913 case time_atime:
1914 when = f->stat.st_atime;
1915 break;
1918 strcpy (timebuf, ctime (&when));
1920 if (full_time)
1921 timebuf[24] = '\0';
1922 else
1924 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
1925 || current_time < when - 60L * 60L) /* In the future. */
1927 /* The file is fairly old or in the future.
1928 POSIX says the cutoff is 6 months old;
1929 approximate this by 6*30 days.
1930 Allow a 1 hour slop factor for what is considered "the future",
1931 to allow for NFS server/client clock disagreement.
1932 Show the year instead of the time of day. */
1933 strcpy (timebuf + 11, timebuf + 19);
1935 timebuf[16] = 0;
1938 p = bigbuf;
1940 if (print_inode)
1942 sprintf (p, "%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
1943 p += strlen (p);
1946 if (print_block_size)
1948 sprintf (p, "%*u ", block_size_size,
1949 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
1950 kilobyte_blocks));
1951 p += strlen (p);
1954 /* The space between the mode and the number of links is the POSIX
1955 "optional alternate access method flag". */
1956 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
1957 p += strlen (p);
1959 if (numeric_users)
1960 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
1961 else
1962 sprintf (p, "%-8.8s ", getuser (f->stat.st_uid));
1963 p += strlen (p);
1965 if (!inhibit_group)
1967 if (numeric_users)
1968 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
1969 else
1970 sprintf (p, "%-8.8s ", getgroup (f->stat.st_gid));
1971 p += strlen (p);
1974 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
1975 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
1976 (unsigned) minor (f->stat.st_rdev));
1977 else
1978 sprintf (p, "%8lu ", (unsigned long) f->stat.st_size);
1979 p += strlen (p);
1981 sprintf (p, "%s ", full_time ? timebuf : timebuf + 4);
1982 p += strlen (p);
1984 DIRED_INDENT ();
1985 FPUTS (bigbuf, stdout, p - bigbuf);
1986 PUSH_CURRENT_DIRED_POS (&dired_obstack);
1987 if (print_with_color)
1988 print_color_indicator (f->stat.st_mode);
1989 print_name_with_quoting (f->name);
1990 if (print_with_color)
1991 put_indicator (C_END);
1992 PUSH_CURRENT_DIRED_POS (&dired_obstack);
1994 if (f->filetype == symbolic_link)
1996 if (f->linkname)
1998 FPUTS_LITERAL (" -> ", stdout);
1999 if (print_with_color)
2000 print_color_indicator (f->linkmode);
2001 print_name_with_quoting (f->linkname);
2002 if (print_with_color)
2003 put_indicator (C_END);
2004 if (indicator_style != none)
2005 print_type_indicator (f->linkmode);
2008 else if (indicator_style != none)
2009 print_type_indicator (f->stat.st_mode);
2012 /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
2013 Otherwise, return xmalloc'd storage containing the quoted version
2014 of P and set QUOTED_LENGTH to the length of the quoted P. */
2016 static char *
2017 quote_filename (register const char *p, size_t *quoted_length)
2019 register unsigned char c;
2020 const char *p0 = p;
2021 char *quoted, *q;
2022 int found_quotable;
2024 if (!quote_as_string && !quote_funny_chars && !qmark_funny_chars)
2026 *quoted_length = strlen (p);
2027 return NULL;
2030 found_quotable = 0;
2031 for (c = *p; c; c = *++p)
2033 if (quote_funny_chars)
2035 switch (c)
2037 case '\\':
2038 case '\n':
2039 case '\b':
2040 case '\r':
2041 case '\t':
2042 case '\f':
2043 case ' ':
2044 case '"':
2045 found_quotable = 1;
2046 break;
2048 default:
2049 /* FIXME: why not just use the ISPRINT macro here? */
2050 if (!((c > 040 && c < 0177)
2051 || (print_iso8859 && c >= 0200 && c <= 0377)))
2052 found_quotable = 1;
2053 break;
2056 else
2058 if (!((c >= 040 && c < 0177)
2059 || (print_iso8859 && c >= 0xA1 && c <= 0xFF))
2060 && qmark_funny_chars)
2061 found_quotable = 1;
2063 if (found_quotable)
2064 break;
2067 if (!found_quotable && !quote_as_string)
2069 *quoted_length = p - p0;
2070 return NULL;
2073 p = p0;
2074 quoted = xmalloc (4 * strlen (p) + 1);
2075 q = quoted;
2077 #define SAVECHAR(c) *q++ = (c)
2078 #define SAVE_2_CHARS(c12) \
2079 do { *q++ = ((c12)[0]); \
2080 *q++ = ((c12)[1]); } while (0)
2082 if (quote_as_string)
2083 SAVECHAR ('"');
2085 while ((c = *p++))
2087 if (quote_funny_chars)
2089 switch (c)
2091 case '\\':
2092 SAVE_2_CHARS ("\\\\");
2093 break;
2095 case '\n':
2096 SAVE_2_CHARS ("\\n");
2097 break;
2099 case '\b':
2100 SAVE_2_CHARS ("\\b");
2101 break;
2103 case '\r':
2104 SAVE_2_CHARS ("\\r");
2105 break;
2107 case '\t':
2108 SAVE_2_CHARS ("\\t");
2109 break;
2111 case '\f':
2112 SAVE_2_CHARS ("\\f");
2113 break;
2115 case ' ':
2116 SAVE_2_CHARS ("\\ ");
2117 break;
2119 case '"':
2120 SAVE_2_CHARS ("\\\"");
2121 break;
2123 default:
2124 if ((c > 040 && c < 0177)
2125 || (print_iso8859 && c >= 0200 && c <= 0377))
2126 SAVECHAR (c);
2127 else
2129 char buf[5];
2130 sprintf (buf, "\\%03o", (unsigned int) c);
2131 q = stpcpy (q, buf);
2135 else
2137 if ((c >= 040 && c < 0177)
2138 || (print_iso8859 && c >= 0200 && c <= 0377))
2139 SAVECHAR (c);
2140 else if (!qmark_funny_chars)
2141 SAVECHAR (c);
2142 else
2143 SAVECHAR ('?');
2147 if (quote_as_string)
2148 SAVECHAR ('"');
2150 *quoted_length = q - quoted;
2152 SAVECHAR ('\0');
2154 return quoted;
2157 static void
2158 print_name_with_quoting (register char *p)
2160 char *quoted;
2161 size_t quoted_length;
2163 quoted = quote_filename (p, &quoted_length);
2164 FPUTS (quoted != NULL ? quoted : p, stdout, quoted_length);
2165 if (quoted)
2166 free (quoted);
2169 /* Print the file name of `f' with appropriate quoting.
2170 Also print file size, inode number, and filetype indicator character,
2171 as requested by switches. */
2173 static void
2174 print_file_name_and_frills (struct fileinfo *f)
2176 if (print_inode)
2177 printf ("%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
2179 if (print_block_size)
2180 printf ("%*u ", block_size_size,
2181 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
2182 kilobyte_blocks));
2184 if (print_with_color)
2185 print_color_indicator (f->stat.st_mode);
2186 print_name_with_quoting (f->name);
2187 if (print_with_color)
2188 put_indicator (C_END);
2190 if (indicator_style != none)
2191 print_type_indicator (f->stat.st_mode);
2194 static void
2195 print_type_indicator (unsigned int mode)
2197 if (S_ISDIR (mode))
2198 PUTCHAR ('/');
2200 #ifdef S_ISLNK
2201 if (S_ISLNK (mode))
2202 PUTCHAR ('@');
2203 #endif
2205 #ifdef S_ISFIFO
2206 if (S_ISFIFO (mode))
2207 PUTCHAR ('|');
2208 #endif
2210 #ifdef S_ISSOCK
2211 if (S_ISSOCK (mode))
2212 PUTCHAR ('=');
2213 #endif
2215 if (S_ISREG (mode) && indicator_style == all
2216 && (mode & (S_IEXEC | S_IXGRP | S_IXOTH)))
2217 PUTCHAR ('*');
2220 static void
2221 print_color_indicator (unsigned int mode)
2223 int type = C_FILE;
2225 if (S_ISDIR (mode))
2226 type = C_DIR;
2228 #ifdef S_ISLNK
2229 else if (S_ISLNK (mode))
2230 type = C_LINK;
2231 #endif
2233 #ifdef S_ISFIFO
2234 else if (S_ISFIFO (mode))
2235 type = C_FIFO;
2236 #endif
2238 #ifdef S_ISSOCK
2239 else if (S_ISSOCK (mode))
2240 type = C_SOCK;
2241 #endif
2243 #ifdef S_ISBLK
2244 else if (S_ISBLK (mode))
2245 type = C_BLK;
2246 #endif
2248 #ifdef S_ISCHR
2249 else if (S_ISCHR (mode))
2250 type = C_CHR;
2251 #endif
2253 if (type == C_FILE && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
2254 type = C_EXEC;
2256 put_indicator (C_LEFT);
2257 put_indicator (type);
2258 put_indicator (C_RIGHT);
2261 /* Output a color indicator (which may contain nulls) */
2262 static void
2263 put_indicator (int n)
2265 register int i;
2266 register char *p;
2268 p = color_indicator[n].string;
2270 for (i = color_indicator[n].len; i; i--)
2272 putchar (*(p++));
2276 static int
2277 length_of_file_name_and_frills (struct fileinfo *f)
2279 register char *p = f->name;
2280 register unsigned char c;
2281 register int len = 0;
2283 if (print_inode)
2284 len += INODE_DIGITS + 1;
2286 if (print_block_size)
2287 len += 1 + block_size_size;
2289 if (quote_as_string)
2290 len += 2;
2292 while ((c = *p++))
2294 if (quote_funny_chars)
2296 switch (c)
2298 case '\\':
2299 case '\n':
2300 case '\b':
2301 case '\r':
2302 case '\t':
2303 case '\f':
2304 case ' ':
2305 len += 2;
2306 break;
2308 case '"':
2309 if (quote_as_string)
2310 len += 2;
2311 else
2312 len += 1;
2313 break;
2315 default:
2316 if ((c >= 040 && c < 0177)
2317 || (print_iso8859 && c >= 0200 && c <= 0377))
2318 len += 1;
2319 else
2320 len += 4;
2323 else
2324 len += 1;
2327 if (indicator_style != none)
2329 unsigned filetype = f->stat.st_mode;
2331 if (S_ISREG (filetype))
2333 if (indicator_style == all
2334 && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
2335 len += 1;
2337 else if (S_ISDIR (filetype)
2338 #ifdef S_ISLNK
2339 || S_ISLNK (filetype)
2340 #endif
2341 #ifdef S_ISFIFO
2342 || S_ISFIFO (filetype)
2343 #endif
2344 #ifdef S_ISSOCK
2345 || S_ISSOCK (filetype)
2346 #endif
2348 len += 1;
2351 return len;
2354 static void
2355 print_many_per_line (void)
2357 int filesno; /* Index into files. */
2358 int row; /* Current row. */
2359 int max_name_length; /* Length of longest file name + frills. */
2360 int name_length; /* Length of each file name + frills. */
2361 int pos; /* Current character column. */
2362 int cols; /* Number of files across. */
2363 int rows; /* Maximum number of files down. */
2365 /* Compute the maximum file name length. */
2366 max_name_length = 0;
2367 for (filesno = 0; filesno < files_index; filesno++)
2369 name_length = length_of_file_name_and_frills (files + filesno);
2370 if (name_length > max_name_length)
2371 max_name_length = name_length;
2374 /* Allow at least two spaces between names. */
2375 max_name_length += 2;
2377 /* Calculate the maximum number of columns that will fit. */
2378 cols = line_length / max_name_length;
2379 if (cols == 0)
2380 cols = 1;
2381 /* Calculate the number of rows that will be in each column except possibly
2382 for a short column on the right. */
2383 rows = files_index / cols + (files_index % cols != 0);
2384 /* Recalculate columns based on rows. */
2385 cols = files_index / rows + (files_index % rows != 0);
2387 for (row = 0; row < rows; row++)
2389 filesno = row;
2390 pos = 0;
2391 /* Print the next row. */
2392 while (1)
2394 print_file_name_and_frills (files + filesno);
2395 name_length = length_of_file_name_and_frills (files + filesno);
2397 filesno += rows;
2398 if (filesno >= files_index)
2399 break;
2401 indent (pos + name_length, pos + max_name_length);
2402 pos += max_name_length;
2404 putchar ('\n');
2408 static void
2409 print_horizontal (void)
2411 int filesno;
2412 int max_name_length;
2413 int name_length;
2414 int cols;
2415 int pos;
2417 /* Compute the maximum file name length. */
2418 max_name_length = 0;
2419 for (filesno = 0; filesno < files_index; filesno++)
2421 name_length = length_of_file_name_and_frills (files + filesno);
2422 if (name_length > max_name_length)
2423 max_name_length = name_length;
2426 /* Allow two spaces between names. */
2427 max_name_length += 2;
2429 cols = line_length / max_name_length;
2430 if (cols == 0)
2431 cols = 1;
2433 pos = 0;
2434 name_length = 0;
2436 for (filesno = 0; filesno < files_index; filesno++)
2438 if (filesno != 0)
2440 if (filesno % cols == 0)
2442 putchar ('\n');
2443 pos = 0;
2445 else
2447 indent (pos + name_length, pos + max_name_length);
2448 pos += max_name_length;
2452 print_file_name_and_frills (files + filesno);
2454 name_length = length_of_file_name_and_frills (files + filesno);
2456 putchar ('\n');
2459 static void
2460 print_with_commas (void)
2462 int filesno;
2463 int pos, old_pos;
2465 pos = 0;
2467 for (filesno = 0; filesno < files_index; filesno++)
2469 old_pos = pos;
2471 pos += length_of_file_name_and_frills (files + filesno);
2472 if (filesno + 1 < files_index)
2473 pos += 2; /* For the comma and space */
2475 if (old_pos != 0 && pos >= line_length)
2477 putchar ('\n');
2478 pos -= old_pos;
2481 print_file_name_and_frills (files + filesno);
2482 if (filesno + 1 < files_index)
2484 putchar (',');
2485 putchar (' ');
2488 putchar ('\n');
2491 /* Assuming cursor is at position FROM, indent up to position TO.
2492 Use a TAB character instead of two or more spaces whenever possible. */
2494 static void
2495 indent (int from, int to)
2497 while (from < to)
2499 if (to / tabsize > (from + 1) / tabsize)
2501 putchar ('\t');
2502 from += tabsize - from % tabsize;
2504 else
2506 putchar (' ');
2507 from++;
2512 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2514 static void
2515 attach (char *dest, const char *dirname, const char *name)
2517 const char *dirnamep = dirname;
2519 /* Copy dirname if it is not ".". */
2520 if (dirname[0] != '.' || dirname[1] != 0)
2522 while (*dirnamep)
2523 *dest++ = *dirnamep++;
2524 /* Add '/' if `dirname' doesn't already end with it. */
2525 if (dirnamep > dirname && dirnamep[-1] != '/')
2526 *dest++ = '/';
2528 while (*name)
2529 *dest++ = *name++;
2530 *dest = 0;
2533 static void
2534 usage (int status)
2536 if (status != 0)
2537 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2538 program_name);
2539 else
2541 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2542 printf (_("\
2543 List information about the FILEs (the current directory by default).\n\
2544 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2546 -A, --almost-all do not list implied . and ..\n\
2547 -a, --all do not hide entries starting with .\n\
2548 -B, --ignore-backups do not list implied entries ending with ~\n\
2549 -b, --escape print octal escapes for nongraphic characters\n\
2550 -C list entries by columns\n\
2551 -c sort by change time; with -l: show ctime\n\
2552 --color colorize entries according to type\n\
2553 --color=WORD yes, no, tty (if output is a terminal)\n\
2554 -D, --dired generate output well suited to Emacs' dired mode\n\
2555 -d, --directory list directory entries instead of contents\n\
2556 -F, --classify append a character for typing each entry\n\
2557 -f do not sort, enable -aU, disable -lst\n\
2558 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2559 single-column -1, verbose -l, vertical -C\n\
2560 --full-time list both full date and full time\n"));
2562 printf (_("\
2563 -G, --no-group inhibit display of group information\n\
2564 -g (ignored)\n\
2565 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2566 -i, --inode print index number of each file\n\
2567 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
2568 -L, --dereference list entries pointed to by symbolic links\n\
2569 -l use a long listing format\n\
2570 -m fill width with a comma separated list of entries\n\
2571 -N, --literal do not quote entry names\n\
2572 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2573 -o use long listing format without group info\n\
2574 -p append a character for typing each entry\n\
2575 -Q, --quote-name enclose entry names in double quotes\n\
2576 -q, --hide-control-chars print ? instead of non graphic characters\n\
2577 -R, --recursive list subdirectories recursively\n\
2578 -r, --reverse reverse order while sorting\n\
2579 -S sort by file size\n"));
2581 printf (_("\
2582 -s, --size print block size of each file\n\
2583 --sort=WORD ctime -c, extension -X, none -U, size -S,\n\
2584 status -c, time -t\n\
2585 --time=WORD atime -u, access -u, use -u\n\
2586 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2587 -t sort by modification time; with -l: show mtime\n\
2588 -U do not sort; list entries in directory order\n\
2589 -u sort by last access time; with -l: show atime\n\
2590 -w, --width=COLS assume screen width instead of current value\n\
2591 -x list entries by lines instead of by columns\n\
2592 -X sort alphabetically by entry extension\n\
2593 -1 list one file per line\n\
2594 -7, --7bit allow only 7-bit ASCII characters to be printed\n\
2595 -8, --8bit allow 8-bit ISO 8859 characters to be printed\n\
2596 --help display this help and exit\n\
2597 --version output version information and exit"));
2599 exit (status);