.
[coreutils.git] / src / ls.c
blobe1efb9cd7269d5c53d22d4c7bb36e43dd1a0b10c
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"
66 #define obstack_chunk_alloc xmalloc
67 #define obstack_chunk_free free
69 #ifndef INT_MAX
70 #define INT_MAX 2147483647
71 #endif
73 /* Return an int indicating the result of comparing two longs. */
74 #if (INT_MAX <= 65535)
75 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
76 #else
77 #define longdiff(a, b) ((a) - (b))
78 #endif
80 /* The maximum number of digits required to print an inode number
81 in an unsigned format. */
82 #ifndef INODE_DIGITS
83 #define INODE_DIGITS 7
84 #endif
86 enum filetype
88 symbolic_link,
89 directory,
90 arg_directory, /* Directory given as command line arg. */
91 normal /* All others. */
94 struct fileinfo
96 /* The file name. */
97 char *name;
99 struct stat stat;
101 /* For symbolic link, name of the file linked to, otherwise zero. */
102 char *linkname;
104 /* For symbolic link and long listing, st_mode of file linked to, otherwise
105 zero. */
106 unsigned int linkmode;
108 enum filetype filetype;
111 #ifndef STDC_HEADERS
112 char *ctime ();
113 time_t time ();
114 void free ();
115 #endif
117 void mode_string ();
119 char *stpcpy ();
120 char *xstrdup ();
121 char *getgroup ();
122 char *getuser ();
123 char *xmalloc ();
124 char *xrealloc ();
125 int argmatch ();
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, 'o'},
505 {"colour", optional_argument, 0, 'o'},
506 {"7bit", no_argument, 0, '7'},
507 {"8bit", no_argument, 0, '8'},
508 {0, 0, 0, 0}
511 static char const *const format_args[] =
513 "verbose", "long", "commas", "horizontal", "across",
514 "vertical", "single-column", 0
517 static enum format const formats[] =
519 long_format, long_format, with_commas, horizontal, horizontal,
520 many_per_line, one_per_line
523 static char const *const sort_args[] =
525 "none", "time", "size", "extension", 0
528 static enum sort_type const sort_types[] =
530 sort_none, sort_time, sort_size, sort_extension
533 static char const *const time_args[] =
535 "atime", "access", "use", "ctime", "status", 0
538 /* This zero-based index is used solely with the --dired option.
539 When that option is in effect, this counter is incremented for each
540 character of output generated by this program so that the beginning
541 and ending indices (in that output) of every file name can be recorded
542 and later output themselves. */
543 static size_t dired_pos;
545 #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
547 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
548 #define FPUTS(s, stream, s_len) \
549 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
551 /* Like FPUTS, but for use when S is a literal string. */
552 #define FPUTS_LITERAL(s, stream) \
553 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
555 #define DIRED_INDENT() \
556 do \
558 /* FIXME: remove the `&& format == long_format' clause. */ \
559 if (dired && format == long_format) \
560 FPUTS_LITERAL (" ", stdout); \
562 while (0)
564 /* With --dired, store pairs of beginning and ending indices of filenames. */
565 static struct obstack dired_obstack;
567 /* With --dired, store pairs of beginning and ending indices of any
568 directory names that appear as headers (just before `total' line)
569 for lists of directory entries. Such directory names are seen when
570 listing hierarchies using -R and when a directory is listed with at
571 least one other command line argument. */
572 static struct obstack subdired_obstack;
574 /* Save the current index on the specified obstack, OBS. */
575 #define PUSH_CURRENT_DIRED_POS(obs) \
576 do \
578 /* FIXME: remove the `&& format == long_format' clause. */ \
579 if (dired && format == long_format) \
580 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
582 while (0)
584 static enum time_type const time_types[] =
586 time_atime, time_atime, time_atime, time_ctime, time_ctime
589 static char const *const color_args[] =
591 /* Note: "no" is a prefix of "none" so we don't include it */
592 "yes", "force", "none", "tty", "if-tty"
595 static enum color_type const color_types[] =
597 color_yes, color_yes, color_no, color_if_tty, color_if_tty
600 /* Write to standard output the string PREFIX followed by a space-separated
601 list of the integers stored in OS all on one line. */
603 static void
604 dired_dump_obstack (const char *prefix, struct obstack *os)
606 int n_pos;
608 n_pos = obstack_object_size (os) / sizeof (size_t);
609 if (n_pos > 0)
611 int i;
612 size_t *pos;
614 pos = (size_t *) obstack_finish (os);
615 fputs (prefix, stdout);
616 for (i = 0; i < n_pos; i++)
617 printf (" %d", (int) pos[i]);
618 fputs ("\n", stdout);
622 void
623 main (int argc, char **argv)
625 register int i;
626 register struct pending *thispend;
628 exit_status = 0;
629 dir_defaulted = 1;
630 print_dir_name = 1;
631 pending_dirs = 0;
632 current_time = time ((time_t *) 0);
634 program_name = argv[0];
635 i = decode_switches (argc, argv);
637 if (show_version)
639 printf ("ls - %s\n", version_string);
640 exit (0);
643 if (show_help)
644 usage (0);
646 format_needs_stat = sort_type == sort_time || sort_type == sort_size
647 || format == long_format
648 || trace_links || trace_dirs || indicator_style != none
649 || print_block_size || print_inode || print_with_color;
651 if (dired && format == long_format)
653 obstack_init (&dired_obstack);
654 obstack_init (&subdired_obstack);
657 nfiles = 100;
658 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
659 files_index = 0;
661 clear_files ();
663 if (i < argc)
664 dir_defaulted = 0;
665 for (; i < argc; i++)
666 gobble_file (argv[i], 1, "");
668 if (dir_defaulted)
670 if (immediate_dirs)
671 gobble_file (".", 1, "");
672 else
673 queue_directory (".", 0);
676 if (files_index)
678 sort_files ();
679 if (!immediate_dirs)
680 extract_dirs_from_files ("", 0);
681 /* `files_index' might be zero now. */
683 if (files_index)
685 print_current_files ();
686 if (pending_dirs)
687 PUTCHAR ('\n');
689 else if (pending_dirs && pending_dirs->next == 0)
690 print_dir_name = 0;
692 while (pending_dirs)
694 thispend = pending_dirs;
695 pending_dirs = pending_dirs->next;
696 print_dir (thispend->name, thispend->realname);
697 free (thispend->name);
698 if (thispend->realname)
699 free (thispend->realname);
700 free (thispend);
701 print_dir_name = 1;
704 if (dired && format == long_format)
706 /* No need to free these since we're about to exit. */
707 dired_dump_obstack ("//DIRED//", &dired_obstack);
708 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
711 exit (exit_status);
714 /* Set all the option flags according to the switches specified.
715 Return the index of the first non-option argument. */
717 static int
718 decode_switches (int argc, char **argv)
720 register char *p;
721 int c;
722 int i;
724 qmark_funny_chars = 0;
725 quote_funny_chars = 0;
727 /* initialize all switches to default settings */
729 switch (ls_mode)
731 case LS_MULTI_COL:
732 /* This is for the `dir' program. */
733 format = many_per_line;
734 quote_funny_chars = 1;
735 break;
737 case LS_LONG_FORMAT:
738 /* This is for the `vdir' program. */
739 format = long_format;
740 quote_funny_chars = 1;
741 break;
743 case LS_LS:
744 /* This is for the `ls' program. */
745 if (isatty (1))
747 format = many_per_line;
748 qmark_funny_chars = 1;
750 else
752 format = one_per_line;
753 qmark_funny_chars = 0;
755 break;
757 default:
758 abort ();
761 time_type = time_mtime;
762 full_time = 0;
763 sort_type = sort_name;
764 sort_reverse = 0;
765 numeric_users = 0;
766 print_block_size = 0;
767 kilobyte_blocks = getenv ("POSIXLY_CORRECT") == 0;
768 indicator_style = none;
769 print_inode = 0;
770 trace_links = 0;
771 trace_dirs = 0;
772 immediate_dirs = 0;
773 all_files = 0;
774 really_all_files = 0;
775 ignore_patterns = 0;
776 quote_as_string = 0;
777 print_with_color = 0;
778 print_iso8859 = DEFAULT_ISO8859;
780 p = getenv ("COLUMNS");
781 line_length = p ? atoi (p) : 80;
783 #ifdef TIOCGWINSZ
785 struct winsize ws;
787 if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
788 line_length = ws.ws_col;
790 #endif
792 /* FIXME: reference TABSIZE iff !posix_pedantic. */
793 p = getenv ("TABSIZE");
794 /* FIXME: use strtol here! */
795 tabsize = p ? atoi (p) : 8;
796 if (tabsize < 1)
798 error (0, 0,
799 _("ignoring invalid tab size in enironment variable TABSIZE: %s"),
800 optarg);
801 tabsize = 8;
804 while ((c = getopt_long (argc, argv,
805 "abcdfgiklmnopqrstuw:xABCDFGI:LNQRST:UX178",
806 long_options, (int *) 0)) != EOF)
808 switch (c)
810 case 0:
811 break;
813 case 'a':
814 all_files = 1;
815 really_all_files = 1;
816 break;
818 case 'b':
819 quote_funny_chars = 1;
820 qmark_funny_chars = 0;
821 break;
823 case 'c':
824 time_type = time_ctime;
825 sort_type = sort_time;
826 break;
828 case 'd':
829 immediate_dirs = 1;
830 break;
832 case 'f':
833 /* Same as enabling -a -U and disabling -l -s. */
834 all_files = 1;
835 really_all_files = 1;
836 sort_type = sort_none;
837 /* disable -l */
838 if (format == long_format)
839 format = (isatty (1) ? many_per_line : one_per_line);
840 print_block_size = 0; /* disable -s */
841 break;
843 case 'g':
844 /* No effect. For BSD compatibility. */
845 break;
847 case 'i':
848 print_inode = 1;
849 break;
851 case 'k':
852 kilobyte_blocks = 1;
853 break;
855 case 'l':
856 format = long_format;
857 break;
859 case 'm':
860 format = with_commas;
861 break;
863 case 'n':
864 numeric_users = 1;
865 break;
867 case 'o':
868 if (optarg)
870 i = argmatch (optarg, color_args);
871 if (i < 0)
873 invalid_arg (_("colorization criterion"), optarg, i);
874 usage (1);
876 i = color_types[i];
878 else
879 i = color_yes; /* -o or --color -> do colorize */
881 if (i == color_if_tty)
882 print_with_color = isatty (1) ? 1 : 0;
883 else
884 print_with_color = i;
886 if (print_with_color)
888 /* Don't use TAB characters in output. Some terminal
889 emulators can't handle the combination of tabs and
890 color codes on the same line. */
891 tabsize = line_length;
893 break;
895 case 'p':
896 indicator_style = not_programs;
897 break;
899 case 'q':
900 qmark_funny_chars = 1;
901 quote_funny_chars = 0;
902 break;
904 case 'r':
905 sort_reverse = 1;
906 break;
908 case 's':
909 print_block_size = 1;
910 break;
912 case 't':
913 sort_type = sort_time;
914 break;
916 case 'u':
917 time_type = time_atime;
918 break;
920 case 'w':
921 line_length = atoi (optarg);
922 if (line_length < 1)
923 error (1, 0, _("invalid line width: %s"), optarg);
924 break;
926 case 'x':
927 format = horizontal;
928 break;
930 case 'A':
931 all_files = 1;
932 break;
934 case 'B':
935 add_ignore_pattern ("*~");
936 add_ignore_pattern (".*~");
937 break;
939 case 'C':
940 format = many_per_line;
941 break;
943 case 'D':
944 dired = 1;
945 break;
947 case 'F':
948 indicator_style = all;
949 break;
951 case 'G': /* inhibit display of group info */
952 inhibit_group = 1;
953 break;
955 case 'I':
956 add_ignore_pattern (optarg);
957 break;
959 case 'L':
960 trace_links = 1;
961 break;
963 case 'N':
964 quote_funny_chars = 0;
965 qmark_funny_chars = 0;
966 break;
968 case 'Q':
969 quote_as_string = 1;
970 quote_funny_chars = 1;
971 qmark_funny_chars = 0;
972 break;
974 case 'R':
975 trace_dirs = 1;
976 break;
978 case 'S':
979 sort_type = sort_size;
980 break;
982 case 'T':
983 tabsize = atoi (optarg);
984 if (tabsize < 1)
985 error (1, 0, _("invalid tab size: %s"), optarg);
986 break;
988 case 'U':
989 sort_type = sort_none;
990 break;
992 case 'X':
993 sort_type = sort_extension;
994 break;
996 case '1':
997 format = one_per_line;
998 break;
1000 case '7':
1001 print_iso8859 = 0;
1002 break;
1004 case '8':
1005 print_iso8859 = 1;
1006 break;
1008 case 10: /* --sort */
1009 i = argmatch (optarg, sort_args);
1010 if (i < 0)
1012 invalid_arg (_("sort type"), optarg, i);
1013 usage (1);
1015 sort_type = sort_types[i];
1016 break;
1018 case 11: /* --time */
1019 i = argmatch (optarg, time_args);
1020 if (i < 0)
1022 invalid_arg (_("time type"), optarg, i);
1023 usage (1);
1025 time_type = time_types[i];
1026 break;
1028 case 12: /* --format */
1029 i = argmatch (optarg, format_args);
1030 if (i < 0)
1032 invalid_arg (_("format type"), optarg, i);
1033 usage (1);
1035 format = formats[i];
1036 break;
1038 default:
1039 usage (1);
1043 if (print_with_color)
1045 parse_ls_color ();
1048 return optind;
1051 /* Parse the LS_COLORS/LS_COLOURS variable */
1053 static void
1054 parse_ls_color (void)
1056 register char *p; /* Pointer to character being parsed */
1057 char *whichvar; /* LS_COLORS or LS_COLOURS? */
1058 int state; /* State of parser */
1059 int ind_no; /* Indicator number */
1060 int ccount; /* Character count */
1061 int num; /* Escape char numeral */
1062 char label[3]; /* Indicator label */
1064 strcpy (label, "??");
1065 if ((p = getenv (whichvar = "LS_COLORS")) ||
1066 (p = getenv (whichvar = "LS_COLOURS")))
1068 state = 1;
1069 while (state > 0)
1071 switch (state)
1073 case 1: /* First label character */
1074 if (*p)
1076 label[0] = *(p++);
1077 state = 2;
1079 else
1080 state = 0; /* Done */
1081 break;
1083 case 2: /* Second label character */
1084 if (*p)
1086 label[1] = *(p++);
1087 state = 3;
1089 else
1090 state = -1; /* Error */
1091 break;
1093 case 3: /* Should be equal sign */
1094 if (*(p++) != '=')
1095 state = -1; /* Error state */
1096 else
1098 ind_no = 0;
1099 state = -1; /* In case we fail */
1100 while (indicator_name[ind_no] != NULL)
1102 if (strcmp (label, indicator_name[ind_no]) == 0)
1104 state = 4; /* We found it */
1105 ccount = 0; /* Nothing stored yet */
1106 break;
1108 else
1109 ind_no++;
1112 break;
1114 case 4: /* Character to store */
1115 switch (*p)
1117 case ':':
1118 color_indicator[ind_no].len = ccount;
1119 state = 1;
1120 break;
1121 case '\\':
1122 /* The escape sequence will always generate a character,
1123 so enter error state if the buffer is full */
1124 state = (ccount >= MAXCOLORLEN) ? -1 : 5;
1125 break;
1126 case '^':
1127 /* Control character in the ^X notation */
1128 state = (ccount >= MAXCOLORLEN) ? -1 : 8;
1129 break;
1130 case '\0':
1131 color_indicator[ind_no].len = ccount;
1132 state = 0; /* Done */
1133 break;
1134 default:
1135 if (ccount >= MAXCOLORLEN)
1136 state = -1; /* Too long */
1137 else
1138 color_indicator[ind_no].string[ccount++] = *p;
1140 p++;
1141 break;
1143 case 5: /* Escape character */
1144 num = -1;
1145 switch (*p)
1147 case '0':
1148 case '1':
1149 case '2':
1150 case '3':
1151 case '4':
1152 case '5':
1153 case '6':
1154 case '7':
1155 state = 6; /* Octal numeral */
1156 num = *p - '0';
1157 break;
1158 case 'x':
1159 case 'X':
1160 state = 7; /* Hex numeral */
1161 num = 0;
1162 break;
1163 case 'a': /* Bell */
1164 num = 7;
1165 break;
1166 case 'b': /* Backspace */
1167 num = '\b';
1168 break;
1169 case 'e': /* Escape */
1170 num = 27;
1171 break;
1172 case 'f': /* Formfeed */
1173 num = '\f';
1174 break;
1175 case 'n': /* Newline */
1176 num = '\n';
1177 break;
1178 case 'r': /* Return */
1179 num = '\r';
1180 break;
1181 case 't': /* Tab */
1182 num = '\t';
1183 break;
1184 case 'v': /* Vtab */
1185 num = '\v';
1186 break;
1187 case '?': /* Delete */
1188 num = 127;
1189 break;
1190 case '\0': /* End of string */
1191 state = -1; /* Error */
1192 break;
1193 default: /* Escaped character */
1194 num = *p;
1195 break;
1197 if (state == 5)
1199 color_indicator[ind_no].string[ccount++] = num;
1200 state = 4;
1202 p++;
1203 break;
1205 case 6: /* Octal numeral */
1206 switch (*p)
1208 case ':':
1209 case '\0':
1210 color_indicator[ind_no].string[ccount++] = num;
1211 color_indicator[ind_no].len = ccount;
1212 state = (*(p++) == ':') ? 1 : 0;
1213 p++;
1214 break;
1215 case '0':
1216 case '1':
1217 case '2':
1218 case '3':
1219 case '4':
1220 case '5':
1221 case '6':
1222 case '7':
1223 num = (num << 3) + (*(p++) - '0');
1224 break;
1225 default:
1226 color_indicator[ind_no].string[ccount++] = num;
1227 state = 4;
1228 break;
1230 break;
1232 case 7: /* Hex numeral */
1233 switch (*p)
1235 case ':':
1236 case '\0':
1237 color_indicator[ind_no].string[ccount++] = num;
1238 color_indicator[ind_no].len = ccount;
1239 state = (*(p++) == ':') ? 1 : 0;
1240 break;
1241 case '0':
1242 case '1':
1243 case '2':
1244 case '3':
1245 case '4':
1246 case '5':
1247 case '6':
1248 case '7':
1249 case '8':
1250 case '9':
1251 num = (num << 4) + (*(p++) - '0');
1252 break;
1253 case 'A':
1254 case 'B':
1255 case 'C':
1256 case 'D':
1257 case 'E':
1258 case 'F':
1259 num = (num << 4) + (*(p++) - 'A' + 10);
1260 break;
1261 case 'a':
1262 case 'b':
1263 case 'c':
1264 case 'd':
1265 case 'e':
1266 case 'f':
1267 num = (num << 4) + (*(p++) - 'a' + 10);
1268 break;
1269 default:
1270 color_indicator[ind_no].string[ccount++] = num;
1271 state = 4;
1272 break;
1274 break;
1276 case 8: /* ^ notation */
1277 state = 4; /* Usually the next state */
1278 if (*p >= '@' && *p <= '~')
1279 color_indicator[ind_no].string[ccount++] = *p & 037;
1280 else if (*p == '?')
1281 color_indicator[ind_no].string[ccount++] = 127;
1282 else
1283 state = -1; /* Error */
1284 p++;
1285 break;
1289 if (state < 0)
1291 error (0, 0, _("bad %s variable\n"), whichvar);
1292 print_with_color = 0;
1297 /* Request that the directory named `name' have its contents listed later.
1298 If `realname' is nonzero, it will be used instead of `name' when the
1299 directory name is printed. This allows symbolic links to directories
1300 to be treated as regular directories but still be listed under their
1301 real names. */
1303 static void
1304 queue_directory (char *name, char *realname)
1306 struct pending *new;
1308 new = (struct pending *) xmalloc (sizeof (struct pending));
1309 new->next = pending_dirs;
1310 pending_dirs = new;
1311 new->name = xstrdup (name);
1312 if (realname)
1313 new->realname = xstrdup (realname);
1314 else
1315 new->realname = 0;
1318 /* Read directory `name', and list the files in it.
1319 If `realname' is nonzero, print its name instead of `name';
1320 this is used for symbolic links to directories. */
1322 static void
1323 print_dir (const char *name, const char *realname)
1325 register DIR *reading;
1326 register struct dirent *next;
1327 register int total_blocks = 0;
1329 errno = 0;
1330 reading = opendir (name);
1331 if (!reading)
1333 error (0, errno, "%s", name);
1334 exit_status = 1;
1335 return;
1338 /* Read the directory entries, and insert the subfiles into the `files'
1339 table. */
1341 clear_files ();
1343 while ((next = readdir (reading)) != NULL)
1344 if (file_interesting (next))
1345 total_blocks += gobble_file (next->d_name, 0, name);
1347 if (CLOSEDIR (reading))
1349 error (0, errno, "%s", name);
1350 exit_status = 1;
1351 /* Don't return; print whatever we got. */
1354 /* Sort the directory contents. */
1355 sort_files ();
1357 /* If any member files are subdirectories, perhaps they should have their
1358 contents listed rather than being mentioned here as files. */
1360 if (trace_dirs)
1361 extract_dirs_from_files (name, 1);
1363 if (print_dir_name)
1365 const char *dir;
1367 DIRED_INDENT ();
1368 dir = (realname ? realname : name);
1369 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1370 FPUTS (dir, stdout, strlen (dir));
1371 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1372 FPUTS_LITERAL (":\n", stdout);
1375 if (format == long_format || print_block_size)
1377 char buf[6 + 20 + 1 + 1];
1379 DIRED_INDENT ();
1380 sprintf (buf, "total %u\n", total_blocks);
1381 FPUTS (buf, stdout, strlen (buf));
1384 if (files_index)
1385 print_current_files ();
1387 if (pending_dirs)
1388 PUTCHAR ('\n');
1391 /* Add `pattern' to the list of patterns for which files that match are
1392 not listed. */
1394 static void
1395 add_ignore_pattern (char *pattern)
1397 register struct ignore_pattern *ignore;
1399 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1400 ignore->pattern = pattern;
1401 /* Add it to the head of the linked list. */
1402 ignore->next = ignore_patterns;
1403 ignore_patterns = ignore;
1406 /* Return nonzero if the file in `next' should be listed. */
1408 static int
1409 file_interesting (register struct dirent *next)
1411 register struct ignore_pattern *ignore;
1413 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1414 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1415 return 0;
1417 if (really_all_files
1418 || next->d_name[0] != '.'
1419 || (all_files
1420 && next->d_name[1] != '\0'
1421 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1422 return 1;
1424 return 0;
1427 /* Enter and remove entries in the table `files'. */
1429 /* Empty the table of files. */
1431 static void
1432 clear_files (void)
1434 register int i;
1436 for (i = 0; i < files_index; i++)
1438 free (files[i].name);
1439 if (files[i].linkname)
1440 free (files[i].linkname);
1443 files_index = 0;
1444 block_size_size = 4;
1447 /* Add a file to the current table of files.
1448 Verify that the file exists, and print an error message if it does not.
1449 Return the number of blocks that the file occupies. */
1451 static int
1452 gobble_file (const char *name, int explicit_arg, const char *dirname)
1454 register int blocks;
1455 register int val;
1456 register char *path;
1458 if (files_index == nfiles)
1460 nfiles *= 2;
1461 files = (struct fileinfo *) xrealloc (files, sizeof (*files) * nfiles);
1464 files[files_index].linkname = 0;
1465 files[files_index].linkmode = 0;
1467 if (explicit_arg || format_needs_stat)
1469 /* `path' is the absolute pathname of this file. */
1471 if (name[0] == '/' || dirname[0] == 0)
1472 path = (char *) name;
1473 else
1475 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1476 attach (path, dirname, name);
1479 if (trace_links)
1481 val = stat (path, &files[files_index].stat);
1482 if (val < 0)
1483 /* Perhaps a symbolically-linked to file doesn't exist; stat
1484 the link instead. */
1485 val = lstat (path, &files[files_index].stat);
1487 else
1488 val = lstat (path, &files[files_index].stat);
1489 if (val < 0)
1491 error (0, errno, "%s", path);
1492 exit_status = 1;
1493 return 0;
1496 #ifdef S_ISLNK
1497 if (S_ISLNK (files[files_index].stat.st_mode)
1498 && (explicit_arg || format == long_format))
1500 char *linkpath;
1501 struct stat linkstats;
1503 get_link_name (path, &files[files_index]);
1504 linkpath = make_link_path (path, files[files_index].linkname);
1506 /* Avoid following symbolic links when possible, ie, when
1507 they won't be traced and when no indicator is needed. */
1508 if (linkpath
1509 && ((explicit_arg && format != long_format)
1510 || indicator_style != none || print_with_color)
1511 && stat (linkpath, &linkstats) == 0)
1513 /* Symbolic links to directories that are mentioned on the
1514 command line are automatically traced if not being
1515 listed as files. */
1516 if (explicit_arg && format != long_format
1517 && S_ISDIR (linkstats.st_mode))
1519 /* Substitute the linked-to directory's name, but
1520 save the real name in `linkname' for printing. */
1521 if (!immediate_dirs)
1523 const char *tempname = name;
1524 name = linkpath;
1525 linkpath = files[files_index].linkname;
1526 files[files_index].linkname = (char *) tempname;
1528 files[files_index].stat = linkstats;
1530 else
1531 /* Get the linked-to file's mode for the filetype indicator
1532 in long listings. */
1533 files[files_index].linkmode = linkstats.st_mode;
1535 if (linkpath)
1536 free (linkpath);
1538 #endif
1540 #ifdef S_ISLNK
1541 if (S_ISLNK (files[files_index].stat.st_mode))
1542 files[files_index].filetype = symbolic_link;
1543 else
1544 #endif
1545 if (S_ISDIR (files[files_index].stat.st_mode))
1547 if (explicit_arg && !immediate_dirs)
1548 files[files_index].filetype = arg_directory;
1549 else
1550 files[files_index].filetype = directory;
1552 else
1553 files[files_index].filetype = normal;
1555 blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
1556 kilobyte_blocks);
1557 if (blocks >= 10000 && block_size_size < 5)
1558 block_size_size = 5;
1559 if (blocks >= 100000 && block_size_size < 6)
1560 block_size_size = 6;
1561 if (blocks >= 1000000 && block_size_size < 7)
1562 block_size_size = 7;
1564 else
1565 blocks = 0;
1567 files[files_index].name = xstrdup (name);
1568 files_index++;
1570 return blocks;
1573 #ifdef S_ISLNK
1575 /* Put the name of the file that `filename' is a symbolic link to
1576 into the `linkname' field of `f'. */
1578 static void
1579 get_link_name (char *filename, struct fileinfo *f)
1581 char *linkbuf;
1582 register int linksize;
1584 linkbuf = (char *) alloca (PATH_MAX + 2);
1585 /* Some automounters give incorrect st_size for mount points.
1586 I can't think of a good workaround for it, though. */
1587 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1588 if (linksize < 0)
1590 error (0, errno, "%s", filename);
1591 exit_status = 1;
1593 else
1595 linkbuf[linksize] = '\0';
1596 f->linkname = xstrdup (linkbuf);
1600 /* If `linkname' is a relative path and `path' contains one or more
1601 leading directories, return `linkname' with those directories
1602 prepended; otherwise, return a copy of `linkname'.
1603 If `linkname' is zero, return zero. */
1605 static char *
1606 make_link_path (char *path, char *linkname)
1608 char *linkbuf;
1609 int bufsiz;
1611 if (linkname == 0)
1612 return 0;
1614 if (*linkname == '/')
1615 return xstrdup (linkname);
1617 /* The link is to a relative path. Prepend any leading path
1618 in `path' to the link name. */
1619 linkbuf = strrchr (path, '/');
1620 if (linkbuf == 0)
1621 return xstrdup (linkname);
1623 bufsiz = linkbuf - path + 1;
1624 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1625 strncpy (linkbuf, path, bufsiz);
1626 strcpy (linkbuf + bufsiz, linkname);
1627 return linkbuf;
1629 #endif
1631 /* Remove any entries from `files' that are for directories,
1632 and queue them to be listed as directories instead.
1633 `dirname' is the prefix to prepend to each dirname
1634 to make it correct relative to ls's working dir.
1635 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1636 This is desirable when processing directories recursively. */
1638 static void
1639 extract_dirs_from_files (const char *dirname, int recursive)
1641 register int i, j;
1642 register char *path;
1643 int dirlen;
1645 dirlen = strlen (dirname) + 2;
1646 /* Queue the directories last one first, because queueing reverses the
1647 order. */
1648 for (i = files_index - 1; i >= 0; i--)
1649 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1650 && (!recursive || is_not_dot_or_dotdot (files[i].name)))
1652 if (files[i].name[0] == '/' || dirname[0] == 0)
1654 queue_directory (files[i].name, files[i].linkname);
1656 else
1658 path = (char *) xmalloc (strlen (files[i].name) + dirlen);
1659 attach (path, dirname, files[i].name);
1660 queue_directory (path, files[i].linkname);
1661 free (path);
1663 if (files[i].filetype == arg_directory)
1664 free (files[i].name);
1667 /* Now delete the directories from the table, compacting all the remaining
1668 entries. */
1670 for (i = 0, j = 0; i < files_index; i++)
1671 if (files[i].filetype != arg_directory)
1672 files[j++] = files[i];
1673 files_index = j;
1676 /* Return nonzero if `name' doesn't end in `.' or `..'
1677 This is so we don't try to recurse on `././././. ...' */
1679 static int
1680 is_not_dot_or_dotdot (char *name)
1682 char *t;
1684 t = strrchr (name, '/');
1685 if (t)
1686 name = t + 1;
1688 if (name[0] == '.'
1689 && (name[1] == '\0'
1690 || (name[1] == '.' && name[2] == '\0')))
1691 return 0;
1693 return 1;
1696 /* Sort the files now in the table. */
1698 static void
1699 sort_files (void)
1701 int (*func) ();
1703 switch (sort_type)
1705 case sort_none:
1706 return;
1707 case sort_time:
1708 switch (time_type)
1710 case time_ctime:
1711 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1712 break;
1713 case time_mtime:
1714 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1715 break;
1716 case time_atime:
1717 func = sort_reverse ? rev_cmp_atime : compare_atime;
1718 break;
1719 default:
1720 abort ();
1722 break;
1723 case sort_name:
1724 func = sort_reverse ? rev_cmp_name : compare_name;
1725 break;
1726 case sort_extension:
1727 func = sort_reverse ? rev_cmp_extension : compare_extension;
1728 break;
1729 case sort_size:
1730 func = sort_reverse ? rev_cmp_size : compare_size;
1731 break;
1732 default:
1733 abort ();
1736 qsort (files, files_index, sizeof (struct fileinfo), func);
1739 /* Comparison routines for sorting the files. */
1741 static int
1742 compare_ctime (struct fileinfo *file1, struct fileinfo *file2)
1744 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1747 static int
1748 rev_cmp_ctime (struct fileinfo *file2, struct fileinfo *file1)
1750 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1753 static int
1754 compare_mtime (struct fileinfo *file1, struct fileinfo *file2)
1756 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1759 static int
1760 rev_cmp_mtime (struct fileinfo *file2, struct fileinfo *file1)
1762 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1765 static int
1766 compare_atime (struct fileinfo *file1, struct fileinfo *file2)
1768 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1771 static int
1772 rev_cmp_atime (struct fileinfo *file2, struct fileinfo *file1)
1774 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1777 static int
1778 compare_size (struct fileinfo *file1, struct fileinfo *file2)
1780 return longdiff (file2->stat.st_size, file1->stat.st_size);
1783 static int
1784 rev_cmp_size (struct fileinfo *file2, struct fileinfo *file1)
1786 return longdiff (file2->stat.st_size, file1->stat.st_size);
1789 static int
1790 compare_name (struct fileinfo *file1, struct fileinfo *file2)
1792 return strcmp (file1->name, file2->name);
1795 static int
1796 rev_cmp_name (struct fileinfo *file2, struct fileinfo *file1)
1798 return strcmp (file1->name, file2->name);
1801 /* Compare file extensions. Files with no extension are `smallest'.
1802 If extensions are the same, compare by filenames instead. */
1804 static int
1805 compare_extension (struct fileinfo *file1, struct fileinfo *file2)
1807 register char *base1, *base2;
1808 register int cmp;
1810 base1 = strrchr (file1->name, '.');
1811 base2 = strrchr (file2->name, '.');
1812 if (base1 == 0 && base2 == 0)
1813 return strcmp (file1->name, file2->name);
1814 if (base1 == 0)
1815 return -1;
1816 if (base2 == 0)
1817 return 1;
1818 cmp = strcmp (base1, base2);
1819 if (cmp == 0)
1820 return strcmp (file1->name, file2->name);
1821 return cmp;
1824 static int
1825 rev_cmp_extension (struct fileinfo *file2, struct fileinfo *file1)
1827 register char *base1, *base2;
1828 register int cmp;
1830 base1 = strrchr (file1->name, '.');
1831 base2 = strrchr (file2->name, '.');
1832 if (base1 == 0 && base2 == 0)
1833 return strcmp (file1->name, file2->name);
1834 if (base1 == 0)
1835 return -1;
1836 if (base2 == 0)
1837 return 1;
1838 cmp = strcmp (base1, base2);
1839 if (cmp == 0)
1840 return strcmp (file1->name, file2->name);
1841 return cmp;
1844 /* List all the files now in the table. */
1846 static void
1847 print_current_files (void)
1849 register int i;
1851 switch (format)
1853 case one_per_line:
1854 for (i = 0; i < files_index; i++)
1856 print_file_name_and_frills (files + i);
1857 putchar ('\n');
1859 break;
1861 case many_per_line:
1862 print_many_per_line ();
1863 break;
1865 case horizontal:
1866 print_horizontal ();
1867 break;
1869 case with_commas:
1870 print_with_commas ();
1871 break;
1873 case long_format:
1874 for (i = 0; i < files_index; i++)
1876 print_long_format (files + i);
1877 PUTCHAR ('\n');
1879 break;
1883 static void
1884 print_long_format (struct fileinfo *f)
1886 char modebuf[20];
1887 char timebuf[40];
1889 /* 7 fields that may (worst case be 64-bit integral values) require 20 bytes,
1890 10 character mode field,
1891 24 characters for the time,
1892 9 spaces following each of these fields,
1893 and 1 trailing NUL byte. */
1894 char bigbuf[7 * 20 + 10 + 24 + 9 + 1];
1895 char *p;
1896 time_t when;
1898 mode_string (f->stat.st_mode, modebuf);
1899 modebuf[10] = '\0';
1901 switch (time_type)
1903 case time_ctime:
1904 when = f->stat.st_ctime;
1905 break;
1906 case time_mtime:
1907 when = f->stat.st_mtime;
1908 break;
1909 case time_atime:
1910 when = f->stat.st_atime;
1911 break;
1914 strcpy (timebuf, ctime (&when));
1916 if (full_time)
1917 timebuf[24] = '\0';
1918 else
1920 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
1921 || current_time < when - 60L * 60L) /* In the future. */
1923 /* The file is fairly old or in the future.
1924 POSIX says the cutoff is 6 months old;
1925 approximate this by 6*30 days.
1926 Allow a 1 hour slop factor for what is considered "the future",
1927 to allow for NFS server/client clock disagreement.
1928 Show the year instead of the time of day. */
1929 strcpy (timebuf + 11, timebuf + 19);
1931 timebuf[16] = 0;
1934 p = bigbuf;
1936 if (print_inode)
1938 sprintf (p, "%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
1939 p += strlen (p);
1942 if (print_block_size)
1944 sprintf (p, "%*u ", block_size_size,
1945 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
1946 kilobyte_blocks));
1947 p += strlen (p);
1950 /* The space between the mode and the number of links is the POSIX
1951 "optional alternate access method flag". */
1952 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
1953 p += strlen (p);
1955 if (numeric_users)
1956 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
1957 else
1958 sprintf (p, "%-8.8s ", getuser (f->stat.st_uid));
1959 p += strlen (p);
1961 if (!inhibit_group)
1963 if (numeric_users)
1964 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
1965 else
1966 sprintf (p, "%-8.8s ", getgroup (f->stat.st_gid));
1967 p += strlen (p);
1970 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
1971 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
1972 (unsigned) minor (f->stat.st_rdev));
1973 else
1974 sprintf (p, "%8lu ", (unsigned long) f->stat.st_size);
1975 p += strlen (p);
1977 sprintf (p, "%s ", full_time ? timebuf : timebuf + 4);
1978 p += strlen (p);
1980 DIRED_INDENT ();
1981 FPUTS (bigbuf, stdout, p - bigbuf);
1982 PUSH_CURRENT_DIRED_POS (&dired_obstack);
1983 if (print_with_color)
1984 print_color_indicator (f->stat.st_mode);
1985 print_name_with_quoting (f->name);
1986 if (print_with_color)
1987 put_indicator (C_END);
1988 PUSH_CURRENT_DIRED_POS (&dired_obstack);
1990 if (f->filetype == symbolic_link)
1992 if (f->linkname)
1994 FPUTS_LITERAL (" -> ", stdout);
1995 if (print_with_color)
1996 print_color_indicator (f->linkmode);
1997 print_name_with_quoting (f->linkname);
1998 if (print_with_color)
1999 put_indicator (C_END);
2000 if (indicator_style != none)
2001 print_type_indicator (f->linkmode);
2004 else if (indicator_style != none)
2005 print_type_indicator (f->stat.st_mode);
2008 /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
2009 Otherwise, return xmalloc'd storage containing the quoted version
2010 of P and set QUOTED_LENGTH to the length of the quoted P. */
2012 static char *
2013 quote_filename (register const char *p, size_t *quoted_length)
2015 register unsigned char c;
2016 const char *p0 = p;
2017 char *quoted, *q;
2018 int found_quotable;
2020 if (!quote_as_string && !quote_funny_chars && !qmark_funny_chars)
2022 *quoted_length = strlen (p);
2023 return NULL;
2026 found_quotable = 0;
2027 for (c = *p; c; c = *++p)
2029 if (quote_funny_chars)
2031 switch (c)
2033 case '\\':
2034 case '\n':
2035 case '\b':
2036 case '\r':
2037 case '\t':
2038 case '\f':
2039 case ' ':
2040 case '"':
2041 found_quotable = 1;
2042 break;
2044 default:
2045 /* FIXME: why not just use the ISPRINT macro here? */
2046 if (!((c > 040 && c < 0177)
2047 || (print_iso8859 && c >= 0200 && c <= 0377)))
2048 found_quotable = 1;
2049 break;
2052 else
2054 if (!((c >= 040 && c < 0177)
2055 || (print_iso8859 && c >= 0xA1 && c <= 0xFF))
2056 && qmark_funny_chars)
2057 found_quotable = 1;
2059 if (found_quotable)
2060 break;
2063 if (!found_quotable && !quote_as_string)
2065 *quoted_length = p - p0;
2066 return NULL;
2069 p = p0;
2070 quoted = xmalloc (4 * strlen (p) + 1);
2071 q = quoted;
2073 #define SAVECHAR(c) *q++ = (c)
2074 #define SAVE_2_CHARS(c12) \
2075 do { *q++ = ((c12)[0]); \
2076 *q++ = ((c12)[1]); } while (0)
2078 if (quote_as_string)
2079 SAVECHAR ('"');
2081 while ((c = *p++))
2083 if (quote_funny_chars)
2085 switch (c)
2087 case '\\':
2088 SAVE_2_CHARS ("\\\\");
2089 break;
2091 case '\n':
2092 SAVE_2_CHARS ("\\n");
2093 break;
2095 case '\b':
2096 SAVE_2_CHARS ("\\b");
2097 break;
2099 case '\r':
2100 SAVE_2_CHARS ("\\r");
2101 break;
2103 case '\t':
2104 SAVE_2_CHARS ("\\t");
2105 break;
2107 case '\f':
2108 SAVE_2_CHARS ("\\f");
2109 break;
2111 case ' ':
2112 SAVE_2_CHARS ("\\ ");
2113 break;
2115 case '"':
2116 SAVE_2_CHARS ("\\\"");
2117 break;
2119 default:
2120 if ((c > 040 && c < 0177)
2121 || (print_iso8859 && c >= 0200 && c <= 0377))
2122 SAVECHAR (c);
2123 else
2125 char buf[5];
2126 sprintf (buf, "\\%03o", (unsigned int) c);
2127 q = stpcpy (q, buf);
2131 else
2133 if ((c >= 040 && c < 0177)
2134 || (print_iso8859 && c >= 0200 && c <= 0377))
2135 SAVECHAR (c);
2136 else if (!qmark_funny_chars)
2137 SAVECHAR (c);
2138 else
2139 SAVECHAR ('?');
2143 if (quote_as_string)
2144 SAVECHAR ('"');
2146 *quoted_length = q - quoted;
2148 SAVECHAR ('\0');
2150 return quoted;
2153 static void
2154 print_name_with_quoting (register char *p)
2156 char *quoted;
2157 size_t quoted_length;
2159 quoted = quote_filename (p, &quoted_length);
2160 FPUTS (quoted != NULL ? quoted : p, stdout, quoted_length);
2161 if (quoted)
2162 free (quoted);
2165 /* Print the file name of `f' with appropriate quoting.
2166 Also print file size, inode number, and filetype indicator character,
2167 as requested by switches. */
2169 static void
2170 print_file_name_and_frills (struct fileinfo *f)
2172 if (print_inode)
2173 printf ("%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
2175 if (print_block_size)
2176 printf ("%*u ", block_size_size,
2177 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
2178 kilobyte_blocks));
2180 if (print_with_color)
2181 print_color_indicator (f->stat.st_mode);
2182 print_name_with_quoting (f->name);
2183 if (print_with_color)
2184 put_indicator (C_END);
2186 if (indicator_style != none)
2187 print_type_indicator (f->stat.st_mode);
2190 static void
2191 print_type_indicator (unsigned int mode)
2193 if (S_ISDIR (mode))
2194 PUTCHAR ('/');
2196 #ifdef S_ISLNK
2197 if (S_ISLNK (mode))
2198 PUTCHAR ('@');
2199 #endif
2201 #ifdef S_ISFIFO
2202 if (S_ISFIFO (mode))
2203 PUTCHAR ('|');
2204 #endif
2206 #ifdef S_ISSOCK
2207 if (S_ISSOCK (mode))
2208 PUTCHAR ('=');
2209 #endif
2211 if (S_ISREG (mode) && indicator_style == all
2212 && (mode & (S_IEXEC | S_IXGRP | S_IXOTH)))
2213 PUTCHAR ('*');
2216 static void
2217 print_color_indicator (unsigned int mode)
2219 int type = C_FILE;
2221 if (S_ISDIR (mode))
2222 type = C_DIR;
2224 #ifdef S_ISLNK
2225 else if (S_ISLNK (mode))
2226 type = C_LINK;
2227 #endif
2229 #ifdef S_ISFIFO
2230 else if (S_ISFIFO (mode))
2231 type = C_FIFO;
2232 #endif
2234 #ifdef S_ISSOCK
2235 else if (S_ISSOCK (mode))
2236 type = C_SOCK;
2237 #endif
2239 #ifdef S_ISBLK
2240 else if (S_ISBLK (mode))
2241 type = C_BLK;
2242 #endif
2244 #ifdef S_ISCHR
2245 else if (S_ISCHR (mode))
2246 type = C_CHR;
2247 #endif
2249 if (type == C_FILE && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
2250 type = C_EXEC;
2252 put_indicator (C_LEFT);
2253 put_indicator (type);
2254 put_indicator (C_RIGHT);
2257 /* Output a color indicator (which may contain nulls) */
2258 static void
2259 put_indicator (int n)
2261 register int i;
2262 register char *p;
2264 p = color_indicator[n].string;
2266 for (i = color_indicator[n].len; i; i--)
2268 putchar (*(p++));
2272 static int
2273 length_of_file_name_and_frills (struct fileinfo *f)
2275 register char *p = f->name;
2276 register unsigned char c;
2277 register int len = 0;
2279 if (print_inode)
2280 len += INODE_DIGITS + 1;
2282 if (print_block_size)
2283 len += 1 + block_size_size;
2285 if (quote_as_string)
2286 len += 2;
2288 while ((c = *p++))
2290 if (quote_funny_chars)
2292 switch (c)
2294 case '\\':
2295 case '\n':
2296 case '\b':
2297 case '\r':
2298 case '\t':
2299 case '\f':
2300 case ' ':
2301 len += 2;
2302 break;
2304 case '"':
2305 if (quote_as_string)
2306 len += 2;
2307 else
2308 len += 1;
2309 break;
2311 default:
2312 if ((c >= 040 && c < 0177)
2313 || (print_iso8859 && c >= 0200 && c <= 0377))
2314 len += 1;
2315 else
2316 len += 4;
2319 else
2320 len += 1;
2323 if (indicator_style != none)
2325 unsigned filetype = f->stat.st_mode;
2327 if (S_ISREG (filetype))
2329 if (indicator_style == all
2330 && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
2331 len += 1;
2333 else if (S_ISDIR (filetype)
2334 #ifdef S_ISLNK
2335 || S_ISLNK (filetype)
2336 #endif
2337 #ifdef S_ISFIFO
2338 || S_ISFIFO (filetype)
2339 #endif
2340 #ifdef S_ISSOCK
2341 || S_ISSOCK (filetype)
2342 #endif
2344 len += 1;
2347 return len;
2350 static void
2351 print_many_per_line (void)
2353 int filesno; /* Index into files. */
2354 int row; /* Current row. */
2355 int max_name_length; /* Length of longest file name + frills. */
2356 int name_length; /* Length of each file name + frills. */
2357 int pos; /* Current character column. */
2358 int cols; /* Number of files across. */
2359 int rows; /* Maximum number of files down. */
2361 /* Compute the maximum file name length. */
2362 max_name_length = 0;
2363 for (filesno = 0; filesno < files_index; filesno++)
2365 name_length = length_of_file_name_and_frills (files + filesno);
2366 if (name_length > max_name_length)
2367 max_name_length = name_length;
2370 /* Allow at least two spaces between names. */
2371 max_name_length += 2;
2373 /* Calculate the maximum number of columns that will fit. */
2374 cols = line_length / max_name_length;
2375 if (cols == 0)
2376 cols = 1;
2377 /* Calculate the number of rows that will be in each column except possibly
2378 for a short column on the right. */
2379 rows = files_index / cols + (files_index % cols != 0);
2380 /* Recalculate columns based on rows. */
2381 cols = files_index / rows + (files_index % rows != 0);
2383 for (row = 0; row < rows; row++)
2385 filesno = row;
2386 pos = 0;
2387 /* Print the next row. */
2388 while (1)
2390 print_file_name_and_frills (files + filesno);
2391 name_length = length_of_file_name_and_frills (files + filesno);
2393 filesno += rows;
2394 if (filesno >= files_index)
2395 break;
2397 indent (pos + name_length, pos + max_name_length);
2398 pos += max_name_length;
2400 putchar ('\n');
2404 static void
2405 print_horizontal (void)
2407 int filesno;
2408 int max_name_length;
2409 int name_length;
2410 int cols;
2411 int pos;
2413 /* Compute the maximum file name length. */
2414 max_name_length = 0;
2415 for (filesno = 0; filesno < files_index; filesno++)
2417 name_length = length_of_file_name_and_frills (files + filesno);
2418 if (name_length > max_name_length)
2419 max_name_length = name_length;
2422 /* Allow two spaces between names. */
2423 max_name_length += 2;
2425 cols = line_length / max_name_length;
2426 if (cols == 0)
2427 cols = 1;
2429 pos = 0;
2430 name_length = 0;
2432 for (filesno = 0; filesno < files_index; filesno++)
2434 if (filesno != 0)
2436 if (filesno % cols == 0)
2438 putchar ('\n');
2439 pos = 0;
2441 else
2443 indent (pos + name_length, pos + max_name_length);
2444 pos += max_name_length;
2448 print_file_name_and_frills (files + filesno);
2450 name_length = length_of_file_name_and_frills (files + filesno);
2452 putchar ('\n');
2455 static void
2456 print_with_commas (void)
2458 int filesno;
2459 int pos, old_pos;
2461 pos = 0;
2463 for (filesno = 0; filesno < files_index; filesno++)
2465 old_pos = pos;
2467 pos += length_of_file_name_and_frills (files + filesno);
2468 if (filesno + 1 < files_index)
2469 pos += 2; /* For the comma and space */
2471 if (old_pos != 0 && pos >= line_length)
2473 putchar ('\n');
2474 pos -= old_pos;
2477 print_file_name_and_frills (files + filesno);
2478 if (filesno + 1 < files_index)
2480 putchar (',');
2481 putchar (' ');
2484 putchar ('\n');
2487 /* Assuming cursor is at position FROM, indent up to position TO.
2488 Use a TAB character instead of two or more spaces whenever possible. */
2490 static void
2491 indent (int from, int to)
2493 while (from < to)
2495 if (to / tabsize > (from + 1) / tabsize)
2497 putchar ('\t');
2498 from += tabsize - from % tabsize;
2500 else
2502 putchar (' ');
2503 from++;
2508 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2510 static void
2511 attach (char *dest, const char *dirname, const char *name)
2513 const char *dirnamep = dirname;
2515 /* Copy dirname if it is not ".". */
2516 if (dirname[0] != '.' || dirname[1] != 0)
2518 while (*dirnamep)
2519 *dest++ = *dirnamep++;
2520 /* Add '/' if `dirname' doesn't already end with it. */
2521 if (dirnamep > dirname && dirnamep[-1] != '/')
2522 *dest++ = '/';
2524 while (*name)
2525 *dest++ = *name++;
2526 *dest = 0;
2529 static void
2530 usage (int status)
2532 if (status != 0)
2533 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2534 program_name);
2535 else
2537 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2538 printf (_("\
2539 List information about the FILEs (the current directory by default).\n\
2540 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2542 -A, --almost-all do not list implied . and ..\n\
2543 -a, --all do not hide entries starting with .\n\
2544 -B, --ignore-backups do not list implied entries ending with ~\n\
2545 -b, --escape print octal escapes for nongraphic characters\n\
2546 -C list entries by columns\n\
2547 -c sort by change time; with -l: show ctime\n\
2548 -D, --dired generate output well suited to Emacs' dired mode\n\
2549 -d, --directory list directory entries instead of contents\n\
2550 -F, --classify append a character for typing each entry\n\
2551 -f do not sort, enable -aU, disable -lst\n\
2552 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2553 single-column -1, verbose -l, vertical -C\n\
2554 --full-time list both full date and full time\n"));
2556 printf (_("\
2557 -G, --no-group inhibit display of group information\n\
2558 -g (ignored)\n\
2559 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2560 -i, --inode print index number of each file\n\
2561 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
2562 -L, --dereference list entries pointed to by symbolic links\n\
2563 -l use a long listing format\n\
2564 -m fill width with a comma separated list of entries\n\
2565 -N, --literal do not quote entry names\n\
2566 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2567 -o, --color, --colour colorize entries according to type\n\
2568 --colo(u)r=WORD yes -o, no, tty (if output is a terminal)\n\
2569 -p append a character for typing each entry\n\
2570 -Q, --quote-name enclose entry names in double quotes\n\
2571 -q, --hide-control-chars print ? instead of non graphic characters\n\
2572 -R, --recursive list subdirectories recursively\n\
2573 -r, --reverse reverse order while sorting\n\
2574 -S sort by file size\n"));
2576 printf (_("\
2577 -s, --size print block size of each file\n\
2578 --sort=WORD ctime -c, extension -X, none -U, size -S,\n\
2579 status -c, time -t\n\
2580 --time=WORD atime -u, access -u, use -u\n\
2581 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2582 -t sort by modification time; with -l: show mtime\n\
2583 -U do not sort; list entries in directory order\n\
2584 -u sort by last access time; with -l: show atime\n\
2585 -w, --width=COLS assume screen width instead of current value\n\
2586 -x list entries by lines instead of by columns\n\
2587 -X sort alphabetically by entry extension\n\
2588 -1 list one file per line\n\
2589 -7, --7bit allow only 7-bit ASCII characters to be printed\n\
2590 -8, --8bit allow 8-bit ISO 8859 characters to be printed\n\
2591 --help display this help and exit\n\
2592 --version output version information and exit"));
2594 exit (status);