3680020246807234082a8990ee1dbfaa2e74663b
[platform/upstream/coreutils.git] / src / ls.c
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2    Copyright (C) 85, 88, 90, 91, 1995-2003 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17
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.
22
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.
27
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. */
32
33 /* Written by Richard Stallman and David MacKenzie.  */
34
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>.  */
38
39 #include <config.h>
40 #include <sys/types.h>
41
42 #if HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
45
46 #ifdef GWINSZ_IN_SYS_IOCTL
47 # include <sys/ioctl.h>
48 #endif
49
50 #ifdef WINSIZE_IN_PTEM
51 # include <sys/stream.h>
52 # include <sys/ptem.h>
53 #endif
54
55 #include <stdio.h>
56 #include <assert.h>
57 #include <setjmp.h>
58 #include <grp.h>
59 #include <pwd.h>
60 #include <getopt.h>
61 #include <signal.h>
62
63 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth().  */
64 #if HAVE_WCHAR_H
65 # include <wchar.h>
66 #endif
67
68 /* Get iswprint().  */
69 #if HAVE_WCTYPE_H
70 # include <wctype.h>
71 #endif
72 #if !defined iswprint && !HAVE_ISWPRINT
73 # define iswprint(wc) 1
74 #endif
75
76 #ifndef HAVE_DECL_WCWIDTH
77 "this configure-time declaration test was not run"
78 #endif
79 #if !HAVE_DECL_WCWIDTH
80 int wcwidth ();
81 #endif
82
83 /* If wcwidth() doesn't exist, assume all printable characters have
84    width 1.  */
85 #ifndef wcwidth
86 # if !HAVE_WCWIDTH
87 #  define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
88 # endif
89 #endif
90
91 #include "system.h"
92 #include <fnmatch.h>
93
94 #include "acl.h"
95 #include "argmatch.h"
96 #include "dev-ino.h"
97 #include "dirname.h"
98 #include "dirfd.h"
99 #include "error.h"
100 #include "full-write.h"
101 #include "hard-locale.h"
102 #include "hash.h"
103 #include "human.h"
104 #include "filemode.h"
105 #include "inttostr.h"
106 #include "ls.h"
107 #include "mbswidth.h"
108 #include "obstack.h"
109 #include "path-concat.h"
110 #include "quote.h"
111 #include "quotearg.h"
112 #include "same.h"
113 #include "strftime.h"
114 #include "strverscmp.h"
115 #include "xstrtol.h"
116 #include "xreadlink.h"
117
118 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
119                       : (ls_mode == LS_MULTI_COL \
120                          ? "dir" : "vdir"))
121
122 #define WRITTEN_BY _("Written by Richard Stallman and David MacKenzie.")
123
124 #define obstack_chunk_alloc malloc
125 #define obstack_chunk_free free
126
127 /* Return an int indicating the result of comparing two integers.
128    Subtracting doesn't always work, due to overflow.  */
129 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
130
131 /* The field width for inode numbers.  On some hosts inode numbers are
132    64 bits, so columns won't line up exactly when a huge inode number
133    is encountered, but in practice 7 digits is usually enough.  */
134 #ifndef INODE_DIGITS
135 # define INODE_DIGITS 7
136 #endif
137
138 /* Arrange to make lstat calls go through the wrapper function
139    on systems with an lstat function that does not dereference symlinks
140    that are specified with a trailing slash.  */
141 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
142 int rpl_lstat (const char *, struct stat *);
143 # undef lstat
144 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
145 #endif
146
147 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
148 # define DT_INIT(Val) = Val
149 #else
150 # define DT_INIT(Val) /* empty */
151 #endif
152
153 #ifdef ST_MTIM_NSEC
154 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
155 #else
156 # define TIMESPEC_NS(timespec) 0
157 #endif
158
159 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
160 # define st_author st_uid
161 #endif
162
163 /* Cray/Unicos DMF: use the file's migrated, not real, status */
164 #if HAVE_ST_DM_MODE
165 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
166 #else
167 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
168 #endif
169
170 #ifndef LOGIN_NAME_MAX
171 # if _POSIX_LOGIN_NAME_MAX
172 #  define LOGIN_NAME_MAX _POSIX_LOGIN_NAME_MAX
173 # else
174 #  define LOGIN_NAME_MAX 17
175 # endif
176 #endif
177
178 /* The maximum length of a string representation of a user or group ID,
179    not counting any terminating NUL byte.  */
180 #define ID_LENGTH_MAX \
181   MAX (LOGIN_NAME_MAX - 1, LONGEST_HUMAN_READABLE)
182
183 enum filetype
184   {
185     unknown DT_INIT (DT_UNKNOWN),
186     fifo DT_INIT (DT_FIFO),
187     chardev DT_INIT (DT_CHR),
188     directory DT_INIT (DT_DIR),
189     blockdev DT_INIT (DT_BLK),
190     normal DT_INIT (DT_REG),
191     symbolic_link DT_INIT (DT_LNK),
192     sock DT_INIT (DT_SOCK),
193     arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
194                                 | DT_REG | DT_LNK | DT_SOCK))
195   };
196
197 struct fileinfo
198   {
199     /* The file name. */
200     char *name;
201
202     struct stat stat;
203
204     /* For symbolic link, name of the file linked to, otherwise zero. */
205     char *linkname;
206
207     /* For symbolic link and long listing, st_mode of file linked to, otherwise
208        zero. */
209     mode_t linkmode;
210
211     /* For symbolic link and color printing, 1 if linked-to file
212        exists, otherwise 0.  */
213     int linkok;
214
215     enum filetype filetype;
216
217 #if HAVE_ACL
218     /* For long listings, true if the file has an access control list.  */
219     bool have_acl;
220 #endif
221   };
222
223 #if HAVE_ACL
224 # define FILE_HAS_ACL(F) ((F)->have_acl)
225 #else
226 # define FILE_HAS_ACL(F) 0
227 #endif
228
229 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
230
231 /* Null is a valid character in a color indicator (think about Epson
232    printers, for example) so we have to use a length/buffer string
233    type.  */
234
235 struct bin_str
236   {
237     size_t len;                 /* Number of bytes */
238     const char *string;         /* Pointer to the same */
239   };
240
241 #ifndef STDC_HEADERS
242 time_t time ();
243 #endif
244
245 char *getgroup ();
246 char *getuser ();
247
248 static size_t quote_name (FILE *out, const char *name,
249                           struct quoting_options const *options,
250                           size_t *width);
251 static char *make_link_path (const char *path, const char *linkname);
252 static int decode_switches (int argc, char **argv);
253 static int file_interesting (const struct dirent *next);
254 static uintmax_t gobble_file (const char *name, enum filetype type,
255                               int explicit_arg, const char *dirname);
256 static void print_color_indicator (const char *name, mode_t mode, int linkok);
257 static void put_indicator (const struct bin_str *ind);
258 static int put_indicator_direct (const struct bin_str *ind);
259 static size_t length_of_file_name_and_frills (const struct fileinfo *f);
260 static void add_ignore_pattern (const char *pattern);
261 static void attach (char *dest, const char *dirname, const char *name);
262 static void clear_files (void);
263 static void extract_dirs_from_files (const char *dirname,
264                                      int ignore_dot_and_dot_dot);
265 static void get_link_name (const char *filename, struct fileinfo *f);
266 static void indent (size_t from, size_t to);
267 static size_t calculate_columns (bool by_columns);
268 static void print_current_files (void);
269 static void print_dir (const char *name, const char *realname);
270 static void print_file_name_and_frills (const struct fileinfo *f);
271 static void print_horizontal (void);
272 static void print_long_format (const struct fileinfo *f);
273 static void print_many_per_line (void);
274 static void print_name_with_quoting (const char *p, mode_t mode,
275                                      int linkok,
276                                      struct obstack *stack);
277 static void prep_non_filename_text (void);
278 static void print_type_indicator (mode_t mode);
279 static void print_with_commas (void);
280 static void queue_directory (const char *name, const char *realname);
281 static void sort_files (void);
282 static void parse_ls_color (void);
283 void usage (int status);
284
285 /* The name the program was run with, stripped of any leading path. */
286 char *program_name;
287
288 /* Initial size of hash table.
289    Most hierarchies are likely to be shallower than this.  */
290 #define INITIAL_TABLE_SIZE 30
291
292 /* The set of `active' directories, from the current command-line argument
293    to the level in the hierarchy at which files are being listed.
294    A directory is represented by its device and inode numbers (struct dev_ino).
295    A directory is added to this set when ls begins listing it or its
296    entries, and it is removed from the set just after ls has finished
297    processing it.  This set is used solely to detect loops, e.g., with
298    mkdir loop; cd loop; ln -s ../loop sub; ls -RL  */
299 static Hash_table *active_dir_set;
300
301 #define LOOP_DETECT (!!active_dir_set)
302
303 /* The table of files in the current directory:
304
305    `files' points to a vector of `struct fileinfo', one per file.
306    `nfiles' is the number of elements space has been allocated for.
307    `files_index' is the number actually in use.  */
308
309 /* Address of block containing the files that are described.  */
310 static struct fileinfo *files;  /* FIXME: rename this to e.g. cwd_file */
311
312 /* Length of block that `files' points to, measured in files.  */
313 static size_t nfiles;  /* FIXME: rename this to e.g. cwd_n_alloc */
314
315 /* Index of first unused in `files'.  */
316 static size_t files_index;  /* FIXME: rename this to e.g. cwd_n_used */
317
318 /* When nonzero, in a color listing, color each symlink name according to the
319    type of file it points to.  Otherwise, color them according to the `ln'
320    directive in LS_COLORS.  Dangling (orphan) symlinks are treated specially,
321    regardless.  This is set when `ln=target' appears in LS_COLORS.  */
322
323 static int color_symlink_as_referent;
324
325 /* mode of appropriate file for colorization */
326 #define FILE_OR_LINK_MODE(File) \
327     ((color_symlink_as_referent && (File)->linkok) \
328      ? (File)->linkmode : (File)->stat.st_mode)
329
330
331 /* Record of one pending directory waiting to be listed.  */
332
333 struct pending
334   {
335     char *name;
336     /* If the directory is actually the file pointed to by a symbolic link we
337        were told to list, `realname' will contain the name of the symbolic
338        link, otherwise zero. */
339     char *realname;
340     struct pending *next;
341   };
342
343 static struct pending *pending_dirs;
344
345 /* Current time in seconds and nanoseconds since 1970, updated as
346    needed when deciding whether a file is recent.  */
347
348 static time_t current_time = TYPE_MINIMUM (time_t);
349 static int current_time_ns = -1;
350
351 /* The number of digits to use for block sizes.
352    4, or more if needed for bigger numbers.  */
353
354 static int block_size_size;
355
356 /* Option flags */
357
358 /* long_format for lots of info, one per line.
359    one_per_line for just names, one per line.
360    many_per_line for just names, many per line, sorted vertically.
361    horizontal for just names, many per line, sorted horizontally.
362    with_commas for just names, many per line, separated by commas.
363
364    -l (and other options that imply -l), -1, -C, -x and -m control
365    this parameter.  */
366
367 enum format
368   {
369     long_format,                /* -l and other options that imply -l */
370     one_per_line,               /* -1 */
371     many_per_line,              /* -C */
372     horizontal,                 /* -x */
373     with_commas                 /* -m */
374   };
375
376 static enum format format;
377
378 /* `full-iso' uses full ISO-style dates and times.  `long-iso' uses longer
379    ISO-style time stamps, though shorter than `full-iso'.  `iso' uses shorter
380    ISO-style time stamps.  `locale' uses locale-dependent time stamps.  */
381 enum time_style
382   {
383     full_iso_time_style,        /* --time-style=full-iso */
384     long_iso_time_style,        /* --time-style=long-iso */
385     iso_time_style,             /* --time-style=iso */
386     locale_time_style           /* --time-style=locale */
387   };
388
389 static char const *const time_style_args[] =
390 {
391   "full-iso", "long-iso", "iso", "locale", 0
392 };
393
394 static enum time_style const time_style_types[] =
395 {
396   full_iso_time_style, long_iso_time_style, iso_time_style,
397   locale_time_style, 0
398 };
399
400 /* Type of time to print or sort by.  Controlled by -c and -u.  */
401
402 enum time_type
403   {
404     time_mtime,                 /* default */
405     time_ctime,                 /* -c */
406     time_atime                  /* -u */
407   };
408
409 static enum time_type time_type;
410
411 /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X, -v. */
412
413 enum sort_type
414   {
415     sort_none,                  /* -U */
416     sort_name,                  /* default */
417     sort_extension,             /* -X */
418     sort_time,                  /* -t */
419     sort_size,                  /* -S */
420     sort_version                /* -v */
421   };
422
423 static enum sort_type sort_type;
424
425 /* Direction of sort.
426    0 means highest first if numeric,
427    lowest first if alphabetic;
428    these are the defaults.
429    1 means the opposite order in each case.  -r  */
430
431 static int sort_reverse;
432
433 /* Nonzero means to display owner information.  -g turns this off.  */
434
435 static int print_owner = 1;
436
437 /* Nonzero means to display author information.  */
438
439 static bool print_author;
440
441 /* Nonzero means to display group information.  -G and -o turn this off.  */
442
443 static int print_group = 1;
444
445 /* Nonzero means print the user and group id's as numbers rather
446    than as names.  -n  */
447
448 static int numeric_ids;
449
450 /* Nonzero means mention the size in blocks of each file.  -s  */
451
452 static int print_block_size;
453
454 /* Human-readable options for output.  */
455 static int human_output_opts;
456
457 /* The units to use when printing sizes other than file sizes.  */
458 static uintmax_t output_block_size;
459
460 /* Likewise, but for file sizes.  */
461 static uintmax_t file_output_block_size = 1;
462
463 /* Precede each line of long output (per file) with a string like `m,n:'
464    where M is the number of characters after the `:' and before the
465    filename and N is the length of the filename.  Using this format,
466    Emacs' dired mode starts up twice as fast, and can handle all
467    strange characters in file names.  */
468 static int dired;
469
470 /* `none' means don't mention the type of files.
471    `classify' means mention file types and mark executables.
472    `file_type' means mention only file types.
473
474    Controlled by -F, -p, and --indicator-style.  */
475
476 enum indicator_style
477   {
478     none,       /*     --indicator-style=none */
479     classify,   /* -F, --indicator-style=classify */
480     file_type   /* -p, --indicator-style=file-type */
481   };
482
483 static enum indicator_style indicator_style;
484
485 /* Names of indicator styles.  */
486 static char const *const indicator_style_args[] =
487 {
488   "none", "classify", "file-type", 0
489 };
490
491 static enum indicator_style const indicator_style_types[]=
492 {
493   none, classify, file_type
494 };
495
496 /* Nonzero means use colors to mark types.  Also define the different
497    colors as well as the stuff for the LS_COLORS environment variable.
498    The LS_COLORS variable is now in a termcap-like format.  */
499
500 static int print_with_color;
501
502 enum color_type
503   {
504     color_never,                /* 0: default or --color=never */
505     color_always,               /* 1: --color=always */
506     color_if_tty                /* 2: --color=tty */
507   };
508
509 enum Dereference_symlink
510   {
511     DEREF_UNDEFINED = 1,
512     DEREF_NEVER,
513     DEREF_COMMAND_LINE_ARGUMENTS,       /* -H */
514     DEREF_COMMAND_LINE_SYMLINK_TO_DIR,  /* the default, in certain cases */
515     DEREF_ALWAYS                        /* -L */
516   };
517
518 enum indicator_no
519   {
520     C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
521     C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
522   };
523
524 static const char *const indicator_name[]=
525   {
526     "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
527     "bd", "cd", "mi", "or", "ex", "do", NULL
528   };
529
530 struct color_ext_type
531   {
532     struct bin_str ext;         /* The extension we're looking for */
533     struct bin_str seq;         /* The sequence to output when we do */
534     struct color_ext_type *next;        /* Next in list */
535   };
536
537 static struct bin_str color_indicator[] =
538   {
539     { LEN_STR_PAIR ("\033[") },         /* lc: Left of color sequence */
540     { LEN_STR_PAIR ("m") },             /* rc: Right of color sequence */
541     { 0, NULL },                        /* ec: End color (replaces lc+no+rc) */
542     { LEN_STR_PAIR ("0") },             /* no: Normal */
543     { LEN_STR_PAIR ("0") },             /* fi: File: default */
544     { LEN_STR_PAIR ("01;34") },         /* di: Directory: bright blue */
545     { LEN_STR_PAIR ("01;36") },         /* ln: Symlink: bright cyan */
546     { LEN_STR_PAIR ("33") },            /* pi: Pipe: yellow/brown */
547     { LEN_STR_PAIR ("01;35") },         /* so: Socket: bright magenta */
548     { LEN_STR_PAIR ("01;33") },         /* bd: Block device: bright yellow */
549     { LEN_STR_PAIR ("01;33") },         /* cd: Char device: bright yellow */
550     { 0, NULL },                        /* mi: Missing file: undefined */
551     { 0, NULL },                        /* or: Orphanned symlink: undefined */
552     { LEN_STR_PAIR ("01;32") },         /* ex: Executable: bright green */
553     { LEN_STR_PAIR ("01;35") }          /* do: Door: bright magenta */
554   };
555
556 /* FIXME: comment  */
557 static struct color_ext_type *color_ext_list = NULL;
558
559 /* Buffer for color sequences */
560 static char *color_buf;
561
562 /* Nonzero means to check for orphaned symbolic link, for displaying
563    colors.  */
564
565 static int check_symlink_color;
566
567 /* Nonzero means mention the inode number of each file.  -i  */
568
569 static int print_inode;
570
571 /* What to do with symbolic links.  Affected by -d, -F, -H, -l (and
572    other options that imply -l), and -L.  */
573
574 static enum Dereference_symlink dereference;
575
576 /* Nonzero means when a directory is found, display info on its
577    contents.  -R  */
578
579 static int recursive;
580
581 /* Nonzero means when an argument is a directory name, display info
582    on it itself.  -d  */
583
584 static int immediate_dirs;
585
586 /* Nonzero means don't omit files whose names start with `.'.  -A */
587
588 static int all_files;
589
590 /* Nonzero means don't omit files `.' and `..'
591    This flag implies `all_files'.  -a  */
592
593 static int really_all_files;
594
595 /* A linked list of shell-style globbing patterns.  If a non-argument
596    file name matches any of these patterns, it is omitted.
597    Controlled by -I.  Multiple -I options accumulate.
598    The -B option adds `*~' and `.*~' to this list.  */
599
600 struct ignore_pattern
601   {
602     const char *pattern;
603     struct ignore_pattern *next;
604   };
605
606 static struct ignore_pattern *ignore_patterns;
607
608 /* Nonzero means output nongraphic chars in file names as `?'.
609    (-q, --hide-control-chars)
610    qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
611    independent.  The algorithm is: first, obey the quoting style to get a
612    string representing the file name;  then, if qmark_funny_chars is set,
613    replace all nonprintable chars in that string with `?'.  It's necessary
614    to replace nonprintable chars even in quoted strings, because we don't
615    want to mess up the terminal if control chars get sent to it, and some
616    quoting methods pass through control chars as-is.  */
617 static int qmark_funny_chars;
618
619 /* Quoting options for file and dir name output.  */
620
621 static struct quoting_options *filename_quoting_options;
622 static struct quoting_options *dirname_quoting_options;
623
624 /* The number of chars per hardware tab stop.  Setting this to zero
625    inhibits the use of TAB characters for separating columns.  -T */
626 static size_t tabsize;
627
628 /* Nonzero means we are listing the working directory because no
629    non-option arguments were given. */
630
631 static int dir_defaulted;
632
633 /* Nonzero means print each directory name before listing it. */
634
635 static int print_dir_name;
636
637 /* The line length to use for breaking lines in many-per-line format.
638    Can be set with -w.  */
639
640 static size_t line_length;
641
642 /* If nonzero, the file listing format requires that stat be called on
643    each file. */
644
645 static int format_needs_stat;
646
647 /* Similar to `format_needs_stat', but set if only the file type is
648    needed.  */
649
650 static int format_needs_type;
651
652 /* strftime formats for non-recent and recent files, respectively, in
653    -l output.  */
654
655 static char const *long_time_format[2] =
656   {
657     /* strftime format for non-recent files (older than 6 months), in
658        -l output when --time-style=locale is specified.  This should
659        contain the year, month and day (at least), in an order that is
660        understood by people in your locale's territory.
661        Please try to keep the number of used screen columns small,
662        because many people work in windows with only 80 columns.  But
663        make this as wide as the other string below, for recent files.  */
664     N_("%b %e  %Y"),
665     /* strftime format for recent files (younger than 6 months), in
666        -l output when --time-style=locale is specified.  This should
667        contain the month, day and time (at least), in an order that is
668        understood by people in your locale's territory.
669        Please try to keep the number of used screen columns small,
670        because many people work in windows with only 80 columns.  But
671        make this as wide as the other string above, for non-recent files.  */
672     N_("%b %e %H:%M")
673   };
674
675 /* The exit status to use if we don't get any fatal errors. */
676
677 static int exit_status;
678
679 /* For long options that have no equivalent short option, use a
680    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
681 enum
682 {
683   AUTHOR_OPTION = CHAR_MAX + 1,
684   BLOCK_SIZE_OPTION,
685   COLOR_OPTION,
686   DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
687   FORMAT_OPTION,
688   FULL_TIME_OPTION,
689   INDICATOR_STYLE_OPTION,
690   QUOTING_STYLE_OPTION,
691   SHOW_CONTROL_CHARS_OPTION,
692   SI_OPTION,
693   SORT_OPTION,
694   TIME_OPTION,
695   TIME_STYLE_OPTION
696 };
697
698 static struct option const long_options[] =
699 {
700   {"all", no_argument, 0, 'a'},
701   {"escape", no_argument, 0, 'b'},
702   {"directory", no_argument, 0, 'd'},
703   {"dired", no_argument, 0, 'D'},
704   {"full-time", no_argument, 0, FULL_TIME_OPTION},
705   {"human-readable", no_argument, 0, 'h'},
706   {"inode", no_argument, 0, 'i'},
707   {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
708   {"numeric-uid-gid", no_argument, 0, 'n'},
709   {"no-group", no_argument, 0, 'G'},
710   {"hide-control-chars", no_argument, 0, 'q'},
711   {"reverse", no_argument, 0, 'r'},
712   {"size", no_argument, 0, 's'},
713   {"width", required_argument, 0, 'w'},
714   {"almost-all", no_argument, 0, 'A'},
715   {"ignore-backups", no_argument, 0, 'B'},
716   {"classify", no_argument, 0, 'F'},
717   {"file-type", no_argument, 0, 'p'},
718   {"si", no_argument, 0, SI_OPTION},
719   {"dereference-command-line", no_argument, 0, 'H'},
720   {"dereference-command-line-symlink-to-dir", no_argument, 0,
721    DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
722   {"ignore", required_argument, 0, 'I'},
723   {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
724   {"dereference", no_argument, 0, 'L'},
725   {"literal", no_argument, 0, 'N'},
726   {"quote-name", no_argument, 0, 'Q'},
727   {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
728   {"recursive", no_argument, 0, 'R'},
729   {"format", required_argument, 0, FORMAT_OPTION},
730   {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
731   {"sort", required_argument, 0, SORT_OPTION},
732   {"tabsize", required_argument, 0, 'T'},
733   {"time", required_argument, 0, TIME_OPTION},
734   {"time-style", required_argument, 0, TIME_STYLE_OPTION},
735   {"color", optional_argument, 0, COLOR_OPTION},
736   {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
737   {"author", no_argument, 0, AUTHOR_OPTION},
738   {GETOPT_HELP_OPTION_DECL},
739   {GETOPT_VERSION_OPTION_DECL},
740   {NULL, 0, NULL, 0}
741 };
742
743 static char const *const format_args[] =
744 {
745   "verbose", "long", "commas", "horizontal", "across",
746   "vertical", "single-column", 0
747 };
748
749 static enum format const format_types[] =
750 {
751   long_format, long_format, with_commas, horizontal, horizontal,
752   many_per_line, one_per_line
753 };
754
755 static char const *const sort_args[] =
756 {
757   "none", "time", "size", "extension", "version", 0
758 };
759
760 static enum sort_type const sort_types[] =
761 {
762   sort_none, sort_time, sort_size, sort_extension, sort_version
763 };
764
765 static char const *const time_args[] =
766 {
767   "atime", "access", "use", "ctime", "status", 0
768 };
769
770 static enum time_type const time_types[] =
771 {
772   time_atime, time_atime, time_atime, time_ctime, time_ctime
773 };
774
775 static char const *const color_args[] =
776 {
777   /* force and none are for compatibility with another color-ls version */
778   "always", "yes", "force",
779   "never", "no", "none",
780   "auto", "tty", "if-tty", 0
781 };
782
783 static enum color_type const color_types[] =
784 {
785   color_always, color_always, color_always,
786   color_never, color_never, color_never,
787   color_if_tty, color_if_tty, color_if_tty
788 };
789
790 /* Information about filling a column.  */
791 struct column_info
792 {
793   bool valid_len;
794   size_t line_len;
795   size_t *col_arr;
796 };
797
798 /* Array with information about column filledness.  */
799 static struct column_info *column_info;
800
801 /* Maximum number of columns ever possible for this display.  */
802 static size_t max_idx;
803
804 /* The minimum width of a colum is 3: 1 character for the name and 2
805    for the separating white space.  */
806 #define MIN_COLUMN_WIDTH        3
807
808
809 /* This zero-based index is used solely with the --dired option.
810    When that option is in effect, this counter is incremented for each
811    character of output generated by this program so that the beginning
812    and ending indices (in that output) of every file name can be recorded
813    and later output themselves.  */
814 static size_t dired_pos;
815
816 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
817
818 /* Write S to STREAM and increment DIRED_POS by S_LEN.  */
819 #define DIRED_FPUTS(s, stream, s_len) \
820     do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
821
822 /* Like DIRED_FPUTS, but for use when S is a literal string.  */
823 #define DIRED_FPUTS_LITERAL(s, stream) \
824     do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
825
826 #define DIRED_INDENT()                                                  \
827     do                                                                  \
828       {                                                                 \
829         if (dired)                                                      \
830           DIRED_FPUTS_LITERAL ("  ", stdout);                           \
831       }                                                                 \
832     while (0)
833
834 /* With --dired, store pairs of beginning and ending indices of filenames.  */
835 static struct obstack dired_obstack;
836
837 /* With --dired, store pairs of beginning and ending indices of any
838    directory names that appear as headers (just before `total' line)
839    for lists of directory entries.  Such directory names are seen when
840    listing hierarchies using -R and when a directory is listed with at
841    least one other command line argument.  */
842 static struct obstack subdired_obstack;
843
844 /* Save the current index on the specified obstack, OBS.  */
845 #define PUSH_CURRENT_DIRED_POS(obs)                                     \
846   do                                                                    \
847     {                                                                   \
848       if (dired)                                                        \
849         obstack_grow ((obs), &dired_pos, sizeof (dired_pos));           \
850     }                                                                   \
851   while (0)
852
853 /* With -R, this stack is used to help detect directory cycles.
854    The device/inode pairs on this stack mirror the pairs in the
855    active_dir_set hash table.  */
856 static struct obstack dev_ino_obstack;
857
858 /* Push a pair onto the device/inode stack.  */
859 #define DEV_INO_PUSH(Dev, Ino)                                          \
860   do                                                                    \
861     {                                                                   \
862       struct dev_ino *di;                                               \
863       obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino));        \
864       di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
865       di->st_dev = (Dev);                                               \
866       di->st_ino = (Ino);                                               \
867     }                                                                   \
868   while (0)
869
870 /* Pop a dev/ino struct off the global dev_ino_obstack
871    and return that struct.  */
872 static struct dev_ino
873 dev_ino_pop (void)
874 {
875   assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
876   obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
877   return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
878 }
879
880 #define ASSERT_MATCHING_DEV_INO(Name, Di)       \
881   do                                            \
882     {                                           \
883       struct stat sb;                           \
884       assert (Name);                            \
885       assert (0 <= stat (Name, &sb));           \
886       assert (sb.st_dev == Di.st_dev);          \
887       assert (sb.st_ino == Di.st_ino);          \
888     }                                           \
889   while (0)
890
891
892 /* Write to standard output PREFIX, followed by the quoting style and
893    a space-separated list of the integers stored in OS all on one line.  */
894
895 static void
896 dired_dump_obstack (const char *prefix, struct obstack *os)
897 {
898   size_t n_pos;
899
900   n_pos = obstack_object_size (os) / sizeof (dired_pos);
901   if (n_pos > 0)
902     {
903       size_t i;
904       size_t *pos;
905
906       pos = (size_t *) obstack_finish (os);
907       fputs (prefix, stdout);
908       for (i = 0; i < n_pos; i++)
909         printf (" %lu", (unsigned long int) pos[i]);
910       putchar ('\n');
911     }
912 }
913
914 static unsigned int
915 dev_ino_hash (void const *x, unsigned int table_size)
916 {
917   struct dev_ino const *p = x;
918   return (uintmax_t) p->st_ino % table_size;
919 }
920
921 static bool
922 dev_ino_compare (void const *x, void const *y)
923 {
924   struct dev_ino const *a = x;
925   struct dev_ino const *b = y;
926   return SAME_INODE (*a, *b) ? true : false;
927 }
928
929 static void
930 dev_ino_free (void *x)
931 {
932   free (x);
933 }
934
935 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
936    active directories.  Return nonzero if there is already a matching
937    entry in the table.  Otherwise, return zero.  */
938
939 static int
940 visit_dir (dev_t dev, ino_t ino)
941 {
942   struct dev_ino *ent;
943   struct dev_ino *ent_from_table;
944   int found_match;
945
946   ent = xmalloc (sizeof *ent);
947   ent->st_ino = ino;
948   ent->st_dev = dev;
949
950   /* Attempt to insert this entry into the table.  */
951   ent_from_table = hash_insert (active_dir_set, ent);
952
953   if (ent_from_table == NULL)
954     {
955       /* Insertion failed due to lack of memory.  */
956       xalloc_die ();
957     }
958
959   found_match = (ent_from_table != ent);
960
961   if (found_match)
962     {
963       /* ent was not inserted, so free it.  */
964       free (ent);
965     }
966
967   return found_match;
968 }
969
970 static void
971 free_pending_ent (struct pending *p)
972 {
973   if (p->name)
974     free (p->name);
975   if (p->realname)
976     free (p->realname);
977   free (p);
978 }
979
980 static void
981 restore_default_color (void)
982 {
983   if (put_indicator_direct (&color_indicator[C_LEFT]) == 0)
984     put_indicator_direct (&color_indicator[C_RIGHT]);
985 }
986
987 /* Upon interrupt, suspend, hangup, etc. ensure that the
988    terminal text color is restored to the default.  */
989 static void
990 sighandler (int sig)
991 {
992 #ifndef SA_NOCLDSTOP
993   signal (sig, SIG_IGN);
994 #endif
995
996   restore_default_color ();
997
998   /* SIGTSTP is special, since the application can receive that signal more
999      than once.  In this case, don't set the signal handler to the default.
1000      Instead, just raise the uncatchable SIGSTOP.  */
1001   if (sig == SIGTSTP)
1002     {
1003       sig = SIGSTOP;
1004     }
1005   else
1006     {
1007 #ifdef SA_NOCLDSTOP
1008       struct sigaction sigact;
1009
1010       sigact.sa_handler = SIG_DFL;
1011       sigemptyset (&sigact.sa_mask);
1012       sigact.sa_flags = 0;
1013       sigaction (sig, &sigact, NULL);
1014 #else
1015       signal (sig, SIG_DFL);
1016 #endif
1017     }
1018
1019   raise (sig);
1020 }
1021
1022 int
1023 main (int argc, char **argv)
1024 {
1025   register int i;
1026   register struct pending *thispend;
1027   unsigned int n_files;
1028
1029   initialize_main (&argc, &argv);
1030   program_name = argv[0];
1031   setlocale (LC_ALL, "");
1032   bindtextdomain (PACKAGE, LOCALEDIR);
1033   textdomain (PACKAGE);
1034
1035   atexit (close_stdout);
1036
1037 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1038   assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1039
1040   exit_status = 0;
1041   dir_defaulted = 1;
1042   print_dir_name = 1;
1043   pending_dirs = 0;
1044
1045   i = decode_switches (argc, argv);
1046
1047   if (print_with_color)
1048     parse_ls_color ();
1049
1050   /* Test print_with_color again, because the call to parse_ls_color
1051      may have just reset it -- e.g., if LS_COLORS is invalid.  */
1052   if (print_with_color)
1053     {
1054       prep_non_filename_text ();
1055       /* Avoid following symbolic links when possible.  */
1056       if (color_indicator[C_ORPHAN].string != NULL
1057           || (color_indicator[C_MISSING].string != NULL
1058               && format == long_format))
1059         check_symlink_color = 1;
1060
1061       {
1062         unsigned int j;
1063         static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE,
1064                                     SIGQUIT, SIGTERM, SIGTSTP };
1065         unsigned int nsigs = sizeof sigs / sizeof *sigs;
1066 #ifdef SA_NOCLDSTOP
1067         struct sigaction oldact, newact;
1068         sigset_t caught_signals;
1069
1070         sigemptyset (&caught_signals);
1071         for (j = 0; j < nsigs; j++)
1072           sigaddset (&caught_signals, sigs[j]);
1073         newact.sa_handler = sighandler;
1074         newact.sa_mask = caught_signals;
1075         newact.sa_flags = 0;
1076 #endif
1077
1078         for (j = 0; j < nsigs; j++)
1079           {
1080             int sig = sigs[j];
1081 #ifdef SA_NOCLDSTOP
1082             sigaction (sig, NULL, &oldact);
1083             if (oldact.sa_handler != SIG_IGN)
1084               sigaction (sig, &newact, NULL);
1085 #else
1086             if (signal (sig, SIG_IGN) != SIG_IGN)
1087               signal (sig, sighandler);
1088 #endif
1089           }
1090       }
1091     }
1092
1093   if (dereference == DEREF_UNDEFINED)
1094     dereference = ((immediate_dirs
1095                     || indicator_style == classify
1096                     || format == long_format)
1097                    ? DEREF_NEVER
1098                    : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1099
1100   /* When using -R, initialize a data structure we'll use to
1101      detect any directory cycles.  */
1102   if (recursive)
1103     {
1104       active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1105                                         dev_ino_hash,
1106                                         dev_ino_compare,
1107                                         dev_ino_free);
1108       if (active_dir_set == NULL)
1109         xalloc_die ();
1110
1111       obstack_init (&dev_ino_obstack);
1112     }
1113
1114   format_needs_stat = sort_type == sort_time || sort_type == sort_size
1115     || format == long_format
1116     || dereference == DEREF_ALWAYS
1117     || print_block_size || print_inode;
1118   format_needs_type = (format_needs_stat == 0
1119                        && (recursive || print_with_color
1120                            || indicator_style != none));
1121
1122   if (dired)
1123     {
1124       obstack_init (&dired_obstack);
1125       obstack_init (&subdired_obstack);
1126     }
1127
1128   nfiles = 100;
1129   files = xnmalloc (nfiles, sizeof *files);
1130   files_index = 0;
1131
1132   clear_files ();
1133
1134   n_files = argc - i;
1135   if (0 < n_files)
1136     dir_defaulted = 0;
1137
1138   for (; i < argc; i++)
1139     {
1140       gobble_file (argv[i], unknown, 1, "");
1141     }
1142
1143   if (dir_defaulted)
1144     {
1145       if (immediate_dirs)
1146         gobble_file (".", directory, 1, "");
1147       else
1148         queue_directory (".", 0);
1149     }
1150
1151   if (files_index)
1152     {
1153       sort_files ();
1154       if (!immediate_dirs)
1155         extract_dirs_from_files ("", 0);
1156       /* `files_index' might be zero now.  */
1157     }
1158
1159   /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1160      (and not pending_dirs->name) because there may be no markers in the queue
1161      at this point.  A marker may be enqueued when extract_dirs_from_files is
1162      called with a non-empty string or via print_dir.  */
1163   if (files_index)
1164     {
1165       print_current_files ();
1166       if (pending_dirs)
1167         DIRED_PUTCHAR ('\n');
1168     }
1169   else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1170     print_dir_name = 0;
1171
1172   while (pending_dirs)
1173     {
1174       thispend = pending_dirs;
1175       pending_dirs = pending_dirs->next;
1176
1177       if (LOOP_DETECT)
1178         {
1179           if (thispend->name == NULL)
1180             {
1181               /* thispend->name == NULL means this is a marker entry
1182                  indicating we've finished processing the directory.
1183                  Use its dev/ino numbers to remove the corresponding
1184                  entry from the active_dir_set hash table.  */
1185               struct dev_ino di = dev_ino_pop ();
1186               struct dev_ino *found = hash_delete (active_dir_set, &di);
1187               /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1188               assert (found);
1189               dev_ino_free (found);
1190               free_pending_ent (thispend);
1191               continue;
1192             }
1193         }
1194
1195       print_dir (thispend->name, thispend->realname);
1196
1197       free_pending_ent (thispend);
1198       print_dir_name = 1;
1199     }
1200
1201   if (dired)
1202     {
1203       /* No need to free these since we're about to exit.  */
1204       dired_dump_obstack ("//DIRED//", &dired_obstack);
1205       dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1206       printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1207               quoting_style_args[get_quoting_style (filename_quoting_options)]);
1208     }
1209
1210   /* Restore default color before exiting */
1211   if (print_with_color)
1212     {
1213       put_indicator (&color_indicator[C_LEFT]);
1214       put_indicator (&color_indicator[C_RIGHT]);
1215     }
1216
1217   if (LOOP_DETECT)
1218     {
1219       assert (hash_get_n_entries (active_dir_set) == 0);
1220       hash_free (active_dir_set);
1221     }
1222
1223   exit (exit_status);
1224 }
1225
1226 /* Set all the option flags according to the switches specified.
1227    Return the index of the first non-option argument.  */
1228
1229 static int
1230 decode_switches (int argc, char **argv)
1231 {
1232   int c;
1233   char *time_style_option = 0;
1234
1235   /* Record whether there is an option specifying sort type.  */
1236   int sort_type_specified = 0;
1237
1238   qmark_funny_chars = 0;
1239
1240   /* initialize all switches to default settings */
1241
1242   switch (ls_mode)
1243     {
1244     case LS_MULTI_COL:
1245       /* This is for the `dir' program.  */
1246       format = many_per_line;
1247       set_quoting_style (NULL, escape_quoting_style);
1248       break;
1249
1250     case LS_LONG_FORMAT:
1251       /* This is for the `vdir' program.  */
1252       format = long_format;
1253       set_quoting_style (NULL, escape_quoting_style);
1254       break;
1255
1256     case LS_LS:
1257       /* This is for the `ls' program.  */
1258       if (isatty (STDOUT_FILENO))
1259         {
1260           format = many_per_line;
1261           /* See description of qmark_funny_chars, above.  */
1262           qmark_funny_chars = 1;
1263         }
1264       else
1265         {
1266           format = one_per_line;
1267           qmark_funny_chars = 0;
1268         }
1269       break;
1270
1271     default:
1272       abort ();
1273     }
1274
1275   time_type = time_mtime;
1276   sort_type = sort_name;
1277   sort_reverse = 0;
1278   numeric_ids = 0;
1279   print_block_size = 0;
1280   indicator_style = none;
1281   print_inode = 0;
1282   dereference = DEREF_UNDEFINED;
1283   recursive = 0;
1284   immediate_dirs = 0;
1285   all_files = 0;
1286   really_all_files = 0;
1287   ignore_patterns = 0;
1288
1289   /* FIXME: put this in a function.  */
1290   {
1291     char const *q_style = getenv ("QUOTING_STYLE");
1292     if (q_style)
1293       {
1294         int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1295         if (0 <= i)
1296           set_quoting_style (NULL, quoting_style_vals[i]);
1297         else
1298           error (0, 0,
1299          _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1300                  quotearg (q_style));
1301       }
1302   }
1303
1304   {
1305     char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1306     human_output_opts = human_options (ls_block_size, false,
1307                                        &output_block_size);
1308     if (ls_block_size || getenv ("BLOCK_SIZE"))
1309       file_output_block_size = output_block_size;
1310   }
1311
1312   line_length = 80;
1313   {
1314     char const *p = getenv ("COLUMNS");
1315     if (p && *p)
1316       {
1317         unsigned long int tmp_ulong;
1318         if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1319             && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1320           {
1321             line_length = tmp_ulong;
1322           }
1323         else
1324           {
1325             error (0, 0,
1326                _("ignoring invalid width in environment variable COLUMNS: %s"),
1327                    quotearg (p));
1328           }
1329       }
1330   }
1331
1332 #ifdef TIOCGWINSZ
1333   {
1334     struct winsize ws;
1335
1336     if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1337         && 0 < ws.ws_col /* && ws.ws_col <= SIZE_MAX */ )
1338       line_length = ws.ws_col;
1339   }
1340 #endif
1341
1342   /* Using the TABSIZE environment variable is not POSIX-approved.
1343      Ignore it when POSIXLY_CORRECT is set.  */
1344   {
1345     char const *p;
1346     tabsize = 8;
1347     if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1348       {
1349         unsigned long int tmp_ulong;
1350         if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1351             && tmp_ulong <= SIZE_MAX)
1352           {
1353             tabsize = tmp_ulong;
1354           }
1355         else
1356           {
1357             error (0, 0,
1358              _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1359                    quotearg (p));
1360           }
1361       }
1362   }
1363
1364   while ((c = getopt_long (argc, argv,
1365                            "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1366                            long_options, NULL)) != -1)
1367     {
1368       switch (c)
1369         {
1370         case 0:
1371           break;
1372
1373         case 'a':
1374           all_files = 1;
1375           really_all_files = 1;
1376           break;
1377
1378         case 'b':
1379           set_quoting_style (NULL, escape_quoting_style);
1380           break;
1381
1382         case 'c':
1383           time_type = time_ctime;
1384           break;
1385
1386         case 'd':
1387           immediate_dirs = 1;
1388           break;
1389
1390         case 'f':
1391           /* Same as enabling -a -U and disabling -l -s.  */
1392           all_files = 1;
1393           really_all_files = 1;
1394           sort_type = sort_none;
1395           sort_type_specified = 1;
1396           /* disable -l */
1397           if (format == long_format)
1398             format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1399           print_block_size = 0; /* disable -s */
1400           print_with_color = 0; /* disable --color */
1401           break;
1402
1403         case 'g':
1404           format = long_format;
1405           print_owner = 0;
1406           break;
1407
1408         case 'h':
1409           human_output_opts = human_autoscale | human_SI | human_base_1024;
1410           file_output_block_size = output_block_size = 1;
1411           break;
1412
1413         case 'i':
1414           print_inode = 1;
1415           break;
1416
1417         case 'k':
1418           human_output_opts = 0;
1419           file_output_block_size = output_block_size = 1024;
1420           break;
1421
1422         case 'l':
1423           format = long_format;
1424           break;
1425
1426         case 'm':
1427           format = with_commas;
1428           break;
1429
1430         case 'n':
1431           numeric_ids = 1;
1432           format = long_format;
1433           break;
1434
1435         case 'o':  /* Just like -l, but don't display group info.  */
1436           format = long_format;
1437           print_group = 0;
1438           break;
1439
1440         case 'p':
1441           indicator_style = file_type;
1442           break;
1443
1444         case 'q':
1445           qmark_funny_chars = 1;
1446           break;
1447
1448         case 'r':
1449           sort_reverse = 1;
1450           break;
1451
1452         case 's':
1453           print_block_size = 1;
1454           break;
1455
1456         case 't':
1457           sort_type = sort_time;
1458           sort_type_specified = 1;
1459           break;
1460
1461         case 'u':
1462           time_type = time_atime;
1463           break;
1464
1465         case 'v':
1466           sort_type = sort_version;
1467           sort_type_specified = 1;
1468           break;
1469
1470         case 'w':
1471           {
1472             unsigned long int tmp_ulong;
1473             if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1474                 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1475               error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1476                      quotearg (optarg));
1477             line_length = tmp_ulong;
1478             break;
1479           }
1480
1481         case 'x':
1482           format = horizontal;
1483           break;
1484
1485         case 'A':
1486           really_all_files = 0;
1487           all_files = 1;
1488           break;
1489
1490         case 'B':
1491           add_ignore_pattern ("*~");
1492           add_ignore_pattern (".*~");
1493           break;
1494
1495         case 'C':
1496           format = many_per_line;
1497           break;
1498
1499         case 'D':
1500           dired = 1;
1501           break;
1502
1503         case 'F':
1504           indicator_style = classify;
1505           break;
1506
1507         case 'G':               /* inhibit display of group info */
1508           print_group = 0;
1509           break;
1510
1511         case 'H':
1512           dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1513           break;
1514
1515         case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1516           dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1517           break;
1518
1519         case 'I':
1520           add_ignore_pattern (optarg);
1521           break;
1522
1523         case 'L':
1524           dereference = DEREF_ALWAYS;
1525           break;
1526
1527         case 'N':
1528           set_quoting_style (NULL, literal_quoting_style);
1529           break;
1530
1531         case 'Q':
1532           set_quoting_style (NULL, c_quoting_style);
1533           break;
1534
1535         case 'R':
1536           recursive = 1;
1537           break;
1538
1539         case 'S':
1540           sort_type = sort_size;
1541           sort_type_specified = 1;
1542           break;
1543
1544         case 'T':
1545           {
1546             unsigned long int tmp_ulong;
1547             if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1548                 || SIZE_MAX < tmp_ulong)
1549               error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1550                      quotearg (optarg));
1551             tabsize = tmp_ulong;
1552             break;
1553           }
1554
1555         case 'U':
1556           sort_type = sort_none;
1557           sort_type_specified = 1;
1558           break;
1559
1560         case 'X':
1561           sort_type = sort_extension;
1562           sort_type_specified = 1;
1563           break;
1564
1565         case '1':
1566           /* -1 has no effect after -l.  */
1567           if (format != long_format)
1568             format = one_per_line;
1569           break;
1570
1571         case AUTHOR_OPTION:
1572           print_author = true;
1573           break;
1574
1575         case SORT_OPTION:
1576           sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1577           sort_type_specified = 1;
1578           break;
1579
1580         case TIME_OPTION:
1581           time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1582           break;
1583
1584         case FORMAT_OPTION:
1585           format = XARGMATCH ("--format", optarg, format_args, format_types);
1586           break;
1587
1588         case FULL_TIME_OPTION:
1589           format = long_format;
1590           time_style_option = "full-iso";
1591           break;
1592
1593         case COLOR_OPTION:
1594           {
1595             int i;
1596             if (optarg)
1597               i = XARGMATCH ("--color", optarg, color_args, color_types);
1598             else
1599               /* Using --color with no argument is equivalent to using
1600                  --color=always.  */
1601               i = color_always;
1602
1603             print_with_color = (i == color_always
1604                                 || (i == color_if_tty
1605                                     && isatty (STDOUT_FILENO)));
1606
1607             if (print_with_color)
1608               {
1609                 /* Don't use TAB characters in output.  Some terminal
1610                    emulators can't handle the combination of tabs and
1611                    color codes on the same line.  */
1612                 tabsize = 0;
1613               }
1614             break;
1615           }
1616
1617         case INDICATOR_STYLE_OPTION:
1618           indicator_style = XARGMATCH ("--indicator-style", optarg,
1619                                        indicator_style_args,
1620                                        indicator_style_types);
1621           break;
1622
1623         case QUOTING_STYLE_OPTION:
1624           set_quoting_style (NULL,
1625                              XARGMATCH ("--quoting-style", optarg,
1626                                         quoting_style_args,
1627                                         quoting_style_vals));
1628           break;
1629
1630         case TIME_STYLE_OPTION:
1631           time_style_option = optarg;
1632           break;
1633
1634         case SHOW_CONTROL_CHARS_OPTION:
1635           qmark_funny_chars = 0;
1636           break;
1637
1638         case BLOCK_SIZE_OPTION:
1639           human_output_opts = human_options (optarg, true, &output_block_size);
1640           file_output_block_size = output_block_size;
1641           break;
1642
1643         case SI_OPTION:
1644           human_output_opts = human_autoscale | human_SI;
1645           file_output_block_size = output_block_size = 1;
1646           break;
1647
1648         case_GETOPT_HELP_CHAR;
1649
1650         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
1651
1652         default:
1653           usage (EXIT_FAILURE);
1654         }
1655     }
1656
1657   max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1658
1659   filename_quoting_options = clone_quoting_options (NULL);
1660   if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1661     set_char_quoting (filename_quoting_options, ' ', 1);
1662   if (indicator_style != none)
1663     {
1664       char const *p;
1665       for (p = "*=@|" + (int) indicator_style - 1;  *p;  p++)
1666         set_char_quoting (filename_quoting_options, *p, 1);
1667     }
1668
1669   dirname_quoting_options = clone_quoting_options (NULL);
1670   set_char_quoting (dirname_quoting_options, ':', 1);
1671
1672   /* --dired is meaningful only with --format=long (-l).
1673      Otherwise, ignore it.  FIXME: warn about this?
1674      Alternatively, make --dired imply --format=long?  */
1675   if (dired && format != long_format)
1676     dired = 0;
1677
1678   /* If -c or -u is specified and not -l (or any other option that implies -l),
1679      and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1680      The behavior of ls when using either -c or -u but with neither -l nor -t
1681      appears to be unspecified by POSIX.  So, with GNU ls, `-u' alone means
1682      sort by atime (this is the one that's not specified by the POSIX spec),
1683      -lu means show atime and sort by name, -lut means show atime and sort
1684      by atime.  */
1685
1686   if ((time_type == time_ctime || time_type == time_atime)
1687       && !sort_type_specified && format != long_format)
1688     {
1689       sort_type = sort_time;
1690     }
1691
1692   if (format == long_format)
1693     {
1694       char *style = time_style_option;
1695       static char const posix_prefix[] = "posix-";
1696
1697       if (! style)
1698         if (! (style = getenv ("TIME_STYLE")))
1699           style = "posix-long-iso";
1700
1701       while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1702         {
1703           if (! hard_locale (LC_TIME))
1704             return optind;
1705           style += sizeof posix_prefix - 1;
1706         }
1707
1708       if (*style == '+')
1709         {
1710           char *p0 = style + 1;
1711           char *p1 = strchr (p0, '\n');
1712           if (! p1)
1713             p1 = p0;
1714           else
1715             {
1716               if (strchr (p1 + 1, '\n'))
1717                 error (EXIT_FAILURE, 0, _("invalid time style format %s"),
1718                        quote (p0));
1719               *p1++ = '\0';
1720             }
1721           long_time_format[0] = p0;
1722           long_time_format[1] = p1;
1723         }
1724       else
1725         switch (XARGMATCH ("time style", style,
1726                            time_style_args,
1727                            time_style_types))
1728           {
1729           case full_iso_time_style:
1730             long_time_format[0] = long_time_format[1] =
1731               "%Y-%m-%d %H:%M:%S.%N %z";
1732             break;
1733
1734           case long_iso_time_style:
1735             long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1736             break;
1737
1738           case iso_time_style:
1739             long_time_format[0] = "%Y-%m-%d ";
1740             long_time_format[1] = "%m-%d %H:%M";
1741             break;
1742
1743           case locale_time_style:
1744             if (hard_locale (LC_TIME))
1745               {
1746                 unsigned int i;
1747                 for (i = 0; i < 2; i++)
1748                   long_time_format[i] =
1749                     dcgettext (NULL, long_time_format[i], LC_TIME);
1750               }
1751           }
1752     }
1753
1754   return optind;
1755 }
1756
1757 /* Parse a string as part of the LS_COLORS variable; this may involve
1758    decoding all kinds of escape characters.  If equals_end is set an
1759    unescaped equal sign ends the string, otherwise only a : or \0
1760    does.  Set *OUTPUT_COUNT to the number of bytes output.  Return
1761    true if successful.
1762
1763    The resulting string is *not* null-terminated, but may contain
1764    embedded nulls.
1765
1766    Note that both dest and src are char **; on return they point to
1767    the first free byte after the array and the character that ended
1768    the input string, respectively.  */
1769
1770 static bool
1771 get_funky_string (char **dest, const char **src, bool equals_end,
1772                   size_t *output_count)
1773 {
1774   int num;                      /* For numerical codes */
1775   size_t count;                 /* Something to count with */
1776   enum {
1777     ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1778   } state;
1779   const char *p;
1780   char *q;
1781
1782   p = *src;                     /* We don't want to double-indirect */
1783   q = *dest;                    /* the whole darn time.  */
1784
1785   count = 0;                    /* No characters counted in yet.  */
1786   num = 0;
1787
1788   state = ST_GND;               /* Start in ground state.  */
1789   while (state < ST_END)
1790     {
1791       switch (state)
1792         {
1793         case ST_GND:            /* Ground state (no escapes) */
1794           switch (*p)
1795             {
1796             case ':':
1797             case '\0':
1798               state = ST_END;   /* End of string */
1799               break;
1800             case '\\':
1801               state = ST_BACKSLASH; /* Backslash scape sequence */
1802               ++p;
1803               break;
1804             case '^':
1805               state = ST_CARET; /* Caret escape */
1806               ++p;
1807               break;
1808             case '=':
1809               if (equals_end)
1810                 {
1811                   state = ST_END; /* End */
1812                   break;
1813                 }
1814               /* else fall through */
1815             default:
1816               *(q++) = *(p++);
1817               ++count;
1818               break;
1819             }
1820           break;
1821
1822         case ST_BACKSLASH:      /* Backslash escaped character */
1823           switch (*p)
1824             {
1825             case '0':
1826             case '1':
1827             case '2':
1828             case '3':
1829             case '4':
1830             case '5':
1831             case '6':
1832             case '7':
1833               state = ST_OCTAL; /* Octal sequence */
1834               num = *p - '0';
1835               break;
1836             case 'x':
1837             case 'X':
1838               state = ST_HEX;   /* Hex sequence */
1839               num = 0;
1840               break;
1841             case 'a':           /* Bell */
1842               num = 7;          /* Not all C compilers know what \a means */
1843               break;
1844             case 'b':           /* Backspace */
1845               num = '\b';
1846               break;
1847             case 'e':           /* Escape */
1848               num = 27;
1849               break;
1850             case 'f':           /* Form feed */
1851               num = '\f';
1852               break;
1853             case 'n':           /* Newline */
1854               num = '\n';
1855               break;
1856             case 'r':           /* Carriage return */
1857               num = '\r';
1858               break;
1859             case 't':           /* Tab */
1860               num = '\t';
1861               break;
1862             case 'v':           /* Vtab */
1863               num = '\v';
1864               break;
1865             case '?':           /* Delete */
1866               num = 127;
1867               break;
1868             case '_':           /* Space */
1869               num = ' ';
1870               break;
1871             case '\0':          /* End of string */
1872               state = ST_ERROR; /* Error! */
1873               break;
1874             default:            /* Escaped character like \ ^ : = */
1875               num = *p;
1876               break;
1877             }
1878           if (state == ST_BACKSLASH)
1879             {
1880               *(q++) = num;
1881               ++count;
1882               state = ST_GND;
1883             }
1884           ++p;
1885           break;
1886
1887         case ST_OCTAL:          /* Octal sequence */
1888           if (*p < '0' || *p > '7')
1889             {
1890               *(q++) = num;
1891               ++count;
1892               state = ST_GND;
1893             }
1894           else
1895             num = (num << 3) + (*(p++) - '0');
1896           break;
1897
1898         case ST_HEX:            /* Hex sequence */
1899           switch (*p)
1900             {
1901             case '0':
1902             case '1':
1903             case '2':
1904             case '3':
1905             case '4':
1906             case '5':
1907             case '6':
1908             case '7':
1909             case '8':
1910             case '9':
1911               num = (num << 4) + (*(p++) - '0');
1912               break;
1913             case 'a':
1914             case 'b':
1915             case 'c':
1916             case 'd':
1917             case 'e':
1918             case 'f':
1919               num = (num << 4) + (*(p++) - 'a') + 10;
1920               break;
1921             case 'A':
1922             case 'B':
1923             case 'C':
1924             case 'D':
1925             case 'E':
1926             case 'F':
1927               num = (num << 4) + (*(p++) - 'A') + 10;
1928               break;
1929             default:
1930               *(q++) = num;
1931               ++count;
1932               state = ST_GND;
1933               break;
1934             }
1935           break;
1936
1937         case ST_CARET:          /* Caret escape */
1938           state = ST_GND;       /* Should be the next state... */
1939           if (*p >= '@' && *p <= '~')
1940             {
1941               *(q++) = *(p++) & 037;
1942               ++count;
1943             }
1944           else if (*p == '?')
1945             {
1946               *(q++) = 127;
1947               ++count;
1948             }
1949           else
1950             state = ST_ERROR;
1951           break;
1952
1953         default:
1954           abort ();
1955         }
1956     }
1957
1958   *dest = q;
1959   *src = p;
1960   *output_count = count;
1961
1962   return state != ST_ERROR;
1963 }
1964
1965 static void
1966 parse_ls_color (void)
1967 {
1968   const char *p;                /* Pointer to character being parsed */
1969   char *buf;                    /* color_buf buffer pointer */
1970   int state;                    /* State of parser */
1971   int ind_no;                   /* Indicator number */
1972   char label[3];                /* Indicator label */
1973   struct color_ext_type *ext;   /* Extension we are working on */
1974
1975   if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1976     return;
1977
1978   ext = NULL;
1979   strcpy (label, "??");
1980
1981   /* This is an overly conservative estimate, but any possible
1982      LS_COLORS string will *not* generate a color_buf longer than
1983      itself, so it is a safe way of allocating a buffer in
1984      advance.  */
1985   buf = color_buf = xstrdup (p);
1986
1987   state = 1;
1988   while (state > 0)
1989     {
1990       switch (state)
1991         {
1992         case 1:         /* First label character */
1993           switch (*p)
1994             {
1995             case ':':
1996               ++p;
1997               break;
1998
1999             case '*':
2000               /* Allocate new extension block and add to head of
2001                  linked list (this way a later definition will
2002                  override an earlier one, which can be useful for
2003                  having terminal-specific defs override global).  */
2004
2005               ext = xmalloc (sizeof *ext);
2006               ext->next = color_ext_list;
2007               color_ext_list = ext;
2008
2009               ++p;
2010               ext->ext.string = buf;
2011
2012               state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2013                        ? 4 : -1);
2014               break;
2015
2016             case '\0':
2017               state = 0;        /* Done! */
2018               break;
2019
2020             default:    /* Assume it is file type label */
2021               label[0] = *(p++);
2022               state = 2;
2023               break;
2024             }
2025           break;
2026
2027         case 2:         /* Second label character */
2028           if (*p)
2029             {
2030               label[1] = *(p++);
2031               state = 3;
2032             }
2033           else
2034             state = -1; /* Error */
2035           break;
2036
2037         case 3:         /* Equal sign after indicator label */
2038           state = -1;   /* Assume failure... */
2039           if (*(p++) == '=')/* It *should* be... */
2040             {
2041               for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2042                 {
2043                   if (STREQ (label, indicator_name[ind_no]))
2044                     {
2045                       color_indicator[ind_no].string = buf;
2046                       state = (get_funky_string (&buf, &p, false,
2047                                                  &color_indicator[ind_no].len)
2048                                ? 1 : -1);
2049                       break;
2050                     }
2051                 }
2052               if (state == -1)
2053                 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2054             }
2055          break;
2056
2057         case 4:         /* Equal sign after *.ext */
2058           if (*(p++) == '=')
2059             {
2060               ext->seq.string = buf;
2061               state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2062                        ? 1 : -1);
2063             }
2064           else
2065             state = -1;
2066           break;
2067         }
2068     }
2069
2070   if (state < 0)
2071     {
2072       struct color_ext_type *e;
2073       struct color_ext_type *e2;
2074
2075       error (0, 0,
2076              _("unparsable value for LS_COLORS environment variable"));
2077       free (color_buf);
2078       for (e = color_ext_list; e != NULL; /* empty */)
2079         {
2080           e2 = e;
2081           e = e->next;
2082           free (e2);
2083         }
2084       print_with_color = 0;
2085     }
2086
2087   if (color_indicator[C_LINK].len == 6
2088       && !strncmp (color_indicator[C_LINK].string, "target", 6))
2089     color_symlink_as_referent = 1;
2090 }
2091
2092 /* Request that the directory named NAME have its contents listed later.
2093    If REALNAME is nonzero, it will be used instead of NAME when the
2094    directory name is printed.  This allows symbolic links to directories
2095    to be treated as regular directories but still be listed under their
2096    real names.  NAME == NULL is used to insert a marker entry for the
2097    directory named in REALNAME.
2098    If F is non-NULL, we use its dev/ino information to save
2099    a call to stat -- when doing a recursive (-R) traversal.  */
2100
2101 static void
2102 queue_directory (const char *name, const char *realname)
2103 {
2104   struct pending *new;
2105
2106   new = xmalloc (sizeof *new);
2107   new->realname = realname ? xstrdup (realname) : NULL;
2108   new->name = name ? xstrdup (name) : NULL;
2109   new->next = pending_dirs;
2110   pending_dirs = new;
2111 }
2112
2113 /* Read directory `name', and list the files in it.
2114    If `realname' is nonzero, print its name instead of `name';
2115    this is used for symbolic links to directories. */
2116
2117 static void
2118 print_dir (const char *name, const char *realname)
2119 {
2120   register DIR *dirp;
2121   register struct dirent *next;
2122   register uintmax_t total_blocks = 0;
2123   static int first = 1;
2124
2125   errno = 0;
2126   dirp = opendir (name);
2127   if (!dirp)
2128     {
2129       error (0, errno, "%s", quotearg_colon (name));
2130       exit_status = 1;
2131       return;
2132     }
2133
2134   if (LOOP_DETECT)
2135     {
2136       struct stat dir_stat;
2137       int fd = dirfd (dirp);
2138
2139       /* If dirfd failed, endure the overhead of using stat.  */
2140       if ((0 <= fd
2141            ? fstat (fd, &dir_stat)
2142            : stat (name, &dir_stat)) < 0)
2143         {
2144           error (0, errno, _("cannot determine device and inode of %s"),
2145                  quotearg_colon (name));
2146           exit_status = 1;
2147           return;
2148         }
2149
2150       /* If we've already visited this dev/inode pair, warn that
2151          we've found a loop, and do not process this directory.  */
2152       if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2153         {
2154           error (0, 0, _("not listing already-listed directory: %s"),
2155                  quotearg_colon (name));
2156           return;
2157         }
2158
2159       DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2160     }
2161
2162   /* Read the directory entries, and insert the subfiles into the `files'
2163      table.  */
2164
2165   clear_files ();
2166
2167   while (1)
2168     {
2169       /* Set errno to zero so we can distinguish between a readdir failure
2170          and when readdir simply finds that there are no more entries.  */
2171       errno = 0;
2172       if ((next = readdir (dirp)) == NULL)
2173         {
2174           if (errno)
2175             {
2176               /* Save/restore errno across closedir call.  */
2177               int e = errno;
2178               closedir (dirp);
2179               errno = e;
2180
2181               /* Arrange to give a diagnostic after exiting this loop.  */
2182               dirp = NULL;
2183             }
2184           break;
2185         }
2186
2187       if (file_interesting (next))
2188         {
2189           enum filetype type = unknown;
2190
2191 #if HAVE_STRUCT_DIRENT_D_TYPE
2192           if (next->d_type == DT_BLK
2193               || next->d_type == DT_CHR
2194               || next->d_type == DT_DIR
2195               || next->d_type == DT_FIFO
2196               || next->d_type == DT_LNK
2197               || next->d_type == DT_REG
2198               || next->d_type == DT_SOCK)
2199             type = next->d_type;
2200 #endif
2201           total_blocks += gobble_file (next->d_name, type, 0, name);
2202         }
2203     }
2204
2205   if (dirp == NULL || CLOSEDIR (dirp))
2206     {
2207       error (0, errno, _("reading directory %s"), quotearg_colon (name));
2208       exit_status = 1;
2209       /* Don't return; print whatever we got. */
2210     }
2211
2212   /* Sort the directory contents.  */
2213   sort_files ();
2214
2215   /* If any member files are subdirectories, perhaps they should have their
2216      contents listed rather than being mentioned here as files.  */
2217
2218   if (recursive)
2219     extract_dirs_from_files (name, 1);
2220
2221   if (recursive || print_dir_name)
2222     {
2223       if (!first)
2224         DIRED_PUTCHAR ('\n');
2225       first = 0;
2226       DIRED_INDENT ();
2227       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2228       dired_pos += quote_name (stdout, realname ? realname : name,
2229                                dirname_quoting_options, NULL);
2230       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2231       DIRED_FPUTS_LITERAL (":\n", stdout);
2232     }
2233
2234   if (format == long_format || print_block_size)
2235     {
2236       const char *p;
2237       char buf[LONGEST_HUMAN_READABLE + 1];
2238
2239       DIRED_INDENT ();
2240       p = _("total");
2241       DIRED_FPUTS (p, stdout, strlen (p));
2242       DIRED_PUTCHAR (' ');
2243       p = human_readable (total_blocks, buf, human_output_opts,
2244                           ST_NBLOCKSIZE, output_block_size);
2245       DIRED_FPUTS (p, stdout, strlen (p));
2246       DIRED_PUTCHAR ('\n');
2247     }
2248
2249   if (files_index)
2250     print_current_files ();
2251 }
2252
2253 /* Add `pattern' to the list of patterns for which files that match are
2254    not listed.  */
2255
2256 static void
2257 add_ignore_pattern (const char *pattern)
2258 {
2259   register struct ignore_pattern *ignore;
2260
2261   ignore = xmalloc (sizeof *ignore);
2262   ignore->pattern = pattern;
2263   /* Add it to the head of the linked list. */
2264   ignore->next = ignore_patterns;
2265   ignore_patterns = ignore;
2266 }
2267
2268 /* Return nonzero if the file in `next' should be listed. */
2269
2270 static int
2271 file_interesting (const struct dirent *next)
2272 {
2273   register struct ignore_pattern *ignore;
2274
2275   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2276     if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2277       return 0;
2278
2279   if (really_all_files
2280       || next->d_name[0] != '.'
2281       || (all_files
2282           && next->d_name[1] != '\0'
2283           && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2284     return 1;
2285
2286   return 0;
2287 }
2288
2289 /* Enter and remove entries in the table `files'.  */
2290
2291 /* Empty the table of files. */
2292
2293 static void
2294 clear_files (void)
2295 {
2296   register size_t i;
2297
2298   for (i = 0; i < files_index; i++)
2299     {
2300       free (files[i].name);
2301       if (files[i].linkname)
2302         free (files[i].linkname);
2303     }
2304
2305   files_index = 0;
2306   block_size_size = 4;
2307 }
2308
2309 /* Add a file to the current table of files.
2310    Verify that the file exists, and print an error message if it does not.
2311    Return the number of blocks that the file occupies.  */
2312
2313 static uintmax_t
2314 gobble_file (const char *name, enum filetype type, int explicit_arg,
2315              const char *dirname)
2316 {
2317   register uintmax_t blocks;
2318   register char *path;
2319
2320   if (files_index == nfiles)
2321     {
2322       files = xnrealloc (files, nfiles, 2 * sizeof *files);
2323       nfiles *= 2;
2324     }
2325
2326   files[files_index].linkname = 0;
2327   files[files_index].linkmode = 0;
2328   files[files_index].linkok = 0;
2329
2330   if (explicit_arg
2331       || format_needs_stat
2332       || (format_needs_type
2333           && (type == unknown
2334
2335               /* FIXME: remove this disjunct.
2336                  I don't think we care about symlinks here, but for now
2337                  this won't make a big performance difference.  */
2338               || type == symbolic_link
2339
2340               /* --indicator-style=classify (aka -F)
2341                  requires that we stat each regular file
2342                  to see if it's executable.  */
2343               || (type == normal && (indicator_style == classify
2344                                      /* This is so that --color ends up
2345                                         highlighting files with the executable
2346                                         bit set even when options like -F are
2347                                         not specified.  */
2348                                      || print_with_color)))))
2349
2350     {
2351       /* `path' is the absolute pathname of this file. */
2352       int err;
2353
2354       if (name[0] == '/' || dirname[0] == 0)
2355         path = (char *) name;
2356       else
2357         {
2358           path = alloca (strlen (name) + strlen (dirname) + 2);
2359           attach (path, dirname, name);
2360         }
2361
2362       switch (dereference)
2363         {
2364         case DEREF_ALWAYS:
2365           err = stat (path, &files[files_index].stat);
2366           break;
2367
2368         case DEREF_COMMAND_LINE_ARGUMENTS:
2369         case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2370           if (explicit_arg)
2371             {
2372               int need_lstat;
2373               err = stat (path, &files[files_index].stat);
2374
2375               if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2376                 break;
2377
2378               need_lstat = (err < 0
2379                             ? errno == ENOENT
2380                             : ! S_ISDIR (files[files_index].stat.st_mode));
2381               if (!need_lstat)
2382                 break;
2383
2384               /* stat failed because of ENOENT, maybe indicating a dangling
2385                  symlink.  Or stat succeeded, PATH does not refer to a
2386                  directory, and --dereference-command-line-symlink-to-dir is
2387                  in effect.  Fall through so that we call lstat instead.  */
2388             }
2389
2390         default: /* DEREF_NEVER */
2391           err = lstat (path, &files[files_index].stat);
2392           break;
2393         }
2394
2395       if (err < 0)
2396         {
2397           error (0, errno, "%s", quotearg_colon (path));
2398           exit_status = 1;
2399           return 0;
2400         }
2401
2402 #if HAVE_ACL
2403       if (format == long_format)
2404         {
2405           int n = file_has_acl (path, &files[files_index].stat);
2406           files[files_index].have_acl = (0 < n);
2407           if (n < 0)
2408             error (0, errno, "%s", quotearg_colon (path));
2409         }
2410 #endif
2411
2412       if (S_ISLNK (files[files_index].stat.st_mode)
2413           && (format == long_format || check_symlink_color))
2414         {
2415           char *linkpath;
2416           struct stat linkstats;
2417
2418           get_link_name (path, &files[files_index]);
2419           linkpath = make_link_path (path, files[files_index].linkname);
2420
2421           /* Avoid following symbolic links when possible, ie, when
2422              they won't be traced and when no indicator is needed. */
2423           if (linkpath
2424               && (indicator_style != none || check_symlink_color)
2425               && stat (linkpath, &linkstats) == 0)
2426             {
2427               files[files_index].linkok = 1;
2428
2429               /* Symbolic links to directories that are mentioned on the
2430                  command line are automatically traced if not being
2431                  listed as files.  */
2432               if (!explicit_arg || format == long_format
2433                   || !S_ISDIR (linkstats.st_mode))
2434                 {
2435                   /* Get the linked-to file's mode for the filetype indicator
2436                      in long listings.  */
2437                   files[files_index].linkmode = linkstats.st_mode;
2438                   files[files_index].linkok = 1;
2439                 }
2440             }
2441           if (linkpath)
2442             free (linkpath);
2443         }
2444
2445       if (S_ISLNK (files[files_index].stat.st_mode))
2446         files[files_index].filetype = symbolic_link;
2447       else if (S_ISDIR (files[files_index].stat.st_mode))
2448         {
2449           if (explicit_arg && !immediate_dirs)
2450             files[files_index].filetype = arg_directory;
2451           else
2452             files[files_index].filetype = directory;
2453         }
2454       else
2455         files[files_index].filetype = normal;
2456
2457       blocks = ST_NBLOCKS (files[files_index].stat);
2458       {
2459         char buf[LONGEST_HUMAN_READABLE + 1];
2460         int len = strlen (human_readable (blocks, buf, human_output_opts,
2461                                           ST_NBLOCKSIZE, output_block_size));
2462         if (block_size_size < len)
2463           block_size_size = len < 7 ? len : 7;
2464       }
2465     }
2466   else
2467     {
2468       files[files_index].filetype = type;
2469 #if HAVE_STRUCT_DIRENT_D_TYPE
2470       files[files_index].stat.st_mode = DTTOIF (type);
2471 #endif
2472       blocks = 0;
2473     }
2474
2475   files[files_index].name = xstrdup (name);
2476   files_index++;
2477
2478   return blocks;
2479 }
2480
2481 #ifdef S_ISLNK
2482
2483 /* Put the name of the file that `filename' is a symbolic link to
2484    into the `linkname' field of `f'. */
2485
2486 static void
2487 get_link_name (const char *filename, struct fileinfo *f)
2488 {
2489   f->linkname = xreadlink (filename);
2490   if (f->linkname == NULL)
2491     {
2492       error (0, errno, _("cannot read symbolic link %s"),
2493              quotearg_colon (filename));
2494       exit_status = 1;
2495     }
2496 }
2497
2498 /* If `linkname' is a relative path and `path' contains one or more
2499    leading directories, return `linkname' with those directories
2500    prepended; otherwise, return a copy of `linkname'.
2501    If `linkname' is zero, return zero. */
2502
2503 static char *
2504 make_link_path (const char *path, const char *linkname)
2505 {
2506   char *linkbuf;
2507   size_t bufsiz;
2508
2509   if (linkname == 0)
2510     return 0;
2511
2512   if (*linkname == '/')
2513     return xstrdup (linkname);
2514
2515   /* The link is to a relative path.  Prepend any leading path
2516      in `path' to the link name. */
2517   linkbuf = strrchr (path, '/');
2518   if (linkbuf == 0)
2519     return xstrdup (linkname);
2520
2521   bufsiz = linkbuf - path + 1;
2522   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2523   strncpy (linkbuf, path, bufsiz);
2524   strcpy (linkbuf + bufsiz, linkname);
2525   return linkbuf;
2526 }
2527 #endif
2528
2529 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2530    This is so we don't try to recurse on `././././. ...' */
2531
2532 static int
2533 basename_is_dot_or_dotdot (const char *name)
2534 {
2535   char const *base = base_name (name);
2536   return DOT_OR_DOTDOT (base);
2537 }
2538
2539 /* Remove any entries from `files' that are for directories,
2540    and queue them to be listed as directories instead.
2541    `dirname' is the prefix to prepend to each dirname
2542    to make it correct relative to ls's working dir.
2543    If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2544    This is desirable when processing directories recursively.  */
2545
2546 static void
2547 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2548 {
2549   register size_t i;
2550   register size_t j;
2551
2552   if (*dirname && LOOP_DETECT)
2553     {
2554       /* Insert a marker entry first.  When we dequeue this marker entry,
2555          we'll know that DIRNAME has been processed and may be removed
2556          from the set of active directories.  */
2557       queue_directory (NULL, dirname);
2558     }
2559
2560   /* Queue the directories last one first, because queueing reverses the
2561      order.  */
2562   for (i = files_index; i-- != 0; )
2563     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2564         && (!ignore_dot_and_dot_dot
2565             || !basename_is_dot_or_dotdot (files[i].name)))
2566       {
2567         if (files[i].name[0] == '/' || dirname[0] == 0)
2568           {
2569             queue_directory (files[i].name, files[i].linkname);
2570           }
2571         else
2572           {
2573             char *path = path_concat (dirname, files[i].name, NULL);
2574             queue_directory (path, files[i].linkname);
2575             free (path);
2576           }
2577         if (files[i].filetype == arg_directory)
2578           free (files[i].name);
2579       }
2580
2581   /* Now delete the directories from the table, compacting all the remaining
2582      entries.  */
2583
2584   for (i = 0, j = 0; i < files_index; i++)
2585     if (files[i].filetype != arg_directory)
2586       files[j++] = files[i];
2587   files_index = j;
2588 }
2589
2590 /* Use strcoll to compare strings in this locale.  If an error occurs,
2591    report an error and longjmp to failed_strcoll.  */
2592
2593 static jmp_buf failed_strcoll;
2594
2595 static int
2596 xstrcoll (char const *a, char const *b)
2597 {
2598   int diff;
2599   errno = 0;
2600   diff = strcoll (a, b);
2601   if (errno)
2602     {
2603       error (0, errno, _("cannot compare file names %s and %s"),
2604              quote_n (0, a), quote_n (1, b));
2605       exit_status = 1;
2606       longjmp (failed_strcoll, 1);
2607     }
2608   return diff;
2609 }
2610
2611 /* Comparison routines for sorting the files. */
2612
2613 typedef void const *V;
2614
2615 static inline int
2616 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2617            int (*cmp) (char const *, char const *))
2618 {
2619   int diff = CTIME_CMP (b->stat, a->stat);
2620   return diff ? diff : cmp (a->name, b->name);
2621 }
2622 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2623 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2624 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2625 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2626
2627 static inline int
2628 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2629            int (*cmp) (char const *, char const *))
2630 {
2631   int diff = MTIME_CMP (b->stat, a->stat);
2632   return diff ? diff : cmp (a->name, b->name);
2633 }
2634 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2635 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2636 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2637 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2638
2639 static inline int
2640 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2641            int (*cmp) (char const *, char const *))
2642 {
2643   int diff = ATIME_CMP (b->stat, a->stat);
2644   return diff ? diff : cmp (a->name, b->name);
2645 }
2646 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2647 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2648 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2649 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2650
2651 static inline int
2652 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2653           int (*cmp) (char const *, char const *))
2654 {
2655   int diff = longdiff (b->stat.st_size, a->stat.st_size);
2656   return diff ? diff : cmp (a->name, b->name);
2657 }
2658 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2659 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2660 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2661 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2662
2663 static inline int
2664 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2665 {
2666   return strverscmp (a->name, b->name);
2667 }
2668 static int compare_version (V a, V b) { return cmp_version (a, b); }
2669 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2670
2671 static inline int
2672 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2673           int (*cmp) (char const *, char const *))
2674 {
2675   return cmp (a->name, b->name);
2676 }
2677 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2678 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2679 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2680 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2681
2682 /* Compare file extensions.  Files with no extension are `smallest'.
2683    If extensions are the same, compare by filenames instead. */
2684
2685 static inline int
2686 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2687                int (*cmp) (char const *, char const *))
2688 {
2689   char const *base1 = strrchr (a->name, '.');
2690   char const *base2 = strrchr (b->name, '.');
2691   int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2692   return diff ? diff : cmp (a->name, b->name);
2693 }
2694 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2695 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2696 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2697 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2698
2699 /* Sort the files now in the table.  */
2700
2701 static void
2702 sort_files (void)
2703 {
2704   /* `func' must be `volatile', so it can't be
2705      clobbered by a `longjmp' into this function.  */
2706   int (* volatile func) (V, V);
2707
2708   switch (sort_type)
2709     {
2710     case sort_none:
2711       return;
2712     case sort_time:
2713       switch (time_type)
2714         {
2715         case time_ctime:
2716           func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2717           break;
2718         case time_mtime:
2719           func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2720           break;
2721         case time_atime:
2722           func = sort_reverse ? rev_cmp_atime : compare_atime;
2723           break;
2724         default:
2725           abort ();
2726         }
2727       break;
2728     case sort_name:
2729       func = sort_reverse ? rev_cmp_name : compare_name;
2730       break;
2731     case sort_extension:
2732       func = sort_reverse ? rev_cmp_extension : compare_extension;
2733       break;
2734     case sort_size:
2735       func = sort_reverse ? rev_cmp_size : compare_size;
2736       break;
2737     case sort_version:
2738       func = sort_reverse ? rev_cmp_version : compare_version;
2739       break;
2740     default:
2741       abort ();
2742     }
2743
2744   /* Try strcoll.  If it fails, fall back on strcmp.  We can't safely
2745      ignore strcoll failures, as a failing strcoll might be a
2746      comparison function that is not a total order, and if we ignored
2747      the failure this might cause qsort to dump core.  */
2748
2749   if (setjmp (failed_strcoll))
2750     {
2751       switch (sort_type)
2752         {
2753         case sort_time:
2754           switch (time_type)
2755             {
2756             case time_ctime:
2757               func = sort_reverse ? rev_str_ctime : compstr_ctime;
2758               break;
2759             case time_mtime:
2760               func = sort_reverse ? rev_str_mtime : compstr_mtime;
2761               break;
2762             case time_atime:
2763               func = sort_reverse ? rev_str_atime : compstr_atime;
2764               break;
2765             default:
2766               abort ();
2767             }
2768           break;
2769         case sort_name:
2770           func = sort_reverse ? rev_str_name : compstr_name;
2771           break;
2772         case sort_extension:
2773           func = sort_reverse ? rev_str_extension : compstr_extension;
2774           break;
2775         case sort_size:
2776           func = sort_reverse ? rev_str_size : compstr_size;
2777           break;
2778         default:
2779           abort ();
2780         }
2781     }
2782
2783   qsort (files, files_index, sizeof (struct fileinfo), func);
2784 }
2785
2786 /* List all the files now in the table.  */
2787
2788 static void
2789 print_current_files (void)
2790 {
2791   register size_t i;
2792
2793   switch (format)
2794     {
2795     case one_per_line:
2796       for (i = 0; i < files_index; i++)
2797         {
2798           print_file_name_and_frills (files + i);
2799           putchar ('\n');
2800         }
2801       break;
2802
2803     case many_per_line:
2804       print_many_per_line ();
2805       break;
2806
2807     case horizontal:
2808       print_horizontal ();
2809       break;
2810
2811     case with_commas:
2812       print_with_commas ();
2813       break;
2814
2815     case long_format:
2816       for (i = 0; i < files_index; i++)
2817         {
2818           print_long_format (files + i);
2819           DIRED_PUTCHAR ('\n');
2820         }
2821       break;
2822     }
2823 }
2824
2825 /* Return the expected number of columns in a long-format time stamp,
2826    or zero if it cannot be calculated.  */
2827
2828 static int
2829 long_time_expected_width (void)
2830 {
2831   static int width = -1;
2832
2833   if (width < 0)
2834     {
2835       time_t epoch = 0;
2836       struct tm const *tm = localtime (&epoch);
2837       char const *fmt = long_time_format[0];
2838       char initbuf[100];
2839       char *buf = initbuf;
2840       size_t bufsize = sizeof initbuf;
2841       size_t len;
2842
2843       for (;;)
2844         {
2845           *buf = '\1';
2846           len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2847           if (len || ! *buf)
2848             break;
2849           buf = alloca (bufsize *= 2);
2850         }
2851
2852       width = mbsnwidth (buf, len, 0);
2853       if (width < 0)
2854         width = 0;
2855     }
2856
2857   return width;
2858 }
2859
2860 /* Get the current time.  */
2861
2862 static void
2863 get_current_time (void)
2864 {
2865 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2866   {
2867     struct timespec timespec;
2868     if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
2869       {
2870         current_time = timespec.tv_sec;
2871         current_time_ns = timespec.tv_nsec;
2872         return;
2873       }
2874   }
2875 #endif
2876
2877   /* The clock does not have nanosecond resolution, so get the maximum
2878      possible value for the current time that is consistent with the
2879      reported clock.  That way, files are not considered to be in the
2880      future merely because their time stamps have higher resolution
2881      than the clock resolution.  */
2882
2883 #if HAVE_GETTIMEOFDAY
2884   {
2885     struct timeval timeval;
2886     if (gettimeofday (&timeval, NULL) == 0)
2887       {
2888         current_time = timeval.tv_sec;
2889         current_time_ns = timeval.tv_usec * 1000 + 999;
2890         return;
2891       }
2892   }
2893 #endif
2894
2895   current_time = time (NULL);
2896   current_time_ns = 999999999;
2897 }
2898
2899 /* Format into BUFFER the name or id of the user with id U.  Return
2900    the length of the formatted buffer, not counting the terminating
2901    null.  */
2902
2903 static size_t
2904 format_user (char *buffer, uid_t u)
2905 {
2906   char const *name = (numeric_ids ? NULL : getuser (u));
2907   if (name)
2908     sprintf (buffer, "%-8s ", name);
2909   else
2910     sprintf (buffer, "%-8lu ", (unsigned long int) u);
2911   return strlen (buffer);
2912 }
2913
2914 /* Print information about F in long format.  */
2915
2916 static void
2917 print_long_format (const struct fileinfo *f)
2918 {
2919   char modebuf[12];
2920   char init_bigbuf
2921     [LONGEST_HUMAN_READABLE + 1         /* inode */
2922      + LONGEST_HUMAN_READABLE + 1       /* size in blocks */
2923      + sizeof (modebuf) - 1 + 1         /* mode string */
2924      + LONGEST_HUMAN_READABLE + 1       /* st_nlink */
2925      + ID_LENGTH_MAX + 1                /* owner name */
2926      + ID_LENGTH_MAX + 1                /* group name */
2927      + ID_LENGTH_MAX + 1                /* author name */
2928      + LONGEST_HUMAN_READABLE + 1       /* major device number */
2929      + LONGEST_HUMAN_READABLE + 1       /* minor device number */
2930      + 35 + 1   /* usual length of time/date -- may be longer; see below */
2931      ];
2932   char *buf = init_bigbuf;
2933   size_t bufsize = sizeof (init_bigbuf);
2934   size_t s;
2935   char *p;
2936   time_t when;
2937   int when_ns IF_LINT (= 0);
2938   struct tm *when_local;
2939
2940   /* Compute mode string.  On most systems, it's based on st_mode.
2941      On systems with migration (via the stat.st_dm_mode field), use
2942      the file's migrated status.  */
2943   mode_string (ST_DM_MODE (f->stat), modebuf);
2944
2945   modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2946   modebuf[11] = '\0';
2947
2948   switch (time_type)
2949     {
2950     case time_ctime:
2951       when = f->stat.st_ctime;
2952       when_ns = TIMESPEC_NS (f->stat.st_ctim);
2953       break;
2954     case time_mtime:
2955       when = f->stat.st_mtime;
2956       when_ns = TIMESPEC_NS (f->stat.st_mtim);
2957       break;
2958     case time_atime:
2959       when = f->stat.st_atime;
2960       when_ns = TIMESPEC_NS (f->stat.st_atim);
2961       break;
2962     }
2963
2964   p = buf;
2965
2966   if (print_inode)
2967     {
2968       char hbuf[LONGEST_HUMAN_READABLE + 1];
2969       sprintf (p, "%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, hbuf));
2970       p += strlen (p);
2971     }
2972
2973   if (print_block_size)
2974     {
2975       char hbuf[LONGEST_HUMAN_READABLE + 1];
2976       sprintf (p, "%*s ", block_size_size,
2977                human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
2978                                ST_NBLOCKSIZE, output_block_size));
2979       p += strlen (p);
2980     }
2981
2982   /* The last byte of the mode string is the POSIX
2983      "optional alternate access method flag".  */
2984   sprintf (p, "%s %3lu ", modebuf, (unsigned long int) f->stat.st_nlink);
2985   p += strlen (p);
2986
2987   if (print_owner)
2988     p += format_user (p, f->stat.st_uid);
2989
2990   if (print_group)
2991     {
2992       char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2993       if (group_name)
2994         sprintf (p, "%-8s ", group_name);
2995       else
2996         sprintf (p, "%-8lu ", (unsigned long int) f->stat.st_gid);
2997       p += strlen (p);
2998     }
2999
3000   if (print_author)
3001     p += format_user (p, f->stat.st_author);
3002
3003   if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3004     sprintf (p, "%3lu, %3lu ",
3005              (unsigned long int) major (f->stat.st_rdev),
3006              (unsigned long int) minor (f->stat.st_rdev));
3007   else
3008     {
3009       char hbuf[LONGEST_HUMAN_READABLE + 1];
3010       uintmax_t size = f->stat.st_size;
3011
3012       /* POSIX requires that the size be printed without a sign, even
3013          when negative.  Assume the typical case where negative sizes
3014          are actually positive values that have wrapped around.  */
3015       size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3016
3017       sprintf (p, "%8s ",
3018                human_readable (size, hbuf, human_output_opts,
3019                                1, file_output_block_size));
3020     }
3021
3022   p += strlen (p);
3023
3024   if ((when_local = localtime (&when)))
3025     {
3026       time_t six_months_ago;
3027       int recent;
3028       char const *fmt;
3029
3030       /* If the file appears to be in the future, update the current
3031          time, in case the file happens to have been modified since
3032          the last time we checked the clock.  */
3033       if (current_time < when
3034           || (current_time == when && current_time_ns < when_ns))
3035         {
3036           /* Note that get_current_time calls gettimeofday which, on some non-
3037              compliant systems, clobbers the buffer used for localtime's result.
3038              But it's ok here, because we use a gettimeofday wrapper that
3039              saves and restores the buffer around the gettimeofday call.  */
3040           get_current_time ();
3041         }
3042
3043       /* Consider a time to be recent if it is within the past six
3044          months.  A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3045          31556952 seconds on the average.  Write this value as an
3046          integer constant to avoid floating point hassles.  */
3047       six_months_ago = current_time - 31556952 / 2;
3048       recent = (six_months_ago <= when
3049                 && (when < current_time
3050                     || (when == current_time && when_ns <= current_time_ns)));
3051       fmt = long_time_format[recent];
3052
3053       for (;;)
3054         {
3055           char *newbuf;
3056           *p = '\1';
3057           s = nstrftime (p, buf + bufsize - p - 1, fmt,
3058                          when_local, 0, when_ns);
3059           if (s || ! *p)
3060             break;
3061           newbuf = alloca (bufsize *= 2);
3062           memcpy (newbuf, buf, p - buf);
3063           p = newbuf + (p - buf);
3064           buf = newbuf;
3065         }
3066
3067       p += s;
3068       *p++ = ' ';
3069
3070       /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it.  */
3071       *p = '\0';
3072     }
3073   else
3074     {
3075       /* The time cannot be represented as a local time;
3076          print it as a huge integer number of seconds.  */
3077       char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3078       sprintf (p, "%*s ", long_time_expected_width (),
3079                (TYPE_SIGNED (time_t)
3080                 ? imaxtostr (when, hbuf)
3081                 : umaxtostr (when, hbuf)));
3082       p += strlen (p);
3083     }
3084
3085   DIRED_INDENT ();
3086   DIRED_FPUTS (buf, stdout, p - buf);
3087   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3088                            &dired_obstack);
3089
3090   if (f->filetype == symbolic_link)
3091     {
3092       if (f->linkname)
3093         {
3094           DIRED_FPUTS_LITERAL (" -> ", stdout);
3095           print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3096                                    NULL);
3097           if (indicator_style != none)
3098             print_type_indicator (f->linkmode);
3099         }
3100     }
3101   else if (indicator_style != none)
3102     print_type_indicator (f->stat.st_mode);
3103 }
3104
3105 /* Output to OUT a quoted representation of the file name NAME,
3106    using OPTIONS to control quoting.  Produce no output if OUT is NULL.
3107    Store the number of screen columns occupied by NAME's quoted
3108    representation into WIDTH, if non-NULL.  Return the number of bytes
3109    produced.  */
3110
3111 static size_t
3112 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3113             size_t *width)
3114 {
3115   char smallbuf[BUFSIZ];
3116   size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3117   char *buf;
3118   size_t displayed_width IF_LINT (= 0);
3119
3120   if (len < sizeof smallbuf)
3121     buf = smallbuf;
3122   else
3123     {
3124       buf = alloca (len + 1);
3125       quotearg_buffer (buf, len + 1, name, -1, options);
3126     }
3127
3128   if (qmark_funny_chars)
3129     {
3130 #if HAVE_MBRTOWC
3131       if (MB_CUR_MAX > 1)
3132         {
3133           char const *p = buf;
3134           char const *plimit = buf + len;
3135           char *q = buf;
3136           displayed_width = 0;
3137
3138           while (p < plimit)
3139             switch (*p)
3140               {
3141                 case ' ': case '!': case '"': case '#': case '%':
3142                 case '&': case '\'': case '(': case ')': case '*':
3143                 case '+': case ',': case '-': case '.': case '/':
3144                 case '0': case '1': case '2': case '3': case '4':
3145                 case '5': case '6': case '7': case '8': case '9':
3146                 case ':': case ';': case '<': case '=': case '>':
3147                 case '?':
3148                 case 'A': case 'B': case 'C': case 'D': case 'E':
3149                 case 'F': case 'G': case 'H': case 'I': case 'J':
3150                 case 'K': case 'L': case 'M': case 'N': case 'O':
3151                 case 'P': case 'Q': case 'R': case 'S': case 'T':
3152                 case 'U': case 'V': case 'W': case 'X': case 'Y':
3153                 case 'Z':
3154                 case '[': case '\\': case ']': case '^': case '_':
3155                 case 'a': case 'b': case 'c': case 'd': case 'e':
3156                 case 'f': case 'g': case 'h': case 'i': case 'j':
3157                 case 'k': case 'l': case 'm': case 'n': case 'o':
3158                 case 'p': case 'q': case 'r': case 's': case 't':
3159                 case 'u': case 'v': case 'w': case 'x': case 'y':
3160                 case 'z': case '{': case '|': case '}': case '~':
3161                   /* These characters are printable ASCII characters.  */
3162                   *q++ = *p++;
3163                   displayed_width += 1;
3164                   break;
3165                 default:
3166                   /* If we have a multibyte sequence, copy it until we
3167                      reach its end, replacing each non-printable multibyte
3168                      character with a single question mark.  */
3169                   {
3170                     mbstate_t mbstate;
3171                     memset (&mbstate, 0, sizeof mbstate);
3172                     do
3173                       {
3174                         wchar_t wc;
3175                         size_t bytes;
3176                         int w;
3177
3178                         bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3179
3180                         if (bytes == (size_t) -1)
3181                           {
3182                             /* An invalid multibyte sequence was
3183                                encountered.  Skip one input byte, and
3184                                put a question mark.  */
3185                             p++;
3186                             *q++ = '?';
3187                             displayed_width += 1;
3188                             break;
3189                           }
3190
3191                         if (bytes == (size_t) -2)
3192                           {
3193                             /* An incomplete multibyte character
3194                                at the end.  Replace it entirely with
3195                                a question mark.  */
3196                             p = plimit;
3197                             *q++ = '?';
3198                             displayed_width += 1;
3199                             break;
3200                           }
3201
3202                         if (bytes == 0)
3203                           /* A null wide character was encountered.  */
3204                           bytes = 1;
3205
3206                         w = wcwidth (wc);
3207                         if (w >= 0)
3208                           {
3209                             /* A printable multibyte character.
3210                                Keep it.  */
3211                             for (; bytes > 0; --bytes)
3212                               *q++ = *p++;
3213                             displayed_width += w;
3214                           }
3215                         else
3216                           {
3217                             /* An unprintable multibyte character.
3218                                Replace it entirely with a question
3219                                mark.  */
3220                             p += bytes;
3221                             *q++ = '?';
3222                             displayed_width += 1;
3223                           }
3224                       }
3225                     while (! mbsinit (&mbstate));
3226                   }
3227                   break;
3228               }
3229
3230           /* The buffer may have shrunk.  */
3231           len = q - buf;
3232         }
3233       else
3234 #endif
3235         {
3236           char *p = buf;
3237           char const *plimit = buf + len;
3238
3239           while (p < plimit)
3240             {
3241               if (! ISPRINT ((unsigned char) *p))
3242                 *p = '?';
3243               p++;
3244             }
3245           displayed_width = len;
3246         }
3247     }
3248   else if (width != NULL)
3249     {
3250 #if HAVE_MBRTOWC
3251       if (MB_CUR_MAX > 1)
3252         displayed_width = mbsnwidth (buf, len, 0);
3253       else
3254 #endif
3255         {
3256           char const *p = buf;
3257           char const *plimit = buf + len;
3258
3259           displayed_width = 0;
3260           while (p < plimit)
3261             {
3262               if (ISPRINT ((unsigned char) *p))
3263                 displayed_width++;
3264               p++;
3265             }
3266         }
3267     }
3268
3269   if (out != NULL)
3270     fwrite (buf, 1, len, out);
3271   if (width != NULL)
3272     *width = displayed_width;
3273   return len;
3274 }
3275
3276 static void
3277 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3278                          struct obstack *stack)
3279 {
3280   if (print_with_color)
3281     print_color_indicator (p, mode, linkok);
3282
3283   if (stack)
3284     PUSH_CURRENT_DIRED_POS (stack);
3285
3286   dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3287
3288   if (stack)
3289     PUSH_CURRENT_DIRED_POS (stack);
3290
3291   if (print_with_color)
3292     prep_non_filename_text ();
3293 }
3294
3295 static void
3296 prep_non_filename_text (void)
3297 {
3298   if (color_indicator[C_END].string != NULL)
3299     put_indicator (&color_indicator[C_END]);
3300   else
3301     {
3302       put_indicator (&color_indicator[C_LEFT]);
3303       put_indicator (&color_indicator[C_NORM]);
3304       put_indicator (&color_indicator[C_RIGHT]);
3305     }
3306 }
3307
3308 /* Print the file name of `f' with appropriate quoting.
3309    Also print file size, inode number, and filetype indicator character,
3310    as requested by switches.  */
3311
3312 static void
3313 print_file_name_and_frills (const struct fileinfo *f)
3314 {
3315   char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3316
3317   if (print_inode)
3318     printf ("%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, buf));
3319
3320   if (print_block_size)
3321     printf ("%*s ", block_size_size,
3322             human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3323                             ST_NBLOCKSIZE, output_block_size));
3324
3325   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3326
3327   if (indicator_style != none)
3328     print_type_indicator (f->stat.st_mode);
3329 }
3330
3331 static void
3332 print_type_indicator (mode_t mode)
3333 {
3334   int c;
3335
3336   if (S_ISREG (mode))
3337     {
3338       if (indicator_style == classify && (mode & S_IXUGO))
3339         c ='*';
3340       else
3341         c = 0;
3342     }
3343   else
3344     {
3345       if (S_ISDIR (mode))
3346         c = '/';
3347       else if (S_ISLNK (mode))
3348         c = '@';
3349       else if (S_ISFIFO (mode))
3350         c = '|';
3351       else if (S_ISSOCK (mode))
3352         c = '=';
3353       else if (S_ISDOOR (mode))
3354         c = '>';
3355       else
3356         c = 0;
3357     }
3358
3359   if (c)
3360     DIRED_PUTCHAR (c);
3361 }
3362
3363 static void
3364 print_color_indicator (const char *name, mode_t mode, int linkok)
3365 {
3366   int type = C_FILE;
3367   struct color_ext_type *ext;   /* Color extension */
3368   size_t len;                   /* Length of name */
3369
3370   /* Is this a nonexistent file?  If so, linkok == -1.  */
3371
3372   if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3373     {
3374       ext = NULL;
3375       type = C_MISSING;
3376     }
3377   else
3378     {
3379       if (S_ISDIR (mode))
3380         type = C_DIR;
3381       else if (S_ISLNK (mode))
3382         type = ((!linkok && color_indicator[C_ORPHAN].string)
3383                 ? C_ORPHAN : C_LINK);
3384       else if (S_ISFIFO (mode))
3385         type = C_FIFO;
3386       else if (S_ISSOCK (mode))
3387         type = C_SOCK;
3388       else if (S_ISBLK (mode))
3389         type = C_BLK;
3390       else if (S_ISCHR (mode))
3391         type = C_CHR;
3392       else if (S_ISDOOR (mode))
3393         type = C_DOOR;
3394
3395       if (type == C_FILE && (mode & S_IXUGO) != 0)
3396         type = C_EXEC;
3397
3398       /* Check the file's suffix only if still classified as C_FILE.  */
3399       ext = NULL;
3400       if (type == C_FILE)
3401         {
3402           /* Test if NAME has a recognized suffix.  */
3403
3404           len = strlen (name);
3405           name += len;          /* Pointer to final \0.  */
3406           for (ext = color_ext_list; ext != NULL; ext = ext->next)
3407             {
3408               if (ext->ext.len <= len
3409                   && strncmp (name - ext->ext.len, ext->ext.string,
3410                               ext->ext.len) == 0)
3411                 break;
3412             }
3413         }
3414     }
3415
3416   put_indicator (&color_indicator[C_LEFT]);
3417   put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3418   put_indicator (&color_indicator[C_RIGHT]);
3419 }
3420
3421 /* Output a color indicator (which may contain nulls).  */
3422 static void
3423 put_indicator (const struct bin_str *ind)
3424 {
3425   register size_t i;
3426   register const char *p;
3427
3428   p = ind->string;
3429
3430   for (i = ind->len; i != 0; --i)
3431     putchar (*(p++));
3432 }
3433
3434 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3435    Return zero if the write is successful or if the string length is zero.
3436    Return nonzero if the write fails.  */
3437 static int
3438 put_indicator_direct (const struct bin_str *ind)
3439 {
3440   size_t len;
3441   if (ind->len == 0)
3442     return 0;
3443
3444   len = ind->len;
3445   return (full_write (STDOUT_FILENO, ind->string, len) != len);
3446 }
3447
3448 static size_t
3449 length_of_file_name_and_frills (const struct fileinfo *f)
3450 {
3451   register size_t len = 0;
3452   size_t name_width;
3453
3454   if (print_inode)
3455     len += INODE_DIGITS + 1;
3456
3457   if (print_block_size)
3458     len += 1 + block_size_size;
3459
3460   quote_name (NULL, f->name, filename_quoting_options, &name_width);
3461   len += name_width;
3462
3463   if (indicator_style != none)
3464     {
3465       mode_t filetype = f->stat.st_mode;
3466
3467       if (S_ISREG (filetype))
3468         {
3469           if (indicator_style == classify
3470               && (f->stat.st_mode & S_IXUGO))
3471             len += 1;
3472         }
3473       else if (S_ISDIR (filetype)
3474                || S_ISLNK (filetype)
3475                || S_ISFIFO (filetype)
3476                || S_ISSOCK (filetype)
3477                || S_ISDOOR (filetype)
3478                )
3479         len += 1;
3480     }
3481
3482   return len;
3483 }
3484
3485 static void
3486 print_many_per_line (void)
3487 {
3488   size_t row;                   /* Current row. */
3489   size_t cols = calculate_columns (true);
3490   struct column_info const *line_fmt = &column_info[cols - 1];
3491
3492   /* Calculate the number of rows that will be in each column except possibly
3493      for a short column on the right. */
3494   size_t rows = files_index / cols + (files_index % cols != 0);
3495
3496   for (row = 0; row < rows; row++)
3497     {
3498       size_t col = 0;
3499       size_t filesno = row;
3500       size_t pos = 0;
3501
3502       /* Print the next row.  */
3503       while (1)
3504         {
3505           size_t name_length = length_of_file_name_and_frills (files + filesno);
3506           size_t max_name_length = line_fmt->col_arr[col++];
3507           print_file_name_and_frills (files + filesno);
3508
3509           filesno += rows;
3510           if (filesno >= files_index)
3511             break;
3512
3513           indent (pos + name_length, pos + max_name_length);
3514           pos += max_name_length;
3515         }
3516       putchar ('\n');
3517     }
3518 }
3519
3520 static void
3521 print_horizontal (void)
3522 {
3523   size_t filesno;
3524   size_t pos = 0;
3525   size_t cols = calculate_columns (false);
3526   struct column_info const *line_fmt = &column_info[cols - 1];
3527   size_t name_length = length_of_file_name_and_frills (files);
3528   size_t max_name_length = line_fmt->col_arr[0];
3529
3530   /* Print first entry.  */
3531   print_file_name_and_frills (files);
3532
3533   /* Now the rest.  */
3534   for (filesno = 1; filesno < files_index; ++filesno)
3535     {
3536       size_t col = filesno % cols;
3537
3538       if (col == 0)
3539         {
3540           putchar ('\n');
3541           pos = 0;
3542         }
3543       else
3544         {
3545           indent (pos + name_length, pos + max_name_length);
3546           pos += max_name_length;
3547         }
3548
3549       print_file_name_and_frills (files + filesno);
3550
3551       name_length = length_of_file_name_and_frills (files + filesno);
3552       max_name_length = line_fmt->col_arr[col];
3553     }
3554   putchar ('\n');
3555 }
3556
3557 static void
3558 print_with_commas (void)
3559 {
3560   size_t filesno;
3561   size_t pos;
3562   size_t old_pos;
3563
3564   pos = 0;
3565
3566   for (filesno = 0; filesno < files_index; filesno++)
3567     {
3568       old_pos = pos;
3569
3570       pos += length_of_file_name_and_frills (files + filesno);
3571       if (filesno + 1 < files_index)
3572         pos += 2;               /* For the comma and space */
3573
3574       if (old_pos != 0 && pos >= line_length)
3575         {
3576           putchar ('\n');
3577           pos -= old_pos;
3578         }
3579
3580       print_file_name_and_frills (files + filesno);
3581       if (filesno + 1 < files_index)
3582         {
3583           putchar (',');
3584           putchar (' ');
3585         }
3586     }
3587   putchar ('\n');
3588 }
3589
3590 /* Assuming cursor is at position FROM, indent up to position TO.
3591    Use a TAB character instead of two or more spaces whenever possible.  */
3592
3593 static void
3594 indent (size_t from, size_t to)
3595 {
3596   while (from < to)
3597     {
3598       if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
3599         {
3600           putchar ('\t');
3601           from += tabsize - from % tabsize;
3602         }
3603       else
3604         {
3605           putchar (' ');
3606           from++;
3607         }
3608     }
3609 }
3610
3611 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3612 /* FIXME: maybe remove this function someday.  See about using a
3613    non-malloc'ing version of path_concat.  */
3614
3615 static void
3616 attach (char *dest, const char *dirname, const char *name)
3617 {
3618   const char *dirnamep = dirname;
3619
3620   /* Copy dirname if it is not ".". */
3621   if (dirname[0] != '.' || dirname[1] != 0)
3622     {
3623       while (*dirnamep)
3624         *dest++ = *dirnamep++;
3625       /* Add '/' if `dirname' doesn't already end with it. */
3626       if (dirnamep > dirname && dirnamep[-1] != '/')
3627         *dest++ = '/';
3628     }
3629   while (*name)
3630     *dest++ = *name++;
3631   *dest = 0;
3632 }
3633
3634 /* Allocate enough column info suitable for the current number of
3635    files and display columns, and initialize the info to represent the
3636    narrowest possible columns.  */
3637
3638 static void
3639 init_column_info (void)
3640 {
3641   size_t i;
3642   size_t max_cols = MIN (max_idx, files_index);
3643
3644   /* Currently allocated columns in column_info.  */
3645   static size_t column_info_alloc;
3646
3647   if (column_info_alloc < max_cols)
3648     {
3649       size_t new_column_info_alloc;
3650       size_t *p;
3651
3652       if (max_cols < max_idx / 2)
3653         {
3654           /* The number of columns is far less than the display width
3655              allows.  Grow the allocation, but only so that it's
3656              double the current requirements.  If the display is
3657              extremely wide, this avoids allocating a lot of memory
3658              that is never needed.  */
3659           column_info = xnrealloc (column_info, max_cols,
3660                                    2 * sizeof *column_info);
3661           new_column_info_alloc = 2 * max_cols;
3662         }
3663       else
3664         {
3665           column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
3666           new_column_info_alloc = max_idx;
3667         }
3668
3669       /* Allocate the new size_t objects by computing the triangle
3670          formula n * (n + 1) / 2, except that we don't need to
3671          allocate the part of the triangle that we've already
3672          allocated.  Check for address arithmetic overflow.  */
3673       {
3674         size_t column_info_growth = new_column_info_alloc - column_info_alloc;
3675         size_t s = column_info_alloc + 1 + new_column_info_alloc;
3676         size_t t = s * column_info_growth;
3677         if (s < new_column_info_alloc || t / column_info_growth != s)
3678           xalloc_die ();
3679         p = xnmalloc (t / 2, sizeof *p);
3680       }
3681
3682       /* Grow the triangle by parceling out the cells just allocated.  */
3683       for (i = column_info_alloc; i < new_column_info_alloc; i++)
3684         {
3685           column_info[i].col_arr = p;
3686           p += i + 1;
3687         }
3688
3689       column_info_alloc = new_column_info_alloc;
3690     }
3691
3692   for (i = 0; i < max_cols; ++i)
3693     {
3694       size_t j;
3695
3696       column_info[i].valid_len = true;
3697       column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3698       for (j = 0; j <= i; ++j)
3699         column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3700     }
3701 }
3702
3703 /* Calculate the number of columns needed to represent the current set
3704    of files in the current display width.  */
3705
3706 static size_t
3707 calculate_columns (bool by_columns)
3708 {
3709   size_t filesno;               /* Index into files. */
3710   size_t cols;                  /* Number of files across. */
3711
3712   /* Normally the maximum number of columns is determined by the
3713      screen width.  But if few files are available this might limit it
3714      as well.  */
3715   size_t max_cols = MIN (max_idx, files_index);
3716
3717   init_column_info ();
3718
3719   /* Compute the maximum number of possible columns.  */
3720   for (filesno = 0; filesno < files_index; ++filesno)
3721     {
3722       size_t name_length = length_of_file_name_and_frills (files + filesno);
3723       size_t i;
3724
3725       for (i = 0; i < max_cols; ++i)
3726         {
3727           if (column_info[i].valid_len)
3728             {
3729               size_t idx = (by_columns
3730                             ? filesno / ((files_index + i) / (i + 1))
3731                             : filesno % (i + 1));
3732               size_t real_length = name_length + (idx == i ? 0 : 2);
3733
3734               if (column_info[i].col_arr[idx] < real_length)
3735                 {
3736                   column_info[i].line_len += (real_length
3737                                               - column_info[i].col_arr[idx]);
3738                   column_info[i].col_arr[idx] = real_length;
3739                   column_info[i].valid_len = (column_info[i].line_len
3740                                               < line_length);
3741                 }
3742             }
3743         }
3744     }
3745
3746   /* Find maximum allowed columns.  */
3747   for (cols = max_cols; 1 < cols; --cols)
3748     {
3749       if (column_info[cols - 1].valid_len)
3750         break;
3751     }
3752
3753   return cols;
3754 }
3755
3756 void
3757 usage (int status)
3758 {
3759   if (status != 0)
3760     fprintf (stderr, _("Try `%s --help' for more information.\n"),
3761              program_name);
3762   else
3763     {
3764       printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3765       fputs (_("\
3766 List information about the FILEs (the current directory by default).\n\
3767 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3768 \n\
3769 "), stdout);
3770       fputs (_("\
3771 Mandatory arguments to long options are mandatory for short options too.\n\
3772 "), stdout);
3773       fputs (_("\
3774   -a, --all                  do not hide entries starting with .\n\
3775   -A, --almost-all           do not list implied . and ..\n\
3776       --author               print the author of each file\n\
3777   -b, --escape               print octal escapes for nongraphic characters\n\
3778 "), stdout);
3779       fputs (_("\
3780       --block-size=SIZE      use SIZE-byte blocks\n\
3781   -B, --ignore-backups       do not list implied entries ending with ~\n\
3782   -c                         with -lt: sort by, and show, ctime (time of last\n\
3783                                modification of file status information)\n\
3784                                with -l: show ctime and sort by name\n\
3785                                otherwise: sort by ctime\n\
3786 "), stdout);
3787       fputs (_("\
3788   -C                         list entries by columns\n\
3789       --color[=WHEN]         control whether color is used to distinguish file\n\
3790                                types.  WHEN may be `never', `always', or `auto'\n\
3791   -d, --directory            list directory entries instead of contents,\n\
3792                                and do not dereference symbolic links\n\
3793   -D, --dired                generate output designed for Emacs' dired mode\n\
3794 "), stdout);
3795       fputs (_("\
3796   -f                         do not sort, enable -aU, disable -lst\n\
3797   -F, --classify             append indicator (one of */=@|) to entries\n\
3798       --format=WORD          across -x, commas -m, horizontal -x, long -l,\n\
3799                                single-column -1, verbose -l, vertical -C\n\
3800       --full-time            like -l --time-style=full-iso\n\
3801 "), stdout);
3802       fputs (_("\
3803   -g                         like -l, but do not list owner\n\
3804   -G, --no-group             inhibit display of group information\n\
3805   -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)\n\
3806       --si                   likewise, but use powers of 1000 not 1024\n\
3807   -H, --dereference-command-line\n\
3808                              follow symbolic links listed on the command line\n\
3809       --dereference-command-line-symlink-to-dir\n\
3810                              follow each command line symbolic link\n\
3811                                that points to a directory\n\
3812 "), stdout);
3813       fputs (_("\
3814       --indicator-style=WORD append indicator with style WORD to entry names:\n\
3815                                none (default), classify (-F), file-type (-p)\n\
3816   -i, --inode                print index number of each file\n\
3817   -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN\n\
3818   -k                         like --block-size=1K\n\
3819 "), stdout);
3820       fputs (_("\
3821   -l                         use a long listing format\n\
3822   -L, --dereference          when showing file information for a symbolic\n\
3823                                link, show information for the file the link\n\
3824                                references rather than for the link itself\n\
3825   -m                         fill width with a comma separated list of entries\n\
3826 "), stdout);
3827       fputs (_("\
3828   -n, --numeric-uid-gid      like -l, but list numeric UIDs and GIDs\n\
3829   -N, --literal              print raw entry names (don't treat e.g. control\n\
3830                                characters specially)\n\
3831   -o                         like -l, but do not list group information\n\
3832   -p, --file-type            append indicator (one of /=@|) to entries\n\
3833 "), stdout);
3834       fputs (_("\
3835   -q, --hide-control-chars   print ? instead of non graphic characters\n\
3836       --show-control-chars   show non graphic characters as-is (default\n\
3837                              unless program is `ls' and output is a terminal)\n\
3838   -Q, --quote-name           enclose entry names in double quotes\n\
3839       --quoting-style=WORD   use quoting style WORD for entry names:\n\
3840                                literal, locale, shell, shell-always, c, escape\n\
3841 "), stdout);
3842       fputs (_("\
3843   -r, --reverse              reverse order while sorting\n\
3844   -R, --recursive            list subdirectories recursively\n\
3845   -s, --size                 print size of each file, in blocks\n\
3846 "), stdout);
3847       fputs (_("\
3848   -S                         sort by file size\n\
3849       --sort=WORD            extension -X, none -U, size -S, time -t,\n\
3850                                version -v\n\
3851                              status -c, time -t, atime -u, access -u, use -u\n\
3852       --time=WORD            show time as WORD instead of modification time:\n\
3853                                atime, access, use, ctime or status; use\n\
3854                                specified time as sort key if --sort=time\n\
3855 "), stdout);
3856       fputs (_("\
3857       --time-style=STYLE     show times using style STYLE:\n\
3858                                full-iso, long-iso, iso, locale, +FORMAT\n\
3859                              FORMAT is interpreted like `date'; if FORMAT is\n\
3860                              FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
3861                              non-recent files and FORMAT2 to recent files;\n\
3862                              if STYLE is prefixed with `posix-', STYLE\n\
3863                              takes effect only outside the POSIX locale\n\
3864   -t                         sort by modification time\n\
3865   -T, --tabsize=COLS         assume tab stops at each COLS instead of 8\n\
3866 "), stdout);
3867       fputs (_("\
3868   -u                         with -lt: sort by, and show, access time\n\
3869                                with -l: show access time and sort by name\n\
3870                                otherwise: sort by access time\n\
3871   -U                         do not sort; list entries in directory order\n\
3872   -v                         sort by version\n\
3873 "), stdout);
3874       fputs (_("\
3875   -w, --width=COLS           assume screen width instead of current value\n\
3876   -x                         list entries by lines instead of by columns\n\
3877   -X                         sort alphabetically by entry extension\n\
3878   -1                         list one file per line\n\
3879 "), stdout);
3880       fputs (HELP_OPTION_DESCRIPTION, stdout);
3881       fputs (VERSION_OPTION_DESCRIPTION, stdout);
3882       fputs (_("\n\
3883 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3884 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
3885 "), stdout);
3886       fputs (_("\
3887 \n\
3888 By default, color is not used to distinguish types of files.  That is\n\
3889 equivalent to using --color=none.  Using the --color option without the\n\
3890 optional WHEN argument is equivalent to using --color=always.  With\n\
3891 --color=auto, color codes are output only if standard output is connected\n\
3892 to a terminal (tty).\n\
3893 "), stdout);
3894       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
3895     }
3896   exit (status);
3897 }