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