1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2006 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* If ls_mode is LS_MULTI_COL,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
29 the output format depends on whether the output
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
40 #include <sys/types.h>
49 # include <sys/ioctl.h>
52 #ifdef WINSIZE_IN_PTEM
53 # include <sys/stream.h>
54 # include <sys/ptem.h>
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
76 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
85 #if !defined iswprint && !HAVE_ISWPRINT
86 # define iswprint(wc) 1
89 #ifndef HAVE_DECL_WCWIDTH
90 "this configure-time declaration test was not run"
92 #if !HAVE_DECL_WCWIDTH
96 /* If wcwidth() doesn't exist, assume all printable characters have
100 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
108 #include "argmatch.h"
113 #include "filenamecat.h"
114 #include "hard-locale.h"
117 #include "filemode.h"
118 #include "inttostr.h"
121 #include "mbswidth.h"
124 #include "quotearg.h"
126 #include "stat-time.h"
127 #include "strftime.h"
128 #include "strverscmp.h"
130 #include "xreadlink.h"
132 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
133 : (ls_mode == LS_MULTI_COL \
136 #define AUTHORS "Richard Stallman", "David MacKenzie"
138 #define obstack_chunk_alloc malloc
139 #define obstack_chunk_free free
141 /* Return an int indicating the result of comparing two integers.
142 Subtracting doesn't always work, due to overflow. */
143 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
145 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
146 # define DT_INIT(Val) = Val
148 # define DT_INIT(Val) /* empty */
151 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
152 # define st_author st_uid
157 unknown DT_INIT (DT_UNKNOWN),
158 fifo DT_INIT (DT_FIFO),
159 chardev DT_INIT (DT_CHR),
160 directory DT_INIT (DT_DIR),
161 blockdev DT_INIT (DT_BLK),
162 normal DT_INIT (DT_REG),
163 symbolic_link DT_INIT (DT_LNK),
164 sock DT_INIT (DT_SOCK),
165 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
166 | DT_REG | DT_LNK | DT_SOCK))
176 /* For symbolic link, name of the file linked to, otherwise zero. */
179 /* For symbolic link and long listing, st_mode of file linked to, otherwise
183 /* For symbolic link and color printing, true if linked-to file
184 exists, otherwise false. */
187 enum filetype filetype;
190 /* For long listings, true if the file has an access control list. */
196 # define FILE_HAS_ACL(F) ((F)->have_acl)
198 # define FILE_HAS_ACL(F) 0
201 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
203 /* Null is a valid character in a color indicator (think about Epson
204 printers, for example) so we have to use a length/buffer string
209 size_t len; /* Number of bytes */
210 const char *string; /* Pointer to the same */
217 # define tcgetpgrp(Fd) 0
220 static size_t quote_name (FILE *out, const char *name,
221 struct quoting_options const *options,
223 static char *make_link_name (char const *name, char const *linkname);
224 static int decode_switches (int argc, char **argv);
225 static bool file_ignored (char const *name);
226 static uintmax_t gobble_file (char const *name, enum filetype type,
227 ino_t inode, bool command_line_arg,
228 char const *dirname);
229 static void print_color_indicator (const char *name, mode_t mode, int linkok);
230 static void put_indicator (const struct bin_str *ind);
231 static void add_ignore_pattern (const char *pattern);
232 static void attach (char *dest, const char *dirname, const char *name);
233 static void clear_files (void);
234 static void extract_dirs_from_files (char const *dirname,
235 bool command_line_arg);
236 static void get_link_name (char const *filename, struct fileinfo *f,
237 bool command_line_arg);
238 static void indent (size_t from, size_t to);
239 static size_t calculate_columns (bool by_columns);
240 static void print_current_files (void);
241 static void print_dir (char const *name, char const *realname,
242 bool command_line_arg);
243 static void print_file_name_and_frills (const struct fileinfo *f);
244 static void print_horizontal (void);
245 static int format_user_width (uid_t u);
246 static int format_group_width (gid_t g);
247 static void print_long_format (const struct fileinfo *f);
248 static void print_many_per_line (void);
249 static void print_name_with_quoting (const char *p, mode_t mode,
251 struct obstack *stack);
252 static void prep_non_filename_text (void);
253 static void print_type_indicator (mode_t mode);
254 static void print_with_commas (void);
255 static void queue_directory (char const *name, char const *realname,
256 bool command_line_arg);
257 static void sort_files (void);
258 static void parse_ls_color (void);
259 void usage (int status);
261 /* The name this program was run with. */
264 /* Initial size of hash table.
265 Most hierarchies are likely to be shallower than this. */
266 #define INITIAL_TABLE_SIZE 30
268 /* The set of `active' directories, from the current command-line argument
269 to the level in the hierarchy at which files are being listed.
270 A directory is represented by its device and inode numbers (struct dev_ino).
271 A directory is added to this set when ls begins listing it or its
272 entries, and it is removed from the set just after ls has finished
273 processing it. This set is used solely to detect loops, e.g., with
274 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
275 static Hash_table *active_dir_set;
277 #define LOOP_DETECT (!!active_dir_set)
279 /* The table of files in the current directory:
281 `files' points to a vector of `struct fileinfo', one per file.
282 `nfiles' is the number of elements space has been allocated for.
283 `files_index' is the number actually in use. */
285 /* Address of block containing the files that are described. */
286 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
288 /* Length of block that `files' points to, measured in files. */
289 static size_t nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
291 /* Index of first unused in `files'. */
292 static size_t files_index; /* FIXME: rename this to e.g. cwd_n_used */
294 /* When true, in a color listing, color each symlink name according to the
295 type of file it points to. Otherwise, color them according to the `ln'
296 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
297 regardless. This is set when `ln=target' appears in LS_COLORS. */
299 static bool color_symlink_as_referent;
301 /* mode of appropriate file for colorization */
302 #define FILE_OR_LINK_MODE(File) \
303 ((color_symlink_as_referent & (File)->linkok) \
304 ? (File)->linkmode : (File)->stat.st_mode)
307 /* Record of one pending directory waiting to be listed. */
312 /* If the directory is actually the file pointed to by a symbolic link we
313 were told to list, `realname' will contain the name of the symbolic
314 link, otherwise zero. */
316 bool command_line_arg;
317 struct pending *next;
320 static struct pending *pending_dirs;
322 /* Current time in seconds and nanoseconds since 1970, updated as
323 needed when deciding whether a file is recent. */
325 static time_t current_time = TYPE_MINIMUM (time_t);
326 static int current_time_ns = -1;
328 /* Whether any of the files has an ACL. This affects the width of the
332 static bool any_has_acl;
334 enum { any_has_acl = false };
337 /* The number of columns to use for columns containing inode numbers,
338 block sizes, link counts, owners, groups, authors, major device
339 numbers, minor device numbers, and file sizes, respectively. */
341 static int inode_number_width;
342 static int block_size_width;
343 static int nlink_width;
344 static int owner_width;
345 static int group_width;
346 static int author_width;
347 static int major_device_number_width;
348 static int minor_device_number_width;
349 static int file_size_width;
353 /* long_format for lots of info, one per line.
354 one_per_line for just names, one per line.
355 many_per_line for just names, many per line, sorted vertically.
356 horizontal for just names, many per line, sorted horizontally.
357 with_commas for just names, many per line, separated by commas.
359 -l (and other options that imply -l), -1, -C, -x and -m control
364 long_format, /* -l and other options that imply -l */
365 one_per_line, /* -1 */
366 many_per_line, /* -C */
371 static enum format format;
373 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
374 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
375 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
378 full_iso_time_style, /* --time-style=full-iso */
379 long_iso_time_style, /* --time-style=long-iso */
380 iso_time_style, /* --time-style=iso */
381 locale_time_style /* --time-style=locale */
384 static char const *const time_style_args[] =
386 "full-iso", "long-iso", "iso", "locale", NULL
388 static enum time_style const time_style_types[] =
390 full_iso_time_style, long_iso_time_style, iso_time_style,
393 ARGMATCH_VERIFY (time_style_args, time_style_types);
395 /* Type of time to print or sort by. Controlled by -c and -u.
396 The values of each item of this enum are important since they are
397 used as indices in the sort functions array (see sort_files()). */
401 time_mtime, /* default */
404 time_numtypes /* the number of elements of this enum */
407 static enum time_type time_type;
409 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
410 The values of each item of this enum are important since they are
411 used as indices in the sort functions array (see sort_files()). */
415 sort_none = -1, /* -U */
416 sort_name, /* default */
417 sort_extension, /* -X */
419 sort_version, /* -v */
421 sort_numtypes /* the number of elements of this enum */
424 static enum sort_type sort_type;
426 /* Direction of sort.
427 false means highest first if numeric,
428 lowest first if alphabetic;
429 these are the defaults.
430 true means the opposite order in each case. -r */
432 static bool sort_reverse;
434 /* True means to display owner information. -g turns this off. */
436 static bool print_owner = true;
438 /* True means to display author information. */
440 static bool print_author;
442 /* True means to display group information. -G and -o turn this off. */
444 static bool print_group = true;
446 /* True means print the user and group id's as numbers rather
449 static bool numeric_ids;
451 /* True means mention the size in blocks of each file. -s */
453 static bool print_block_size;
455 /* Human-readable options for output. */
456 static int human_output_opts;
458 /* The units to use when printing sizes other than file sizes. */
459 static uintmax_t output_block_size;
461 /* Likewise, but for file sizes. */
462 static uintmax_t file_output_block_size = 1;
464 /* Follow the output with a special string. Using this format,
465 Emacs' dired mode starts up twice as fast, and can handle all
466 strange characters in file names. */
469 /* `none' means don't mention the type of files.
470 `slash' means mention directories only, with a '/'.
471 `file_type' means mention file types.
472 `classify' means mention file types and mark executables.
474 Controlled by -F, -p, and --indicator-style. */
478 none, /* --indicator-style=none */
479 slash, /* -p, --indicator-style=slash */
480 file_type, /* --indicator-style=file-type */
481 classify /* -F, --indicator-style=classify */
484 static enum indicator_style indicator_style;
486 /* Names of indicator styles. */
487 static char const *const indicator_style_args[] =
489 "none", "slash", "file-type", "classify", NULL
491 static enum indicator_style const indicator_style_types[] =
493 none, slash, file_type, classify
495 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
497 /* True means use colors to mark types. Also define the different
498 colors as well as the stuff for the LS_COLORS environment variable.
499 The LS_COLORS variable is now in a termcap-like format. */
501 static bool print_with_color;
505 color_never, /* 0: default or --color=never */
506 color_always, /* 1: --color=always */
507 color_if_tty /* 2: --color=tty */
510 enum Dereference_symlink
514 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
515 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
516 DEREF_ALWAYS /* -L */
521 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
522 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
523 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE
526 static const char *const indicator_name[]=
528 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
529 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
533 struct color_ext_type
535 struct bin_str ext; /* The extension we're looking for */
536 struct bin_str seq; /* The sequence to output when we do */
537 struct color_ext_type *next; /* Next in list */
540 static struct bin_str color_indicator[] =
542 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
543 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
544 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
545 { LEN_STR_PAIR ("0") }, /* no: Normal */
546 { LEN_STR_PAIR ("0") }, /* fi: File: default */
547 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
548 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
549 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
550 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
551 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
552 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
553 { 0, NULL }, /* mi: Missing file: undefined */
554 { 0, NULL }, /* or: Orphaned symlink: undefined */
555 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
556 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
557 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
558 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
559 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
560 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
561 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
565 static struct color_ext_type *color_ext_list = NULL;
567 /* Buffer for color sequences */
568 static char *color_buf;
570 /* True means to check for orphaned symbolic link, for displaying
573 static bool check_symlink_color;
575 /* True means mention the inode number of each file. -i */
577 static bool print_inode;
579 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
580 other options that imply -l), and -L. */
582 static enum Dereference_symlink dereference;
584 /* True means when a directory is found, display info on its
587 static bool recursive;
589 /* True means when an argument is a directory name, display info
592 static bool immediate_dirs;
594 /* True means that directories are grouped before files. */
596 static bool directories_first;
598 /* Which files to ignore. */
602 /* Ignore files whose names start with `.', and files specified by
603 --hide and --ignore. */
606 /* Ignore `.', `..', and files specified by --ignore. */
607 IGNORE_DOT_AND_DOTDOT,
609 /* Ignore only files specified by --ignore. */
613 /* A linked list of shell-style globbing patterns. If a non-argument
614 file name matches any of these patterns, it is ignored.
615 Controlled by -I. Multiple -I options accumulate.
616 The -B option adds `*~' and `.*~' to this list. */
618 struct ignore_pattern
621 struct ignore_pattern *next;
624 static struct ignore_pattern *ignore_patterns;
626 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
627 variable itself to be ignored. */
628 static struct ignore_pattern *hide_patterns;
630 /* True means output nongraphic chars in file names as `?'.
631 (-q, --hide-control-chars)
632 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
633 independent. The algorithm is: first, obey the quoting style to get a
634 string representing the file name; then, if qmark_funny_chars is set,
635 replace all nonprintable chars in that string with `?'. It's necessary
636 to replace nonprintable chars even in quoted strings, because we don't
637 want to mess up the terminal if control chars get sent to it, and some
638 quoting methods pass through control chars as-is. */
639 static bool qmark_funny_chars;
641 /* Quoting options for file and dir name output. */
643 static struct quoting_options *filename_quoting_options;
644 static struct quoting_options *dirname_quoting_options;
646 /* The number of chars per hardware tab stop. Setting this to zero
647 inhibits the use of TAB characters for separating columns. -T */
648 static size_t tabsize;
650 /* True means print each directory name before listing it. */
652 static bool print_dir_name;
654 /* The line length to use for breaking lines in many-per-line format.
655 Can be set with -w. */
657 static size_t line_length;
659 /* If true, the file listing format requires that stat be called on
662 static bool format_needs_stat;
664 /* Similar to `format_needs_stat', but set if only the file type is
667 static bool format_needs_type;
669 /* An arbitrary limit on the number of bytes in a printed time stamp.
670 This is set to a relatively small value to avoid the need to worry
671 about denial-of-service attacks on servers that run "ls" on behalf
672 of remote clients. 1000 bytes should be enough for any practical
673 time stamp format. */
675 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
677 /* strftime formats for non-recent and recent files, respectively, in
680 static char const *long_time_format[2] =
682 /* strftime format for non-recent files (older than 6 months), in
683 -l output. This should contain the year, month and day (at
684 least), in an order that is understood by people in your
685 locale's territory. Please try to keep the number of used
686 screen columns small, because many people work in windows with
687 only 80 columns. But make this as wide as the other string
688 below, for recent files. */
690 /* strftime format for recent files (younger than 6 months), in -l
691 output. This should contain the month, day and time (at
692 least), in an order that is understood by people in your
693 locale's territory. Please try to keep the number of used
694 screen columns small, because many people work in windows with
695 only 80 columns. But make this as wide as the other string
696 above, for non-recent files. */
700 /* The set of signals that are caught. */
702 static sigset_t caught_signals;
704 /* If nonzero, the value of the pending fatal signal. */
706 static sig_atomic_t volatile interrupt_signal;
708 /* A count of the number of pending stop signals that have been received. */
710 static sig_atomic_t volatile stop_signal_count;
712 /* Desired exit status. */
714 static int exit_status;
719 /* "ls" had a minor problem (e.g., it could not stat a directory
721 LS_MINOR_PROBLEM = 1,
723 /* "ls" had more serious trouble. */
727 /* For long options that have no equivalent short option, use a
728 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
731 AUTHOR_OPTION = CHAR_MAX + 1,
734 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
737 GROUP_DIRECTORIES_FIRST_OPTION,
739 INDICATOR_STYLE_OPTION,
741 /* FIXME: --kilobytes is deprecated (but not -k); remove in late 2006 */
742 KILOBYTES_LONG_OPTION,
744 QUOTING_STYLE_OPTION,
745 SHOW_CONTROL_CHARS_OPTION,
752 static struct option const long_options[] =
754 {"all", no_argument, NULL, 'a'},
755 {"escape", no_argument, NULL, 'b'},
756 {"directory", no_argument, NULL, 'd'},
757 {"dired", no_argument, NULL, 'D'},
758 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
759 {"group-directories-first", no_argument, NULL,
760 GROUP_DIRECTORIES_FIRST_OPTION},
761 {"human-readable", no_argument, NULL, 'h'},
762 {"inode", no_argument, NULL, 'i'},
763 {"kilobytes", no_argument, NULL, KILOBYTES_LONG_OPTION},
764 {"numeric-uid-gid", no_argument, NULL, 'n'},
765 {"no-group", no_argument, NULL, 'G'},
766 {"hide-control-chars", no_argument, NULL, 'q'},
767 {"reverse", no_argument, NULL, 'r'},
768 {"size", no_argument, NULL, 's'},
769 {"width", required_argument, NULL, 'w'},
770 {"almost-all", no_argument, NULL, 'A'},
771 {"ignore-backups", no_argument, NULL, 'B'},
772 {"classify", no_argument, NULL, 'F'},
773 {"file-type", no_argument, NULL, 'p'},
774 {"si", no_argument, NULL, SI_OPTION},
775 {"dereference-command-line", no_argument, NULL, 'H'},
776 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
777 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
778 {"hide", required_argument, NULL, HIDE_OPTION},
779 {"ignore", required_argument, NULL, 'I'},
780 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
781 {"dereference", no_argument, NULL, 'L'},
782 {"literal", no_argument, NULL, 'N'},
783 {"quote-name", no_argument, NULL, 'Q'},
784 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
785 {"recursive", no_argument, NULL, 'R'},
786 {"format", required_argument, NULL, FORMAT_OPTION},
787 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
788 {"sort", required_argument, NULL, SORT_OPTION},
789 {"tabsize", required_argument, NULL, 'T'},
790 {"time", required_argument, NULL, TIME_OPTION},
791 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
792 {"color", optional_argument, NULL, COLOR_OPTION},
793 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
794 {"author", no_argument, NULL, AUTHOR_OPTION},
795 {GETOPT_HELP_OPTION_DECL},
796 {GETOPT_VERSION_OPTION_DECL},
800 static char const *const format_args[] =
802 "verbose", "long", "commas", "horizontal", "across",
803 "vertical", "single-column", NULL
805 static enum format const format_types[] =
807 long_format, long_format, with_commas, horizontal, horizontal,
808 many_per_line, one_per_line
810 ARGMATCH_VERIFY (format_args, format_types);
812 static char const *const sort_args[] =
814 "none", "time", "size", "extension", "version", NULL
816 static enum sort_type const sort_types[] =
818 sort_none, sort_time, sort_size, sort_extension, sort_version
820 ARGMATCH_VERIFY (sort_args, sort_types);
822 static char const *const time_args[] =
824 "atime", "access", "use", "ctime", "status", NULL
826 static enum time_type const time_types[] =
828 time_atime, time_atime, time_atime, time_ctime, time_ctime
830 ARGMATCH_VERIFY (time_args, time_types);
832 static char const *const color_args[] =
834 /* force and none are for compatibility with another color-ls version */
835 "always", "yes", "force",
836 "never", "no", "none",
837 "auto", "tty", "if-tty", NULL
839 static enum color_type const color_types[] =
841 color_always, color_always, color_always,
842 color_never, color_never, color_never,
843 color_if_tty, color_if_tty, color_if_tty
845 ARGMATCH_VERIFY (color_args, color_types);
847 /* Information about filling a column. */
855 /* Array with information about column filledness. */
856 static struct column_info *column_info;
858 /* Maximum number of columns ever possible for this display. */
859 static size_t max_idx;
861 /* The minimum width of a column is 3: 1 character for the name and 2
862 for the separating white space. */
863 #define MIN_COLUMN_WIDTH 3
866 /* This zero-based index is used solely with the --dired option.
867 When that option is in effect, this counter is incremented for each
868 byte of output generated by this program so that the beginning
869 and ending indices (in that output) of every file name can be recorded
870 and later output themselves. */
871 static size_t dired_pos;
873 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
875 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
876 #define DIRED_FPUTS(s, stream, s_len) \
877 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
879 /* Like DIRED_FPUTS, but for use when S is a literal string. */
880 #define DIRED_FPUTS_LITERAL(s, stream) \
881 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
883 #define DIRED_INDENT() \
887 DIRED_FPUTS_LITERAL (" ", stdout); \
891 /* With --dired, store pairs of beginning and ending indices of filenames. */
892 static struct obstack dired_obstack;
894 /* With --dired, store pairs of beginning and ending indices of any
895 directory names that appear as headers (just before `total' line)
896 for lists of directory entries. Such directory names are seen when
897 listing hierarchies using -R and when a directory is listed with at
898 least one other command line argument. */
899 static struct obstack subdired_obstack;
901 /* Save the current index on the specified obstack, OBS. */
902 #define PUSH_CURRENT_DIRED_POS(obs) \
906 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
910 /* With -R, this stack is used to help detect directory cycles.
911 The device/inode pairs on this stack mirror the pairs in the
912 active_dir_set hash table. */
913 static struct obstack dev_ino_obstack;
915 /* Push a pair onto the device/inode stack. */
916 #define DEV_INO_PUSH(Dev, Ino) \
919 struct dev_ino *di; \
920 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
921 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
922 di->st_dev = (Dev); \
923 di->st_ino = (Ino); \
927 /* Pop a dev/ino struct off the global dev_ino_obstack
928 and return that struct. */
929 static struct dev_ino
932 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
933 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
934 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
937 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
942 assert (0 <= stat (Name, &sb)); \
943 assert (sb.st_dev == Di.st_dev); \
944 assert (sb.st_ino == Di.st_ino); \
949 /* Write to standard output PREFIX, followed by the quoting style and
950 a space-separated list of the integers stored in OS all on one line. */
953 dired_dump_obstack (const char *prefix, struct obstack *os)
957 n_pos = obstack_object_size (os) / sizeof (dired_pos);
963 pos = (size_t *) obstack_finish (os);
964 fputs (prefix, stdout);
965 for (i = 0; i < n_pos; i++)
966 printf (" %lu", (unsigned long int) pos[i]);
972 dev_ino_hash (void const *x, size_t table_size)
974 struct dev_ino const *p = x;
975 return (uintmax_t) p->st_ino % table_size;
979 dev_ino_compare (void const *x, void const *y)
981 struct dev_ino const *a = x;
982 struct dev_ino const *b = y;
983 return SAME_INODE (*a, *b) ? true : false;
987 dev_ino_free (void *x)
992 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
993 active directories. Return true if there is already a matching
994 entry in the table. */
997 visit_dir (dev_t dev, ino_t ino)
1000 struct dev_ino *ent_from_table;
1003 ent = xmalloc (sizeof *ent);
1007 /* Attempt to insert this entry into the table. */
1008 ent_from_table = hash_insert (active_dir_set, ent);
1010 if (ent_from_table == NULL)
1012 /* Insertion failed due to lack of memory. */
1016 found_match = (ent_from_table != ent);
1020 /* ent was not inserted, so free it. */
1028 free_pending_ent (struct pending *p)
1036 is_colored (enum indicator_no type)
1038 size_t len = color_indicator[type].len;
1039 char const *s = color_indicator[type].string;
1041 || (len == 1 && strncmp (s, "0", 1) == 0)
1042 || (len == 2 && strncmp (s, "00", 2) == 0));
1046 restore_default_color (void)
1048 put_indicator (&color_indicator[C_LEFT]);
1049 put_indicator (&color_indicator[C_RIGHT]);
1052 /* An ordinary signal was received; arrange for the program to exit. */
1055 sighandler (int sig)
1058 signal (sig, SIG_IGN);
1059 if (! interrupt_signal)
1060 interrupt_signal = sig;
1063 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1066 stophandler (int sig)
1069 signal (sig, stophandler);
1070 if (! interrupt_signal)
1071 stop_signal_count++;
1074 /* Process any pending signals. If signals are caught, this function
1075 should be called periodically. Ideally there should never be an
1076 unbounded amount of time when signals are not being processed.
1077 Signal handling can restore the default colors, so callers must
1078 immediately change colors after invoking this function. */
1081 process_signals (void)
1083 while (interrupt_signal | stop_signal_count)
1089 restore_default_color ();
1092 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1094 /* Reload interrupt_signal and stop_signal_count, in case a new
1095 signal was handled before sigprocmask took effect. */
1096 sig = interrupt_signal;
1097 stops = stop_signal_count;
1099 /* SIGTSTP is special, since the application can receive that signal
1100 more than once. In this case, don't set the signal handler to the
1101 default. Instead, just raise the uncatchable SIGSTOP. */
1104 stop_signal_count = stops - 1;
1108 signal (sig, SIG_DFL);
1110 /* Exit or suspend the program. */
1112 sigprocmask (SIG_SETMASK, &oldset, NULL);
1114 /* If execution reaches here, then the program has been
1115 continued (after being suspended). */
1120 main (int argc, char **argv)
1123 struct pending *thispend;
1126 /* The signals that are trapped, and the number of such signals. */
1127 static int const sig[] = { SIGHUP, SIGINT, SIGPIPE,
1128 SIGQUIT, SIGTERM, SIGTSTP };
1129 enum { nsigs = sizeof sig / sizeof sig[0] };
1132 bool caught_sig[nsigs];
1135 initialize_main (&argc, &argv);
1136 program_name = argv[0];
1137 setlocale (LC_ALL, "");
1138 bindtextdomain (PACKAGE, LOCALEDIR);
1139 textdomain (PACKAGE);
1141 initialize_exit_failure (LS_FAILURE);
1142 atexit (close_stdout);
1144 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1145 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1147 exit_status = EXIT_SUCCESS;
1148 print_dir_name = true;
1149 pending_dirs = NULL;
1151 i = decode_switches (argc, argv);
1153 if (print_with_color)
1156 /* Test print_with_color again, because the call to parse_ls_color
1157 may have just reset it -- e.g., if LS_COLORS is invalid. */
1158 if (print_with_color)
1160 /* Avoid following symbolic links when possible. */
1161 if (is_colored (C_ORPHAN)
1162 || is_colored (C_EXEC)
1163 || (is_colored (C_MISSING) && format == long_format))
1164 check_symlink_color = true;
1166 /* If the standard output is a controlling terminal, watch out
1167 for signals, so that the colors can be restored to the
1168 default state if "ls" is suspended or interrupted. */
1170 if (0 <= tcgetpgrp (STDOUT_FILENO))
1174 struct sigaction act;
1176 sigemptyset (&caught_signals);
1177 for (j = 0; j < nsigs; j++)
1179 sigaction (sig[j], NULL, &act);
1180 if (act.sa_handler != SIG_IGN)
1181 sigaddset (&caught_signals, sig[j]);
1184 act.sa_mask = caught_signals;
1185 act.sa_flags = SA_RESTART;
1187 for (j = 0; j < nsigs; j++)
1188 if (sigismember (&caught_signals, sig[j]))
1190 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1191 sigaction (sig[j], &act, NULL);
1194 for (j = 0; j < nsigs; j++)
1196 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1199 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1200 siginterrupt (sig[j], 0);
1206 prep_non_filename_text ();
1209 if (dereference == DEREF_UNDEFINED)
1210 dereference = ((immediate_dirs
1211 || indicator_style == classify
1212 || format == long_format)
1214 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1216 /* When using -R, initialize a data structure we'll use to
1217 detect any directory cycles. */
1220 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1224 if (active_dir_set == NULL)
1227 obstack_init (&dev_ino_obstack);
1230 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1231 || format == long_format
1232 || print_block_size;
1233 format_needs_type = (! format_needs_stat
1236 || indicator_style != none
1237 || directories_first));
1241 obstack_init (&dired_obstack);
1242 obstack_init (&subdired_obstack);
1246 files = xnmalloc (nfiles, sizeof *files);
1256 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1258 queue_directory (".", NULL, true);
1262 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1268 if (!immediate_dirs)
1269 extract_dirs_from_files (NULL, true);
1270 /* `files_index' might be zero now. */
1273 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1274 (and not pending_dirs->name) because there may be no markers in the queue
1275 at this point. A marker may be enqueued when extract_dirs_from_files is
1276 called with a non-empty string or via print_dir. */
1279 print_current_files ();
1281 DIRED_PUTCHAR ('\n');
1283 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1284 print_dir_name = false;
1286 while (pending_dirs)
1288 thispend = pending_dirs;
1289 pending_dirs = pending_dirs->next;
1293 if (thispend->name == NULL)
1295 /* thispend->name == NULL means this is a marker entry
1296 indicating we've finished processing the directory.
1297 Use its dev/ino numbers to remove the corresponding
1298 entry from the active_dir_set hash table. */
1299 struct dev_ino di = dev_ino_pop ();
1300 struct dev_ino *found = hash_delete (active_dir_set, &di);
1301 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1303 dev_ino_free (found);
1304 free_pending_ent (thispend);
1309 print_dir (thispend->name, thispend->realname,
1310 thispend->command_line_arg);
1312 free_pending_ent (thispend);
1313 print_dir_name = true;
1316 if (print_with_color)
1320 restore_default_color ();
1323 /* Restore the default signal handling. */
1325 for (j = 0; j < nsigs; j++)
1326 if (sigismember (&caught_signals, sig[j]))
1327 signal (sig[j], SIG_DFL);
1329 for (j = 0; j < nsigs; j++)
1331 signal (sig[j], SIG_DFL);
1334 /* Act on any signals that arrived before the default was restored.
1335 This can process signals out of order, but there doesn't seem to
1336 be an easy way to do them in order, and the order isn't that
1337 important anyway. */
1338 for (j = stop_signal_count; j; j--)
1340 j = interrupt_signal;
1347 /* No need to free these since we're about to exit. */
1348 dired_dump_obstack ("//DIRED//", &dired_obstack);
1349 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1350 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1351 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1356 assert (hash_get_n_entries (active_dir_set) == 0);
1357 hash_free (active_dir_set);
1363 /* Set all the option flags according to the switches specified.
1364 Return the index of the first non-option argument. */
1367 decode_switches (int argc, char **argv)
1370 char *time_style_option = NULL;
1372 /* Record whether there is an option specifying sort type. */
1373 bool sort_type_specified = false;
1375 qmark_funny_chars = false;
1377 /* initialize all switches to default settings */
1382 /* This is for the `dir' program. */
1383 format = many_per_line;
1384 set_quoting_style (NULL, escape_quoting_style);
1387 case LS_LONG_FORMAT:
1388 /* This is for the `vdir' program. */
1389 format = long_format;
1390 set_quoting_style (NULL, escape_quoting_style);
1394 /* This is for the `ls' program. */
1395 if (isatty (STDOUT_FILENO))
1397 format = many_per_line;
1398 /* See description of qmark_funny_chars, above. */
1399 qmark_funny_chars = true;
1403 format = one_per_line;
1404 qmark_funny_chars = false;
1412 time_type = time_mtime;
1413 sort_type = sort_name;
1414 sort_reverse = false;
1415 numeric_ids = false;
1416 print_block_size = false;
1417 indicator_style = none;
1418 print_inode = false;
1419 dereference = DEREF_UNDEFINED;
1421 immediate_dirs = false;
1422 ignore_mode = IGNORE_DEFAULT;
1423 ignore_patterns = NULL;
1424 hide_patterns = NULL;
1426 /* FIXME: put this in a function. */
1428 char const *q_style = getenv ("QUOTING_STYLE");
1431 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1433 set_quoting_style (NULL, quoting_style_vals[i]);
1436 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1437 quotearg (q_style));
1442 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1443 human_output_opts = human_options (ls_block_size, false,
1444 &output_block_size);
1445 if (ls_block_size || getenv ("BLOCK_SIZE"))
1446 file_output_block_size = output_block_size;
1451 char const *p = getenv ("COLUMNS");
1454 unsigned long int tmp_ulong;
1455 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1456 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1458 line_length = tmp_ulong;
1463 _("ignoring invalid width in environment variable COLUMNS: %s"),
1473 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1474 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1475 line_length = ws.ws_col;
1480 char const *p = getenv ("TABSIZE");
1484 unsigned long int tmp_ulong;
1485 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1486 && tmp_ulong <= SIZE_MAX)
1488 tabsize = tmp_ulong;
1493 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1499 while ((c = getopt_long (argc, argv,
1500 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1501 long_options, NULL)) != -1)
1506 ignore_mode = IGNORE_MINIMAL;
1510 set_quoting_style (NULL, escape_quoting_style);
1514 time_type = time_ctime;
1518 immediate_dirs = true;
1522 /* Same as enabling -a -U and disabling -l -s. */
1523 ignore_mode = IGNORE_MINIMAL;
1524 sort_type = sort_none;
1525 sort_type_specified = true;
1527 if (format == long_format)
1528 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1529 print_block_size = false; /* disable -s */
1530 print_with_color = false; /* disable --color */
1534 format = long_format;
1535 print_owner = false;
1539 human_output_opts = human_autoscale | human_SI | human_base_1024;
1540 file_output_block_size = output_block_size = 1;
1547 case KILOBYTES_LONG_OPTION:
1549 _("the --kilobytes option is deprecated; use -k instead"));
1552 human_output_opts = 0;
1553 file_output_block_size = output_block_size = 1024;
1557 format = long_format;
1561 format = with_commas;
1566 format = long_format;
1569 case 'o': /* Just like -l, but don't display group info. */
1570 format = long_format;
1571 print_group = false;
1575 indicator_style = slash;
1579 qmark_funny_chars = true;
1583 sort_reverse = true;
1587 print_block_size = true;
1591 sort_type = sort_time;
1592 sort_type_specified = true;
1596 time_type = time_atime;
1600 sort_type = sort_version;
1601 sort_type_specified = true;
1606 unsigned long int tmp_ulong;
1607 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1608 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1609 error (LS_FAILURE, 0, _("invalid line width: %s"),
1611 line_length = tmp_ulong;
1616 format = horizontal;
1620 if (ignore_mode == IGNORE_DEFAULT)
1621 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1625 add_ignore_pattern ("*~");
1626 add_ignore_pattern (".*~");
1630 format = many_per_line;
1638 indicator_style = classify;
1641 case 'G': /* inhibit display of group info */
1642 print_group = false;
1646 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1649 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1650 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1654 add_ignore_pattern (optarg);
1658 dereference = DEREF_ALWAYS;
1662 set_quoting_style (NULL, literal_quoting_style);
1666 set_quoting_style (NULL, c_quoting_style);
1674 sort_type = sort_size;
1675 sort_type_specified = true;
1680 unsigned long int tmp_ulong;
1681 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1682 || SIZE_MAX < tmp_ulong)
1683 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1685 tabsize = tmp_ulong;
1690 sort_type = sort_none;
1691 sort_type_specified = true;
1695 sort_type = sort_extension;
1696 sort_type_specified = true;
1700 /* -1 has no effect after -l. */
1701 if (format != long_format)
1702 format = one_per_line;
1706 print_author = true;
1711 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1712 hide->pattern = optarg;
1713 hide->next = hide_patterns;
1714 hide_patterns = hide;
1719 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1720 sort_type_specified = true;
1723 case GROUP_DIRECTORIES_FIRST_OPTION:
1724 directories_first = true;
1728 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1732 format = XARGMATCH ("--format", optarg, format_args, format_types);
1735 case FULL_TIME_OPTION:
1736 format = long_format;
1737 time_style_option = "full-iso";
1744 i = XARGMATCH ("--color", optarg, color_args, color_types);
1746 /* Using --color with no argument is equivalent to using
1750 print_with_color = (i == color_always
1751 || (i == color_if_tty
1752 && isatty (STDOUT_FILENO)));
1754 if (print_with_color)
1756 /* Don't use TAB characters in output. Some terminal
1757 emulators can't handle the combination of tabs and
1758 color codes on the same line. */
1764 case INDICATOR_STYLE_OPTION:
1765 indicator_style = XARGMATCH ("--indicator-style", optarg,
1766 indicator_style_args,
1767 indicator_style_types);
1770 case QUOTING_STYLE_OPTION:
1771 set_quoting_style (NULL,
1772 XARGMATCH ("--quoting-style", optarg,
1774 quoting_style_vals));
1777 case TIME_STYLE_OPTION:
1778 time_style_option = optarg;
1781 case SHOW_CONTROL_CHARS_OPTION:
1782 qmark_funny_chars = false;
1785 case BLOCK_SIZE_OPTION:
1786 human_output_opts = human_options (optarg, true, &output_block_size);
1787 file_output_block_size = output_block_size;
1791 human_output_opts = human_autoscale | human_SI;
1792 file_output_block_size = output_block_size = 1;
1795 case_GETOPT_HELP_CHAR;
1797 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1804 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1806 filename_quoting_options = clone_quoting_options (NULL);
1807 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1808 set_char_quoting (filename_quoting_options, ' ', 1);
1809 if (file_type <= indicator_style)
1812 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1813 set_char_quoting (filename_quoting_options, *p, 1);
1816 dirname_quoting_options = clone_quoting_options (NULL);
1817 set_char_quoting (dirname_quoting_options, ':', 1);
1819 /* --dired is meaningful only with --format=long (-l).
1820 Otherwise, ignore it. FIXME: warn about this?
1821 Alternatively, make --dired imply --format=long? */
1822 if (dired && format != long_format)
1825 /* If -c or -u is specified and not -l (or any other option that implies -l),
1826 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1827 The behavior of ls when using either -c or -u but with neither -l nor -t
1828 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1829 sort by atime (this is the one that's not specified by the POSIX spec),
1830 -lu means show atime and sort by name, -lut means show atime and sort
1833 if ((time_type == time_ctime || time_type == time_atime)
1834 && !sort_type_specified && format != long_format)
1836 sort_type = sort_time;
1839 if (format == long_format)
1841 char *style = time_style_option;
1842 static char const posix_prefix[] = "posix-";
1845 if (! (style = getenv ("TIME_STYLE")))
1848 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1850 if (! hard_locale (LC_TIME))
1852 style += sizeof posix_prefix - 1;
1857 char *p0 = style + 1;
1858 char *p1 = strchr (p0, '\n');
1863 if (strchr (p1 + 1, '\n'))
1864 error (LS_FAILURE, 0, _("invalid time style format %s"),
1868 long_time_format[0] = p0;
1869 long_time_format[1] = p1;
1872 switch (XARGMATCH ("time style", style,
1876 case full_iso_time_style:
1877 long_time_format[0] = long_time_format[1] =
1878 "%Y-%m-%d %H:%M:%S.%N %z";
1881 case long_iso_time_style:
1882 case_long_iso_time_style:
1883 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1886 case iso_time_style:
1887 long_time_format[0] = "%Y-%m-%d ";
1888 long_time_format[1] = "%m-%d %H:%M";
1891 case locale_time_style:
1892 if (hard_locale (LC_TIME))
1894 /* Ensure that the locale has translations for both
1895 formats. If not, fall back on long-iso format. */
1897 for (i = 0; i < 2; i++)
1899 char const *locale_format =
1900 dcgettext (NULL, long_time_format[i], LC_TIME);
1901 if (locale_format == long_time_format[i])
1902 goto case_long_iso_time_style;
1903 long_time_format[i] = locale_format;
1912 /* Parse a string as part of the LS_COLORS variable; this may involve
1913 decoding all kinds of escape characters. If equals_end is set an
1914 unescaped equal sign ends the string, otherwise only a : or \0
1915 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1918 The resulting string is *not* null-terminated, but may contain
1921 Note that both dest and src are char **; on return they point to
1922 the first free byte after the array and the character that ended
1923 the input string, respectively. */
1926 get_funky_string (char **dest, const char **src, bool equals_end,
1927 size_t *output_count)
1929 char num; /* For numerical codes */
1930 size_t count; /* Something to count with */
1932 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1937 p = *src; /* We don't want to double-indirect */
1938 q = *dest; /* the whole darn time. */
1940 count = 0; /* No characters counted in yet. */
1943 state = ST_GND; /* Start in ground state. */
1944 while (state < ST_END)
1948 case ST_GND: /* Ground state (no escapes) */
1953 state = ST_END; /* End of string */
1956 state = ST_BACKSLASH; /* Backslash scape sequence */
1960 state = ST_CARET; /* Caret escape */
1966 state = ST_END; /* End */
1969 /* else fall through */
1977 case ST_BACKSLASH: /* Backslash escaped character */
1988 state = ST_OCTAL; /* Octal sequence */
1993 state = ST_HEX; /* Hex sequence */
1996 case 'a': /* Bell */
1999 case 'b': /* Backspace */
2002 case 'e': /* Escape */
2005 case 'f': /* Form feed */
2008 case 'n': /* Newline */
2011 case 'r': /* Carriage return */
2017 case 'v': /* Vtab */
2020 case '?': /* Delete */
2023 case '_': /* Space */
2026 case '\0': /* End of string */
2027 state = ST_ERROR; /* Error! */
2029 default: /* Escaped character like \ ^ : = */
2033 if (state == ST_BACKSLASH)
2042 case ST_OCTAL: /* Octal sequence */
2043 if (*p < '0' || *p > '7')
2050 num = (num << 3) + (*(p++) - '0');
2053 case ST_HEX: /* Hex sequence */
2066 num = (num << 4) + (*(p++) - '0');
2074 num = (num << 4) + (*(p++) - 'a') + 10;
2082 num = (num << 4) + (*(p++) - 'A') + 10;
2092 case ST_CARET: /* Caret escape */
2093 state = ST_GND; /* Should be the next state... */
2094 if (*p >= '@' && *p <= '~')
2096 *(q++) = *(p++) & 037;
2115 *output_count = count;
2117 return state != ST_ERROR;
2121 parse_ls_color (void)
2123 const char *p; /* Pointer to character being parsed */
2124 char *buf; /* color_buf buffer pointer */
2125 int state; /* State of parser */
2126 int ind_no; /* Indicator number */
2127 char label[3]; /* Indicator label */
2128 struct color_ext_type *ext; /* Extension we are working on */
2130 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2134 strcpy (label, "??");
2136 /* This is an overly conservative estimate, but any possible
2137 LS_COLORS string will *not* generate a color_buf longer than
2138 itself, so it is a safe way of allocating a buffer in
2140 buf = color_buf = xstrdup (p);
2147 case 1: /* First label character */
2155 /* Allocate new extension block and add to head of
2156 linked list (this way a later definition will
2157 override an earlier one, which can be useful for
2158 having terminal-specific defs override global). */
2160 ext = xmalloc (sizeof *ext);
2161 ext->next = color_ext_list;
2162 color_ext_list = ext;
2165 ext->ext.string = buf;
2167 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2172 state = 0; /* Done! */
2175 default: /* Assume it is file type label */
2182 case 2: /* Second label character */
2189 state = -1; /* Error */
2192 case 3: /* Equal sign after indicator label */
2193 state = -1; /* Assume failure... */
2194 if (*(p++) == '=')/* It *should* be... */
2196 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2198 if (STREQ (label, indicator_name[ind_no]))
2200 color_indicator[ind_no].string = buf;
2201 state = (get_funky_string (&buf, &p, false,
2202 &color_indicator[ind_no].len)
2208 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2212 case 4: /* Equal sign after *.ext */
2215 ext->seq.string = buf;
2216 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2227 struct color_ext_type *e;
2228 struct color_ext_type *e2;
2231 _("unparsable value for LS_COLORS environment variable"));
2233 for (e = color_ext_list; e != NULL; /* empty */)
2239 print_with_color = false;
2242 if (color_indicator[C_LINK].len == 6
2243 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2244 color_symlink_as_referent = true;
2247 /* Set the exit status to report a failure. If SERIOUS, it is a
2248 serious failure; otherwise, it is merely a minor problem. */
2251 set_exit_status (bool serious)
2254 exit_status = LS_FAILURE;
2255 else if (exit_status == EXIT_SUCCESS)
2256 exit_status = LS_MINOR_PROBLEM;
2259 /* Assuming a failure is serious if SERIOUS, use the printf-style
2260 MESSAGE to report the failure to access a file named FILE. Assume
2261 errno is set appropriately for the failure. */
2264 file_failure (bool serious, char const *message, char const *file)
2266 error (0, errno, message, quotearg_colon (file));
2267 set_exit_status (serious);
2270 /* Request that the directory named NAME have its contents listed later.
2271 If REALNAME is nonzero, it will be used instead of NAME when the
2272 directory name is printed. This allows symbolic links to directories
2273 to be treated as regular directories but still be listed under their
2274 real names. NAME == NULL is used to insert a marker entry for the
2275 directory named in REALNAME.
2276 If NAME is non-NULL, we use its dev/ino information to save
2277 a call to stat -- when doing a recursive (-R) traversal.
2278 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2281 queue_directory (char const *name, char const *realname, bool command_line_arg)
2283 struct pending *new = xmalloc (sizeof *new);
2284 new->realname = realname ? xstrdup (realname) : NULL;
2285 new->name = name ? xstrdup (name) : NULL;
2286 new->command_line_arg = command_line_arg;
2287 new->next = pending_dirs;
2291 /* Read directory NAME, and list the files in it.
2292 If REALNAME is nonzero, print its name instead of NAME;
2293 this is used for symbolic links to directories.
2294 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2297 print_dir (char const *name, char const *realname, bool command_line_arg)
2300 struct dirent *next;
2301 uintmax_t total_blocks = 0;
2302 static bool first = true;
2305 dirp = opendir (name);
2308 file_failure (command_line_arg, "%s", name);
2314 struct stat dir_stat;
2315 int fd = dirfd (dirp);
2317 /* If dirfd failed, endure the overhead of using stat. */
2319 ? fstat (fd, &dir_stat)
2320 : stat (name, &dir_stat)) < 0)
2322 file_failure (command_line_arg,
2323 _("cannot determine device and inode of %s"), name);
2327 /* If we've already visited this dev/inode pair, warn that
2328 we've found a loop, and do not process this directory. */
2329 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2331 error (0, 0, _("%s: not listing already-listed directory"),
2332 quotearg_colon (name));
2336 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2339 /* Read the directory entries, and insert the subfiles into the `files'
2346 /* Set errno to zero so we can distinguish between a readdir failure
2347 and when readdir simply finds that there are no more entries. */
2349 next = readdir (dirp);
2352 if (! file_ignored (next->d_name))
2354 enum filetype type = unknown;
2356 #if HAVE_STRUCT_DIRENT_D_TYPE
2357 if (next->d_type == DT_BLK
2358 || next->d_type == DT_CHR
2359 || next->d_type == DT_DIR
2360 || next->d_type == DT_FIFO
2361 || next->d_type == DT_LNK
2362 || next->d_type == DT_REG
2363 || next->d_type == DT_SOCK)
2364 type = next->d_type;
2366 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2370 else if (errno != 0)
2372 file_failure (command_line_arg, _("reading directory %s"), name);
2373 if (errno != EOVERFLOW)
2380 if (closedir (dirp) != 0)
2382 file_failure (command_line_arg, _("closing directory %s"), name);
2383 /* Don't return; print whatever we got. */
2386 /* Sort the directory contents. */
2389 /* If any member files are subdirectories, perhaps they should have their
2390 contents listed rather than being mentioned here as files. */
2393 extract_dirs_from_files (name, command_line_arg);
2395 if (recursive | print_dir_name)
2398 DIRED_PUTCHAR ('\n');
2401 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2402 dired_pos += quote_name (stdout, realname ? realname : name,
2403 dirname_quoting_options, NULL);
2404 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2405 DIRED_FPUTS_LITERAL (":\n", stdout);
2408 if (format == long_format || print_block_size)
2411 char buf[LONGEST_HUMAN_READABLE + 1];
2415 DIRED_FPUTS (p, stdout, strlen (p));
2416 DIRED_PUTCHAR (' ');
2417 p = human_readable (total_blocks, buf, human_output_opts,
2418 ST_NBLOCKSIZE, output_block_size);
2419 DIRED_FPUTS (p, stdout, strlen (p));
2420 DIRED_PUTCHAR ('\n');
2424 print_current_files ();
2427 /* Add `pattern' to the list of patterns for which files that match are
2431 add_ignore_pattern (const char *pattern)
2433 struct ignore_pattern *ignore;
2435 ignore = xmalloc (sizeof *ignore);
2436 ignore->pattern = pattern;
2437 /* Add it to the head of the linked list. */
2438 ignore->next = ignore_patterns;
2439 ignore_patterns = ignore;
2442 /* Return true if one of the PATTERNS matches FILE. */
2445 patterns_match (struct ignore_pattern const *patterns, char const *file)
2447 struct ignore_pattern const *p;
2448 for (p = patterns; p; p = p->next)
2449 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2454 /* Return true if FILE should be ignored. */
2457 file_ignored (char const *name)
2459 return ((ignore_mode != IGNORE_MINIMAL
2461 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2462 || (ignore_mode == IGNORE_DEFAULT
2463 && patterns_match (hide_patterns, name))
2464 || patterns_match (ignore_patterns, name));
2467 /* POSIX requires that a file size be printed without a sign, even
2468 when negative. Assume the typical case where negative sizes are
2469 actually positive values that have wrapped around. */
2472 unsigned_file_size (off_t size)
2474 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2477 /* Enter and remove entries in the table `files'. */
2479 /* Empty the table of files. */
2486 for (i = 0; i < files_index; i++)
2488 free (files[i].name);
2489 free (files[i].linkname);
2494 any_has_acl = false;
2496 inode_number_width = 0;
2497 block_size_width = 0;
2502 major_device_number_width = 0;
2503 minor_device_number_width = 0;
2504 file_size_width = 0;
2507 /* Add a file to the current table of files.
2508 Verify that the file exists, and print an error message if it does not.
2509 Return the number of blocks that the file occupies. */
2512 gobble_file (char const *name, enum filetype type, ino_t inode,
2513 bool command_line_arg, char const *dirname)
2518 /* An inode value prior to gobble_file necessarily came from readdir,
2519 which is not used for command line arguments. */
2520 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2522 if (files_index == nfiles)
2524 files = xnrealloc (files, nfiles, 2 * sizeof *files);
2528 f = &files[files_index];
2533 if (command_line_arg
2534 || format_needs_stat
2536 && (inode == NOT_AN_INODE_NUMBER
2537 /* When dereferencing symlinks, the inode must come from
2538 stat, but readdir provides the inode of lstat. Command
2539 line dereferences are already taken care of by the above
2540 assertion that the inode number is not yet known. */
2541 || (dereference == DEREF_ALWAYS
2542 && (type == symbolic_link || type == unknown))))
2543 || (format_needs_type
2546 /* FIXME: remove this disjunct.
2547 I don't think we care about symlinks here, but for now
2548 this won't make a big performance difference. */
2549 || type == symbolic_link
2551 /* --indicator-style=classify (aka -F)
2552 requires that we stat each regular file
2553 to see if it's executable. */
2554 || (type == normal && (indicator_style == classify
2555 /* This is so that --color ends up
2556 highlighting files with the executable
2557 bit set even when options like -F are
2559 || (print_with_color
2560 && is_colored (C_EXEC))
2564 /* Absolute name of this file. */
2565 char *absolute_name;
2569 if (name[0] == '/' || dirname[0] == 0)
2570 absolute_name = (char *) name;
2573 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2574 attach (absolute_name, dirname, name);
2577 switch (dereference)
2580 err = stat (absolute_name, &f->stat);
2583 case DEREF_COMMAND_LINE_ARGUMENTS:
2584 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2585 if (command_line_arg)
2588 err = stat (absolute_name, &f->stat);
2590 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2593 need_lstat = (err < 0
2595 : ! S_ISDIR (f->stat.st_mode));
2599 /* stat failed because of ENOENT, maybe indicating a dangling
2600 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2601 directory, and --dereference-command-line-symlink-to-dir is
2602 in effect. Fall through so that we call lstat instead. */
2605 default: /* DEREF_NEVER */
2606 err = lstat (absolute_name, &f->stat);
2612 file_failure (command_line_arg, "%s", absolute_name);
2617 if (format == long_format)
2619 int n = file_has_acl (absolute_name, &f->stat);
2620 f->have_acl = (0 < n);
2621 any_has_acl |= f->have_acl;
2623 error (0, errno, "%s", quotearg_colon (absolute_name));
2627 if (S_ISLNK (f->stat.st_mode)
2628 && (format == long_format || check_symlink_color))
2631 struct stat linkstats;
2633 get_link_name (absolute_name, f, command_line_arg);
2634 linkname = make_link_name (absolute_name, f->linkname);
2636 /* Avoid following symbolic links when possible, ie, when
2637 they won't be traced and when no indicator is needed. */
2639 && (file_type <= indicator_style || check_symlink_color)
2640 && stat (linkname, &linkstats) == 0)
2644 /* Symbolic links to directories that are mentioned on the
2645 command line are automatically traced if not being
2647 if (!command_line_arg || format == long_format
2648 || !S_ISDIR (linkstats.st_mode))
2650 /* Get the linked-to file's mode for the filetype indicator
2651 in long listings. */
2652 f->linkmode = linkstats.st_mode;
2659 if (S_ISLNK (f->stat.st_mode))
2660 f->filetype = symbolic_link;
2661 else if (S_ISDIR (f->stat.st_mode))
2663 if (command_line_arg & !immediate_dirs)
2664 f->filetype = arg_directory;
2666 f->filetype = directory;
2669 f->filetype = normal;
2671 blocks = ST_NBLOCKS (f->stat);
2673 char buf[LONGEST_HUMAN_READABLE + 1];
2674 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2675 ST_NBLOCKSIZE, output_block_size),
2677 if (block_size_width < len)
2678 block_size_width = len;
2683 int len = format_user_width (f->stat.st_uid);
2684 if (owner_width < len)
2690 int len = format_group_width (f->stat.st_gid);
2691 if (group_width < len)
2697 int len = format_user_width (f->stat.st_author);
2698 if (author_width < len)
2703 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2704 int len = strlen (umaxtostr (f->stat.st_nlink, buf));
2705 if (nlink_width < len)
2709 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2711 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2712 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2713 if (major_device_number_width < len)
2714 major_device_number_width = len;
2715 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2716 if (minor_device_number_width < len)
2717 minor_device_number_width = len;
2718 len = major_device_number_width + 2 + minor_device_number_width;
2719 if (file_size_width < len)
2720 file_size_width = len;
2724 char buf[LONGEST_HUMAN_READABLE + 1];
2725 uintmax_t size = unsigned_file_size (f->stat.st_size);
2726 int len = mbswidth (human_readable (size, buf, human_output_opts,
2727 1, file_output_block_size),
2729 if (file_size_width < len)
2730 file_size_width = len;
2736 f->stat.st_ino = inode;
2737 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
2738 f->stat.st_mode = DTTOIF (type);
2745 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2746 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2747 if (inode_number_width < len)
2748 inode_number_width = len;
2751 f->name = xstrdup (name);
2757 /* Return true if F refers to a directory. */
2759 is_directory (const struct fileinfo *f)
2761 return f->filetype == directory || f->filetype == arg_directory;
2767 /* Put the name of the file that FILENAME is a symbolic link to
2768 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2769 FILENAME is a command-line argument. */
2772 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2774 f->linkname = xreadlink (filename, f->stat.st_size);
2775 if (f->linkname == NULL)
2776 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2780 /* If `linkname' is a relative name and `name' contains one or more
2781 leading directories, return `linkname' with those directories
2782 prepended; otherwise, return a copy of `linkname'.
2783 If `linkname' is zero, return zero. */
2786 make_link_name (char const *name, char const *linkname)
2794 if (*linkname == '/')
2795 return xstrdup (linkname);
2797 /* The link is to a relative name. Prepend any leading directory
2798 in `name' to the link name. */
2799 linkbuf = strrchr (name, '/');
2801 return xstrdup (linkname);
2803 bufsiz = linkbuf - name + 1;
2804 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2805 strncpy (linkbuf, name, bufsiz);
2806 strcpy (linkbuf + bufsiz, linkname);
2811 /* Return true if the last component of NAME is `.' or `..'
2812 This is so we don't try to recurse on `././././. ...' */
2815 basename_is_dot_or_dotdot (const char *name)
2817 char const *base = last_component (name);
2818 return DOT_OR_DOTDOT (base);
2821 /* Remove any entries from FILES that are for directories,
2822 and queue them to be listed as directories instead.
2823 DIRNAME is the prefix to prepend to each dirname
2824 to make it correct relative to ls's working dir;
2825 if it is null, no prefix is needed and "." and ".." should not be ignored.
2826 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2827 This is desirable when processing directories recursively. */
2830 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2834 bool ignore_dot_and_dot_dot = (dirname != NULL);
2836 if (dirname && LOOP_DETECT)
2838 /* Insert a marker entry first. When we dequeue this marker entry,
2839 we'll know that DIRNAME has been processed and may be removed
2840 from the set of active directories. */
2841 queue_directory (NULL, dirname, false);
2844 /* Queue the directories last one first, because queueing reverses the
2846 for (i = files_index; i-- != 0; )
2847 if (is_directory (&files[i])
2848 && (! ignore_dot_and_dot_dot
2849 || ! basename_is_dot_or_dotdot (files[i].name)))
2851 if (!dirname || files[i].name[0] == '/')
2853 queue_directory (files[i].name, files[i].linkname,
2858 char *name = file_name_concat (dirname, files[i].name, NULL);
2859 queue_directory (name, files[i].linkname, command_line_arg);
2862 if (files[i].filetype == arg_directory)
2863 free (files[i].name);
2866 /* Now delete the directories from the table, compacting all the remaining
2869 for (i = 0, j = 0; i < files_index; i++)
2871 if (files[i].filetype != arg_directory)
2874 files[j] = files[i];
2881 /* Use strcoll to compare strings in this locale. If an error occurs,
2882 report an error and longjmp to failed_strcoll. */
2884 static jmp_buf failed_strcoll;
2887 xstrcoll (char const *a, char const *b)
2891 diff = strcoll (a, b);
2894 error (0, errno, _("cannot compare file names %s and %s"),
2895 quote_n (0, a), quote_n (1, b));
2896 set_exit_status (false);
2897 longjmp (failed_strcoll, 1);
2902 /* Comparison routines for sorting the files. */
2904 typedef void const *V;
2905 typedef int (*qsortFunc)(V a, V b);
2907 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
2908 The do { ... } while(0) makes it possible to use the macro more like
2909 a statement, without violating C89 rules: */
2910 #define DIRFIRST_CHECK(a, b) \
2913 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
2914 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
2915 if (a_is_dir && !b_is_dir) \
2916 return -1; /* a goes before b */ \
2917 if (!a_is_dir && b_is_dir) \
2918 return 1; /* b goes before a */ \
2922 /* Define the 8 different sort function variants required for each sortkey.
2923 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
2924 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
2925 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
2926 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
2927 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
2928 /* direct, non-dirfirst versions */ \
2929 static int xstrcoll_##key_name (V a, V b) \
2930 { return key_cmp_func (a, b, xstrcoll); } \
2931 static int strcmp_##key_name (V a, V b) \
2932 { return key_cmp_func (a, b, strcmp); } \
2934 /* reverse, non-dirfirst versions */ \
2935 static int rev_xstrcoll_##key_name (V a, V b) \
2936 { return key_cmp_func (b, a, xstrcoll); } \
2937 static int rev_strcmp_##key_name (V a, V b) \
2938 { return key_cmp_func (b, a, strcmp); } \
2940 /* direct, dirfirst versions */ \
2941 static int xstrcoll_df_##key_name (V a, V b) \
2942 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
2943 static int strcmp_df_##key_name (V a, V b) \
2944 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
2946 /* reverse, dirfirst versions */ \
2947 static int rev_xstrcoll_df_##key_name (V a, V b) \
2948 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
2949 static int rev_strcmp_df_##key_name (V a, V b) \
2950 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
2953 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2954 int (*cmp) (char const *, char const *))
2956 int diff = timespec_cmp (get_stat_ctime (&b->stat),
2957 get_stat_ctime (&a->stat));
2958 return diff ? diff : cmp (a->name, b->name);
2962 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2963 int (*cmp) (char const *, char const *))
2965 int diff = timespec_cmp (get_stat_mtime (&b->stat),
2966 get_stat_mtime (&a->stat));
2967 return diff ? diff : cmp (a->name, b->name);
2971 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2972 int (*cmp) (char const *, char const *))
2974 int diff = timespec_cmp (get_stat_atime (&b->stat),
2975 get_stat_atime (&a->stat));
2976 return diff ? diff : cmp (a->name, b->name);
2980 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2981 int (*cmp) (char const *, char const *))
2983 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2984 return diff ? diff : cmp (a->name, b->name);
2988 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2989 int (*cmp) (char const *, char const *))
2991 return cmp (a->name, b->name);
2994 /* Compare file extensions. Files with no extension are `smallest'.
2995 If extensions are the same, compare by filenames instead. */
2998 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2999 int (*cmp) (char const *, char const *))
3001 char const *base1 = strrchr (a->name, '.');
3002 char const *base2 = strrchr (b->name, '.');
3003 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3004 return diff ? diff : cmp (a->name, b->name);
3007 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3008 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3009 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3010 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3011 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3012 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3014 /* Compare file versions.
3015 Unlike all other compare functions above, cmp_version depends only
3016 on strverscmp, which does not fail (even for locale reasons), and does not
3017 need a secondary sort key.
3018 All the other sort options, in fact, need xstrcoll and strcmp variants,
3019 because they all use a string comparison (either as the primary or secondary
3020 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3021 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3022 thanks to the gnulib library. */
3024 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3026 return strverscmp (a->name, b->name);
3029 static int xstrcoll_version (V a, V b)
3030 { return cmp_version (a, b); }
3031 static int rev_xstrcoll_version (V a, V b)
3032 { return cmp_version (b, a); }
3033 static int xstrcoll_df_version (V a, V b)
3034 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3035 static int rev_xstrcoll_df_version (V a, V b)
3036 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3039 /* We have 2^3 different variants for each sortkey function
3040 (for 3 independent sort modes).
3041 The function pointers stored in this array must be dereferenced as:
3043 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3045 Note that the order in which sortkeys are listed in the function pointer
3046 array below is defined by the order of the elements in the time_type and
3049 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3052 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3053 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3056 { strcmp_##key_name, strcmp_df_##key_name }, \
3057 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3061 static qsortFunc sort_functions[][2][2][2] =
3063 LIST_SORTFUNCTION_VARIANTS (name),
3064 LIST_SORTFUNCTION_VARIANTS (extension),
3065 LIST_SORTFUNCTION_VARIANTS (size),
3069 { xstrcoll_version, xstrcoll_df_version },
3070 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3073 /* We use NULL for the strcmp variants of version comparison
3074 since as explained in cmp_version definition, version comparison
3075 does not rely on xstrcoll, so it will never longjmp, and never
3076 need to try the strcmp fallback. */
3083 /* last are time sort functions */
3084 LIST_SORTFUNCTION_VARIANTS (mtime),
3085 LIST_SORTFUNCTION_VARIANTS (ctime),
3086 LIST_SORTFUNCTION_VARIANTS (atime)
3089 /* The number of sortkeys is calculated as
3090 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3091 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3092 This is because when sort_type==sort_time, we have up to
3093 time_numtypes possible sortkeys.
3095 This line verifies at compile-time that the array of sort functions has been
3096 initialized for all possible sortkeys. */
3097 verify (ARRAY_CARDINALITY (sort_functions)
3098 == sort_numtypes + time_numtypes - 1 );
3101 /* Sort the files now in the table. */
3108 if (sort_type == sort_none)
3111 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3112 ignore strcoll failures, as a failing strcoll might be a
3113 comparison function that is not a total order, and if we ignored
3114 the failure this might cause qsort to dump core. */
3116 if (! setjmp (failed_strcoll))
3117 use_strcmp = false; /* strcoll() succeeded */
3121 assert (sort_type != sort_version);
3124 /* When sort_type == sort_time, use time_type as subindex. */
3125 int timeoffset = sort_type == sort_time ? time_type : 0;
3127 qsort (files, files_index, sizeof *files,
3128 sort_functions[sort_type + timeoffset][use_strcmp][sort_reverse]
3129 [directories_first]);
3132 /* List all the files now in the table. */
3135 print_current_files (void)
3142 for (i = 0; i < files_index; i++)
3144 print_file_name_and_frills (files + i);
3150 print_many_per_line ();
3154 print_horizontal ();
3158 print_with_commas ();
3162 for (i = 0; i < files_index; i++)
3164 print_long_format (files + i);
3165 DIRED_PUTCHAR ('\n');
3171 /* Return the expected number of columns in a long-format time stamp,
3172 or zero if it cannot be calculated. */
3175 long_time_expected_width (void)
3177 static int width = -1;
3182 struct tm const *tm = localtime (&epoch);
3183 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3185 /* In case you're wondering if localtime can fail with an input time_t
3186 value of 0, let's just say it's very unlikely, but not inconceivable.
3187 The TZ environment variable would have to specify a time zone that
3188 is 2**31-1900 years or more ahead of UTC. This could happen only on
3189 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3190 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3191 their implementations limit the offset to 167:59 and 24:00, resp. */
3195 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3197 width = mbsnwidth (buf, len, 0);
3207 /* Get the current time. */
3210 get_current_time (void)
3212 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
3214 struct timespec timespec;
3215 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
3217 current_time = timespec.tv_sec;
3218 current_time_ns = timespec.tv_nsec;
3224 /* The clock does not have nanosecond resolution, so get the maximum
3225 possible value for the current time that is consistent with the
3226 reported clock. That way, files are not considered to be in the
3227 future merely because their time stamps have higher resolution
3228 than the clock resolution. */
3230 #if HAVE_GETTIMEOFDAY
3232 struct timeval timeval;
3233 gettimeofday (&timeval, NULL);
3234 current_time = timeval.tv_sec;
3235 current_time_ns = timeval.tv_usec * 1000 + 999;
3238 current_time = time (NULL);
3239 current_time_ns = 999999999;
3243 /* Print the user or group name NAME, with numeric id ID, using a
3244 print width of WIDTH columns. */
3247 format_user_or_group (char const *name, unsigned long int id, int width)
3253 int width_gap = width - mbswidth (name, 0);
3254 int pad = MAX (0, width_gap);
3255 fputs (name, stdout);
3256 len = strlen (name) + pad;
3264 printf ("%*lu ", width, id);
3268 dired_pos += len + 1;
3271 /* Print the name or id of the user with id U, using a print width of
3275 format_user (uid_t u, int width)
3277 format_user_or_group (numeric_ids ? NULL : getuser (u), u, width);
3280 /* Likewise, for groups. */
3283 format_group (gid_t g, int width)
3285 format_user_or_group (numeric_ids ? NULL : getgroup (g), g, width);
3288 /* Return the number of columns that format_user_or_group will print. */
3291 format_user_or_group_width (char const *name, unsigned long int id)
3295 int len = mbswidth (name, 0);
3296 return MAX (0, len);
3300 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3301 sprintf (buf, "%lu", id);
3302 return strlen (buf);
3306 /* Return the number of columns that format_user will print. */
3309 format_user_width (uid_t u)
3311 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3314 /* Likewise, for groups. */
3317 format_group_width (gid_t g)
3319 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3323 /* Print information about F in long format. */
3326 print_long_format (const struct fileinfo *f)
3330 [LONGEST_HUMAN_READABLE + 1 /* inode */
3331 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3332 + sizeof (modebuf) - 1 + 1 /* mode string */
3333 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3334 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3335 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3336 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3342 struct timespec when_timespec;
3343 struct tm *when_local;
3345 /* Compute the mode string, except remove the trailing space if no
3346 files in this directory have ACLs. */
3347 filemodestring (&f->stat, modebuf);
3350 else if (FILE_HAS_ACL (f))
3356 when_timespec = get_stat_ctime (&f->stat);
3359 when_timespec = get_stat_mtime (&f->stat);
3362 when_timespec = get_stat_atime (&f->stat);
3368 when = when_timespec.tv_sec;
3369 when_ns = when_timespec.tv_nsec;
3375 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3376 sprintf (p, "%*s ", inode_number_width,
3377 umaxtostr (f->stat.st_ino, hbuf));
3378 p += inode_number_width + 1;
3381 if (print_block_size)
3383 char hbuf[LONGEST_HUMAN_READABLE + 1];
3384 char const *blocks =
3385 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3386 ST_NBLOCKSIZE, output_block_size);
3388 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3390 while ((*p++ = *blocks++))
3395 /* The last byte of the mode string is the POSIX
3396 "optional alternate access method flag". */
3398 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3399 sprintf (p, "%s %*s ", modebuf, nlink_width,
3400 umaxtostr (f->stat.st_nlink, hbuf));
3402 p += sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1;
3406 if (print_owner | print_group | print_author)
3408 DIRED_FPUTS (buf, stdout, p - buf);
3411 format_user (f->stat.st_uid, owner_width);
3414 format_group (f->stat.st_gid, group_width);
3417 format_user (f->stat.st_author, author_width);
3422 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3424 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3425 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3426 int blanks_width = (file_size_width
3427 - (major_device_number_width + 2
3428 + minor_device_number_width));
3429 sprintf (p, "%*s, %*s ",
3430 major_device_number_width + MAX (0, blanks_width),
3431 umaxtostr (major (f->stat.st_rdev), majorbuf),
3432 minor_device_number_width,
3433 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3434 p += file_size_width + 1;
3438 char hbuf[LONGEST_HUMAN_READABLE + 1];
3440 human_readable (unsigned_file_size (f->stat.st_size),
3441 hbuf, human_output_opts, 1, file_output_block_size);
3443 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3445 while ((*p++ = *size++))
3450 when_local = localtime (&when_timespec.tv_sec);
3456 time_t six_months_ago;
3460 /* If the file appears to be in the future, update the current
3461 time, in case the file happens to have been modified since
3462 the last time we checked the clock. */
3463 if (current_time < when
3464 || (current_time == when && current_time_ns < when_ns))
3466 /* Note that get_current_time calls gettimeofday which, on some non-
3467 compliant systems, clobbers the buffer used for localtime's result.
3468 But it's ok here, because we use a gettimeofday wrapper that
3469 saves and restores the buffer around the gettimeofday call. */
3470 get_current_time ();
3473 /* Consider a time to be recent if it is within the past six
3474 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3475 31556952 seconds on the average. Write this value as an
3476 integer constant to avoid floating point hassles. */
3477 six_months_ago = current_time - 31556952 / 2;
3478 recent = (six_months_ago <= when
3479 && (when < current_time
3480 || (when == current_time && when_ns <= current_time_ns)));
3481 fmt = long_time_format[recent];
3483 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3484 when_local, 0, when_ns);
3492 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3497 /* The time cannot be converted using the desired format, so
3498 print it as a huge integer number of seconds. */
3499 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3500 sprintf (p, "%*s ", long_time_expected_width (),
3501 (TYPE_SIGNED (time_t)
3502 ? imaxtostr (when, hbuf)
3503 : umaxtostr (when, hbuf)));
3507 DIRED_FPUTS (buf, stdout, p - buf);
3508 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3511 if (f->filetype == symbolic_link)
3515 DIRED_FPUTS_LITERAL (" -> ", stdout);
3516 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3518 if (indicator_style != none)
3519 print_type_indicator (f->linkmode);
3522 else if (indicator_style != none)
3523 print_type_indicator (f->stat.st_mode);
3526 /* Output to OUT a quoted representation of the file name NAME,
3527 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3528 Store the number of screen columns occupied by NAME's quoted
3529 representation into WIDTH, if non-NULL. Return the number of bytes
3533 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3536 char smallbuf[BUFSIZ];
3537 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3539 size_t displayed_width IF_LINT (= 0);
3541 if (len < sizeof smallbuf)
3545 buf = alloca (len + 1);
3546 quotearg_buffer (buf, len + 1, name, -1, options);
3549 if (qmark_funny_chars)
3554 char const *p = buf;
3555 char const *plimit = buf + len;
3557 displayed_width = 0;
3562 case ' ': case '!': case '"': case '#': case '%':
3563 case '&': case '\'': case '(': case ')': case '*':
3564 case '+': case ',': case '-': case '.': case '/':
3565 case '0': case '1': case '2': case '3': case '4':
3566 case '5': case '6': case '7': case '8': case '9':
3567 case ':': case ';': case '<': case '=': case '>':
3569 case 'A': case 'B': case 'C': case 'D': case 'E':
3570 case 'F': case 'G': case 'H': case 'I': case 'J':
3571 case 'K': case 'L': case 'M': case 'N': case 'O':
3572 case 'P': case 'Q': case 'R': case 'S': case 'T':
3573 case 'U': case 'V': case 'W': case 'X': case 'Y':
3575 case '[': case '\\': case ']': case '^': case '_':
3576 case 'a': case 'b': case 'c': case 'd': case 'e':
3577 case 'f': case 'g': case 'h': case 'i': case 'j':
3578 case 'k': case 'l': case 'm': case 'n': case 'o':
3579 case 'p': case 'q': case 'r': case 's': case 't':
3580 case 'u': case 'v': case 'w': case 'x': case 'y':
3581 case 'z': case '{': case '|': case '}': case '~':
3582 /* These characters are printable ASCII characters. */
3584 displayed_width += 1;
3587 /* If we have a multibyte sequence, copy it until we
3588 reach its end, replacing each non-printable multibyte
3589 character with a single question mark. */
3592 memset (&mbstate, 0, sizeof mbstate);
3599 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3601 if (bytes == (size_t) -1)
3603 /* An invalid multibyte sequence was
3604 encountered. Skip one input byte, and
3605 put a question mark. */
3608 displayed_width += 1;
3612 if (bytes == (size_t) -2)
3614 /* An incomplete multibyte character
3615 at the end. Replace it entirely with
3619 displayed_width += 1;
3624 /* A null wide character was encountered. */
3630 /* A printable multibyte character.
3632 for (; bytes > 0; --bytes)
3634 displayed_width += w;
3638 /* An unprintable multibyte character.
3639 Replace it entirely with a question
3643 displayed_width += 1;
3646 while (! mbsinit (&mbstate));
3651 /* The buffer may have shrunk. */
3658 char const *plimit = buf + len;
3662 if (! ISPRINT (to_uchar (*p)))
3666 displayed_width = len;
3669 else if (width != NULL)
3673 displayed_width = mbsnwidth (buf, len, 0);
3677 char const *p = buf;
3678 char const *plimit = buf + len;
3680 displayed_width = 0;
3683 if (ISPRINT (to_uchar (*p)))
3691 fwrite (buf, 1, len, out);
3693 *width = displayed_width;
3698 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3699 struct obstack *stack)
3701 if (print_with_color)
3702 print_color_indicator (p, mode, linkok);
3705 PUSH_CURRENT_DIRED_POS (stack);
3707 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3710 PUSH_CURRENT_DIRED_POS (stack);
3712 if (print_with_color)
3715 prep_non_filename_text ();
3720 prep_non_filename_text (void)
3722 if (color_indicator[C_END].string != NULL)
3723 put_indicator (&color_indicator[C_END]);
3726 put_indicator (&color_indicator[C_LEFT]);
3727 put_indicator (&color_indicator[C_NORM]);
3728 put_indicator (&color_indicator[C_RIGHT]);
3732 /* Print the file name of `f' with appropriate quoting.
3733 Also print file size, inode number, and filetype indicator character,
3734 as requested by switches. */
3737 print_file_name_and_frills (const struct fileinfo *f)
3739 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3742 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3743 umaxtostr (f->stat.st_ino, buf));
3745 if (print_block_size)
3746 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3747 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3748 ST_NBLOCKSIZE, output_block_size));
3750 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3752 if (indicator_style != none)
3753 print_type_indicator (f->stat.st_mode);
3757 print_type_indicator (mode_t mode)
3763 if (indicator_style == classify && (mode & S_IXUGO))
3772 else if (indicator_style == slash)
3774 else if (S_ISLNK (mode))
3776 else if (S_ISFIFO (mode))
3778 else if (S_ISSOCK (mode))
3780 else if (S_ISDOOR (mode))
3791 print_color_indicator (const char *name, mode_t mode, int linkok)
3794 struct color_ext_type *ext; /* Color extension */
3795 size_t len; /* Length of name */
3797 /* Is this a nonexistent file? If so, linkok == -1. */
3799 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3808 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3809 type = C_STICKY_OTHER_WRITABLE;
3810 else if ((mode & S_IWOTH) != 0)
3811 type = C_OTHER_WRITABLE;
3812 else if ((mode & S_ISVTX) != 0)
3817 else if (S_ISLNK (mode))
3818 type = ((!linkok && color_indicator[C_ORPHAN].string)
3819 ? C_ORPHAN : C_LINK);
3820 else if (S_ISFIFO (mode))
3822 else if (S_ISSOCK (mode))
3824 else if (S_ISBLK (mode))
3826 else if (S_ISCHR (mode))
3828 else if (S_ISDOOR (mode))
3833 if ((mode & S_ISUID) != 0)
3835 else if ((mode & S_ISGID) != 0)
3837 else if ((mode & S_IXUGO) != 0)
3841 /* Check the file's suffix only if still classified as C_FILE. */
3845 /* Test if NAME has a recognized suffix. */
3847 len = strlen (name);
3848 name += len; /* Pointer to final \0. */
3849 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3851 if (ext->ext.len <= len
3852 && strncmp (name - ext->ext.len, ext->ext.string,
3859 put_indicator (&color_indicator[C_LEFT]);
3860 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3861 put_indicator (&color_indicator[C_RIGHT]);
3864 /* Output a color indicator (which may contain nulls). */
3866 put_indicator (const struct bin_str *ind)
3873 for (i = ind->len; i != 0; --i)
3878 length_of_file_name_and_frills (const struct fileinfo *f)
3882 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3885 len += 1 + (format == with_commas
3886 ? strlen (umaxtostr (f->stat.st_ino, buf))
3887 : inode_number_width);
3889 if (print_block_size)
3890 len += 1 + (format == with_commas
3891 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
3892 human_output_opts, ST_NBLOCKSIZE,
3894 : block_size_width);
3896 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3899 if (indicator_style != none)
3901 mode_t mode = f->stat.st_mode;
3903 len += (S_ISREG (mode)
3904 ? (indicator_style == classify && (mode & S_IXUGO))
3906 || (indicator_style != slash
3910 || S_ISDOOR (mode)))));
3917 print_many_per_line (void)
3919 size_t row; /* Current row. */
3920 size_t cols = calculate_columns (true);
3921 struct column_info const *line_fmt = &column_info[cols - 1];
3923 /* Calculate the number of rows that will be in each column except possibly
3924 for a short column on the right. */
3925 size_t rows = files_index / cols + (files_index % cols != 0);
3927 for (row = 0; row < rows; row++)
3930 size_t filesno = row;
3933 /* Print the next row. */
3936 size_t name_length = length_of_file_name_and_frills (files + filesno);
3937 size_t max_name_length = line_fmt->col_arr[col++];
3938 print_file_name_and_frills (files + filesno);
3941 if (filesno >= files_index)
3944 indent (pos + name_length, pos + max_name_length);
3945 pos += max_name_length;
3952 print_horizontal (void)
3956 size_t cols = calculate_columns (false);
3957 struct column_info const *line_fmt = &column_info[cols - 1];
3958 size_t name_length = length_of_file_name_and_frills (files);
3959 size_t max_name_length = line_fmt->col_arr[0];
3961 /* Print first entry. */
3962 print_file_name_and_frills (files);
3965 for (filesno = 1; filesno < files_index; ++filesno)
3967 size_t col = filesno % cols;
3976 indent (pos + name_length, pos + max_name_length);
3977 pos += max_name_length;
3980 print_file_name_and_frills (files + filesno);
3982 name_length = length_of_file_name_and_frills (files + filesno);
3983 max_name_length = line_fmt->col_arr[col];
3989 print_with_commas (void)
3994 for (filesno = 0; filesno < files_index; filesno++)
3996 size_t len = length_of_file_name_and_frills (files + filesno);
4002 if (pos + len + 2 < line_length)
4014 putchar (separator);
4017 print_file_name_and_frills (files + filesno);
4023 /* Assuming cursor is at position FROM, indent up to position TO.
4024 Use a TAB character instead of two or more spaces whenever possible. */
4027 indent (size_t from, size_t to)
4031 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4034 from += tabsize - from % tabsize;
4044 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4045 /* FIXME: maybe remove this function someday. See about using a
4046 non-malloc'ing version of file_name_concat. */
4049 attach (char *dest, const char *dirname, const char *name)
4051 const char *dirnamep = dirname;
4053 /* Copy dirname if it is not ".". */
4054 if (dirname[0] != '.' || dirname[1] != 0)
4057 *dest++ = *dirnamep++;
4058 /* Add '/' if `dirname' doesn't already end with it. */
4059 if (dirnamep > dirname && dirnamep[-1] != '/')
4067 /* Allocate enough column info suitable for the current number of
4068 files and display columns, and initialize the info to represent the
4069 narrowest possible columns. */
4072 init_column_info (void)
4075 size_t max_cols = MIN (max_idx, files_index);
4077 /* Currently allocated columns in column_info. */
4078 static size_t column_info_alloc;
4080 if (column_info_alloc < max_cols)
4082 size_t new_column_info_alloc;
4085 if (max_cols < max_idx / 2)
4087 /* The number of columns is far less than the display width
4088 allows. Grow the allocation, but only so that it's
4089 double the current requirements. If the display is
4090 extremely wide, this avoids allocating a lot of memory
4091 that is never needed. */
4092 column_info = xnrealloc (column_info, max_cols,
4093 2 * sizeof *column_info);
4094 new_column_info_alloc = 2 * max_cols;
4098 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4099 new_column_info_alloc = max_idx;
4102 /* Allocate the new size_t objects by computing the triangle
4103 formula n * (n + 1) / 2, except that we don't need to
4104 allocate the part of the triangle that we've already
4105 allocated. Check for address arithmetic overflow. */
4107 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4108 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4109 size_t t = s * column_info_growth;
4110 if (s < new_column_info_alloc || t / column_info_growth != s)
4112 p = xnmalloc (t / 2, sizeof *p);
4115 /* Grow the triangle by parceling out the cells just allocated. */
4116 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4118 column_info[i].col_arr = p;
4122 column_info_alloc = new_column_info_alloc;
4125 for (i = 0; i < max_cols; ++i)
4129 column_info[i].valid_len = true;
4130 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4131 for (j = 0; j <= i; ++j)
4132 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4136 /* Calculate the number of columns needed to represent the current set
4137 of files in the current display width. */
4140 calculate_columns (bool by_columns)
4142 size_t filesno; /* Index into files. */
4143 size_t cols; /* Number of files across. */
4145 /* Normally the maximum number of columns is determined by the
4146 screen width. But if few files are available this might limit it
4148 size_t max_cols = MIN (max_idx, files_index);
4150 init_column_info ();
4152 /* Compute the maximum number of possible columns. */
4153 for (filesno = 0; filesno < files_index; ++filesno)
4155 size_t name_length = length_of_file_name_and_frills (files + filesno);
4158 for (i = 0; i < max_cols; ++i)
4160 if (column_info[i].valid_len)
4162 size_t idx = (by_columns
4163 ? filesno / ((files_index + i) / (i + 1))
4164 : filesno % (i + 1));
4165 size_t real_length = name_length + (idx == i ? 0 : 2);
4167 if (column_info[i].col_arr[idx] < real_length)
4169 column_info[i].line_len += (real_length
4170 - column_info[i].col_arr[idx]);
4171 column_info[i].col_arr[idx] = real_length;
4172 column_info[i].valid_len = (column_info[i].line_len
4179 /* Find maximum allowed columns. */
4180 for (cols = max_cols; 1 < cols; --cols)
4182 if (column_info[cols - 1].valid_len)
4192 if (status != EXIT_SUCCESS)
4193 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4197 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4199 List information about the FILEs (the current directory by default).\n\
4200 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4204 Mandatory arguments to long options are mandatory for short options too.\n\
4207 -a, --all do not ignore entries starting with .\n\
4208 -A, --almost-all do not list implied . and ..\n\
4209 --author with -l, print the author of each file\n\
4210 -b, --escape print octal escapes for nongraphic characters\n\
4213 --block-size=SIZE use SIZE-byte blocks\n\
4214 -B, --ignore-backups do not list implied entries ending with ~\n\
4215 -c with -lt: sort by, and show, ctime (time of last\n\
4216 modification of file status information)\n\
4217 with -l: show ctime and sort by name\n\
4218 otherwise: sort by ctime\n\
4221 -C list entries by columns\n\
4222 --color[=WHEN] control whether color is used to distinguish file\n\
4223 types. WHEN may be `never', `always', or `auto'\n\
4224 -d, --directory list directory entries instead of contents,\n\
4225 and do not dereference symbolic links\n\
4226 -D, --dired generate output designed for Emacs' dired mode\n\
4229 -f do not sort, enable -aU, disable -ls --color\n\
4230 -F, --classify append indicator (one of */=>@|) to entries\n\
4231 --file-type likewise, except do not append `*'\n\
4232 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4233 single-column -1, verbose -l, vertical -C\n\
4234 --full-time like -l --time-style=full-iso\n\
4237 -g like -l, but do not list owner\n\
4240 --group-directories-first\n\
4241 group directories before files\n\
4244 -G, --no-group like -l, but do not list group\n\
4245 -h, --human-readable with -l, print sizes in human readable format\n\
4246 (e.g., 1K 234M 2G)\n\
4247 --si likewise, but use powers of 1000 not 1024\n\
4248 -H, --dereference-command-line\n\
4249 follow symbolic links listed on the command line\n\
4250 --dereference-command-line-symlink-to-dir\n\
4251 follow each command line symbolic link\n\
4252 that points to a directory\n\
4253 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4254 (overridden by -a or -A)\n\
4257 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4258 none (default), slash (-p),\n\
4259 file-type (--file-type), classify (-F)\n\
4260 -i, --inode print the index number of each file\n\
4261 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4262 -k like --block-size=1K\n\
4265 -l use a long listing format\n\
4266 -L, --dereference when showing file information for a symbolic\n\
4267 link, show information for the file the link\n\
4268 references rather than for the link itself\n\
4269 -m fill width with a comma separated list of entries\n\
4272 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4273 -N, --literal print raw entry names (don't treat e.g. control\n\
4274 characters specially)\n\
4275 -o like -l, but do not list group information\n\
4276 -p, --indicator-style=slash\n\
4277 append / indicator to directories\n\
4280 -q, --hide-control-chars print ? instead of non graphic characters\n\
4281 --show-control-chars show non graphic characters as-is (default\n\
4282 unless program is `ls' and output is a terminal)\n\
4283 -Q, --quote-name enclose entry names in double quotes\n\
4284 --quoting-style=WORD use quoting style WORD for entry names:\n\
4285 literal, locale, shell, shell-always, c, escape\n\
4288 -r, --reverse reverse order while sorting\n\
4289 -R, --recursive list subdirectories recursively\n\
4290 -s, --size with -l, print size of each file, in blocks\n\
4293 -S sort by file size\n\
4294 --sort=WORD sort by WORD instead of name: none -U,\n\
4295 extension -X, size -S, time -t, version -v\n\
4296 --time=WORD with -l, show time as WORD instead of modification\n\
4297 time: atime -u, access -u, use -u, ctime -c,\n\
4298 or status -c; use specified time as sort key\n\
4302 --time-style=STYLE with -l, show times using style STYLE:\n\
4303 full-iso, long-iso, iso, locale, +FORMAT.\n\
4304 FORMAT is interpreted like `date'; if FORMAT is\n\
4305 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4306 non-recent files and FORMAT2 to recent files;\n\
4307 if STYLE is prefixed with `posix-', STYLE\n\
4308 takes effect only outside the POSIX locale\n\
4309 -t sort by modification time\n\
4310 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4313 -u with -lt: sort by, and show, access time\n\
4314 with -l: show access time and sort by name\n\
4315 otherwise: sort by access time\n\
4316 -U do not sort; list entries in directory order\n\
4317 -v sort by version\n\
4320 -w, --width=COLS assume screen width instead of current value\n\
4321 -x list entries by lines instead of by columns\n\
4322 -X sort alphabetically by entry extension\n\
4323 -1 list one file per line\n\
4325 fputs (HELP_OPTION_DESCRIPTION, stdout);
4326 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4328 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4329 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4333 By default, color is not used to distinguish types of files. That is\n\
4334 equivalent to using --color=none. Using the --color option without the\n\
4335 optional WHEN argument is equivalent to using --color=always. With\n\
4336 --color=auto, color codes are output only if standard output is connected\n\
4337 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4338 colors, and can be set easily by the dircolors command.\n\
4342 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4344 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);