1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 95, 1996 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)
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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* If ls_mode is LS_MULTI_COL,
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 ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
29 the output format depends on whether the output
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
44 #include <sys/types.h>
47 #ifdef GWINSZ_IN_SYS_IOCTL
48 # include <sys/ioctl.h>
57 /* limits.h must come before system.h because limits.h on some systems
58 undefs PATH_MAX, whereas system.h includes pathmax.h which sets
72 #define obstack_chunk_alloc xmalloc
73 #define obstack_chunk_free free
76 # define INT_MAX 2147483647
79 /* Return an int indicating the result of comparing two longs. */
80 #if (INT_MAX <= 65535)
81 # define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
83 # define longdiff(a, b) ((a) - (b))
86 /* The maximum number of digits required to print an inode number
87 in an unsigned format. */
89 # define INODE_DIGITS 7
96 arg_directory, /* Directory given as command line arg. */
97 normal /* All others. */
107 /* For symbolic link, name of the file linked to, otherwise zero. */
110 /* For symbolic link and long listing, st_mode of file linked to, otherwise
112 unsigned int linkmode;
114 /* For symbolic link and color printing, 1 if linked-to file
115 exists, otherwise 0. */
118 enum filetype filetype;
121 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
123 /* Null is a valid character in a color indicator (think about Epson
124 printers, for example) so we have to use a length/buffer string
129 unsigned int len; /* Number of bytes */
130 char *string; /* Pointer to the same */
148 static char *make_link_path __P ((const char *path, const char *linkname));
149 static int compare_atime __P ((const struct fileinfo *file1,
150 const struct fileinfo *file2));
151 static int rev_cmp_atime __P ((const struct fileinfo *file2,
152 const struct fileinfo *file1));
153 static int compare_ctime __P ((const struct fileinfo *file1,
154 const struct fileinfo *file2));
155 static int rev_cmp_ctime __P ((const struct fileinfo *file2,
156 const struct fileinfo *file1));
157 static int compare_mtime __P ((const struct fileinfo *file1,
158 const struct fileinfo *file2));
159 static int rev_cmp_mtime __P ((const struct fileinfo *file2,
160 const struct fileinfo *file1));
161 static int compare_size __P ((const struct fileinfo *file1,
162 const struct fileinfo *file2));
163 static int rev_cmp_size __P ((const struct fileinfo *file2,
164 const struct fileinfo *file1));
165 static int compare_name __P ((const struct fileinfo *file1,
166 const struct fileinfo *file2));
167 static int rev_cmp_name __P ((const struct fileinfo *file2,
168 const struct fileinfo *file1));
169 static int compare_extension __P ((const struct fileinfo *file1,
170 const struct fileinfo *file2));
171 static int rev_cmp_extension __P ((const struct fileinfo *file2,
172 const struct fileinfo *file1));
173 static int decode_switches __P ((int argc, char **argv));
174 static int file_interesting __P ((const struct dirent *next));
175 static int gobble_file __P ((const char *name, int explicit_arg,
176 const char *dirname));
177 static int is_not_dot_or_dotdot __P ((const char *name));
178 static void print_color_indicator __P ((const char *name, unsigned int mode,
180 static void put_indicator __P ((const struct bin_str *ind));
181 static int length_of_file_name_and_frills __P ((const struct fileinfo *f));
182 static void add_ignore_pattern __P ((const char *pattern));
183 static void attach __P ((char *dest, const char *dirname, const char *name));
184 static void clear_files __P ((void));
185 static void extract_dirs_from_files __P ((const char *dirname, int recursive));
186 static void get_link_name __P ((const char *filename, struct fileinfo *f));
187 static void indent __P ((int from, int to));
188 static void print_current_files __P ((void));
189 static void print_dir __P ((const char *name, const char *realname));
190 static void print_file_name_and_frills __P ((const struct fileinfo *f));
191 static void print_horizontal __P ((void));
192 static void print_long_format __P ((const struct fileinfo *f));
193 static void print_many_per_line __P ((void));
194 static void print_name_with_quoting __P ((const char *p, unsigned int mode,
196 static void prep_non_filename_text __P ((void));
197 static void print_type_indicator __P ((unsigned int mode));
198 static void print_with_commas __P ((void));
199 static void queue_directory __P ((const char *name, const char *realname));
200 static void sort_files __P ((void));
201 static void parse_ls_color __P ((void));
202 static void usage __P ((int status));
204 /* The name the program was run with, stripped of any leading path. */
207 /* The table of files in the current directory:
209 `files' points to a vector of `struct fileinfo', one per file.
210 `nfiles' is the number of elements space has been allocated for.
211 `files_index' is the number actually in use. */
213 /* Address of block containing the files that are described. */
215 static struct fileinfo *files;
217 /* Length of block that `files' points to, measured in files. */
221 /* Index of first unused in `files'. */
223 static int files_index;
225 /* Record of one pending directory waiting to be listed. */
230 /* If the directory is actually the file pointed to by a symbolic link we
231 were told to list, `realname' will contain the name of the symbolic
232 link, otherwise zero. */
234 struct pending *next;
237 static struct pending *pending_dirs;
239 /* Current time (seconds since 1970). When we are printing a file's time,
240 include the year if it is more than 6 months before this time. */
242 static time_t current_time;
244 /* The number of digits to use for block sizes.
245 4, or more if needed for bigger numbers. */
247 static int block_size_size;
251 /* long_format for lots of info, one per line.
252 one_per_line for just names, one per line.
253 many_per_line for just names, many per line, sorted vertically.
254 horizontal for just names, many per line, sorted horizontally.
255 with_commas for just names, many per line, separated by commas.
257 -l, -1, -C, -x and -m control this parameter. */
261 long_format, /* -l */
262 one_per_line, /* -1 */
263 many_per_line, /* -C */
268 static enum format format;
270 /* Type of time to print or sort by. Controlled by -c and -u. */
274 time_mtime, /* default */
279 static enum time_type time_type;
281 /* print the full time, otherwise the standard unix heuristics. */
285 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X. */
290 sort_name, /* default */
291 sort_extension, /* -X */
296 static enum sort_type sort_type;
298 /* Direction of sort.
299 0 means highest first if numeric,
300 lowest first if alphabetic;
301 these are the defaults.
302 1 means the opposite order in each case. -r */
304 static int sort_reverse;
306 /* Nonzero means to NOT display group information. -G */
310 /* Nonzero means print the user and group id's as numbers rather
313 static int numeric_users;
315 /* Nonzero means mention the size in 512 byte blocks of each file. -s */
317 static int print_block_size;
319 /* Nonzero means show file sizes in kilobytes instead of blocks
320 (the size of which is system-dependent). -k */
322 static int kilobyte_blocks;
324 /* Precede each line of long output (per file) with a string like `m,n:'
325 where M is the number of characters after the `:' and before the
326 filename and N is the length of the filename. Using this format,
327 Emacs' dired mode starts up twice as fast, and can handle all
328 strange characters in file names. */
331 /* `none' means don't mention the type of files.
332 `all' means mention the types of all files.
333 `not_programs' means do so except for executables.
335 Controlled by -F and -p. */
341 not_programs /* -p */
344 static enum indicator_style indicator_style;
346 /* Nonzero means use colors to mark types. Also define the different
347 colors as well as the stuff for the LS_COLORS environment variable.
348 The LS_COLORS variable is now in a termcap-like format. */
350 static int print_with_color;
354 color_never, /* 0: default or --color=never */
355 color_always, /* 1: --color=always */
356 color_if_tty /* 2: --color=tty */
361 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
362 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC
365 static const char *const indicator_name[]=
367 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
368 "bd", "cd", "mi", "or", "ex", NULL
373 struct bin_str ext; /* The extension we're looking for */
374 struct bin_str seq; /* The sequence to output when we do */
375 struct col_ext_type *next; /* Next in list */
378 static struct bin_str color_indicator[] =
380 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
381 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
382 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
383 { LEN_STR_PAIR ("0") }, /* no: Normal */
384 { LEN_STR_PAIR ("0") }, /* fi: File: default */
385 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
386 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
387 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
388 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
389 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
390 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
391 { 0, NULL }, /* mi: Missing file: undefined */
392 { 0, NULL }, /* or: Orphanned symlink: undefined */
393 { LEN_STR_PAIR ("01;32") } /* ex: Executable: bright green */
397 struct col_ext_type *col_ext_list = NULL;
399 /* Buffer for color sequences */
400 static char *color_buf;
402 /* Nonzero means mention the inode number of each file. -i */
404 static int print_inode;
406 /* Nonzero means when a symbolic link is found, display info on
407 the file linked to. -L */
409 static int trace_links;
411 /* Nonzero means when a directory is found, display info on its
414 static int trace_dirs;
416 /* Nonzero means when an argument is a directory name, display info
419 static int immediate_dirs;
421 /* Nonzero means don't omit files whose names start with `.'. -A */
423 static int all_files;
425 /* Nonzero means don't omit files `.' and `..'
426 This flag implies `all_files'. -a */
428 static int really_all_files;
430 /* A linked list of shell-style globbing patterns. If a non-argument
431 file name matches any of these patterns, it is omitted.
432 Controlled by -I. Multiple -I options accumulate.
433 The -B option adds `*~' and `.*~' to this list. */
435 struct ignore_pattern
438 struct ignore_pattern *next;
441 static struct ignore_pattern *ignore_patterns;
443 /* Nonzero means quote nongraphic chars in file names. -b */
445 static int quote_funny_chars;
447 /* Nonzero means output nongraphic chars in file names as `?'. -q */
449 static int qmark_funny_chars;
451 /* Nonzero means output each file name using C syntax for a string.
452 Always accompanied by `quote_funny_chars'.
453 This mode, together with -x or -C or -m,
454 and without such frills as -F or -s,
455 is guaranteed to make it possible for a program receiving
456 the output to tell exactly what file names are present. -Q */
458 static int quote_as_string;
460 /* The number of chars per hardware tab stop. Setting this to zero
461 inhibits the use of TAB characters for separating columns. -T */
464 /* Nonzero means we are listing the working directory because no
465 non-option arguments were given. */
467 static int dir_defaulted;
469 /* Nonzero means print each directory name before listing it. */
471 static int print_dir_name;
473 /* The line length to use for breaking lines in many-per-line format.
474 Can be set with -w. */
476 static int line_length;
478 /* If nonzero, the file listing format requires that stat be called on
481 static int format_needs_stat;
483 /* The exit status to use if we don't get any fatal errors. */
485 static int exit_status;
487 /* If nonzero, display usage information and exit. */
488 static int show_help;
490 /* If nonzero, print the version on standard output and exit. */
491 static int show_version;
493 static struct option const long_options[] =
495 {"all", no_argument, 0, 'a'},
496 {"escape", no_argument, 0, 'b'},
497 {"directory", no_argument, 0, 'd'},
498 {"dired", no_argument, 0, 'D'},
499 {"full-time", no_argument, &full_time, 1},
500 {"inode", no_argument, 0, 'i'},
501 {"kilobytes", no_argument, 0, 'k'},
502 {"numeric-uid-gid", no_argument, 0, 'n'},
503 {"no-group", no_argument, 0, 'G'},
504 {"hide-control-chars", no_argument, 0, 'q'},
505 {"reverse", no_argument, 0, 'r'},
506 {"size", no_argument, 0, 's'},
507 {"width", required_argument, 0, 'w'},
508 {"almost-all", no_argument, 0, 'A'},
509 {"ignore-backups", no_argument, 0, 'B'},
510 {"classify", no_argument, 0, 'F'},
511 {"file-type", no_argument, 0, 'F'},
512 {"ignore", required_argument, 0, 'I'},
513 {"dereference", no_argument, 0, 'L'},
514 {"literal", no_argument, 0, 'N'},
515 {"quote-name", no_argument, 0, 'Q'},
516 {"recursive", no_argument, 0, 'R'},
517 {"format", required_argument, 0, 12},
518 {"sort", required_argument, 0, 10},
519 {"tabsize", required_argument, 0, 'T'},
520 {"time", required_argument, 0, 11},
521 {"help", no_argument, &show_help, 1},
522 {"version", no_argument, &show_version, 1},
523 {"color", optional_argument, 0, 13},
527 static char const *const format_args[] =
529 "verbose", "long", "commas", "horizontal", "across",
530 "vertical", "single-column", 0
533 static enum format const formats[] =
535 long_format, long_format, with_commas, horizontal, horizontal,
536 many_per_line, one_per_line
539 static char const *const sort_args[] =
541 "none", "time", "size", "extension", 0
544 static enum sort_type const sort_types[] =
546 sort_none, sort_time, sort_size, sort_extension
549 static char const *const time_args[] =
551 "atime", "access", "use", "ctime", "status", 0
554 /* This zero-based index is used solely with the --dired option.
555 When that option is in effect, this counter is incremented for each
556 character of output generated by this program so that the beginning
557 and ending indices (in that output) of every file name can be recorded
558 and later output themselves. */
559 static size_t dired_pos;
561 #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
563 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
564 #define FPUTS(s, stream, s_len) \
565 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
567 /* Like FPUTS, but for use when S is a literal string. */
568 #define FPUTS_LITERAL(s, stream) \
569 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
571 #define DIRED_INDENT() \
574 /* FIXME: remove the `&& format == long_format' clause. */ \
575 if (dired && format == long_format) \
576 FPUTS_LITERAL (" ", stdout); \
580 /* With --dired, store pairs of beginning and ending indices of filenames. */
581 static struct obstack dired_obstack;
583 /* With --dired, store pairs of beginning and ending indices of any
584 directory names that appear as headers (just before `total' line)
585 for lists of directory entries. Such directory names are seen when
586 listing hierarchies using -R and when a directory is listed with at
587 least one other command line argument. */
588 static struct obstack subdired_obstack;
590 /* Save the current index on the specified obstack, OBS. */
591 #define PUSH_CURRENT_DIRED_POS(obs) \
594 /* FIXME: remove the `&& format == long_format' clause. */ \
595 if (dired && format == long_format) \
596 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
600 static enum time_type const time_types[] =
602 time_atime, time_atime, time_atime, time_ctime, time_ctime
605 static char const *const color_args[] =
607 /* Note: "no" is a prefix of "none" so we don't include it. */
608 /* force and none are for compatibility with another color-ls version */
609 "always", "yes", "force",
611 "auto", "tty", "if-tty", 0
614 static enum color_type const color_types[] =
616 color_always, color_always, color_always,
617 color_never, color_never,
618 color_if_tty, color_if_tty, color_if_tty
622 /* Write to standard output the string PREFIX followed by a space-separated
623 list of the integers stored in OS all on one line. */
626 dired_dump_obstack (const char *prefix, struct obstack *os)
630 n_pos = obstack_object_size (os) / sizeof (size_t);
636 pos = (size_t *) obstack_finish (os);
637 fputs (prefix, stdout);
638 for (i = 0; i < n_pos; i++)
639 printf (" %d", (int) pos[i]);
640 fputs ("\n", stdout);
645 main (int argc, char **argv)
648 register struct pending *thispend;
650 program_name = argv[0];
651 setlocale (LC_ALL, "");
652 bindtextdomain (PACKAGE, LOCALEDIR);
653 textdomain (PACKAGE);
659 current_time = time ((time_t *) 0);
661 i = decode_switches (argc, argv);
665 printf ("%s (%s) %s\n",
666 (ls_mode == LS_LS ? "ls"
667 : (ls_mode == LS_MULTI_COL ? "dir" : "vdir")),
668 GNU_PACKAGE, VERSION);
673 usage (EXIT_SUCCESS);
675 if (print_with_color)
678 prep_non_filename_text ();
681 format_needs_stat = sort_type == sort_time || sort_type == sort_size
682 || format == long_format
683 || trace_links || trace_dirs || indicator_style != none
684 || print_block_size || print_inode || print_with_color;
686 if (dired && format == long_format)
688 obstack_init (&dired_obstack);
689 obstack_init (&subdired_obstack);
693 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
700 for (; i < argc; i++)
701 gobble_file (argv[i], 1, "");
706 gobble_file (".", 1, "");
708 queue_directory (".", 0);
715 extract_dirs_from_files ("", 0);
716 /* `files_index' might be zero now. */
720 print_current_files ();
724 else if (pending_dirs && pending_dirs->next == 0)
729 thispend = pending_dirs;
730 pending_dirs = pending_dirs->next;
731 print_dir (thispend->name, thispend->realname);
732 free (thispend->name);
733 if (thispend->realname)
734 free (thispend->realname);
739 if (dired && format == long_format)
741 /* No need to free these since we're about to exit. */
742 dired_dump_obstack ("//DIRED//", &dired_obstack);
743 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
746 if (fclose (stdout) == EOF)
747 error (EXIT_FAILURE, errno, _("write error"));
749 /* Restore default color before exiting */
750 if (print_with_color)
752 put_indicator (&color_indicator[C_LEFT]);
753 put_indicator (&color_indicator[C_RIGHT]);
759 /* Set all the option flags according to the switches specified.
760 Return the index of the first non-option argument. */
763 decode_switches (int argc, char **argv)
770 qmark_funny_chars = 0;
771 quote_funny_chars = 0;
773 /* initialize all switches to default settings */
778 /* This is for the `dir' program. */
779 format = many_per_line;
780 quote_funny_chars = 1;
784 /* This is for the `vdir' program. */
785 format = long_format;
786 quote_funny_chars = 1;
790 /* This is for the `ls' program. */
793 format = many_per_line;
794 qmark_funny_chars = 1;
798 format = one_per_line;
799 qmark_funny_chars = 0;
807 time_type = time_mtime;
809 sort_type = sort_name;
812 print_block_size = 0;
813 kilobyte_blocks = getenv ("POSIXLY_CORRECT") == 0;
814 indicator_style = none;
820 really_all_files = 0;
825 if ((p = getenv ("COLUMNS")))
827 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
828 && 0 < tmp_long && tmp_long <= INT_MAX)
830 line_length = (int) tmp_long;
835 _("ignoring invalid width in environment variable COLUMNS: %s"),
844 if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
845 line_length = ws.ws_col;
849 /* Using the TABSIZE environment variable is not POSIX-approved.
850 Ignore it when POSIXLY_CORRECT is set. */
852 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
854 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
855 && 0 <= tmp_long && tmp_long <= INT_MAX)
857 tabsize = (int) tmp_long;
862 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
867 while ((c = getopt_long (argc, argv,
868 "abcdfgiklmnopqrstuw:xABCDFGI:LNQRST:UX1",
869 long_options, NULL)) != -1)
878 really_all_files = 1;
882 quote_funny_chars = 1;
883 qmark_funny_chars = 0;
887 time_type = time_ctime;
888 sort_type = sort_time;
896 /* Same as enabling -a -U and disabling -l -s. */
898 really_all_files = 1;
899 sort_type = sort_none;
901 if (format == long_format)
902 format = (isatty (1) ? many_per_line : one_per_line);
903 print_block_size = 0; /* disable -s */
904 print_with_color = 0; /* disable --color */
908 /* No effect. For BSD compatibility. */
920 format = long_format;
924 format = with_commas;
931 case 'o': /* Just like -l, but don't display group info. */
932 format = long_format;
937 indicator_style = not_programs;
941 qmark_funny_chars = 1;
942 quote_funny_chars = 0;
950 print_block_size = 1;
954 sort_type = sort_time;
958 time_type = time_atime;
962 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
963 || tmp_long <= 0 || tmp_long > INT_MAX)
964 error (EXIT_FAILURE, 0, _("invalid line width: %s"), optarg);
965 line_length = (int) tmp_long;
973 really_all_files = 0;
978 add_ignore_pattern ("*~");
979 add_ignore_pattern (".*~");
983 format = many_per_line;
991 indicator_style = all;
994 case 'G': /* inhibit display of group info */
999 add_ignore_pattern (optarg);
1007 quote_funny_chars = 0;
1008 qmark_funny_chars = 0;
1012 quote_as_string = 1;
1013 quote_funny_chars = 1;
1014 qmark_funny_chars = 0;
1022 sort_type = sort_size;
1026 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1027 || tmp_long < 0 || tmp_long > INT_MAX)
1028 error (EXIT_FAILURE, 0, _("invalid tab size: %s"), optarg);
1029 tabsize = (int) tmp_long;
1033 sort_type = sort_none;
1037 sort_type = sort_extension;
1041 format = one_per_line;
1044 case 10: /* --sort */
1045 i = argmatch (optarg, sort_args);
1048 invalid_arg (_("sort type"), optarg, i);
1049 usage (EXIT_FAILURE);
1051 sort_type = sort_types[i];
1054 case 11: /* --time */
1055 i = argmatch (optarg, time_args);
1058 invalid_arg (_("time type"), optarg, i);
1059 usage (EXIT_FAILURE);
1061 time_type = time_types[i];
1064 case 12: /* --format */
1065 i = argmatch (optarg, format_args);
1068 invalid_arg (_("format type"), optarg, i);
1069 usage (EXIT_FAILURE);
1071 format = formats[i];
1074 case 13: /* --color */
1077 i = argmatch (optarg, color_args);
1080 invalid_arg (_("colorization criterion"), optarg, i);
1081 usage (EXIT_FAILURE);
1087 /* Using --color with no argument is equivalent to using
1092 print_with_color = (i == color_always
1093 || (i == color_if_tty
1094 && isatty (STDOUT_FILENO)));
1096 if (print_with_color)
1098 /* Don't use TAB characters in output. Some terminal
1099 emulators can't handle the combination of tabs and
1100 color codes on the same line. */
1106 usage (EXIT_FAILURE);
1113 /* Parse a string as part of the LS_COLORS variable; this may involve
1114 decoding all kinds of escape characters. If equals_end is set an
1115 unescaped equal sign ends the string, otherwise only a : or \0
1116 does. Returns the number of characters output, or -1 on failure.
1118 The resulting string is *not* null-terminated, but may contain
1121 Note that both dest and src are char **; on return they point to
1122 the first free byte after the array and the character that ended
1123 the input string, respectively. */
1126 get_funky_string (char **dest, const char **src, int equals_end)
1128 int num; /* For numerical codes */
1129 int count; /* Something to count with */
1131 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1136 p = *src; /* We don't want to double-indirect */
1137 q = *dest; /* the whole darn time. */
1139 count = 0; /* No characters counted in yet. */
1142 state = ST_GND; /* Start in ground state. */
1143 while (state < ST_END)
1147 case ST_GND: /* Ground state (no escapes) */
1152 state = ST_END; /* End of string */
1155 state = ST_BACKSLASH; /* Backslash scape sequence */
1159 state = ST_CARET; /* Caret escape */
1165 state = ST_END; /* End */
1168 /* else fall through */
1176 case ST_BACKSLASH: /* Backslash escaped character */
1187 state = ST_OCTAL; /* Octal sequence */
1192 state = ST_HEX; /* Hex sequence */
1195 case 'a': /* Bell */
1196 num = 7; /* Not all C compilers know what \a means */
1198 case 'b': /* Backspace */
1201 case 'e': /* Escape */
1204 case 'f': /* Form feed */
1207 case 'n': /* Newline */
1210 case 'r': /* Carriage return */
1216 case 'v': /* Vtab */
1219 case '?': /* Delete */
1222 case '_': /* Space */
1225 case '\0': /* End of string */
1226 state = ST_ERROR; /* Error! */
1228 default: /* Escaped character like \ ^ : = */
1232 if (state == ST_BACKSLASH)
1241 case ST_OCTAL: /* Octal sequence */
1242 if (*p < '0' || *p > '7')
1249 num = (num << 3) + (*(p++) - '0');
1252 case ST_HEX: /* Hex sequence */
1265 num = (num << 4) + (*(p++) - '0');
1273 num = (num << 4) + (*(p++) - 'a') + 10;
1281 num = (num << 4) + (*(p++) - 'A') + 10;
1291 case ST_CARET: /* Caret escape */
1292 state = ST_GND; /* Should be the next state... */
1293 if (*p >= '@' && *p <= '~')
1295 *(q++) = *(p++) & 037;
1298 else if ( *p == '?')
1315 return state == ST_ERROR ? -1 : count;
1319 parse_ls_color (void)
1321 const char *p; /* Pointer to character being parsed */
1322 char *buf; /* color_buf buffer pointer */
1323 int state; /* State of parser */
1324 int ind_no; /* Indicator number */
1325 char label[3]; /* Indicator label */
1326 struct col_ext_type *ext; /* Extension we are working on */
1327 struct col_ext_type *ext2; /* Extra pointer */
1329 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1333 strcpy (label, "??");
1335 /* This is an overly conservative estimate, but any possible
1336 LS_COLORS string will *not* generate a color_buf longer than
1337 itself, so it is a safe way of allocating a buffer in
1339 buf = color_buf = xstrdup (p);
1346 case 1: /* First label character */
1354 /* Allocate new extension block and add to head of
1355 linked list (this way a later definition will
1356 override an earlier one, which can be useful for
1357 having terminal-specific defs override global). */
1359 ext = (struct col_ext_type *)
1360 xmalloc (sizeof (struct col_ext_type));
1361 ext->next = col_ext_list;
1365 ext->ext.string = buf;
1367 state = (ext->ext.len =
1368 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1372 state = 0; /* Done! */
1375 default: /* Assume it is file type label */
1382 case 2: /* Second label character */
1389 state = -1; /* Error */
1392 case 3: /* Equal sign after indicator label */
1393 state = -1; /* Assume failure... */
1394 if (*(p++) == '=')/* It *should* be... */
1396 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1398 if (STREQ (label, indicator_name[ind_no]))
1400 color_indicator[ind_no].string = buf;
1401 state = ((color_indicator[ind_no].len =
1402 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1407 error (0, 0, _("unrecognized prefix: %s"), label);
1411 case 4: /* Equal sign after *.ext */
1414 ext->seq.string = buf;
1415 state = (ext->seq.len =
1416 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1426 struct col_ext_type *e;
1429 _("unparsable value for LS_COLORS environment variable"));
1431 for (e = col_ext_list; e != NULL ; /* empty */)
1437 print_with_color = 0;
1441 /* Request that the directory named `name' have its contents listed later.
1442 If `realname' is nonzero, it will be used instead of `name' when the
1443 directory name is printed. This allows symbolic links to directories
1444 to be treated as regular directories but still be listed under their
1448 queue_directory (const char *name, const char *realname)
1450 struct pending *new;
1452 new = (struct pending *) xmalloc (sizeof (struct pending));
1453 new->next = pending_dirs;
1455 new->name = xstrdup (name);
1457 new->realname = xstrdup (realname);
1462 /* Read directory `name', and list the files in it.
1463 If `realname' is nonzero, print its name instead of `name';
1464 this is used for symbolic links to directories. */
1467 print_dir (const char *name, const char *realname)
1469 register DIR *reading;
1470 register struct dirent *next;
1471 register int total_blocks = 0;
1474 reading = opendir (name);
1477 error (0, errno, "%s", name);
1482 /* Read the directory entries, and insert the subfiles into the `files'
1487 while ((next = readdir (reading)) != NULL)
1488 if (file_interesting (next))
1489 total_blocks += gobble_file (next->d_name, 0, name);
1491 if (CLOSEDIR (reading))
1493 error (0, errno, "%s", name);
1495 /* Don't return; print whatever we got. */
1498 /* Sort the directory contents. */
1501 /* If any member files are subdirectories, perhaps they should have their
1502 contents listed rather than being mentioned here as files. */
1505 extract_dirs_from_files (name, 1);
1512 dir = (realname ? realname : name);
1513 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1514 FPUTS (dir, stdout, strlen (dir));
1515 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1516 FPUTS_LITERAL (":\n", stdout);
1519 if (format == long_format || print_block_size)
1521 char buf[6 + 20 + 1 + 1];
1524 sprintf (buf, "total %u\n", total_blocks);
1525 FPUTS (buf, stdout, strlen (buf));
1529 print_current_files ();
1535 /* Add `pattern' to the list of patterns for which files that match are
1539 add_ignore_pattern (const char *pattern)
1541 register struct ignore_pattern *ignore;
1543 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1544 ignore->pattern = pattern;
1545 /* Add it to the head of the linked list. */
1546 ignore->next = ignore_patterns;
1547 ignore_patterns = ignore;
1550 /* Return nonzero if the file in `next' should be listed. */
1553 file_interesting (const struct dirent *next)
1555 register struct ignore_pattern *ignore;
1557 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1558 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1561 if (really_all_files
1562 || next->d_name[0] != '.'
1564 && next->d_name[1] != '\0'
1565 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1571 /* Enter and remove entries in the table `files'. */
1573 /* Empty the table of files. */
1580 for (i = 0; i < files_index; i++)
1582 free (files[i].name);
1583 if (files[i].linkname)
1584 free (files[i].linkname);
1588 block_size_size = 4;
1591 /* Add a file to the current table of files.
1592 Verify that the file exists, and print an error message if it does not.
1593 Return the number of blocks that the file occupies. */
1596 gobble_file (const char *name, int explicit_arg, const char *dirname)
1598 register int blocks;
1600 register char *path;
1602 if (files_index == nfiles)
1605 files = (struct fileinfo *) xrealloc (files, sizeof (*files) * nfiles);
1608 files[files_index].linkname = 0;
1609 files[files_index].linkmode = 0;
1610 files[files_index].linkok = 0;
1612 if (explicit_arg || format_needs_stat)
1614 /* `path' is the absolute pathname of this file. */
1616 if (name[0] == '/' || dirname[0] == 0)
1617 path = (char *) name;
1620 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1621 attach (path, dirname, name);
1626 val = stat (path, &files[files_index].stat);
1628 /* Perhaps a symbolically-linked to file doesn't exist; stat
1629 the link instead. */
1630 val = lstat (path, &files[files_index].stat);
1633 val = lstat (path, &files[files_index].stat);
1636 error (0, errno, "%s", path);
1642 if (S_ISLNK (files[files_index].stat.st_mode)
1643 && (explicit_arg || format == long_format || print_with_color))
1646 struct stat linkstats;
1648 get_link_name (path, &files[files_index]);
1649 linkpath = make_link_path (path, files[files_index].linkname);
1651 /* Avoid following symbolic links when possible, ie, when
1652 they won't be traced and when no indicator is needed. */
1654 && ((explicit_arg && format != long_format)
1655 || indicator_style != none
1656 || print_with_color)
1657 && stat (linkpath, &linkstats) == 0)
1659 files[files_index].linkok = 1;
1661 /* Symbolic links to directories that are mentioned on the
1662 command line are automatically traced if not being
1664 if (explicit_arg && format != long_format
1665 && S_ISDIR (linkstats.st_mode))
1667 /* Substitute the linked-to directory's name, but
1668 save the real name in `linkname' for printing. */
1669 if (!immediate_dirs)
1671 const char *tempname = name;
1673 linkpath = files[files_index].linkname;
1674 files[files_index].linkname = (char *) tempname;
1676 files[files_index].stat = linkstats;
1680 /* Get the linked-to file's mode for the filetype indicator
1681 in long listings. */
1682 files[files_index].linkmode = linkstats.st_mode;
1683 files[files_index].linkok = 1;
1692 if (S_ISLNK (files[files_index].stat.st_mode))
1693 files[files_index].filetype = symbolic_link;
1696 if (S_ISDIR (files[files_index].stat.st_mode))
1698 if (explicit_arg && !immediate_dirs)
1699 files[files_index].filetype = arg_directory;
1701 files[files_index].filetype = directory;
1704 files[files_index].filetype = normal;
1706 blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
1708 if (blocks >= 10000 && block_size_size < 5)
1709 block_size_size = 5;
1710 if (blocks >= 100000 && block_size_size < 6)
1711 block_size_size = 6;
1712 if (blocks >= 1000000 && block_size_size < 7)
1713 block_size_size = 7;
1718 files[files_index].name = xstrdup (name);
1726 /* Put the name of the file that `filename' is a symbolic link to
1727 into the `linkname' field of `f'. */
1730 get_link_name (const char *filename, struct fileinfo *f)
1733 register int linksize;
1735 linkbuf = (char *) alloca (PATH_MAX + 2);
1736 /* Some automounters give incorrect st_size for mount points.
1737 I can't think of a good workaround for it, though. */
1738 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1741 error (0, errno, "%s", filename);
1746 linkbuf[linksize] = '\0';
1747 f->linkname = xstrdup (linkbuf);
1751 /* If `linkname' is a relative path and `path' contains one or more
1752 leading directories, return `linkname' with those directories
1753 prepended; otherwise, return a copy of `linkname'.
1754 If `linkname' is zero, return zero. */
1757 make_link_path (const char *path, const char *linkname)
1765 if (*linkname == '/')
1766 return xstrdup (linkname);
1768 /* The link is to a relative path. Prepend any leading path
1769 in `path' to the link name. */
1770 linkbuf = strrchr (path, '/');
1772 return xstrdup (linkname);
1774 bufsiz = linkbuf - path + 1;
1775 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1776 strncpy (linkbuf, path, bufsiz);
1777 strcpy (linkbuf + bufsiz, linkname);
1782 /* Remove any entries from `files' that are for directories,
1783 and queue them to be listed as directories instead.
1784 `dirname' is the prefix to prepend to each dirname
1785 to make it correct relative to ls's working dir.
1786 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1787 This is desirable when processing directories recursively. */
1790 extract_dirs_from_files (const char *dirname, int recursive)
1793 register char *path;
1796 dirlen = strlen (dirname) + 2;
1797 /* Queue the directories last one first, because queueing reverses the
1799 for (i = files_index - 1; i >= 0; i--)
1800 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1801 && (!recursive || is_not_dot_or_dotdot (files[i].name)))
1803 if (files[i].name[0] == '/' || dirname[0] == 0)
1805 queue_directory (files[i].name, files[i].linkname);
1809 path = (char *) xmalloc (strlen (files[i].name) + dirlen);
1810 attach (path, dirname, files[i].name);
1811 queue_directory (path, files[i].linkname);
1814 if (files[i].filetype == arg_directory)
1815 free (files[i].name);
1818 /* Now delete the directories from the table, compacting all the remaining
1821 for (i = 0, j = 0; i < files_index; i++)
1822 if (files[i].filetype != arg_directory)
1823 files[j++] = files[i];
1827 /* Return nonzero if `name' doesn't end in `.' or `..'
1828 This is so we don't try to recurse on `././././. ...' */
1831 is_not_dot_or_dotdot (const char *name)
1835 t = strrchr (name, '/');
1841 || (name[1] == '.' && name[2] == '\0')))
1847 /* Sort the files now in the table. */
1862 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1865 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1868 func = sort_reverse ? rev_cmp_atime : compare_atime;
1875 func = sort_reverse ? rev_cmp_name : compare_name;
1877 case sort_extension:
1878 func = sort_reverse ? rev_cmp_extension : compare_extension;
1881 func = sort_reverse ? rev_cmp_size : compare_size;
1887 qsort (files, files_index, sizeof (struct fileinfo), func);
1890 /* Comparison routines for sorting the files. */
1893 compare_ctime (const struct fileinfo *file1, const struct fileinfo *file2)
1895 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1899 rev_cmp_ctime (const struct fileinfo *file2, const struct fileinfo *file1)
1901 return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
1905 compare_mtime (const struct fileinfo *file1, const struct fileinfo *file2)
1907 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1911 rev_cmp_mtime (const struct fileinfo *file2, const struct fileinfo *file1)
1913 return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
1917 compare_atime (const struct fileinfo *file1, const struct fileinfo *file2)
1919 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1923 rev_cmp_atime (const struct fileinfo *file2, const struct fileinfo *file1)
1925 return longdiff (file2->stat.st_atime, file1->stat.st_atime);
1929 compare_size (const struct fileinfo *file1, const struct fileinfo *file2)
1931 return longdiff (file2->stat.st_size, file1->stat.st_size);
1935 rev_cmp_size (const struct fileinfo *file2, const struct fileinfo *file1)
1937 return longdiff (file2->stat.st_size, file1->stat.st_size);
1941 compare_name (const struct fileinfo *file1, const struct fileinfo *file2)
1943 return strcmp (file1->name, file2->name);
1947 rev_cmp_name (const struct fileinfo *file2, const struct fileinfo *file1)
1949 return strcmp (file1->name, file2->name);
1952 /* Compare file extensions. Files with no extension are `smallest'.
1953 If extensions are the same, compare by filenames instead. */
1956 compare_extension (const struct fileinfo *file1, const struct fileinfo *file2)
1958 register char *base1, *base2;
1961 base1 = strrchr (file1->name, '.');
1962 base2 = strrchr (file2->name, '.');
1963 if (base1 == 0 && base2 == 0)
1964 return strcmp (file1->name, file2->name);
1969 cmp = strcmp (base1, base2);
1971 return strcmp (file1->name, file2->name);
1976 rev_cmp_extension (const struct fileinfo *file2, const struct fileinfo *file1)
1978 register char *base1, *base2;
1981 base1 = strrchr (file1->name, '.');
1982 base2 = strrchr (file2->name, '.');
1983 if (base1 == 0 && base2 == 0)
1984 return strcmp (file1->name, file2->name);
1989 cmp = strcmp (base1, base2);
1991 return strcmp (file1->name, file2->name);
1995 /* List all the files now in the table. */
1998 print_current_files (void)
2005 for (i = 0; i < files_index; i++)
2007 print_file_name_and_frills (files + i);
2013 print_many_per_line ();
2017 print_horizontal ();
2021 print_with_commas ();
2025 for (i = 0; i < files_index; i++)
2027 print_long_format (files + i);
2035 print_long_format (const struct fileinfo *f)
2039 /* 7 fields that may (worst case: 64-bit integral values) require 20 bytes,
2040 1 10-byte mode string,
2041 1 24-byte time string (may be longer in some locales -- see below),
2042 9 spaces, one following each of these fields, and
2043 1 trailing NUL byte. */
2044 char init_bigbuf[7 * 20 + 10 + 24 + 9 + 1];
2045 char *buf = init_bigbuf;
2046 size_t bufsize = sizeof (init_bigbuf);
2052 #ifdef HAVE_ST_DM_MODE
2053 mode_string (f->stat.st_dm_mode, modebuf);
2055 mode_string (f->stat.st_mode, modebuf);
2063 when = f->stat.st_ctime;
2066 when = f->stat.st_mtime;
2069 when = f->stat.st_atime;
2075 fmt = "%a %b %d %H:%M:%S %Y";
2079 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
2080 || current_time < when - 60L * 60L) /* In the future. */
2082 /* The file is fairly old or in the future.
2083 POSIX says the cutoff is 6 months old;
2084 approximate this by 6*30 days.
2085 Allow a 1 hour slop factor for what is considered "the future",
2086 to allow for NFS server/client clock disagreement.
2087 Show the year instead of the time of day. */
2092 fmt = "%b %e %H:%M";
2100 sprintf (p, "%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
2104 if (print_block_size)
2106 sprintf (p, "%*u ", block_size_size,
2107 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
2112 /* The space between the mode and the number of links is the POSIX
2113 "optional alternate access method flag". */
2114 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
2118 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
2120 sprintf (p, "%-8.8s ", getuser (f->stat.st_uid));
2126 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
2128 sprintf (p, "%-8.8s ", getgroup (f->stat.st_gid));
2132 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2133 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
2134 (unsigned) minor (f->stat.st_rdev));
2136 sprintf (p, "%8lu ", (unsigned long) f->stat.st_size);
2139 /* Use strftime rather than ctime, because the former can produce
2140 locale-dependent names for the weekday (%a) and month (%b). */
2142 while (! (s = strftime (p, buf + bufsize - p - 1, fmt, localtime (&when))))
2144 char *newbuf = (char *) alloca (bufsize *= 2);
2145 memcpy (newbuf, buf, p - buf);
2146 p = newbuf + (p - buf);
2153 /* NUL-terminate the string -- fputs (via FPUTS) requires it. */
2157 FPUTS (buf, stdout, p - buf);
2158 PUSH_CURRENT_DIRED_POS (&dired_obstack);
2159 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok);
2160 PUSH_CURRENT_DIRED_POS (&dired_obstack);
2162 if (f->filetype == symbolic_link)
2166 FPUTS_LITERAL (" -> ", stdout);
2167 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1);
2168 if (indicator_style != none)
2169 print_type_indicator (f->linkmode);
2172 else if (indicator_style != none)
2173 print_type_indicator (f->stat.st_mode);
2176 /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
2177 Otherwise, return xmalloc'd storage containing the quoted version
2178 of P and set QUOTED_LENGTH to the length of the quoted P. */
2181 quote_filename (register const char *p, size_t *quoted_length)
2183 register unsigned char c;
2188 if (!quote_as_string && !quote_funny_chars && !qmark_funny_chars)
2190 *quoted_length = strlen (p);
2195 for (c = *p; c; c = *++p)
2197 if (quote_funny_chars)
2220 if (!ISPRINT (c) && qmark_funny_chars)
2227 if (!found_quotable && !quote_as_string)
2229 *quoted_length = p - p0;
2234 quoted = xmalloc (4 * strlen (p) + 1);
2237 #define SAVECHAR(c) *q++ = (c)
2238 #define SAVE_2_CHARS(c12) \
2239 do { *q++ = ((c12)[0]); \
2240 *q++ = ((c12)[1]); } while (0)
2242 if (quote_as_string)
2247 if (quote_funny_chars)
2252 SAVE_2_CHARS ("\\\\");
2256 SAVE_2_CHARS ("\\n");
2260 SAVE_2_CHARS ("\\b");
2264 SAVE_2_CHARS ("\\r");
2268 SAVE_2_CHARS ("\\t");
2272 SAVE_2_CHARS ("\\f");
2276 SAVE_2_CHARS ("\\ ");
2280 SAVE_2_CHARS ("\\\"");
2289 sprintf (buf, "\\%03o", (unsigned int) c);
2290 q = stpcpy (q, buf);
2298 else if (!qmark_funny_chars)
2305 if (quote_as_string)
2308 *quoted_length = q - quoted;
2316 print_name_with_quoting (const char *p, unsigned int mode, int linkok)
2319 size_t quoted_length;
2321 if (print_with_color)
2322 print_color_indicator (p, mode, linkok);
2324 quoted = quote_filename (p, "ed_length);
2325 FPUTS (quoted != NULL ? quoted : p, stdout, quoted_length);
2329 if (print_with_color)
2330 prep_non_filename_text ();
2334 prep_non_filename_text (void)
2336 if (color_indicator[C_END].string != NULL)
2337 put_indicator (&color_indicator[C_END]);
2340 put_indicator (&color_indicator[C_LEFT]);
2341 put_indicator (&color_indicator[C_NORM]);
2342 put_indicator (&color_indicator[C_RIGHT]);
2346 /* Print the file name of `f' with appropriate quoting.
2347 Also print file size, inode number, and filetype indicator character,
2348 as requested by switches. */
2351 print_file_name_and_frills (const struct fileinfo *f)
2354 printf ("%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
2356 if (print_block_size)
2357 printf ("%*u ", block_size_size,
2358 (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
2361 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok);
2363 if (indicator_style != none)
2364 print_type_indicator (f->stat.st_mode);
2368 print_type_indicator (unsigned int mode)
2379 if (S_ISFIFO (mode))
2384 if (S_ISSOCK (mode))
2388 if (S_ISREG (mode) && indicator_style == all
2389 && (mode & S_IXUGO))
2394 print_color_indicator (const char *name, unsigned int mode, int linkok)
2397 struct col_ext_type *ext; /* Color extension */
2398 size_t len; /* Length of name */
2400 /* Is this a nonexistent file? If so, linkok == -1. */
2402 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
2413 else if (S_ISLNK (mode))
2414 type = ((!linkok && color_indicator[C_ORPHAN].string)
2415 ? C_ORPHAN : C_LINK);
2419 else if (S_ISFIFO (mode))
2424 else if (S_ISSOCK (mode))
2429 else if (S_ISBLK (mode))
2434 else if (S_ISCHR (mode))
2438 if (type == C_FILE && (mode & S_IXUGO) != 0)
2441 /* Check the file's suffix only if still classified as C_FILE. */
2445 /* Test if NAME has a recognized suffix. */
2447 len = strlen (name);
2448 name += len; /* Pointer to final \0. */
2449 for (ext = col_ext_list; ext != NULL; ext = ext->next)
2451 if (ext->ext.len <= len
2452 && strncmp (name - ext->ext.len, ext->ext.string,
2459 put_indicator (&color_indicator[C_LEFT]);
2460 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
2461 put_indicator (&color_indicator[C_RIGHT]);
2464 /* Output a color indicator (which may contain nulls). */
2466 put_indicator (const struct bin_str *ind)
2473 for (i = ind->len; i > 0; --i)
2478 length_of_file_name_and_frills (const struct fileinfo *f)
2480 register char *p = f->name;
2481 register unsigned char c;
2482 register int len = 0;
2485 len += INODE_DIGITS + 1;
2487 if (print_block_size)
2488 len += 1 + block_size_size;
2490 if (quote_as_string)
2495 if (quote_funny_chars)
2510 if (quote_as_string)
2527 if (indicator_style != none)
2529 unsigned filetype = f->stat.st_mode;
2531 if (S_ISREG (filetype))
2533 if (indicator_style == all
2534 && (f->stat.st_mode & S_IXUGO))
2537 else if (S_ISDIR (filetype)
2539 || S_ISLNK (filetype)
2542 || S_ISFIFO (filetype)
2545 || S_ISSOCK (filetype)
2555 print_many_per_line (void)
2557 int filesno; /* Index into files. */
2558 int row; /* Current row. */
2559 int max_name_length; /* Length of longest file name + frills. */
2560 int name_length; /* Length of each file name + frills. */
2561 int pos; /* Current character column. */
2562 int cols; /* Number of files across. */
2563 int rows; /* Maximum number of files down. */
2565 /* Compute the maximum file name length. */
2566 max_name_length = 0;
2567 for (filesno = 0; filesno < files_index; filesno++)
2569 name_length = length_of_file_name_and_frills (files + filesno);
2570 if (name_length > max_name_length)
2571 max_name_length = name_length;
2574 /* Allow at least two spaces between names. */
2575 max_name_length += 2;
2577 /* Calculate the maximum number of columns that will fit. */
2578 cols = line_length / max_name_length;
2581 /* Calculate the number of rows that will be in each column except possibly
2582 for a short column on the right. */
2583 rows = files_index / cols + (files_index % cols != 0);
2584 /* Recalculate columns based on rows. */
2585 cols = files_index / rows + (files_index % rows != 0);
2587 for (row = 0; row < rows; row++)
2591 /* Print the next row. */
2594 print_file_name_and_frills (files + filesno);
2595 name_length = length_of_file_name_and_frills (files + filesno);
2598 if (filesno >= files_index)
2601 indent (pos + name_length, pos + max_name_length);
2602 pos += max_name_length;
2609 print_horizontal (void)
2612 int max_name_length;
2617 /* Compute the maximum file name length. */
2618 max_name_length = 0;
2619 for (filesno = 0; filesno < files_index; filesno++)
2621 name_length = length_of_file_name_and_frills (files + filesno);
2622 if (name_length > max_name_length)
2623 max_name_length = name_length;
2626 /* Allow two spaces between names. */
2627 max_name_length += 2;
2629 cols = line_length / max_name_length;
2636 for (filesno = 0; filesno < files_index; filesno++)
2640 if (filesno % cols == 0)
2647 indent (pos + name_length, pos + max_name_length);
2648 pos += max_name_length;
2652 print_file_name_and_frills (files + filesno);
2654 name_length = length_of_file_name_and_frills (files + filesno);
2660 print_with_commas (void)
2667 for (filesno = 0; filesno < files_index; filesno++)
2671 pos += length_of_file_name_and_frills (files + filesno);
2672 if (filesno + 1 < files_index)
2673 pos += 2; /* For the comma and space */
2675 if (old_pos != 0 && pos >= line_length)
2681 print_file_name_and_frills (files + filesno);
2682 if (filesno + 1 < files_index)
2691 /* Assuming cursor is at position FROM, indent up to position TO.
2692 Use a TAB character instead of two or more spaces whenever possible. */
2695 indent (int from, int to)
2699 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
2702 from += tabsize - from % tabsize;
2712 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2715 attach (char *dest, const char *dirname, const char *name)
2717 const char *dirnamep = dirname;
2719 /* Copy dirname if it is not ".". */
2720 if (dirname[0] != '.' || dirname[1] != 0)
2723 *dest++ = *dirnamep++;
2724 /* Add '/' if `dirname' doesn't already end with it. */
2725 if (dirnamep > dirname && dirnamep[-1] != '/')
2737 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2741 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2743 List information about the FILEs (the current directory by default).\n\
2744 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2746 -a, --all do not hide entries starting with .\n\
2747 -A, --almost-all do not list implied . and ..\n\
2748 -b, --escape print octal escapes for nongraphic characters\n\
2749 -B, --ignore-backups do not list implied entries ending with ~\n\
2750 -c sort by change time; with -l: show ctime\n\
2751 -C list entries by columns\n\
2752 --color[=WHEN] control whether color is used to distinguish file\n\
2753 types. WHEN may be `never', `always', or `auto'\n\
2754 -d, --directory list directory entries instead of contents\n\
2755 -D, --dired generate output designed for Emacs' dired mode\n\
2756 -f do not sort, enable -aU, disable -lst\n\
2757 -F, --classify append a character for typing each entry\n\
2758 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2759 single-column -1, verbose -l, vertical -C\n\
2760 --full-time list both full date and full time\n"));
2764 -G, --no-group inhibit display of group information\n\
2765 -i, --inode print index number of each file\n\
2766 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2767 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
2768 -l use a long listing format\n\
2769 -L, --dereference list entries pointed to by symbolic links\n\
2770 -m fill width with a comma separated list of entries\n\
2771 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2772 -N, --literal print raw entry names (don't treat e.g. control\n\
2773 characters specially)\n\
2774 -o use long listing format without group info\n\
2775 -p append a character for typing each entry\n\
2776 -q, --hide-control-chars print ? instead of non graphic characters\n\
2777 -Q, --quote-name enclose entry names in double quotes\n\
2778 -r, --reverse reverse order while sorting\n\
2779 -R, --recursive list subdirectories recursively\n\
2780 -s, --size print size of each file, in blocks\n"));
2783 -S sort by file size\n\
2784 --sort=WORD ctime -c, extension -X, none -U, size -S,\n\
2785 status -c, time -t, atime -u, access -u, use -u\n\
2786 --time=WORD show time as WORD instead of modification time:\n\
2787 atime, access, use, ctime or status\n\
2788 -t sort by modification time; with -l: show mtime\n\
2789 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2790 -u sort by last access time; with -l: show atime\n\
2791 -U do not sort; list entries in directory order\n\
2792 -w, --width=COLS assume screen width instead of current value\n\
2793 -x list entries by lines instead of by columns\n\
2794 -X sort alphabetically by entry extension\n\
2795 -1 list one file per line\n\
2796 --help display this help and exit\n\
2797 --version output version information and exit\n\
2799 By default, color is not used to distinguish types of files. That is\n\
2800 equivalent to using --color=none. Using the --color option without the\n\
2801 optional WHEN argument is equivalent to using --color=always. With\n\
2802 --color=auto, color codes are output only if standard output is connected\n\
2803 to a terminal (tty).\n\
2805 puts (_("\nReport bugs to <fileutils-bugs@gnu.ai.mit.edu>."));