(do_link): Produce the same sort of one-line output for
[coreutils.git] / src / ls.c
blob692b4483e579393c69c074d37ba61d0f29555639
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-1999 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 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.
28 If ls_mode is LS_LS,
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 /* 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>. */
39 #ifdef _AIX
40 #pragma alloca
41 #endif
43 #include <config.h>
44 #include <sys/types.h>
46 #if HAVE_INTTYPES_H
47 # include <inttypes.h>
48 #endif
50 #if HAVE_TERMIOS_H
51 # include <termios.h>
52 #endif
54 #ifdef GWINSZ_IN_SYS_IOCTL
55 # include <sys/ioctl.h>
56 #endif
58 #ifdef WINSIZE_IN_PTEM
59 # include <sys/stream.h>
60 # include <sys/ptem.h>
61 #endif
63 #if HAVE_SYS_ACL_H
64 # include <sys/acl.h>
65 #endif
67 #include <stdio.h>
68 #include <assert.h>
69 #include <grp.h>
70 #include <pwd.h>
71 #include <getopt.h>
73 #include "system.h"
74 #include <fnmatch.h>
76 #include "argmatch.h"
77 #include "error.h"
78 #include "human.h"
79 #include "filemode.h"
80 #include "ls.h"
81 #include "obstack.h"
82 #include "path-concat.h"
83 #include "quotearg.h"
84 #include "strverscmp.h"
85 #include "xstrtol.h"
87 /* Use access control lists only under all the following conditions.
88 Some systems (OSF4, Irix5, Irix6) have the acl function, but not
89 sys/acl.h or don't define the GETACLCNT macro. */
90 #if HAVE_SYS_ACL_H && HAVE_ACL && defined GETACLCNT
91 # define USE_ACL 1
92 #endif
94 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
95 : (ls_mode == LS_MULTI_COL \
96 ? "dir" : "vdir"))
98 #define AUTHORS "Richard Stallman and David MacKenzie"
100 #define obstack_chunk_alloc malloc
101 #define obstack_chunk_free free
103 /* Return an int indicating the result of comparing two integers.
104 Subtracting doesn't always work, due to overflow. */
105 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
107 /* The field width for inode numbers. On some hosts inode numbers are
108 64 bits, so columns won't line up exactly when a huge inode number
109 is encountered, but in practice 7 digits is usually enough. */
110 #ifndef INODE_DIGITS
111 # define INODE_DIGITS 7
112 #endif
114 #ifdef S_ISLNK
115 # define HAVE_SYMLINKS 1
116 #else
117 # define HAVE_SYMLINKS 0
118 #endif
120 /* If any of the S_* macros are undefined, define them here so each
121 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
122 #ifndef S_ISLNK
123 # define S_ISLNK(Mode) 0
124 #endif
126 #ifndef S_ISFIFO
127 # define S_ISFIFO(Mode) 0
128 #endif
130 #ifndef S_ISSOCK
131 # define S_ISSOCK(Mode) 0
132 #endif
134 #ifndef S_ISCHR
135 # define S_ISCHR(Mode) 0
136 #endif
138 #ifndef S_ISBLK
139 # define S_ISBLK(Mode) 0
140 #endif
142 #ifndef S_ISDOOR
143 # define S_ISDOOR(Mode) 0
144 #endif
146 /* Arrange to make lstat calls go through the wrapper function
147 on systems with an lstat function that does not dereference symlinks
148 that are specified with a trailing slash. */
149 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
150 int rpl_lstat PARAMS((const char *, struct stat *));
151 # undef lstat
152 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
153 #endif
155 enum filetype
157 symbolic_link,
158 directory,
159 arg_directory, /* Directory given as command line arg. */
160 normal /* All others. */
163 struct fileinfo
165 /* The file name. */
166 char *name;
168 struct stat stat;
170 /* For symbolic link, name of the file linked to, otherwise zero. */
171 char *linkname;
173 /* For symbolic link and long listing, st_mode of file linked to, otherwise
174 zero. */
175 unsigned int linkmode;
177 /* For symbolic link and color printing, 1 if linked-to file
178 exists, otherwise 0. */
179 int linkok;
181 enum filetype filetype;
183 #if USE_ACL
184 /* For long listings, nonzero if the file has an access control list,
185 otherwise zero. */
186 int have_acl;
187 #endif
190 #if USE_ACL
191 # define FILE_HAS_ACL(F) ((F)->have_acl)
192 #else
193 # define FILE_HAS_ACL(F) 0
194 #endif
196 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
198 /* Null is a valid character in a color indicator (think about Epson
199 printers, for example) so we have to use a length/buffer string
200 type. */
202 struct bin_str
204 int len; /* Number of bytes */
205 char *string; /* Pointer to the same */
208 #ifndef STDC_HEADERS
209 time_t time ();
210 #endif
212 char *getgroup ();
213 char *getuser ();
215 static size_t quote_name PARAMS ((FILE *out, const char *name,
216 struct quoting_options const *options));
217 static char *make_link_path PARAMS ((const char *path, const char *linkname));
218 static int compare_atime PARAMS ((const struct fileinfo *file1,
219 const struct fileinfo *file2));
220 static int rev_cmp_atime PARAMS ((const struct fileinfo *file2,
221 const struct fileinfo *file1));
222 static int compare_ctime PARAMS ((const struct fileinfo *file1,
223 const struct fileinfo *file2));
224 static int rev_cmp_ctime PARAMS ((const struct fileinfo *file2,
225 const struct fileinfo *file1));
226 static int compare_mtime PARAMS ((const struct fileinfo *file1,
227 const struct fileinfo *file2));
228 static int rev_cmp_mtime PARAMS ((const struct fileinfo *file2,
229 const struct fileinfo *file1));
230 static int compare_size PARAMS ((const struct fileinfo *file1,
231 const struct fileinfo *file2));
232 static int rev_cmp_size PARAMS ((const struct fileinfo *file2,
233 const struct fileinfo *file1));
234 static int compare_name PARAMS ((const struct fileinfo *file1,
235 const struct fileinfo *file2));
236 static int rev_cmp_name PARAMS ((const struct fileinfo *file2,
237 const struct fileinfo *file1));
238 static int compare_extension PARAMS ((const struct fileinfo *file1,
239 const struct fileinfo *file2));
240 static int rev_cmp_extension PARAMS ((const struct fileinfo *file2,
241 const struct fileinfo *file1));
242 static int compare_version PARAMS ((const struct fileinfo *file1,
243 const struct fileinfo *file2));
244 static int rev_cmp_version PARAMS ((const struct fileinfo *file2,
245 const struct fileinfo *file1));
246 static int decode_switches PARAMS ((int argc, char **argv));
247 static int file_interesting PARAMS ((const struct dirent *next));
248 static uintmax_t gobble_file PARAMS ((const char *name, int explicit_arg,
249 const char *dirname));
250 static void print_color_indicator PARAMS ((const char *name, unsigned int mode,
251 int linkok));
252 static void put_indicator PARAMS ((const struct bin_str *ind));
253 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
254 static void add_ignore_pattern PARAMS ((const char *pattern));
255 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
256 static void clear_files PARAMS ((void));
257 static void extract_dirs_from_files PARAMS ((const char *dirname,
258 int recursive));
259 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
260 static void indent PARAMS ((int from, int to));
261 static void init_column_info PARAMS ((void));
262 static void print_current_files PARAMS ((void));
263 static void print_dir PARAMS ((const char *name, const char *realname));
264 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
265 static void print_horizontal PARAMS ((void));
266 static void print_long_format PARAMS ((const struct fileinfo *f));
267 static void print_many_per_line PARAMS ((void));
268 static void print_name_with_quoting PARAMS ((const char *p, unsigned int mode,
269 int linkok,
270 struct obstack *stack));
271 static void prep_non_filename_text PARAMS ((void));
272 static void print_type_indicator PARAMS ((unsigned int mode));
273 static void print_with_commas PARAMS ((void));
274 static void queue_directory PARAMS ((const char *name, const char *realname));
275 static void sort_files PARAMS ((void));
276 static void parse_ls_color PARAMS ((void));
277 void usage PARAMS ((int status));
279 /* The name the program was run with, stripped of any leading path. */
280 char *program_name;
282 /* The table of files in the current directory:
284 `files' points to a vector of `struct fileinfo', one per file.
285 `nfiles' is the number of elements space has been allocated for.
286 `files_index' is the number actually in use. */
288 /* Address of block containing the files that are described. */
290 static struct fileinfo *files;
292 /* Length of block that `files' points to, measured in files. */
294 static int nfiles;
296 /* Index of first unused in `files'. */
298 static int files_index;
300 /* Record of one pending directory waiting to be listed. */
302 struct pending
304 char *name;
305 /* If the directory is actually the file pointed to by a symbolic link we
306 were told to list, `realname' will contain the name of the symbolic
307 link, otherwise zero. */
308 char *realname;
309 struct pending *next;
312 static struct pending *pending_dirs;
314 /* Current time (seconds since 1970). When we are printing a file's time,
315 include the year if it is more than 6 months before this time. */
317 static time_t current_time;
319 /* The number of digits to use for block sizes.
320 4, or more if needed for bigger numbers. */
322 static int block_size_size;
324 /* Option flags */
326 /* long_format for lots of info, one per line.
327 one_per_line for just names, one per line.
328 many_per_line for just names, many per line, sorted vertically.
329 horizontal for just names, many per line, sorted horizontally.
330 with_commas for just names, many per line, separated by commas.
332 -l, -1, -C, -x and -m control this parameter. */
334 enum format
336 long_format, /* -l */
337 one_per_line, /* -1 */
338 many_per_line, /* -C */
339 horizontal, /* -x */
340 with_commas /* -m */
343 static enum format format;
345 /* Type of time to print or sort by. Controlled by -c and -u. */
347 enum time_type
349 time_mtime, /* default */
350 time_ctime, /* -c */
351 time_atime /* -u */
354 static enum time_type time_type;
356 /* print the full time, otherwise the standard unix heuristics. */
358 static int full_time;
360 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
362 enum sort_type
364 sort_none, /* -U */
365 sort_name, /* default */
366 sort_extension, /* -X */
367 sort_time, /* -t */
368 sort_size, /* -S */
369 sort_version /* -v */
372 static enum sort_type sort_type;
374 /* Direction of sort.
375 0 means highest first if numeric,
376 lowest first if alphabetic;
377 these are the defaults.
378 1 means the opposite order in each case. -r */
380 static int sort_reverse;
382 /* Nonzero means to NOT display group information. -G */
384 static int inhibit_group;
386 /* Nonzero means print the user and group id's as numbers rather
387 than as names. -n */
389 static int numeric_ids;
391 /* Nonzero means mention the size in blocks of each file. -s */
393 static int print_block_size;
395 /* If positive, the units to use when printing sizes;
396 if negative, the human-readable base. */
397 static int output_block_size;
399 /* Precede each line of long output (per file) with a string like `m,n:'
400 where M is the number of characters after the `:' and before the
401 filename and N is the length of the filename. Using this format,
402 Emacs' dired mode starts up twice as fast, and can handle all
403 strange characters in file names. */
404 static int dired;
406 /* `none' means don't mention the type of files.
407 `classify' means mention file types and mark executables.
408 `file_type' means mention only file types.
410 Controlled by -F, -p, and --indicator-style. */
412 enum indicator_style
414 none, /* --indicator-style=none */
415 classify, /* -F, --indicator-style=classify */
416 file_type /* -p, --indicator-style=file-type */
419 static enum indicator_style indicator_style;
421 /* Names of indicator styles. */
422 static char const *const indicator_style_args[] =
424 "none", "classify", "file-type", 0
427 static enum indicator_style const indicator_style_types[]=
429 none, classify, file_type
432 /* Nonzero means use colors to mark types. Also define the different
433 colors as well as the stuff for the LS_COLORS environment variable.
434 The LS_COLORS variable is now in a termcap-like format. */
436 static int print_with_color;
438 enum color_type
440 color_never, /* 0: default or --color=never */
441 color_always, /* 1: --color=always */
442 color_if_tty /* 2: --color=tty */
445 enum indicator_no
447 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
448 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
451 static const char *const indicator_name[]=
453 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
454 "bd", "cd", "mi", "or", "ex", "do", NULL
457 struct color_ext_type
459 struct bin_str ext; /* The extension we're looking for */
460 struct bin_str seq; /* The sequence to output when we do */
461 struct color_ext_type *next; /* Next in list */
464 static struct bin_str color_indicator[] =
466 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
467 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
468 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
469 { LEN_STR_PAIR ("0") }, /* no: Normal */
470 { LEN_STR_PAIR ("0") }, /* fi: File: default */
471 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
472 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
473 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
474 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
475 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
476 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
477 { 0, NULL }, /* mi: Missing file: undefined */
478 { 0, NULL }, /* or: Orphanned symlink: undefined */
479 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
480 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
483 /* FIXME: comment */
484 static struct color_ext_type *color_ext_list = NULL;
486 /* Buffer for color sequences */
487 static char *color_buf;
489 /* Nonzero means to check for orphaned symbolic link, for displaying
490 colors. */
492 static int check_symlink_color;
494 /* Nonzero means mention the inode number of each file. -i */
496 static int print_inode;
498 /* Nonzero means when a symbolic link is found, display info on
499 the file linked to. -L */
501 static int trace_links;
503 /* Nonzero means when a directory is found, display info on its
504 contents. -R */
506 static int trace_dirs;
508 /* Nonzero means when an argument is a directory name, display info
509 on it itself. -d */
511 static int immediate_dirs;
513 /* Nonzero means don't omit files whose names start with `.'. -A */
515 static int all_files;
517 /* Nonzero means don't omit files `.' and `..'
518 This flag implies `all_files'. -a */
520 static int really_all_files;
522 /* A linked list of shell-style globbing patterns. If a non-argument
523 file name matches any of these patterns, it is omitted.
524 Controlled by -I. Multiple -I options accumulate.
525 The -B option adds `*~' and `.*~' to this list. */
527 struct ignore_pattern
529 const char *pattern;
530 struct ignore_pattern *next;
533 static struct ignore_pattern *ignore_patterns;
535 /* Nonzero means output nongraphic chars in file names as `?'.
536 (-q, --hide-control-chars)
537 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
538 independent. The algorithm is: first, obey the quoting style to get a
539 string representing the file name; then, if qmark_funny_chars is set,
540 replace all nonprintable chars in that string with `?'. It's necessary
541 to replace nonprintable chars even in quoted strings, because we don't
542 want to mess up the terminal if control chars get sent to it, and some
543 quoting methods pass through control chars as-is. */
544 static int qmark_funny_chars;
546 /* Quoting options for file and dir name output. */
548 static struct quoting_options *filename_quoting_options;
549 static struct quoting_options *dirname_quoting_options;
551 /* The number of chars per hardware tab stop. Setting this to zero
552 inhibits the use of TAB characters for separating columns. -T */
553 static int tabsize;
555 /* Nonzero means we are listing the working directory because no
556 non-option arguments were given. */
558 static int dir_defaulted;
560 /* Nonzero means print each directory name before listing it. */
562 static int print_dir_name;
564 /* The line length to use for breaking lines in many-per-line format.
565 Can be set with -w. */
567 static int line_length;
569 /* If nonzero, the file listing format requires that stat be called on
570 each file. */
572 static int format_needs_stat;
574 /* The exit status to use if we don't get any fatal errors. */
576 static int exit_status;
578 static struct option const long_options[] =
580 {"all", no_argument, 0, 'a'},
581 {"escape", no_argument, 0, 'b'},
582 {"directory", no_argument, 0, 'd'},
583 {"dired", no_argument, 0, 'D'},
584 {"full-time", no_argument, &full_time, 1},
585 {"human-readable", no_argument, 0, 'h'},
586 {"inode", no_argument, 0, 'i'},
587 {"kilobytes", no_argument, 0, 'k'},
588 {"numeric-uid-gid", no_argument, 0, 'n'},
589 {"no-group", no_argument, 0, 'G'},
590 {"hide-control-chars", no_argument, 0, 'q'},
591 {"reverse", no_argument, 0, 'r'},
592 {"size", no_argument, 0, 's'},
593 {"width", required_argument, 0, 'w'},
594 {"almost-all", no_argument, 0, 'A'},
595 {"ignore-backups", no_argument, 0, 'B'},
596 {"classify", no_argument, 0, 'F'},
597 {"file-type", no_argument, 0, 'p'},
598 {"si", no_argument, 0, 'H'},
599 {"ignore", required_argument, 0, 'I'},
600 {"indicator-style", required_argument, 0, 14},
601 {"dereference", no_argument, 0, 'L'},
602 {"literal", no_argument, 0, 'N'},
603 {"quote-name", no_argument, 0, 'Q'},
604 {"quoting-style", required_argument, 0, 15},
605 {"recursive", no_argument, 0, 'R'},
606 {"format", required_argument, 0, 12},
607 {"show-control-chars", no_argument, 0, 16},
608 {"sort", required_argument, 0, 10},
609 {"tabsize", required_argument, 0, 'T'},
610 {"time", required_argument, 0, 11},
611 {"color", optional_argument, 0, 13},
612 {"block-size", required_argument, 0, 17},
613 {GETOPT_HELP_OPTION_DECL},
614 {GETOPT_VERSION_OPTION_DECL},
615 {NULL, 0, NULL, 0}
618 static char const *const format_args[] =
620 "verbose", "long", "commas", "horizontal", "across",
621 "vertical", "single-column", 0
624 static enum format const format_types[] =
626 long_format, long_format, with_commas, horizontal, horizontal,
627 many_per_line, one_per_line
630 static char const *const sort_args[] =
632 "none", "time", "size", "extension", "version", 0
635 static enum sort_type const sort_types[] =
637 sort_none, sort_time, sort_size, sort_extension, sort_version
640 static char const *const time_args[] =
642 "atime", "access", "use", "ctime", "status", 0
645 static enum time_type const time_types[] =
647 time_atime, time_atime, time_atime, time_ctime, time_ctime
650 static char const *const color_args[] =
652 /* force and none are for compatibility with another color-ls version */
653 "always", "yes", "force",
654 "never", "no", "none",
655 "auto", "tty", "if-tty", 0
658 static enum color_type const color_types[] =
660 color_always, color_always, color_always,
661 color_never, color_never, color_never,
662 color_if_tty, color_if_tty, color_if_tty
665 /* Information about filling a column. */
666 struct column_info
668 int valid_len;
669 int line_len;
670 int *col_arr;
673 /* Array with information about column filledness. */
674 static struct column_info *column_info;
676 /* Maximum number of columns ever possible for this display. */
677 static int max_idx;
679 /* The minimum width of a colum is 3: 1 character for the name and 2
680 for the separating white space. */
681 #define MIN_COLUMN_WIDTH 3
684 /* This zero-based index is used solely with the --dired option.
685 When that option is in effect, this counter is incremented for each
686 character of output generated by this program so that the beginning
687 and ending indices (in that output) of every file name can be recorded
688 and later output themselves. */
689 static size_t dired_pos;
691 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
693 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
694 #define DIRED_FPUTS(s, stream, s_len) \
695 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
697 /* Like DIRED_FPUTS, but for use when S is a literal string. */
698 #define DIRED_FPUTS_LITERAL(s, stream) \
699 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
701 #define DIRED_INDENT() \
702 do \
704 /* FIXME: remove the `&& format == long_format' clause. */ \
705 if (dired && format == long_format) \
706 DIRED_FPUTS_LITERAL (" ", stdout); \
708 while (0)
710 /* With --dired, store pairs of beginning and ending indices of filenames. */
711 static struct obstack dired_obstack;
713 /* With --dired, store pairs of beginning and ending indices of any
714 directory names that appear as headers (just before `total' line)
715 for lists of directory entries. Such directory names are seen when
716 listing hierarchies using -R and when a directory is listed with at
717 least one other command line argument. */
718 static struct obstack subdired_obstack;
720 /* Save the current index on the specified obstack, OBS. */
721 #define PUSH_CURRENT_DIRED_POS(obs) \
722 do \
724 /* FIXME: remove the `&& format == long_format' clause. */ \
725 if (dired && format == long_format) \
726 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
728 while (0)
731 /* Write to standard output PREFIX, followed by the quoting style and
732 a space-separated list of the integers stored in OS all on one line. */
734 static void
735 dired_dump_obstack (const char *prefix, struct obstack *os)
737 int n_pos;
739 n_pos = obstack_object_size (os) / sizeof (dired_pos);
740 if (n_pos > 0)
742 int i;
743 size_t *pos;
745 pos = (size_t *) obstack_finish (os);
746 fputs (prefix, stdout);
747 for (i = 0; i < n_pos; i++)
748 printf (" %d", (int) pos[i]);
749 fputs ("\n", stdout);
754 main (int argc, char **argv)
756 register int i;
757 register struct pending *thispend;
759 program_name = argv[0];
760 setlocale (LC_ALL, "");
761 bindtextdomain (PACKAGE, LOCALEDIR);
762 textdomain (PACKAGE);
764 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
765 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
767 exit_status = 0;
768 dir_defaulted = 1;
769 print_dir_name = 1;
770 pending_dirs = 0;
771 current_time = time ((time_t *) 0);
773 i = decode_switches (argc, argv);
775 if (print_with_color)
777 parse_ls_color ();
778 prep_non_filename_text ();
779 /* Avoid following symbolic links when possible. */
780 if (color_indicator[C_ORPHAN].string != NULL
781 || (color_indicator[C_MISSING].string != NULL
782 && format == long_format))
783 check_symlink_color = 1;
786 format_needs_stat = sort_type == sort_time || sort_type == sort_size
787 || format == long_format
788 || trace_links || trace_dirs || indicator_style != none
789 || print_block_size || print_inode || print_with_color;
791 if (dired && format == long_format)
793 obstack_init (&dired_obstack);
794 obstack_init (&subdired_obstack);
797 nfiles = 100;
798 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
799 files_index = 0;
801 clear_files ();
803 if (i < argc)
804 dir_defaulted = 0;
805 for (; i < argc; i++)
807 gobble_file (argv[i], 1, "");
810 if (dir_defaulted)
812 if (immediate_dirs)
813 gobble_file (".", 1, "");
814 else
815 queue_directory (".", 0);
818 if (files_index)
820 sort_files ();
821 if (!immediate_dirs)
822 extract_dirs_from_files ("", 0);
823 /* `files_index' might be zero now. */
825 if (files_index)
827 print_current_files ();
828 if (pending_dirs)
829 DIRED_PUTCHAR ('\n');
831 else if (pending_dirs && pending_dirs->next == 0)
832 print_dir_name = 0;
834 while (pending_dirs)
836 thispend = pending_dirs;
837 pending_dirs = pending_dirs->next;
838 print_dir (thispend->name, thispend->realname);
839 free (thispend->name);
840 if (thispend->realname)
841 free (thispend->realname);
842 free (thispend);
843 print_dir_name = 1;
846 if (dired && format == long_format)
848 /* No need to free these since we're about to exit. */
849 dired_dump_obstack ("//DIRED//", &dired_obstack);
850 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
851 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
852 ARGMATCH_TO_ARGUMENT (filename_quoting_options,
853 quoting_style_args, quoting_style_vals));
856 /* Restore default color before exiting */
857 if (print_with_color)
859 put_indicator (&color_indicator[C_LEFT]);
860 put_indicator (&color_indicator[C_RIGHT]);
863 close_stdout ();
864 exit (exit_status);
867 /* Set all the option flags according to the switches specified.
868 Return the index of the first non-option argument. */
870 static int
871 decode_switches (int argc, char **argv)
873 register char const *p;
874 int c;
875 int i;
876 long int tmp_long;
878 /* Record whether there is an option specifying sort type. */
879 int sort_type_specified = 0;
881 qmark_funny_chars = 0;
883 /* initialize all switches to default settings */
885 switch (ls_mode)
887 case LS_MULTI_COL:
888 /* This is for the `dir' program. */
889 format = many_per_line;
890 set_quoting_style (NULL, escape_quoting_style);
891 break;
893 case LS_LONG_FORMAT:
894 /* This is for the `vdir' program. */
895 format = long_format;
896 set_quoting_style (NULL, escape_quoting_style);
897 break;
899 case LS_LS:
900 /* This is for the `ls' program. */
901 if (isatty (STDOUT_FILENO))
903 format = many_per_line;
904 /* See description of qmark_funny_chars, above. */
905 qmark_funny_chars = 1;
907 else
909 format = one_per_line;
910 qmark_funny_chars = 0;
912 break;
914 default:
915 abort ();
918 time_type = time_mtime;
919 full_time = 0;
920 sort_type = sort_name;
921 sort_reverse = 0;
922 numeric_ids = 0;
923 print_block_size = 0;
924 indicator_style = none;
925 print_inode = 0;
926 trace_links = 0;
927 trace_dirs = 0;
928 immediate_dirs = 0;
929 all_files = 0;
930 really_all_files = 0;
931 ignore_patterns = 0;
933 /* FIXME: Shouldn't we complain on wrong values? */
934 if ((p = getenv ("QUOTING_STYLE"))
935 && 0 <= (i = ARGCASEMATCH (p, quoting_style_args, quoting_style_vals)))
936 set_quoting_style (NULL, quoting_style_vals[i]);
938 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
940 line_length = 80;
941 if ((p = getenv ("COLUMNS")) && *p)
943 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
944 && 0 < tmp_long && tmp_long <= INT_MAX)
946 line_length = (int) tmp_long;
948 else
950 error (0, 0,
951 _("ignoring invalid width in environment variable COLUMNS: %s"),
952 quotearg (p));
956 #ifdef TIOCGWINSZ
958 struct winsize ws;
960 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
961 line_length = ws.ws_col;
963 #endif
965 /* Using the TABSIZE environment variable is not POSIX-approved.
966 Ignore it when POSIXLY_CORRECT is set. */
967 tabsize = 8;
968 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
970 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
971 && 0 <= tmp_long && tmp_long <= INT_MAX)
973 tabsize = (int) tmp_long;
975 else
977 error (0, 0,
978 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
979 quotearg (p));
983 while ((c = getopt_long (argc, argv,
984 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
985 long_options, NULL)) != -1)
987 switch (c)
989 case 0:
990 break;
992 case 'a':
993 all_files = 1;
994 really_all_files = 1;
995 break;
997 case 'b':
998 set_quoting_style (NULL, escape_quoting_style);
999 break;
1001 case 'c':
1002 time_type = time_ctime;
1003 break;
1005 case 'd':
1006 immediate_dirs = 1;
1007 break;
1009 case 'f':
1010 /* Same as enabling -a -U and disabling -l -s. */
1011 all_files = 1;
1012 really_all_files = 1;
1013 sort_type = sort_none;
1014 sort_type_specified = 1;
1015 /* disable -l */
1016 if (format == long_format)
1017 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1018 print_block_size = 0; /* disable -s */
1019 print_with_color = 0; /* disable --color */
1020 break;
1022 case 'g':
1023 /* No effect. For BSD compatibility. */
1024 break;
1026 case 'h':
1027 output_block_size = -1024;
1028 break;
1030 case 'H':
1031 output_block_size = -1000;
1032 break;
1034 case 'i':
1035 print_inode = 1;
1036 break;
1038 case 'k':
1039 output_block_size = 1024;
1040 break;
1042 case 'l':
1043 format = long_format;
1044 break;
1046 case 'm':
1047 format = with_commas;
1048 break;
1050 case 'n':
1051 numeric_ids = 1;
1052 break;
1054 case 'o': /* Just like -l, but don't display group info. */
1055 format = long_format;
1056 inhibit_group = 1;
1057 break;
1059 case 'p':
1060 indicator_style = file_type;
1061 break;
1063 case 'q':
1064 qmark_funny_chars = 1;
1065 break;
1067 case 'r':
1068 sort_reverse = 1;
1069 break;
1071 case 's':
1072 print_block_size = 1;
1073 break;
1075 case 't':
1076 sort_type = sort_time;
1077 sort_type_specified = 1;
1078 break;
1080 case 'u':
1081 time_type = time_atime;
1082 break;
1084 case 'v':
1085 sort_type = sort_version;
1086 sort_type_specified = 1;
1087 break;
1089 case 'w':
1090 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1091 || tmp_long <= 0 || tmp_long > INT_MAX)
1092 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1093 quotearg (optarg));
1094 line_length = (int) tmp_long;
1095 break;
1097 case 'x':
1098 format = horizontal;
1099 break;
1101 case 'A':
1102 really_all_files = 0;
1103 all_files = 1;
1104 break;
1106 case 'B':
1107 add_ignore_pattern ("*~");
1108 add_ignore_pattern (".*~");
1109 break;
1111 case 'C':
1112 format = many_per_line;
1113 break;
1115 case 'D':
1116 dired = 1;
1117 break;
1119 case 'F':
1120 indicator_style = classify;
1121 break;
1123 case 'G': /* inhibit display of group info */
1124 inhibit_group = 1;
1125 break;
1127 case 'I':
1128 add_ignore_pattern (optarg);
1129 break;
1131 case 'L':
1132 trace_links = 1;
1133 break;
1135 case 'N':
1136 set_quoting_style (NULL, literal_quoting_style);
1137 break;
1139 case 'Q':
1140 set_quoting_style (NULL, c_quoting_style);
1141 break;
1143 case 'R':
1144 trace_dirs = 1;
1145 break;
1147 case 'S':
1148 sort_type = sort_size;
1149 sort_type_specified = 1;
1150 break;
1152 case 'T':
1153 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1154 || tmp_long < 0 || tmp_long > INT_MAX)
1155 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1156 quotearg (optarg));
1157 tabsize = (int) tmp_long;
1158 break;
1160 case 'U':
1161 sort_type = sort_none;
1162 sort_type_specified = 1;
1163 break;
1165 case 'X':
1166 sort_type = sort_extension;
1167 sort_type_specified = 1;
1168 break;
1170 case '1':
1171 format = one_per_line;
1172 break;
1174 case 10: /* --sort */
1175 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1176 sort_type_specified = 1;
1177 break;
1179 case 11: /* --time */
1180 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1181 break;
1183 case 12: /* --format */
1184 format = XARGMATCH ("--format", optarg, format_args, format_types);
1185 break;
1187 case 13: /* --color */
1188 if (optarg)
1189 i = XARGMATCH ("--color", optarg, color_args, color_types);
1190 else
1191 /* Using --color with no argument is equivalent to using
1192 --color=always. */
1193 i = color_always;
1195 print_with_color = (i == color_always
1196 || (i == color_if_tty
1197 && isatty (STDOUT_FILENO)));
1199 if (print_with_color)
1201 /* Don't use TAB characters in output. Some terminal
1202 emulators can't handle the combination of tabs and
1203 color codes on the same line. */
1204 tabsize = 0;
1206 break;
1208 case 14: /* --indicator-style */
1209 indicator_style = XARGMATCH ("--indicator-style", optarg,
1210 indicator_style_args,
1211 indicator_style_types);
1212 break;
1214 case 15: /* --quoting-style */
1215 set_quoting_style (NULL,
1216 XARGMATCH ("--quoting-style", optarg,
1217 quoting_style_args,
1218 quoting_style_vals));
1219 break;
1221 case 16:
1222 qmark_funny_chars = 0;
1223 break;
1225 case 17:
1226 human_block_size (optarg, 1, &output_block_size);
1227 break;
1229 case_GETOPT_HELP_CHAR;
1231 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1233 default:
1234 usage (EXIT_FAILURE);
1238 filename_quoting_options = clone_quoting_options (NULL);
1239 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1240 set_char_quoting (filename_quoting_options, ' ', 1);
1241 if (indicator_style != none)
1242 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1243 set_char_quoting (filename_quoting_options, *p, 1);
1245 dirname_quoting_options = clone_quoting_options (NULL);
1246 set_char_quoting (dirname_quoting_options, ':', 1);
1248 /* If -c or -u is specified and not -l (or any other option that implies -l),
1249 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1250 The behavior of ls when using either -c or -u but with neither -l nor -t
1251 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1252 sort by atime (this is the one that's not specified by the POSIX spec),
1253 -lu means show atime and sort by name, -lut means show atime and sort
1254 by atime. */
1256 if ((time_type == time_ctime || time_type == time_atime)
1257 && !sort_type_specified && format != long_format)
1259 sort_type = sort_time;
1262 return optind;
1265 /* Parse a string as part of the LS_COLORS variable; this may involve
1266 decoding all kinds of escape characters. If equals_end is set an
1267 unescaped equal sign ends the string, otherwise only a : or \0
1268 does. Returns the number of characters output, or -1 on failure.
1270 The resulting string is *not* null-terminated, but may contain
1271 embedded nulls.
1273 Note that both dest and src are char **; on return they point to
1274 the first free byte after the array and the character that ended
1275 the input string, respectively. */
1277 static int
1278 get_funky_string (char **dest, const char **src, int equals_end)
1280 int num; /* For numerical codes */
1281 int count; /* Something to count with */
1282 enum {
1283 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1284 } state;
1285 const char *p;
1286 char *q;
1288 p = *src; /* We don't want to double-indirect */
1289 q = *dest; /* the whole darn time. */
1291 count = 0; /* No characters counted in yet. */
1292 num = 0;
1294 state = ST_GND; /* Start in ground state. */
1295 while (state < ST_END)
1297 switch (state)
1299 case ST_GND: /* Ground state (no escapes) */
1300 switch (*p)
1302 case ':':
1303 case '\0':
1304 state = ST_END; /* End of string */
1305 break;
1306 case '\\':
1307 state = ST_BACKSLASH; /* Backslash scape sequence */
1308 ++p;
1309 break;
1310 case '^':
1311 state = ST_CARET; /* Caret escape */
1312 ++p;
1313 break;
1314 case '=':
1315 if (equals_end)
1317 state = ST_END; /* End */
1318 break;
1320 /* else fall through */
1321 default:
1322 *(q++) = *(p++);
1323 ++count;
1324 break;
1326 break;
1328 case ST_BACKSLASH: /* Backslash escaped character */
1329 switch (*p)
1331 case '0':
1332 case '1':
1333 case '2':
1334 case '3':
1335 case '4':
1336 case '5':
1337 case '6':
1338 case '7':
1339 state = ST_OCTAL; /* Octal sequence */
1340 num = *p - '0';
1341 break;
1342 case 'x':
1343 case 'X':
1344 state = ST_HEX; /* Hex sequence */
1345 num = 0;
1346 break;
1347 case 'a': /* Bell */
1348 num = 7; /* Not all C compilers know what \a means */
1349 break;
1350 case 'b': /* Backspace */
1351 num = '\b';
1352 break;
1353 case 'e': /* Escape */
1354 num = 27;
1355 break;
1356 case 'f': /* Form feed */
1357 num = '\f';
1358 break;
1359 case 'n': /* Newline */
1360 num = '\n';
1361 break;
1362 case 'r': /* Carriage return */
1363 num = '\r';
1364 break;
1365 case 't': /* Tab */
1366 num = '\t';
1367 break;
1368 case 'v': /* Vtab */
1369 num = '\v';
1370 break;
1371 case '?': /* Delete */
1372 num = 127;
1373 break;
1374 case '_': /* Space */
1375 num = ' ';
1376 break;
1377 case '\0': /* End of string */
1378 state = ST_ERROR; /* Error! */
1379 break;
1380 default: /* Escaped character like \ ^ : = */
1381 num = *p;
1382 break;
1384 if (state == ST_BACKSLASH)
1386 *(q++) = num;
1387 ++count;
1388 state = ST_GND;
1390 ++p;
1391 break;
1393 case ST_OCTAL: /* Octal sequence */
1394 if (*p < '0' || *p > '7')
1396 *(q++) = num;
1397 ++count;
1398 state = ST_GND;
1400 else
1401 num = (num << 3) + (*(p++) - '0');
1402 break;
1404 case ST_HEX: /* Hex sequence */
1405 switch (*p)
1407 case '0':
1408 case '1':
1409 case '2':
1410 case '3':
1411 case '4':
1412 case '5':
1413 case '6':
1414 case '7':
1415 case '8':
1416 case '9':
1417 num = (num << 4) + (*(p++) - '0');
1418 break;
1419 case 'a':
1420 case 'b':
1421 case 'c':
1422 case 'd':
1423 case 'e':
1424 case 'f':
1425 num = (num << 4) + (*(p++) - 'a') + 10;
1426 break;
1427 case 'A':
1428 case 'B':
1429 case 'C':
1430 case 'D':
1431 case 'E':
1432 case 'F':
1433 num = (num << 4) + (*(p++) - 'A') + 10;
1434 break;
1435 default:
1436 *(q++) = num;
1437 ++count;
1438 state = ST_GND;
1439 break;
1441 break;
1443 case ST_CARET: /* Caret escape */
1444 state = ST_GND; /* Should be the next state... */
1445 if (*p >= '@' && *p <= '~')
1447 *(q++) = *(p++) & 037;
1448 ++count;
1450 else if (*p == '?')
1452 *(q++) = 127;
1453 ++count;
1455 else
1456 state = ST_ERROR;
1457 break;
1459 default:
1460 abort ();
1464 *dest = q;
1465 *src = p;
1467 return state == ST_ERROR ? -1 : count;
1470 static void
1471 parse_ls_color (void)
1473 const char *p; /* Pointer to character being parsed */
1474 char *buf; /* color_buf buffer pointer */
1475 int state; /* State of parser */
1476 int ind_no; /* Indicator number */
1477 char label[3]; /* Indicator label */
1478 struct color_ext_type *ext; /* Extension we are working on */
1480 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1481 return;
1483 ext = NULL;
1484 strcpy (label, "??");
1486 /* This is an overly conservative estimate, but any possible
1487 LS_COLORS string will *not* generate a color_buf longer than
1488 itself, so it is a safe way of allocating a buffer in
1489 advance. */
1490 buf = color_buf = xstrdup (p);
1492 state = 1;
1493 while (state > 0)
1495 switch (state)
1497 case 1: /* First label character */
1498 switch (*p)
1500 case ':':
1501 ++p;
1502 break;
1504 case '*':
1505 /* Allocate new extension block and add to head of
1506 linked list (this way a later definition will
1507 override an earlier one, which can be useful for
1508 having terminal-specific defs override global). */
1510 ext = (struct color_ext_type *)
1511 xmalloc (sizeof (struct color_ext_type));
1512 ext->next = color_ext_list;
1513 color_ext_list = ext;
1515 ++p;
1516 ext->ext.string = buf;
1518 state = (ext->ext.len =
1519 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1520 break;
1522 case '\0':
1523 state = 0; /* Done! */
1524 break;
1526 default: /* Assume it is file type label */
1527 label[0] = *(p++);
1528 state = 2;
1529 break;
1531 break;
1533 case 2: /* Second label character */
1534 if (*p)
1536 label[1] = *(p++);
1537 state = 3;
1539 else
1540 state = -1; /* Error */
1541 break;
1543 case 3: /* Equal sign after indicator label */
1544 state = -1; /* Assume failure... */
1545 if (*(p++) == '=')/* It *should* be... */
1547 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1549 if (STREQ (label, indicator_name[ind_no]))
1551 color_indicator[ind_no].string = buf;
1552 state = ((color_indicator[ind_no].len =
1553 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1554 break;
1557 if (state == -1)
1558 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1560 break;
1562 case 4: /* Equal sign after *.ext */
1563 if (*(p++) == '=')
1565 ext->seq.string = buf;
1566 state = (ext->seq.len =
1567 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1569 else
1570 state = -1;
1571 break;
1575 if (state < 0)
1577 struct color_ext_type *e;
1578 struct color_ext_type *e2;
1580 error (0, 0,
1581 _("unparsable value for LS_COLORS environment variable"));
1582 free (color_buf);
1583 for (e = color_ext_list; e != NULL; /* empty */)
1585 e2 = e;
1586 e = e->next;
1587 free (e2);
1589 print_with_color = 0;
1593 /* Request that the directory named `name' have its contents listed later.
1594 If `realname' is nonzero, it will be used instead of `name' when the
1595 directory name is printed. This allows symbolic links to directories
1596 to be treated as regular directories but still be listed under their
1597 real names. */
1599 static void
1600 queue_directory (const char *name, const char *realname)
1602 struct pending *new;
1604 new = (struct pending *) xmalloc (sizeof (struct pending));
1605 new->next = pending_dirs;
1606 pending_dirs = new;
1607 new->name = xstrdup (name);
1608 if (realname)
1609 new->realname = xstrdup (realname);
1610 else
1611 new->realname = 0;
1614 /* Read directory `name', and list the files in it.
1615 If `realname' is nonzero, print its name instead of `name';
1616 this is used for symbolic links to directories. */
1618 static void
1619 print_dir (const char *name, const char *realname)
1621 register DIR *reading;
1622 register struct dirent *next;
1623 register uintmax_t total_blocks = 0;
1625 errno = 0;
1626 reading = opendir (name);
1627 if (!reading)
1629 error (0, errno, "%s", quotearg_colon (name));
1630 exit_status = 1;
1631 return;
1634 /* Read the directory entries, and insert the subfiles into the `files'
1635 table. */
1637 clear_files ();
1639 while ((next = readdir (reading)) != NULL)
1640 if (file_interesting (next))
1641 total_blocks += gobble_file (next->d_name, 0, name);
1643 if (CLOSEDIR (reading))
1645 error (0, errno, "%s", quotearg_colon (name));
1646 exit_status = 1;
1647 /* Don't return; print whatever we got. */
1650 /* Sort the directory contents. */
1651 sort_files ();
1653 /* If any member files are subdirectories, perhaps they should have their
1654 contents listed rather than being mentioned here as files. */
1656 if (trace_dirs)
1657 extract_dirs_from_files (name, 1);
1659 if (trace_dirs || print_dir_name)
1661 DIRED_INDENT ();
1662 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1663 dired_pos += quote_name (stdout, realname ? realname : name,
1664 dirname_quoting_options);
1665 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1666 DIRED_FPUTS_LITERAL (":\n", stdout);
1669 if (format == long_format || print_block_size)
1671 const char *p;
1672 char buf[LONGEST_HUMAN_READABLE + 1];
1674 DIRED_INDENT ();
1675 p = _("total");
1676 DIRED_FPUTS (p, stdout, strlen (p));
1677 DIRED_PUTCHAR (' ');
1678 p = human_readable (total_blocks, buf, ST_NBLOCKSIZE, output_block_size);
1679 DIRED_FPUTS (p, stdout, strlen (p));
1680 DIRED_PUTCHAR ('\n');
1683 if (files_index)
1684 print_current_files ();
1686 if (pending_dirs)
1687 DIRED_PUTCHAR ('\n');
1690 /* Add `pattern' to the list of patterns for which files that match are
1691 not listed. */
1693 static void
1694 add_ignore_pattern (const char *pattern)
1696 register struct ignore_pattern *ignore;
1698 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1699 ignore->pattern = pattern;
1700 /* Add it to the head of the linked list. */
1701 ignore->next = ignore_patterns;
1702 ignore_patterns = ignore;
1705 /* Return nonzero if the file in `next' should be listed. */
1707 static int
1708 file_interesting (const struct dirent *next)
1710 register struct ignore_pattern *ignore;
1712 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1713 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1714 return 0;
1716 if (really_all_files
1717 || next->d_name[0] != '.'
1718 || (all_files
1719 && next->d_name[1] != '\0'
1720 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1721 return 1;
1723 return 0;
1726 /* Enter and remove entries in the table `files'. */
1728 /* Empty the table of files. */
1730 static void
1731 clear_files (void)
1733 register int i;
1735 for (i = 0; i < files_index; i++)
1737 free (files[i].name);
1738 if (files[i].linkname)
1739 free (files[i].linkname);
1742 files_index = 0;
1743 block_size_size = 4;
1746 /* Add a file to the current table of files.
1747 Verify that the file exists, and print an error message if it does not.
1748 Return the number of blocks that the file occupies. */
1750 static uintmax_t
1751 gobble_file (const char *name, int explicit_arg, const char *dirname)
1753 register uintmax_t blocks;
1754 register int val;
1755 register char *path;
1757 if (files_index == nfiles)
1759 nfiles *= 2;
1760 files = (struct fileinfo *) xrealloc ((char *) files,
1761 sizeof (*files) * nfiles);
1764 files[files_index].linkname = 0;
1765 files[files_index].linkmode = 0;
1766 files[files_index].linkok = 0;
1768 if (explicit_arg || format_needs_stat)
1770 /* `path' is the absolute pathname of this file. */
1772 if (name[0] == '/' || dirname[0] == 0)
1773 path = (char *) name;
1774 else
1776 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1777 attach (path, dirname, name);
1780 if (trace_links)
1782 val = stat (path, &files[files_index].stat);
1783 if (val < 0)
1785 /* Perhaps a symbolically-linked to file doesn't exist; stat
1786 the link instead. */
1787 val = lstat (path, &files[files_index].stat);
1790 else
1792 val = lstat (path, &files[files_index].stat);
1793 #if USE_ACL
1794 files[files_index].have_acl = (acl (path, GETACLCNT, 0, NULL) > 4);
1795 #endif
1798 if (val < 0)
1800 error (0, errno, "%s", quotearg_colon (path));
1801 exit_status = 1;
1802 return 0;
1805 if (S_ISLNK (files[files_index].stat.st_mode)
1806 && (explicit_arg || format == long_format || check_symlink_color))
1808 char *linkpath;
1809 struct stat linkstats;
1811 get_link_name (path, &files[files_index]);
1812 linkpath = make_link_path (path, files[files_index].linkname);
1814 /* Avoid following symbolic links when possible, ie, when
1815 they won't be traced and when no indicator is needed. */
1816 if (linkpath
1817 && ((explicit_arg && format != long_format)
1818 || indicator_style != none
1819 || check_symlink_color)
1820 && stat (linkpath, &linkstats) == 0)
1822 files[files_index].linkok = 1;
1824 /* Symbolic links to directories that are mentioned on the
1825 command line are automatically traced if not being
1826 listed as files. */
1827 if (explicit_arg && format != long_format
1828 && S_ISDIR (linkstats.st_mode))
1830 /* Substitute the linked-to directory's name, but
1831 save the real name in `linkname' for printing. */
1832 if (!immediate_dirs)
1834 const char *tempname = name;
1835 name = linkpath;
1836 linkpath = files[files_index].linkname;
1837 files[files_index].linkname = (char *) tempname;
1839 files[files_index].stat = linkstats;
1841 else
1843 /* Get the linked-to file's mode for the filetype indicator
1844 in long listings. */
1845 files[files_index].linkmode = linkstats.st_mode;
1846 files[files_index].linkok = 1;
1849 if (linkpath)
1850 free (linkpath);
1853 if (S_ISLNK (files[files_index].stat.st_mode))
1854 files[files_index].filetype = symbolic_link;
1855 else if (S_ISDIR (files[files_index].stat.st_mode))
1857 if (explicit_arg && !immediate_dirs)
1858 files[files_index].filetype = arg_directory;
1859 else
1860 files[files_index].filetype = directory;
1862 else
1863 files[files_index].filetype = normal;
1865 blocks = ST_NBLOCKS (files[files_index].stat);
1867 char buf[LONGEST_HUMAN_READABLE + 1];
1868 int len = strlen (human_readable (blocks, buf, ST_NBLOCKSIZE,
1869 output_block_size));
1870 if (block_size_size < len)
1871 block_size_size = len < 7 ? len : 7;
1874 else
1875 blocks = 0;
1877 files[files_index].name = xstrdup (name);
1878 files_index++;
1880 return blocks;
1883 #if HAVE_SYMLINKS
1885 /* Put the name of the file that `filename' is a symbolic link to
1886 into the `linkname' field of `f'. */
1888 static void
1889 get_link_name (const char *filename, struct fileinfo *f)
1891 char *linkbuf;
1892 register int linksize;
1894 linkbuf = (char *) alloca (PATH_MAX + 2);
1895 /* Some automounters give incorrect st_size for mount points.
1896 I can't think of a good workaround for it, though. */
1897 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1898 if (linksize < 0)
1900 error (0, errno, "%s", quotearg_colon (filename));
1901 exit_status = 1;
1903 else
1905 linkbuf[linksize] = '\0';
1906 f->linkname = xstrdup (linkbuf);
1910 /* If `linkname' is a relative path and `path' contains one or more
1911 leading directories, return `linkname' with those directories
1912 prepended; otherwise, return a copy of `linkname'.
1913 If `linkname' is zero, return zero. */
1915 static char *
1916 make_link_path (const char *path, const char *linkname)
1918 char *linkbuf;
1919 int bufsiz;
1921 if (linkname == 0)
1922 return 0;
1924 if (*linkname == '/')
1925 return xstrdup (linkname);
1927 /* The link is to a relative path. Prepend any leading path
1928 in `path' to the link name. */
1929 linkbuf = strrchr (path, '/');
1930 if (linkbuf == 0)
1931 return xstrdup (linkname);
1933 bufsiz = linkbuf - path + 1;
1934 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1935 strncpy (linkbuf, path, bufsiz);
1936 strcpy (linkbuf + bufsiz, linkname);
1937 return linkbuf;
1939 #endif
1941 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1942 This is so we don't try to recurse on `././././. ...' */
1944 static int
1945 basename_is_dot_or_dotdot (const char *name)
1947 char *base = base_name (name);
1948 return DOT_OR_DOTDOT (base);
1951 /* Remove any entries from `files' that are for directories,
1952 and queue them to be listed as directories instead.
1953 `dirname' is the prefix to prepend to each dirname
1954 to make it correct relative to ls's working dir.
1955 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1956 This is desirable when processing directories recursively. */
1958 static void
1959 extract_dirs_from_files (const char *dirname, int recursive)
1961 register int i, j;
1962 int dirlen;
1964 dirlen = strlen (dirname) + 2;
1965 /* Queue the directories last one first, because queueing reverses the
1966 order. */
1967 for (i = files_index - 1; i >= 0; i--)
1968 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1969 && (!recursive || !basename_is_dot_or_dotdot (files[i].name)))
1971 if (files[i].name[0] == '/' || dirname[0] == 0)
1973 queue_directory (files[i].name, files[i].linkname);
1975 else
1977 char *path = path_concat (dirname, files[i].name, NULL);
1978 queue_directory (path, files[i].linkname);
1979 free (path);
1981 if (files[i].filetype == arg_directory)
1982 free (files[i].name);
1985 /* Now delete the directories from the table, compacting all the remaining
1986 entries. */
1988 for (i = 0, j = 0; i < files_index; i++)
1989 if (files[i].filetype != arg_directory)
1990 files[j++] = files[i];
1991 files_index = j;
1994 /* Sort the files now in the table. */
1996 static void
1997 sort_files (void)
1999 int (*func) ();
2001 switch (sort_type)
2003 case sort_none:
2004 return;
2005 case sort_time:
2006 switch (time_type)
2008 case time_ctime:
2009 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2010 break;
2011 case time_mtime:
2012 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2013 break;
2014 case time_atime:
2015 func = sort_reverse ? rev_cmp_atime : compare_atime;
2016 break;
2017 default:
2018 abort ();
2020 break;
2021 case sort_name:
2022 func = sort_reverse ? rev_cmp_name : compare_name;
2023 break;
2024 case sort_extension:
2025 func = sort_reverse ? rev_cmp_extension : compare_extension;
2026 break;
2027 case sort_size:
2028 func = sort_reverse ? rev_cmp_size : compare_size;
2029 break;
2030 case sort_version:
2031 func = sort_reverse ? rev_cmp_version : compare_version;
2032 break;
2033 default:
2034 abort ();
2037 qsort (files, files_index, sizeof (struct fileinfo), func);
2040 /* Comparison routines for sorting the files. */
2042 static int
2043 compare_ctime (const struct fileinfo *file1, const struct fileinfo *file2)
2045 int diff = CTIME_CMP (file2->stat, file1->stat);
2046 if (diff == 0)
2047 diff = strcmp (file1->name, file2->name);
2048 return diff;
2051 static int
2052 rev_cmp_ctime (const struct fileinfo *file2, const struct fileinfo *file1)
2054 int diff = CTIME_CMP (file2->stat, file1->stat);
2055 if (diff == 0)
2056 diff = strcmp (file1->name, file2->name);
2057 return diff;
2060 static int
2061 compare_mtime (const struct fileinfo *file1, const struct fileinfo *file2)
2063 int diff = MTIME_CMP (file2->stat, file1->stat);
2064 if (diff == 0)
2065 diff = strcmp (file1->name, file2->name);
2066 return diff;
2069 static int
2070 rev_cmp_mtime (const struct fileinfo *file2, const struct fileinfo *file1)
2072 int diff = MTIME_CMP (file2->stat, file1->stat);
2073 if (diff == 0)
2074 diff = strcmp (file1->name, file2->name);
2075 return diff;
2078 static int
2079 compare_atime (const struct fileinfo *file1, const struct fileinfo *file2)
2081 int diff = ATIME_CMP (file2->stat, file1->stat);
2082 if (diff == 0)
2083 diff = strcmp (file1->name, file2->name);
2084 return diff;
2087 static int
2088 rev_cmp_atime (const struct fileinfo *file2, const struct fileinfo *file1)
2090 int diff = ATIME_CMP (file2->stat, file1->stat);
2091 if (diff == 0)
2092 diff = strcmp (file1->name, file2->name);
2093 return diff;
2096 static int
2097 compare_size (const struct fileinfo *file1, const struct fileinfo *file2)
2099 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2100 if (diff == 0)
2101 diff = strcmp (file1->name, file2->name);
2102 return diff;
2105 static int
2106 rev_cmp_size (const struct fileinfo *file2, const struct fileinfo *file1)
2108 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2109 if (diff == 0)
2110 diff = strcmp (file1->name, file2->name);
2111 return diff;
2114 static int
2115 compare_version (const struct fileinfo *file1, const struct fileinfo *file2)
2117 return strverscmp (file1->name, file2->name);
2120 static int
2121 rev_cmp_version (const struct fileinfo *file2, const struct fileinfo *file1)
2123 return strverscmp (file1->name, file2->name);
2126 static int
2127 compare_name (const struct fileinfo *file1, const struct fileinfo *file2)
2129 return strcmp (file1->name, file2->name);
2132 static int
2133 rev_cmp_name (const struct fileinfo *file2, const struct fileinfo *file1)
2135 return strcmp (file1->name, file2->name);
2138 /* Compare file extensions. Files with no extension are `smallest'.
2139 If extensions are the same, compare by filenames instead. */
2141 static int
2142 compare_extension (const struct fileinfo *file1, const struct fileinfo *file2)
2144 register char *base1, *base2;
2145 register int cmp;
2147 base1 = strrchr (file1->name, '.');
2148 base2 = strrchr (file2->name, '.');
2149 if (base1 == 0 && base2 == 0)
2150 return strcmp (file1->name, file2->name);
2151 if (base1 == 0)
2152 return -1;
2153 if (base2 == 0)
2154 return 1;
2155 cmp = strcmp (base1, base2);
2156 if (cmp == 0)
2157 return strcmp (file1->name, file2->name);
2158 return cmp;
2161 static int
2162 rev_cmp_extension (const struct fileinfo *file2, const struct fileinfo *file1)
2164 register char *base1, *base2;
2165 register int cmp;
2167 base1 = strrchr (file1->name, '.');
2168 base2 = strrchr (file2->name, '.');
2169 if (base1 == 0 && base2 == 0)
2170 return strcmp (file1->name, file2->name);
2171 if (base1 == 0)
2172 return -1;
2173 if (base2 == 0)
2174 return 1;
2175 cmp = strcmp (base1, base2);
2176 if (cmp == 0)
2177 return strcmp (file1->name, file2->name);
2178 return cmp;
2181 /* List all the files now in the table. */
2183 static void
2184 print_current_files (void)
2186 register int i;
2188 switch (format)
2190 case one_per_line:
2191 for (i = 0; i < files_index; i++)
2193 print_file_name_and_frills (files + i);
2194 putchar ('\n');
2196 break;
2198 case many_per_line:
2199 init_column_info ();
2200 print_many_per_line ();
2201 break;
2203 case horizontal:
2204 init_column_info ();
2205 print_horizontal ();
2206 break;
2208 case with_commas:
2209 print_with_commas ();
2210 break;
2212 case long_format:
2213 for (i = 0; i < files_index; i++)
2215 print_long_format (files + i);
2216 DIRED_PUTCHAR ('\n');
2218 break;
2222 static void
2223 print_long_format (const struct fileinfo *f)
2225 char modebuf[12];
2227 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2228 1 10-byte mode string,
2229 1 24-byte time string (may be longer in some locales -- see below)
2230 or LONGEST_HUMAN_READABLE integer,
2231 9 spaces, one following each of these fields, and
2232 1 trailing NUL byte. */
2233 char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2234 + (LONGEST_HUMAN_READABLE < 24 ? 24 : LONGEST_HUMAN_READABLE)
2235 + 9 + 1];
2236 char *buf = init_bigbuf;
2237 size_t bufsize = sizeof (init_bigbuf);
2238 size_t s;
2239 char *p;
2240 time_t when;
2241 struct tm *when_local;
2242 const char *fmt;
2243 char *user_name;
2245 #if HAVE_ST_DM_MODE
2246 /* Cray DMF: look at the file's migrated, not real, status */
2247 mode_string (f->stat.st_dm_mode, modebuf);
2248 #else
2249 mode_string (f->stat.st_mode, modebuf);
2250 #endif
2252 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2253 modebuf[11] = '\0';
2255 switch (time_type)
2257 case time_ctime:
2258 when = f->stat.st_ctime;
2259 break;
2260 case time_mtime:
2261 when = f->stat.st_mtime;
2262 break;
2263 case time_atime:
2264 when = f->stat.st_atime;
2265 break;
2268 if (full_time)
2270 fmt = "%a %b %d %H:%M:%S %Y";
2272 else
2274 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
2275 || current_time < when - 60L * 60L) /* In the future. */
2277 /* The file is fairly old or in the future.
2278 POSIX says the cutoff is 6 months old;
2279 approximate this by 6*30 days.
2280 Allow a 1 hour slop factor for what is considered "the future",
2281 to allow for NFS server/client clock disagreement.
2282 Show the year instead of the time of day. */
2283 fmt = "%b %e %Y";
2285 else
2287 fmt = "%b %e %H:%M";
2291 p = buf;
2293 if (print_inode)
2295 char hbuf[LONGEST_HUMAN_READABLE + 1];
2296 sprintf (p, "%*s ", INODE_DIGITS,
2297 human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2298 p += strlen (p);
2301 if (print_block_size)
2303 char hbuf[LONGEST_HUMAN_READABLE + 1];
2304 sprintf (p, "%*s ", block_size_size,
2305 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2306 ST_NBLOCKSIZE, output_block_size));
2307 p += strlen (p);
2310 /* The last byte of the mode string is the POSIX
2311 "optional alternate access method flag". */
2312 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
2313 p += strlen (p);
2315 user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2316 if (user_name)
2317 sprintf (p, "%-8.8s ", user_name);
2318 else
2319 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
2320 p += strlen (p);
2322 if (!inhibit_group)
2324 char *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2325 if (group_name)
2326 sprintf (p, "%-8.8s ", group_name);
2327 else
2328 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
2329 p += strlen (p);
2332 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2333 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
2334 (unsigned) minor (f->stat.st_rdev));
2335 else
2337 char hbuf[LONGEST_HUMAN_READABLE + 1];
2338 sprintf (p, "%8s ",
2339 human_readable ((uintmax_t) f->stat.st_size, hbuf, 1,
2340 output_block_size < 0 ? output_block_size : 1));
2343 p += strlen (p);
2345 /* Use strftime rather than ctime, because the former can produce
2346 locale-dependent names for the weekday (%a) and month (%b). */
2348 if ((when_local = localtime (&when)))
2350 while (! (s = strftime (p, buf + bufsize - p - 1, fmt, when_local)))
2352 char *newbuf = (char *) alloca (bufsize *= 2);
2353 memcpy (newbuf, buf, p - buf);
2354 p = newbuf + (p - buf);
2355 buf = newbuf;
2358 p += s;
2359 *p++ = ' ';
2361 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2362 *p = '\0';
2364 else
2366 /* The time cannot be represented as a local time;
2367 print it as a huge integer number of seconds. */
2368 char hbuf[LONGEST_HUMAN_READABLE + 1];
2369 int width = full_time ? 24 : 12;
2371 if (when < 0)
2373 const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2374 int sign_width = width - strlen (num);
2375 sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2377 else
2378 sprintf (p, "%*s ", width,
2379 human_readable ((uintmax_t) when, hbuf, 1, 1));
2381 p += strlen (p);
2384 DIRED_INDENT ();
2385 DIRED_FPUTS (buf, stdout, p - buf);
2386 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok,
2387 &dired_obstack);
2389 if (f->filetype == symbolic_link)
2391 if (f->linkname)
2393 DIRED_FPUTS_LITERAL (" -> ", stdout);
2394 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2395 NULL);
2396 if (indicator_style != none)
2397 print_type_indicator (f->linkmode);
2400 else if (indicator_style != none)
2401 print_type_indicator (f->stat.st_mode);
2404 /* Output to OUT a quoted representation of the file name P,
2405 using OPTIONS to control quoting.
2406 Return the number of characters in P's quoted representation. */
2408 static size_t
2409 quote_name (FILE *out, const char *p, struct quoting_options const *options)
2411 char smallbuf[BUFSIZ];
2412 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, p, -1, options);
2413 char *buf;
2415 if (len < sizeof smallbuf)
2416 buf = smallbuf;
2417 else
2419 buf = (char *) alloca (len + 1);
2420 quotearg_buffer (buf, len + 1, p, -1, options);
2423 if (qmark_funny_chars)
2425 size_t i;
2426 for (i = 0; i < len; i++)
2427 if (! ISPRINT ((unsigned char) buf[i]))
2428 buf[i] = '?';
2431 fwrite (buf, 1, len, out);
2432 return len;
2435 static void
2436 print_name_with_quoting (const char *p, unsigned int mode, int linkok,
2437 struct obstack *stack)
2439 if (print_with_color)
2440 print_color_indicator (p, mode, linkok);
2442 if (stack)
2443 PUSH_CURRENT_DIRED_POS (stack);
2445 dired_pos += quote_name (stdout, p, filename_quoting_options);
2447 if (stack)
2448 PUSH_CURRENT_DIRED_POS (stack);
2450 if (print_with_color)
2451 prep_non_filename_text ();
2454 static void
2455 prep_non_filename_text (void)
2457 if (color_indicator[C_END].string != NULL)
2458 put_indicator (&color_indicator[C_END]);
2459 else
2461 put_indicator (&color_indicator[C_LEFT]);
2462 put_indicator (&color_indicator[C_NORM]);
2463 put_indicator (&color_indicator[C_RIGHT]);
2467 /* Print the file name of `f' with appropriate quoting.
2468 Also print file size, inode number, and filetype indicator character,
2469 as requested by switches. */
2471 static void
2472 print_file_name_and_frills (const struct fileinfo *f)
2474 char buf[LONGEST_HUMAN_READABLE + 1];
2476 if (print_inode)
2477 printf ("%*s ", INODE_DIGITS,
2478 human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
2480 if (print_block_size)
2481 printf ("%*s ", block_size_size,
2482 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), buf,
2483 ST_NBLOCKSIZE, output_block_size));
2485 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok, NULL);
2487 if (indicator_style != none)
2488 print_type_indicator (f->stat.st_mode);
2491 static void
2492 print_type_indicator (unsigned int mode)
2494 int c;
2496 if (S_ISREG (mode))
2498 if (indicator_style == classify && (mode & S_IXUGO))
2499 c ='*';
2500 else
2501 c = 0;
2503 else
2505 if (S_ISDIR (mode))
2506 c = '/';
2507 else if (S_ISLNK (mode))
2508 c = '@';
2509 else if (S_ISFIFO (mode))
2510 c = '|';
2511 else if (S_ISSOCK (mode))
2512 c = '=';
2513 else if (S_ISDOOR (mode))
2514 c = '>';
2515 else
2516 c = 0;
2519 if (c)
2520 DIRED_PUTCHAR (c);
2523 static void
2524 print_color_indicator (const char *name, unsigned int mode, int linkok)
2526 int type = C_FILE;
2527 struct color_ext_type *ext; /* Color extension */
2528 size_t len; /* Length of name */
2530 /* Is this a nonexistent file? If so, linkok == -1. */
2532 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
2534 ext = NULL;
2535 type = C_MISSING;
2537 else
2539 if (S_ISDIR (mode))
2540 type = C_DIR;
2541 else if (S_ISLNK (mode))
2542 type = ((!linkok && color_indicator[C_ORPHAN].string)
2543 ? C_ORPHAN : C_LINK);
2544 else if (S_ISFIFO (mode))
2545 type = C_FIFO;
2546 else if (S_ISSOCK (mode))
2547 type = C_SOCK;
2548 else if (S_ISBLK (mode))
2549 type = C_BLK;
2550 else if (S_ISCHR (mode))
2551 type = C_CHR;
2552 else if (S_ISDOOR (mode))
2553 type = C_DOOR;
2555 if (type == C_FILE && (mode & S_IXUGO) != 0)
2556 type = C_EXEC;
2558 /* Check the file's suffix only if still classified as C_FILE. */
2559 ext = NULL;
2560 if (type == C_FILE)
2562 /* Test if NAME has a recognized suffix. */
2564 len = strlen (name);
2565 name += len; /* Pointer to final \0. */
2566 for (ext = color_ext_list; ext != NULL; ext = ext->next)
2568 if ((size_t) ext->ext.len <= len
2569 && strncmp (name - ext->ext.len, ext->ext.string,
2570 ext->ext.len) == 0)
2571 break;
2576 put_indicator (&color_indicator[C_LEFT]);
2577 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
2578 put_indicator (&color_indicator[C_RIGHT]);
2581 /* Output a color indicator (which may contain nulls). */
2582 static void
2583 put_indicator (const struct bin_str *ind)
2585 register int i;
2586 register char *p;
2588 p = ind->string;
2590 for (i = ind->len; i > 0; --i)
2591 putchar (*(p++));
2594 static int
2595 length_of_file_name_and_frills (const struct fileinfo *f)
2597 register int len = 0;
2599 if (print_inode)
2600 len += INODE_DIGITS + 1;
2602 if (print_block_size)
2603 len += 1 + block_size_size;
2605 len += quotearg_buffer (0, 0, f->name, -1, filename_quoting_options);
2607 if (indicator_style != none)
2609 unsigned filetype = f->stat.st_mode;
2611 if (S_ISREG (filetype))
2613 if (indicator_style == classify
2614 && (f->stat.st_mode & S_IXUGO))
2615 len += 1;
2617 else if (S_ISDIR (filetype)
2618 || S_ISLNK (filetype)
2619 || S_ISFIFO (filetype)
2620 || S_ISSOCK (filetype)
2621 || S_ISDOOR (filetype)
2623 len += 1;
2626 return len;
2629 static void
2630 print_many_per_line (void)
2632 struct column_info *line_fmt;
2633 int filesno; /* Index into files. */
2634 int row; /* Current row. */
2635 int max_name_length; /* Length of longest file name + frills. */
2636 int name_length; /* Length of each file name + frills. */
2637 int pos; /* Current character column. */
2638 int cols; /* Number of files across. */
2639 int rows; /* Maximum number of files down. */
2640 int max_cols;
2642 /* Normally the maximum number of columns is determined by the
2643 screen width. But if few files are available this might limit it
2644 as well. */
2645 max_cols = max_idx > files_index ? files_index : max_idx;
2647 /* Compute the maximum number of possible columns. */
2648 for (filesno = 0; filesno < files_index; ++filesno)
2650 int i;
2652 name_length = length_of_file_name_and_frills (files + filesno);
2654 for (i = 0; i < max_cols; ++i)
2656 if (column_info[i].valid_len)
2658 int idx = filesno / ((files_index + i) / (i + 1));
2659 int real_length = name_length + (idx == i ? 0 : 2);
2661 if (real_length > column_info[i].col_arr[idx])
2663 column_info[i].line_len += (real_length
2664 - column_info[i].col_arr[idx]);
2665 column_info[i].col_arr[idx] = real_length;
2666 column_info[i].valid_len = column_info[i].line_len < line_length;
2672 /* Find maximum allowed columns. */
2673 for (cols = max_cols; cols > 1; --cols)
2675 if (column_info[cols - 1].valid_len)
2676 break;
2679 line_fmt = &column_info[cols - 1];
2681 /* Calculate the number of rows that will be in each column except possibly
2682 for a short column on the right. */
2683 rows = files_index / cols + (files_index % cols != 0);
2685 for (row = 0; row < rows; row++)
2687 int col = 0;
2688 filesno = row;
2689 pos = 0;
2690 /* Print the next row. */
2691 while (1)
2693 print_file_name_and_frills (files + filesno);
2694 name_length = length_of_file_name_and_frills (files + filesno);
2695 max_name_length = line_fmt->col_arr[col++];
2697 filesno += rows;
2698 if (filesno >= files_index)
2699 break;
2701 indent (pos + name_length, pos + max_name_length);
2702 pos += max_name_length;
2704 putchar ('\n');
2708 static void
2709 print_horizontal (void)
2711 struct column_info *line_fmt;
2712 int filesno;
2713 int max_name_length;
2714 int name_length;
2715 int cols;
2716 int pos;
2717 int max_cols;
2719 /* Normally the maximum number of columns is determined by the
2720 screen width. But if few files are available this might limit it
2721 as well. */
2722 max_cols = max_idx > files_index ? files_index : max_idx;
2724 /* Compute the maximum file name length. */
2725 max_name_length = 0;
2726 for (filesno = 0; filesno < files_index; ++filesno)
2728 int i;
2730 name_length = length_of_file_name_and_frills (files + filesno);
2732 for (i = 0; i < max_cols; ++i)
2734 if (column_info[i].valid_len)
2736 int idx = filesno % (i + 1);
2737 int real_length = name_length + (idx == i ? 0 : 2);
2739 if (real_length > column_info[i].col_arr[idx])
2741 column_info[i].line_len += (real_length
2742 - column_info[i].col_arr[idx]);
2743 column_info[i].col_arr[idx] = real_length;
2744 column_info[i].valid_len = column_info[i].line_len < line_length;
2750 /* Find maximum allowed columns. */
2751 for (cols = max_cols; cols > 1; --cols)
2753 if (column_info[cols - 1].valid_len)
2754 break;
2757 line_fmt = &column_info[cols - 1];
2759 pos = 0;
2761 /* Print first entry. */
2762 print_file_name_and_frills (files);
2763 name_length = length_of_file_name_and_frills (files);
2764 max_name_length = line_fmt->col_arr[0];
2766 /* Now the rest. */
2767 for (filesno = 1; filesno < files_index; ++filesno)
2769 int col = filesno % cols;
2771 if (col == 0)
2773 putchar ('\n');
2774 pos = 0;
2776 else
2778 indent (pos + name_length, pos + max_name_length);
2779 pos += max_name_length;
2782 print_file_name_and_frills (files + filesno);
2784 name_length = length_of_file_name_and_frills (files + filesno);
2785 max_name_length = line_fmt->col_arr[col];
2787 putchar ('\n');
2790 static void
2791 print_with_commas (void)
2793 int filesno;
2794 int pos, old_pos;
2796 pos = 0;
2798 for (filesno = 0; filesno < files_index; filesno++)
2800 old_pos = pos;
2802 pos += length_of_file_name_and_frills (files + filesno);
2803 if (filesno + 1 < files_index)
2804 pos += 2; /* For the comma and space */
2806 if (old_pos != 0 && pos >= line_length)
2808 putchar ('\n');
2809 pos -= old_pos;
2812 print_file_name_and_frills (files + filesno);
2813 if (filesno + 1 < files_index)
2815 putchar (',');
2816 putchar (' ');
2819 putchar ('\n');
2822 /* Assuming cursor is at position FROM, indent up to position TO.
2823 Use a TAB character instead of two or more spaces whenever possible. */
2825 static void
2826 indent (int from, int to)
2828 while (from < to)
2830 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
2832 putchar ('\t');
2833 from += tabsize - from % tabsize;
2835 else
2837 putchar (' ');
2838 from++;
2843 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2844 /* FIXME: maybe remove this function someday. See about using a
2845 non-malloc'ing version of path_concat. */
2847 static void
2848 attach (char *dest, const char *dirname, const char *name)
2850 const char *dirnamep = dirname;
2852 /* Copy dirname if it is not ".". */
2853 if (dirname[0] != '.' || dirname[1] != 0)
2855 while (*dirnamep)
2856 *dest++ = *dirnamep++;
2857 /* Add '/' if `dirname' doesn't already end with it. */
2858 if (dirnamep > dirname && dirnamep[-1] != '/')
2859 *dest++ = '/';
2861 while (*name)
2862 *dest++ = *name++;
2863 *dest = 0;
2866 static void
2867 init_column_info (void)
2869 int i;
2870 int allocate = 0;
2872 max_idx = line_length / MIN_COLUMN_WIDTH;
2873 if (max_idx == 0)
2874 max_idx = 1;
2876 if (column_info == NULL)
2878 column_info = (struct column_info *) xmalloc (max_idx
2879 * sizeof (struct column_info));
2880 allocate = 1;
2883 for (i = 0; i < max_idx; ++i)
2885 int j;
2887 column_info[i].valid_len = 1;
2888 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
2890 if (allocate)
2891 column_info[i].col_arr = (int *) xmalloc ((i + 1) * sizeof (int));
2893 for (j = 0; j <= i; ++j)
2894 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
2898 void
2899 usage (int status)
2901 if (status != 0)
2902 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2903 program_name);
2904 else
2906 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2907 printf (_("\
2908 List information about the FILEs (the current directory by default).\n\
2909 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2911 -a, --all do not hide entries starting with .\n\
2912 -A, --almost-all do not list implied . and ..\n\
2913 -b, --escape print octal escapes for nongraphic characters\n\
2914 --block-size=SIZE use SIZE-byte blocks\n\
2915 -B, --ignore-backups do not list implied entries ending with ~\n\
2916 -c with -lt: sort by, and show, ctime (time of last\n\
2917 modification of file status information)\n\
2918 with -l: show ctime and sort by name\n\
2919 otherwise: sort by ctime\n\
2920 -C list entries by columns\n\
2921 --color[=WHEN] control whether color is used to distinguish file\n\
2922 types. WHEN may be `never', `always', or `auto'\n\
2923 -d, --directory list directory entries instead of contents\n\
2924 -D, --dired generate output designed for Emacs' dired mode\n\
2925 -f do not sort, enable -aU, disable -lst\n\
2926 -F, --classify append indicator (one of */=@|) to entries\n\
2927 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2928 single-column -1, verbose -l, vertical -C\n\
2929 --full-time list both full date and full time\n"));
2931 printf (_("\
2932 -g (ignored)\n\
2933 -G, --no-group inhibit display of group information\n\
2934 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2935 -H, --si likewise, but use powers of 1000 not 1024\n\
2936 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2937 none (default), classify (-F), file-type (-p)\n\
2938 -i, --inode print index number of each file\n\
2939 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2940 -k, --kilobytes like --block-size=1024\n\
2941 -l use a long listing format\n\
2942 -L, --dereference list entries pointed to by symbolic links\n\
2943 -m fill width with a comma separated list of entries\n\
2944 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2945 -N, --literal print raw entry names (don't treat e.g. control\n\
2946 characters specially)\n\
2947 -o use long listing format without group info\n\
2948 -p, --file-type append indicator (one of /=@|) to entries\n\
2949 -q, --hide-control-chars print ? instead of non graphic characters\n\
2950 --show-control-chars show non graphic characters as-is (default\n\
2951 unless program is `ls' and output is a terminal)\n\
2952 -Q, --quote-name enclose entry names in double quotes\n\
2953 --quoting-style=WORD use quoting style WORD for entry names:\n\
2954 literal, locale, shell, shell-always, c, escape\n\
2955 -r, --reverse reverse order while sorting\n\
2956 -R, --recursive list subdirectories recursively\n\
2957 -s, --size print size of each file, in blocks\n"));
2959 printf (_("\
2960 -S sort by file size\n\
2961 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2962 version -v\n\
2963 status -c, time -t, atime -u, access -u, use -u\n\
2964 --time=WORD show time as WORD instead of modification time:\n\
2965 atime, access, use, ctime or status; use\n\
2966 specified time as sort key if --sort=time\n\
2967 -t sort by modification time\n\
2968 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2969 -u with -lt: sort by, and show, access time\n\
2970 with -l: show access time and sort by name\n\
2971 otherwise: sort by access time\n\
2972 -U do not sort; list entries in directory order\n\
2973 -v sort by version\n\
2974 -w, --width=COLS assume screen width instead of current value\n\
2975 -x list entries by lines instead of by columns\n\
2976 -X sort alphabetically by entry extension\n\
2977 -1 list one file per line\n\
2978 --help display this help and exit\n\
2979 --version output version information and exit\n\
2981 By default, color is not used to distinguish types of files. That is\n\
2982 equivalent to using --color=none. Using the --color option without the\n\
2983 optional WHEN argument is equivalent to using --color=always. With\n\
2984 --color=auto, color codes are output only if standard output is connected\n\
2985 to a terminal (tty).\n\
2986 "));
2987 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
2988 close_stdout ();
2990 exit (status);