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
1233 || directories_first;
1234 format_needs_type = (! format_needs_stat
1235 && (recursive || print_with_color
1236 || indicator_style != none));
1240 obstack_init (&dired_obstack);
1241 obstack_init (&subdired_obstack);
1245 files = xnmalloc (nfiles, sizeof *files);
1255 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1257 queue_directory (".", NULL, true);
1261 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1267 if (!immediate_dirs)
1268 extract_dirs_from_files (NULL, true);
1269 /* `files_index' might be zero now. */
1272 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1273 (and not pending_dirs->name) because there may be no markers in the queue
1274 at this point. A marker may be enqueued when extract_dirs_from_files is
1275 called with a non-empty string or via print_dir. */
1278 print_current_files ();
1280 DIRED_PUTCHAR ('\n');
1282 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1283 print_dir_name = false;
1285 while (pending_dirs)
1287 thispend = pending_dirs;
1288 pending_dirs = pending_dirs->next;
1292 if (thispend->name == NULL)
1294 /* thispend->name == NULL means this is a marker entry
1295 indicating we've finished processing the directory.
1296 Use its dev/ino numbers to remove the corresponding
1297 entry from the active_dir_set hash table. */
1298 struct dev_ino di = dev_ino_pop ();
1299 struct dev_ino *found = hash_delete (active_dir_set, &di);
1300 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1302 dev_ino_free (found);
1303 free_pending_ent (thispend);
1308 print_dir (thispend->name, thispend->realname,
1309 thispend->command_line_arg);
1311 free_pending_ent (thispend);
1312 print_dir_name = true;
1315 if (print_with_color)
1319 restore_default_color ();
1322 /* Restore the default signal handling. */
1324 for (j = 0; j < nsigs; j++)
1325 if (sigismember (&caught_signals, sig[j]))
1326 signal (sig[j], SIG_DFL);
1328 for (j = 0; j < nsigs; j++)
1330 signal (sig[j], SIG_DFL);
1333 /* Act on any signals that arrived before the default was restored.
1334 This can process signals out of order, but there doesn't seem to
1335 be an easy way to do them in order, and the order isn't that
1336 important anyway. */
1337 for (j = stop_signal_count; j; j--)
1339 j = interrupt_signal;
1346 /* No need to free these since we're about to exit. */
1347 dired_dump_obstack ("//DIRED//", &dired_obstack);
1348 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1349 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1350 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1355 assert (hash_get_n_entries (active_dir_set) == 0);
1356 hash_free (active_dir_set);
1362 /* Set all the option flags according to the switches specified.
1363 Return the index of the first non-option argument. */
1366 decode_switches (int argc, char **argv)
1369 char *time_style_option = NULL;
1371 /* Record whether there is an option specifying sort type. */
1372 bool sort_type_specified = false;
1374 qmark_funny_chars = false;
1376 /* initialize all switches to default settings */
1381 /* This is for the `dir' program. */
1382 format = many_per_line;
1383 set_quoting_style (NULL, escape_quoting_style);
1386 case LS_LONG_FORMAT:
1387 /* This is for the `vdir' program. */
1388 format = long_format;
1389 set_quoting_style (NULL, escape_quoting_style);
1393 /* This is for the `ls' program. */
1394 if (isatty (STDOUT_FILENO))
1396 format = many_per_line;
1397 /* See description of qmark_funny_chars, above. */
1398 qmark_funny_chars = true;
1402 format = one_per_line;
1403 qmark_funny_chars = false;
1411 time_type = time_mtime;
1412 sort_type = sort_name;
1413 sort_reverse = false;
1414 numeric_ids = false;
1415 print_block_size = false;
1416 indicator_style = none;
1417 print_inode = false;
1418 dereference = DEREF_UNDEFINED;
1420 immediate_dirs = false;
1421 ignore_mode = IGNORE_DEFAULT;
1422 ignore_patterns = NULL;
1423 hide_patterns = NULL;
1425 /* FIXME: put this in a function. */
1427 char const *q_style = getenv ("QUOTING_STYLE");
1430 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1432 set_quoting_style (NULL, quoting_style_vals[i]);
1435 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1436 quotearg (q_style));
1441 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1442 human_output_opts = human_options (ls_block_size, false,
1443 &output_block_size);
1444 if (ls_block_size || getenv ("BLOCK_SIZE"))
1445 file_output_block_size = output_block_size;
1450 char const *p = getenv ("COLUMNS");
1453 unsigned long int tmp_ulong;
1454 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1455 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1457 line_length = tmp_ulong;
1462 _("ignoring invalid width in environment variable COLUMNS: %s"),
1472 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1473 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1474 line_length = ws.ws_col;
1479 char const *p = getenv ("TABSIZE");
1483 unsigned long int tmp_ulong;
1484 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1485 && tmp_ulong <= SIZE_MAX)
1487 tabsize = tmp_ulong;
1492 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1498 while ((c = getopt_long (argc, argv,
1499 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1500 long_options, NULL)) != -1)
1505 ignore_mode = IGNORE_MINIMAL;
1509 set_quoting_style (NULL, escape_quoting_style);
1513 time_type = time_ctime;
1517 immediate_dirs = true;
1521 /* Same as enabling -a -U and disabling -l -s. */
1522 ignore_mode = IGNORE_MINIMAL;
1523 sort_type = sort_none;
1524 sort_type_specified = true;
1526 if (format == long_format)
1527 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1528 print_block_size = false; /* disable -s */
1529 print_with_color = false; /* disable --color */
1533 format = long_format;
1534 print_owner = false;
1538 human_output_opts = human_autoscale | human_SI | human_base_1024;
1539 file_output_block_size = output_block_size = 1;
1546 case KILOBYTES_LONG_OPTION:
1548 _("the --kilobytes option is deprecated; use -k instead"));
1551 human_output_opts = 0;
1552 file_output_block_size = output_block_size = 1024;
1556 format = long_format;
1560 format = with_commas;
1565 format = long_format;
1568 case 'o': /* Just like -l, but don't display group info. */
1569 format = long_format;
1570 print_group = false;
1574 indicator_style = slash;
1578 qmark_funny_chars = true;
1582 sort_reverse = true;
1586 print_block_size = true;
1590 sort_type = sort_time;
1591 sort_type_specified = true;
1595 time_type = time_atime;
1599 sort_type = sort_version;
1600 sort_type_specified = true;
1605 unsigned long int tmp_ulong;
1606 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1607 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1608 error (LS_FAILURE, 0, _("invalid line width: %s"),
1610 line_length = tmp_ulong;
1615 format = horizontal;
1619 if (ignore_mode == IGNORE_DEFAULT)
1620 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1624 add_ignore_pattern ("*~");
1625 add_ignore_pattern (".*~");
1629 format = many_per_line;
1637 indicator_style = classify;
1640 case 'G': /* inhibit display of group info */
1641 print_group = false;
1645 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1648 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1649 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1653 add_ignore_pattern (optarg);
1657 dereference = DEREF_ALWAYS;
1661 set_quoting_style (NULL, literal_quoting_style);
1665 set_quoting_style (NULL, c_quoting_style);
1673 sort_type = sort_size;
1674 sort_type_specified = true;
1679 unsigned long int tmp_ulong;
1680 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1681 || SIZE_MAX < tmp_ulong)
1682 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1684 tabsize = tmp_ulong;
1689 sort_type = sort_none;
1690 sort_type_specified = true;
1694 sort_type = sort_extension;
1695 sort_type_specified = true;
1699 /* -1 has no effect after -l. */
1700 if (format != long_format)
1701 format = one_per_line;
1705 print_author = true;
1710 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1711 hide->pattern = optarg;
1712 hide->next = hide_patterns;
1713 hide_patterns = hide;
1718 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1719 sort_type_specified = true;
1722 case GROUP_DIRECTORIES_FIRST_OPTION:
1723 directories_first = true;
1727 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1731 format = XARGMATCH ("--format", optarg, format_args, format_types);
1734 case FULL_TIME_OPTION:
1735 format = long_format;
1736 time_style_option = "full-iso";
1743 i = XARGMATCH ("--color", optarg, color_args, color_types);
1745 /* Using --color with no argument is equivalent to using
1749 print_with_color = (i == color_always
1750 || (i == color_if_tty
1751 && isatty (STDOUT_FILENO)));
1753 if (print_with_color)
1755 /* Don't use TAB characters in output. Some terminal
1756 emulators can't handle the combination of tabs and
1757 color codes on the same line. */
1763 case INDICATOR_STYLE_OPTION:
1764 indicator_style = XARGMATCH ("--indicator-style", optarg,
1765 indicator_style_args,
1766 indicator_style_types);
1769 case QUOTING_STYLE_OPTION:
1770 set_quoting_style (NULL,
1771 XARGMATCH ("--quoting-style", optarg,
1773 quoting_style_vals));
1776 case TIME_STYLE_OPTION:
1777 time_style_option = optarg;
1780 case SHOW_CONTROL_CHARS_OPTION:
1781 qmark_funny_chars = false;
1784 case BLOCK_SIZE_OPTION:
1785 human_output_opts = human_options (optarg, true, &output_block_size);
1786 file_output_block_size = output_block_size;
1790 human_output_opts = human_autoscale | human_SI;
1791 file_output_block_size = output_block_size = 1;
1794 case_GETOPT_HELP_CHAR;
1796 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1803 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1805 filename_quoting_options = clone_quoting_options (NULL);
1806 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1807 set_char_quoting (filename_quoting_options, ' ', 1);
1808 if (file_type <= indicator_style)
1811 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1812 set_char_quoting (filename_quoting_options, *p, 1);
1815 dirname_quoting_options = clone_quoting_options (NULL);
1816 set_char_quoting (dirname_quoting_options, ':', 1);
1818 /* --dired is meaningful only with --format=long (-l).
1819 Otherwise, ignore it. FIXME: warn about this?
1820 Alternatively, make --dired imply --format=long? */
1821 if (dired && format != long_format)
1824 /* If -c or -u is specified and not -l (or any other option that implies -l),
1825 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1826 The behavior of ls when using either -c or -u but with neither -l nor -t
1827 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1828 sort by atime (this is the one that's not specified by the POSIX spec),
1829 -lu means show atime and sort by name, -lut means show atime and sort
1832 if ((time_type == time_ctime || time_type == time_atime)
1833 && !sort_type_specified && format != long_format)
1835 sort_type = sort_time;
1838 if (format == long_format)
1840 char *style = time_style_option;
1841 static char const posix_prefix[] = "posix-";
1844 if (! (style = getenv ("TIME_STYLE")))
1847 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1849 if (! hard_locale (LC_TIME))
1851 style += sizeof posix_prefix - 1;
1856 char *p0 = style + 1;
1857 char *p1 = strchr (p0, '\n');
1862 if (strchr (p1 + 1, '\n'))
1863 error (LS_FAILURE, 0, _("invalid time style format %s"),
1867 long_time_format[0] = p0;
1868 long_time_format[1] = p1;
1871 switch (XARGMATCH ("time style", style,
1875 case full_iso_time_style:
1876 long_time_format[0] = long_time_format[1] =
1877 "%Y-%m-%d %H:%M:%S.%N %z";
1880 case long_iso_time_style:
1881 case_long_iso_time_style:
1882 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1885 case iso_time_style:
1886 long_time_format[0] = "%Y-%m-%d ";
1887 long_time_format[1] = "%m-%d %H:%M";
1890 case locale_time_style:
1891 if (hard_locale (LC_TIME))
1893 /* Ensure that the locale has translations for both
1894 formats. If not, fall back on long-iso format. */
1896 for (i = 0; i < 2; i++)
1898 char const *locale_format =
1899 dcgettext (NULL, long_time_format[i], LC_TIME);
1900 if (locale_format == long_time_format[i])
1901 goto case_long_iso_time_style;
1902 long_time_format[i] = locale_format;
1911 /* Parse a string as part of the LS_COLORS variable; this may involve
1912 decoding all kinds of escape characters. If equals_end is set an
1913 unescaped equal sign ends the string, otherwise only a : or \0
1914 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1917 The resulting string is *not* null-terminated, but may contain
1920 Note that both dest and src are char **; on return they point to
1921 the first free byte after the array and the character that ended
1922 the input string, respectively. */
1925 get_funky_string (char **dest, const char **src, bool equals_end,
1926 size_t *output_count)
1928 char num; /* For numerical codes */
1929 size_t count; /* Something to count with */
1931 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1936 p = *src; /* We don't want to double-indirect */
1937 q = *dest; /* the whole darn time. */
1939 count = 0; /* No characters counted in yet. */
1942 state = ST_GND; /* Start in ground state. */
1943 while (state < ST_END)
1947 case ST_GND: /* Ground state (no escapes) */
1952 state = ST_END; /* End of string */
1955 state = ST_BACKSLASH; /* Backslash scape sequence */
1959 state = ST_CARET; /* Caret escape */
1965 state = ST_END; /* End */
1968 /* else fall through */
1976 case ST_BACKSLASH: /* Backslash escaped character */
1987 state = ST_OCTAL; /* Octal sequence */
1992 state = ST_HEX; /* Hex sequence */
1995 case 'a': /* Bell */
1998 case 'b': /* Backspace */
2001 case 'e': /* Escape */
2004 case 'f': /* Form feed */
2007 case 'n': /* Newline */
2010 case 'r': /* Carriage return */
2016 case 'v': /* Vtab */
2019 case '?': /* Delete */
2022 case '_': /* Space */
2025 case '\0': /* End of string */
2026 state = ST_ERROR; /* Error! */
2028 default: /* Escaped character like \ ^ : = */
2032 if (state == ST_BACKSLASH)
2041 case ST_OCTAL: /* Octal sequence */
2042 if (*p < '0' || *p > '7')
2049 num = (num << 3) + (*(p++) - '0');
2052 case ST_HEX: /* Hex sequence */
2065 num = (num << 4) + (*(p++) - '0');
2073 num = (num << 4) + (*(p++) - 'a') + 10;
2081 num = (num << 4) + (*(p++) - 'A') + 10;
2091 case ST_CARET: /* Caret escape */
2092 state = ST_GND; /* Should be the next state... */
2093 if (*p >= '@' && *p <= '~')
2095 *(q++) = *(p++) & 037;
2114 *output_count = count;
2116 return state != ST_ERROR;
2120 parse_ls_color (void)
2122 const char *p; /* Pointer to character being parsed */
2123 char *buf; /* color_buf buffer pointer */
2124 int state; /* State of parser */
2125 int ind_no; /* Indicator number */
2126 char label[3]; /* Indicator label */
2127 struct color_ext_type *ext; /* Extension we are working on */
2129 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2133 strcpy (label, "??");
2135 /* This is an overly conservative estimate, but any possible
2136 LS_COLORS string will *not* generate a color_buf longer than
2137 itself, so it is a safe way of allocating a buffer in
2139 buf = color_buf = xstrdup (p);
2146 case 1: /* First label character */
2154 /* Allocate new extension block and add to head of
2155 linked list (this way a later definition will
2156 override an earlier one, which can be useful for
2157 having terminal-specific defs override global). */
2159 ext = xmalloc (sizeof *ext);
2160 ext->next = color_ext_list;
2161 color_ext_list = ext;
2164 ext->ext.string = buf;
2166 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2171 state = 0; /* Done! */
2174 default: /* Assume it is file type label */
2181 case 2: /* Second label character */
2188 state = -1; /* Error */
2191 case 3: /* Equal sign after indicator label */
2192 state = -1; /* Assume failure... */
2193 if (*(p++) == '=')/* It *should* be... */
2195 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2197 if (STREQ (label, indicator_name[ind_no]))
2199 color_indicator[ind_no].string = buf;
2200 state = (get_funky_string (&buf, &p, false,
2201 &color_indicator[ind_no].len)
2207 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2211 case 4: /* Equal sign after *.ext */
2214 ext->seq.string = buf;
2215 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2226 struct color_ext_type *e;
2227 struct color_ext_type *e2;
2230 _("unparsable value for LS_COLORS environment variable"));
2232 for (e = color_ext_list; e != NULL; /* empty */)
2238 print_with_color = false;
2241 if (color_indicator[C_LINK].len == 6
2242 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2243 color_symlink_as_referent = true;
2246 /* Set the exit status to report a failure. If SERIOUS, it is a
2247 serious failure; otherwise, it is merely a minor problem. */
2250 set_exit_status (bool serious)
2253 exit_status = LS_FAILURE;
2254 else if (exit_status == EXIT_SUCCESS)
2255 exit_status = LS_MINOR_PROBLEM;
2258 /* Assuming a failure is serious if SERIOUS, use the printf-style
2259 MESSAGE to report the failure to access a file named FILE. Assume
2260 errno is set appropriately for the failure. */
2263 file_failure (bool serious, char const *message, char const *file)
2265 error (0, errno, message, quotearg_colon (file));
2266 set_exit_status (serious);
2269 /* Request that the directory named NAME have its contents listed later.
2270 If REALNAME is nonzero, it will be used instead of NAME when the
2271 directory name is printed. This allows symbolic links to directories
2272 to be treated as regular directories but still be listed under their
2273 real names. NAME == NULL is used to insert a marker entry for the
2274 directory named in REALNAME.
2275 If NAME is non-NULL, we use its dev/ino information to save
2276 a call to stat -- when doing a recursive (-R) traversal.
2277 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2280 queue_directory (char const *name, char const *realname, bool command_line_arg)
2282 struct pending *new = xmalloc (sizeof *new);
2283 new->realname = realname ? xstrdup (realname) : NULL;
2284 new->name = name ? xstrdup (name) : NULL;
2285 new->command_line_arg = command_line_arg;
2286 new->next = pending_dirs;
2290 /* Read directory NAME, and list the files in it.
2291 If REALNAME is nonzero, print its name instead of NAME;
2292 this is used for symbolic links to directories.
2293 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2296 print_dir (char const *name, char const *realname, bool command_line_arg)
2299 struct dirent *next;
2300 uintmax_t total_blocks = 0;
2301 static bool first = true;
2304 dirp = opendir (name);
2307 file_failure (command_line_arg, "%s", name);
2313 struct stat dir_stat;
2314 int fd = dirfd (dirp);
2316 /* If dirfd failed, endure the overhead of using stat. */
2318 ? fstat (fd, &dir_stat)
2319 : stat (name, &dir_stat)) < 0)
2321 file_failure (command_line_arg,
2322 _("cannot determine device and inode of %s"), name);
2326 /* If we've already visited this dev/inode pair, warn that
2327 we've found a loop, and do not process this directory. */
2328 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2330 error (0, 0, _("%s: not listing already-listed directory"),
2331 quotearg_colon (name));
2335 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2338 /* Read the directory entries, and insert the subfiles into the `files'
2345 /* Set errno to zero so we can distinguish between a readdir failure
2346 and when readdir simply finds that there are no more entries. */
2348 next = readdir (dirp);
2351 if (! file_ignored (next->d_name))
2353 enum filetype type = unknown;
2355 #if HAVE_STRUCT_DIRENT_D_TYPE
2356 if (next->d_type == DT_BLK
2357 || next->d_type == DT_CHR
2358 || next->d_type == DT_DIR
2359 || next->d_type == DT_FIFO
2360 || next->d_type == DT_LNK
2361 || next->d_type == DT_REG
2362 || next->d_type == DT_SOCK)
2363 type = next->d_type;
2365 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2369 else if (errno != 0)
2371 file_failure (command_line_arg, _("reading directory %s"), name);
2372 if (errno != EOVERFLOW)
2379 if (CLOSEDIR (dirp) != 0)
2381 file_failure (command_line_arg, _("closing directory %s"), name);
2382 /* Don't return; print whatever we got. */
2385 /* Sort the directory contents. */
2388 /* If any member files are subdirectories, perhaps they should have their
2389 contents listed rather than being mentioned here as files. */
2392 extract_dirs_from_files (name, command_line_arg);
2394 if (recursive | print_dir_name)
2397 DIRED_PUTCHAR ('\n');
2400 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2401 dired_pos += quote_name (stdout, realname ? realname : name,
2402 dirname_quoting_options, NULL);
2403 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2404 DIRED_FPUTS_LITERAL (":\n", stdout);
2407 if (format == long_format || print_block_size)
2410 char buf[LONGEST_HUMAN_READABLE + 1];
2414 DIRED_FPUTS (p, stdout, strlen (p));
2415 DIRED_PUTCHAR (' ');
2416 p = human_readable (total_blocks, buf, human_output_opts,
2417 ST_NBLOCKSIZE, output_block_size);
2418 DIRED_FPUTS (p, stdout, strlen (p));
2419 DIRED_PUTCHAR ('\n');
2423 print_current_files ();
2426 /* Add `pattern' to the list of patterns for which files that match are
2430 add_ignore_pattern (const char *pattern)
2432 struct ignore_pattern *ignore;
2434 ignore = xmalloc (sizeof *ignore);
2435 ignore->pattern = pattern;
2436 /* Add it to the head of the linked list. */
2437 ignore->next = ignore_patterns;
2438 ignore_patterns = ignore;
2441 /* Return true if one of the PATTERNS matches FILE. */
2444 patterns_match (struct ignore_pattern const *patterns, char const *file)
2446 struct ignore_pattern const *p;
2447 for (p = patterns; p; p = p->next)
2448 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2453 /* Return true if FILE should be ignored. */
2456 file_ignored (char const *name)
2458 return ((ignore_mode != IGNORE_MINIMAL
2460 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2461 || (ignore_mode == IGNORE_DEFAULT
2462 && patterns_match (hide_patterns, name))
2463 || patterns_match (ignore_patterns, name));
2466 /* POSIX requires that a file size be printed without a sign, even
2467 when negative. Assume the typical case where negative sizes are
2468 actually positive values that have wrapped around. */
2471 unsigned_file_size (off_t size)
2473 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2476 /* Enter and remove entries in the table `files'. */
2478 /* Empty the table of files. */
2485 for (i = 0; i < files_index; i++)
2487 free (files[i].name);
2488 free (files[i].linkname);
2493 any_has_acl = false;
2495 inode_number_width = 0;
2496 block_size_width = 0;
2501 major_device_number_width = 0;
2502 minor_device_number_width = 0;
2503 file_size_width = 0;
2506 /* Add a file to the current table of files.
2507 Verify that the file exists, and print an error message if it does not.
2508 Return the number of blocks that the file occupies. */
2511 gobble_file (char const *name, enum filetype type, ino_t inode,
2512 bool command_line_arg, char const *dirname)
2517 /* An inode value prior to gobble_file necessarily came from readdir,
2518 which is not used for command line arguments. */
2519 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2521 if (files_index == nfiles)
2523 files = xnrealloc (files, nfiles, 2 * sizeof *files);
2527 f = &files[files_index];
2532 if (command_line_arg
2533 || format_needs_stat
2535 && (inode == NOT_AN_INODE_NUMBER
2536 /* When dereferencing symlinks, the inode must come from
2537 stat, but readdir provides the inode of lstat. Command
2538 line dereferences are already taken care of by the above
2539 assertion that the inode number is not yet known. */
2540 || (dereference == DEREF_ALWAYS
2541 && (type == symbolic_link || type == unknown))))
2542 || (format_needs_type
2545 /* FIXME: remove this disjunct.
2546 I don't think we care about symlinks here, but for now
2547 this won't make a big performance difference. */
2548 || type == symbolic_link
2550 /* --indicator-style=classify (aka -F)
2551 requires that we stat each regular file
2552 to see if it's executable. */
2553 || (type == normal && (indicator_style == classify
2554 /* This is so that --color ends up
2555 highlighting files with the executable
2556 bit set even when options like -F are
2558 || (print_with_color
2559 && is_colored (C_EXEC))
2563 /* Absolute name of this file. */
2564 char *absolute_name;
2568 if (name[0] == '/' || dirname[0] == 0)
2569 absolute_name = (char *) name;
2572 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2573 attach (absolute_name, dirname, name);
2576 switch (dereference)
2579 err = stat (absolute_name, &f->stat);
2582 case DEREF_COMMAND_LINE_ARGUMENTS:
2583 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2584 if (command_line_arg)
2587 err = stat (absolute_name, &f->stat);
2589 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2592 need_lstat = (err < 0
2594 : ! S_ISDIR (f->stat.st_mode));
2598 /* stat failed because of ENOENT, maybe indicating a dangling
2599 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2600 directory, and --dereference-command-line-symlink-to-dir is
2601 in effect. Fall through so that we call lstat instead. */
2604 default: /* DEREF_NEVER */
2605 err = lstat (absolute_name, &f->stat);
2611 file_failure (command_line_arg, "%s", absolute_name);
2616 if (format == long_format)
2618 int n = file_has_acl (absolute_name, &f->stat);
2619 f->have_acl = (0 < n);
2620 any_has_acl |= f->have_acl;
2622 error (0, errno, "%s", quotearg_colon (absolute_name));
2626 if (S_ISLNK (f->stat.st_mode)
2627 && (format == long_format || check_symlink_color))
2630 struct stat linkstats;
2632 get_link_name (absolute_name, f, command_line_arg);
2633 linkname = make_link_name (absolute_name, f->linkname);
2635 /* Avoid following symbolic links when possible, ie, when
2636 they won't be traced and when no indicator is needed. */
2638 && (file_type <= indicator_style || check_symlink_color)
2639 && stat (linkname, &linkstats) == 0)
2643 /* Symbolic links to directories that are mentioned on the
2644 command line are automatically traced if not being
2646 if (!command_line_arg || format == long_format
2647 || !S_ISDIR (linkstats.st_mode))
2649 /* Get the linked-to file's mode for the filetype indicator
2650 in long listings. */
2651 f->linkmode = linkstats.st_mode;
2658 if (S_ISLNK (f->stat.st_mode))
2659 f->filetype = symbolic_link;
2660 else if (S_ISDIR (f->stat.st_mode))
2662 if (command_line_arg & !immediate_dirs)
2663 f->filetype = arg_directory;
2665 f->filetype = directory;
2668 f->filetype = normal;
2670 blocks = ST_NBLOCKS (f->stat);
2672 char buf[LONGEST_HUMAN_READABLE + 1];
2673 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2674 ST_NBLOCKSIZE, output_block_size),
2676 if (block_size_width < len)
2677 block_size_width = len;
2682 int len = format_user_width (f->stat.st_uid);
2683 if (owner_width < len)
2689 int len = format_group_width (f->stat.st_gid);
2690 if (group_width < len)
2696 int len = format_user_width (f->stat.st_author);
2697 if (author_width < len)
2702 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2703 int len = strlen (umaxtostr (f->stat.st_nlink, buf));
2704 if (nlink_width < len)
2708 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2710 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2711 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2712 if (major_device_number_width < len)
2713 major_device_number_width = len;
2714 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2715 if (minor_device_number_width < len)
2716 minor_device_number_width = len;
2717 len = major_device_number_width + 2 + minor_device_number_width;
2718 if (file_size_width < len)
2719 file_size_width = len;
2723 char buf[LONGEST_HUMAN_READABLE + 1];
2724 uintmax_t size = unsigned_file_size (f->stat.st_size);
2725 int len = mbswidth (human_readable (size, buf, human_output_opts,
2726 1, file_output_block_size),
2728 if (file_size_width < len)
2729 file_size_width = len;
2735 f->stat.st_ino = inode;
2736 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
2737 f->stat.st_mode = DTTOIF (type);
2744 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2745 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2746 if (inode_number_width < len)
2747 inode_number_width = len;
2750 f->name = xstrdup (name);
2756 /* Return true if F refers to a directory. */
2758 is_directory (const struct fileinfo *f)
2760 return f->filetype == directory || f->filetype == arg_directory;
2766 /* Put the name of the file that FILENAME is a symbolic link to
2767 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2768 FILENAME is a command-line argument. */
2771 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2773 f->linkname = xreadlink (filename, f->stat.st_size);
2774 if (f->linkname == NULL)
2775 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2779 /* If `linkname' is a relative name and `name' contains one or more
2780 leading directories, return `linkname' with those directories
2781 prepended; otherwise, return a copy of `linkname'.
2782 If `linkname' is zero, return zero. */
2785 make_link_name (char const *name, char const *linkname)
2793 if (*linkname == '/')
2794 return xstrdup (linkname);
2796 /* The link is to a relative name. Prepend any leading directory
2797 in `name' to the link name. */
2798 linkbuf = strrchr (name, '/');
2800 return xstrdup (linkname);
2802 bufsiz = linkbuf - name + 1;
2803 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2804 strncpy (linkbuf, name, bufsiz);
2805 strcpy (linkbuf + bufsiz, linkname);
2810 /* Return true if the last component of NAME is `.' or `..'
2811 This is so we don't try to recurse on `././././. ...' */
2814 basename_is_dot_or_dotdot (const char *name)
2816 char const *base = last_component (name);
2817 return DOT_OR_DOTDOT (base);
2820 /* Remove any entries from FILES that are for directories,
2821 and queue them to be listed as directories instead.
2822 DIRNAME is the prefix to prepend to each dirname
2823 to make it correct relative to ls's working dir;
2824 if it is null, no prefix is needed and "." and ".." should not be ignored.
2825 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2826 This is desirable when processing directories recursively. */
2829 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2833 bool ignore_dot_and_dot_dot = (dirname != NULL);
2835 if (dirname && LOOP_DETECT)
2837 /* Insert a marker entry first. When we dequeue this marker entry,
2838 we'll know that DIRNAME has been processed and may be removed
2839 from the set of active directories. */
2840 queue_directory (NULL, dirname, false);
2843 /* Queue the directories last one first, because queueing reverses the
2845 for (i = files_index; i-- != 0; )
2846 if (is_directory (&files[i])
2847 && (! ignore_dot_and_dot_dot
2848 || ! basename_is_dot_or_dotdot (files[i].name)))
2850 if (!dirname || files[i].name[0] == '/')
2852 queue_directory (files[i].name, files[i].linkname,
2857 char *name = file_name_concat (dirname, files[i].name, NULL);
2858 queue_directory (name, files[i].linkname, command_line_arg);
2861 if (files[i].filetype == arg_directory)
2862 free (files[i].name);
2865 /* Now delete the directories from the table, compacting all the remaining
2868 for (i = 0, j = 0; i < files_index; i++)
2870 if (files[i].filetype != arg_directory)
2873 files[j] = files[i];
2880 /* Use strcoll to compare strings in this locale. If an error occurs,
2881 report an error and longjmp to failed_strcoll. */
2883 static jmp_buf failed_strcoll;
2886 xstrcoll (char const *a, char const *b)
2890 diff = strcoll (a, b);
2893 error (0, errno, _("cannot compare file names %s and %s"),
2894 quote_n (0, a), quote_n (1, b));
2895 set_exit_status (false);
2896 longjmp (failed_strcoll, 1);
2901 /* Comparison routines for sorting the files. */
2903 typedef void const *V;
2904 typedef int (*qsortFunc)(V a, V b);
2906 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
2907 The do { ... } while(0) makes it possible to use the macro more like
2908 a statement, without violating C89 rules: */
2909 #define DIRFIRST_CHECK(a, b) \
2912 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
2913 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
2914 if (a_is_dir && !b_is_dir) \
2915 return -1; /* a goes before b */ \
2916 if (!a_is_dir && b_is_dir) \
2917 return 1; /* b goes before a */ \
2921 /* Define the 8 different sort function variants required for each sortkey.
2922 The 'basefunc' should be an inline function so that compiler will be able
2923 to optimize all these functions. The 'basename' argument is prefixed with
2924 the '[rev_][x]str{cmp|coll}[_df]_' string to create the function name. */
2925 #define DEFINE_SORT_FUNCTIONS(basename, basefunc) \
2926 /* direct, non-dirfirst versions */ \
2927 static int xstrcoll_##basename (V a, V b) \
2928 { return basefunc (a, b, xstrcoll); } \
2929 static int strcmp_##basename (V a, V b) \
2930 { return basefunc (a, b, strcmp); } \
2932 /* reverse, non-dirfirst versions */ \
2933 static int rev_xstrcoll_##basename (V a, V b) \
2934 { return basefunc (b, a, xstrcoll); } \
2935 static int rev_strcmp_##basename (V a, V b) \
2936 { return basefunc (b, a, strcmp); } \
2938 /* direct, dirfirst versions */ \
2939 static int xstrcoll_df_##basename (V a, V b) \
2940 { DIRFIRST_CHECK (a, b); return basefunc (a, b, xstrcoll); } \
2941 static int strcmp_df_##basename (V a, V b) \
2942 { DIRFIRST_CHECK (a, b); return basefunc (a, b, strcmp); } \
2944 /* reverse, dirfirst versions */ \
2945 static int rev_xstrcoll_df_##basename (V a, V b) \
2946 { DIRFIRST_CHECK (a, b); return basefunc (b, a, xstrcoll); } \
2947 static int rev_strcmp_df_##basename (V a, V b) \
2948 { DIRFIRST_CHECK (a, b); return basefunc (b, a, strcmp); }
2951 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2952 int (*cmp) (char const *, char const *))
2954 int diff = timespec_cmp (get_stat_ctime (&b->stat),
2955 get_stat_ctime (&a->stat));
2956 return diff ? diff : cmp (a->name, b->name);
2960 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2961 int (*cmp) (char const *, char const *))
2963 int diff = timespec_cmp (get_stat_mtime (&b->stat),
2964 get_stat_mtime (&a->stat));
2965 return diff ? diff : cmp (a->name, b->name);
2969 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2970 int (*cmp) (char const *, char const *))
2972 int diff = timespec_cmp (get_stat_atime (&b->stat),
2973 get_stat_atime (&a->stat));
2974 return diff ? diff : cmp (a->name, b->name);
2978 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2979 int (*cmp) (char const *, char const *))
2981 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2982 return diff ? diff : cmp (a->name, b->name);
2986 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2987 int (*cmp) (char const *, char const *))
2989 return cmp (a->name, b->name);
2992 /* Compare file extensions. Files with no extension are `smallest'.
2993 If extensions are the same, compare by filenames instead. */
2996 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2997 int (*cmp) (char const *, char const *))
2999 char const *base1 = strrchr (a->name, '.');
3000 char const *base2 = strrchr (b->name, '.');
3001 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3002 return diff ? diff : cmp (a->name, b->name);
3005 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3006 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3007 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3008 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3009 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3010 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3012 /* Compare file versions.
3013 Unlike all other compare functions above, cmp_version depends only
3014 on strverscmp, which does not fail (even for locale reasons), and does not
3015 need a secondary sort key.
3016 All the other sort options, in fact, need xstrcoll and strcmp variants,
3017 because they all use a string comparison (either as the primary or secondary
3018 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3019 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3020 thanks to the gnulib library. */
3022 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3024 return strverscmp (a->name, b->name);
3027 static int xstrcoll_version (V a, V b)
3028 { return cmp_version (a, b); }
3029 static int rev_xstrcoll_version (V a, V b)
3030 { return cmp_version (b, a); }
3031 static int xstrcoll_df_version (V a, V b)
3032 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3033 static int rev_xstrcoll_df_version (V a, V b)
3034 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3037 /* We have 2^3 different variants for each sortkey function
3038 (for 3 indipendent sort modes).
3039 The function pointers stored in this array must be dereferenced as:
3041 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3043 Note that the order in which sortkeys are listed in the function pointer
3044 array below is defined by the order of the elements in the time_type and
3047 #define LIST_SORTFUNCTION_VARIANTS(basename) \
3050 { xstrcoll_##basename, xstrcoll_df_##basename }, \
3051 { rev_xstrcoll_##basename, rev_xstrcoll_df_##basename }, \
3054 { strcmp_##basename, strcmp_df_##basename }, \
3055 { rev_strcmp_##basename, rev_strcmp_df_##basename }, \
3059 static qsortFunc sort_functions[][2][2][2] =
3061 LIST_SORTFUNCTION_VARIANTS (name),
3062 LIST_SORTFUNCTION_VARIANTS (extension),
3063 LIST_SORTFUNCTION_VARIANTS (size),
3067 { xstrcoll_version, xstrcoll_df_version },
3068 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3071 /* We use NULL for the strcmp variants of version comparison
3072 since as explained in cmp_version definition, version comparison
3073 does not rely on xstrcoll, so it will never longjmp, and never
3074 need to try the strcmp fallback. */
3081 /* last are time sort functions */
3082 LIST_SORTFUNCTION_VARIANTS (mtime),
3083 LIST_SORTFUNCTION_VARIANTS (ctime),
3084 LIST_SORTFUNCTION_VARIANTS (atime)
3087 /* The number of sortkeys is calculated as
3088 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3089 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3090 This is because when sort_type==sort_time, we have up to
3091 time_numtypes possible sortkeys.
3093 This line verifies at compile-time that the array of sort functions has been
3094 initialized for all possible sortkeys. */
3095 verify (ARRAY_CARDINALITY (sort_functions)
3096 == sort_numtypes + time_numtypes - 1 );
3099 /* Sort the files now in the table. */
3106 if (sort_type == sort_none)
3109 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3110 ignore strcoll failures, as a failing strcoll might be a
3111 comparison function that is not a total order, and if we ignored
3112 the failure this might cause qsort to dump core. */
3114 if (! setjmp (failed_strcoll))
3115 use_strcmp = false; /* strcoll() succeeded */
3119 assert (sort_type != sort_version);
3122 /* When sort_type == sort_time, use time_type as subindex. */
3123 int timeoffset = sort_type == sort_time ? time_type : 0;
3125 qsort (files, files_index, sizeof *files,
3126 sort_functions[sort_type + timeoffset][use_strcmp][sort_reverse]
3127 [directories_first]);
3130 /* List all the files now in the table. */
3133 print_current_files (void)
3140 for (i = 0; i < files_index; i++)
3142 print_file_name_and_frills (files + i);
3148 print_many_per_line ();
3152 print_horizontal ();
3156 print_with_commas ();
3160 for (i = 0; i < files_index; i++)
3162 print_long_format (files + i);
3163 DIRED_PUTCHAR ('\n');
3169 /* Return the expected number of columns in a long-format time stamp,
3170 or zero if it cannot be calculated. */
3173 long_time_expected_width (void)
3175 static int width = -1;
3180 struct tm const *tm = localtime (&epoch);
3181 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3183 /* In case you're wondering if localtime can fail with an input time_t
3184 value of 0, let's just say it's very unlikely, but not inconceivable.
3185 The TZ environment variable would have to specify a time zone that
3186 is 2**31-1900 years or more ahead of UTC. This could happen only on
3187 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3188 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3189 their implementations limit the offset to 167:59 and 24:00, resp. */
3193 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3195 width = mbsnwidth (buf, len, 0);
3205 /* Get the current time. */
3208 get_current_time (void)
3210 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
3212 struct timespec timespec;
3213 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
3215 current_time = timespec.tv_sec;
3216 current_time_ns = timespec.tv_nsec;
3222 /* The clock does not have nanosecond resolution, so get the maximum
3223 possible value for the current time that is consistent with the
3224 reported clock. That way, files are not considered to be in the
3225 future merely because their time stamps have higher resolution
3226 than the clock resolution. */
3228 #if HAVE_GETTIMEOFDAY
3230 struct timeval timeval;
3231 gettimeofday (&timeval, NULL);
3232 current_time = timeval.tv_sec;
3233 current_time_ns = timeval.tv_usec * 1000 + 999;
3236 current_time = time (NULL);
3237 current_time_ns = 999999999;
3241 /* Print the user or group name NAME, with numeric id ID, using a
3242 print width of WIDTH columns. */
3245 format_user_or_group (char const *name, unsigned long int id, int width)
3251 int width_gap = width - mbswidth (name, 0);
3252 int pad = MAX (0, width_gap);
3253 fputs (name, stdout);
3254 len = strlen (name) + pad;
3262 printf ("%*lu ", width, id);
3266 dired_pos += len + 1;
3269 /* Print the name or id of the user with id U, using a print width of
3273 format_user (uid_t u, int width)
3275 format_user_or_group (numeric_ids ? NULL : getuser (u), u, width);
3278 /* Likewise, for groups. */
3281 format_group (gid_t g, int width)
3283 format_user_or_group (numeric_ids ? NULL : getgroup (g), g, width);
3286 /* Return the number of columns that format_user_or_group will print. */
3289 format_user_or_group_width (char const *name, unsigned long int id)
3293 int len = mbswidth (name, 0);
3294 return MAX (0, len);
3298 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3299 sprintf (buf, "%lu", id);
3300 return strlen (buf);
3304 /* Return the number of columns that format_user will print. */
3307 format_user_width (uid_t u)
3309 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3312 /* Likewise, for groups. */
3315 format_group_width (gid_t g)
3317 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3321 /* Print information about F in long format. */
3324 print_long_format (const struct fileinfo *f)
3328 [LONGEST_HUMAN_READABLE + 1 /* inode */
3329 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3330 + sizeof (modebuf) - 1 + 1 /* mode string */
3331 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3332 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3333 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3334 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3340 struct timespec when_timespec;
3341 struct tm *when_local;
3343 /* Compute the mode string, except remove the trailing space if no
3344 files in this directory have ACLs. */
3345 filemodestring (&f->stat, modebuf);
3348 else if (FILE_HAS_ACL (f))
3354 when_timespec = get_stat_ctime (&f->stat);
3357 when_timespec = get_stat_mtime (&f->stat);
3360 when_timespec = get_stat_atime (&f->stat);
3366 when = when_timespec.tv_sec;
3367 when_ns = when_timespec.tv_nsec;
3373 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3374 sprintf (p, "%*s ", inode_number_width,
3375 umaxtostr (f->stat.st_ino, hbuf));
3376 p += inode_number_width + 1;
3379 if (print_block_size)
3381 char hbuf[LONGEST_HUMAN_READABLE + 1];
3382 char const *blocks =
3383 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3384 ST_NBLOCKSIZE, output_block_size);
3386 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3388 while ((*p++ = *blocks++))
3393 /* The last byte of the mode string is the POSIX
3394 "optional alternate access method flag". */
3396 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3397 sprintf (p, "%s %*s ", modebuf, nlink_width,
3398 umaxtostr (f->stat.st_nlink, hbuf));
3400 p += sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1;
3404 if (print_owner | print_group | print_author)
3406 DIRED_FPUTS (buf, stdout, p - buf);
3409 format_user (f->stat.st_uid, owner_width);
3412 format_group (f->stat.st_gid, group_width);
3415 format_user (f->stat.st_author, author_width);
3420 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3422 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3423 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3424 int blanks_width = (file_size_width
3425 - (major_device_number_width + 2
3426 + minor_device_number_width));
3427 sprintf (p, "%*s, %*s ",
3428 major_device_number_width + MAX (0, blanks_width),
3429 umaxtostr (major (f->stat.st_rdev), majorbuf),
3430 minor_device_number_width,
3431 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3432 p += file_size_width + 1;
3436 char hbuf[LONGEST_HUMAN_READABLE + 1];
3438 human_readable (unsigned_file_size (f->stat.st_size),
3439 hbuf, human_output_opts, 1, file_output_block_size);
3441 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3443 while ((*p++ = *size++))
3448 when_local = localtime (&when_timespec.tv_sec);
3454 time_t six_months_ago;
3458 /* If the file appears to be in the future, update the current
3459 time, in case the file happens to have been modified since
3460 the last time we checked the clock. */
3461 if (current_time < when
3462 || (current_time == when && current_time_ns < when_ns))
3464 /* Note that get_current_time calls gettimeofday which, on some non-
3465 compliant systems, clobbers the buffer used for localtime's result.
3466 But it's ok here, because we use a gettimeofday wrapper that
3467 saves and restores the buffer around the gettimeofday call. */
3468 get_current_time ();
3471 /* Consider a time to be recent if it is within the past six
3472 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3473 31556952 seconds on the average. Write this value as an
3474 integer constant to avoid floating point hassles. */
3475 six_months_ago = current_time - 31556952 / 2;
3476 recent = (six_months_ago <= when
3477 && (when < current_time
3478 || (when == current_time && when_ns <= current_time_ns)));
3479 fmt = long_time_format[recent];
3481 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3482 when_local, 0, when_ns);
3490 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3495 /* The time cannot be converted using the desired format, so
3496 print it as a huge integer number of seconds. */
3497 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3498 sprintf (p, "%*s ", long_time_expected_width (),
3499 (TYPE_SIGNED (time_t)
3500 ? imaxtostr (when, hbuf)
3501 : umaxtostr (when, hbuf)));
3505 DIRED_FPUTS (buf, stdout, p - buf);
3506 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3509 if (f->filetype == symbolic_link)
3513 DIRED_FPUTS_LITERAL (" -> ", stdout);
3514 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3516 if (indicator_style != none)
3517 print_type_indicator (f->linkmode);
3520 else if (indicator_style != none)
3521 print_type_indicator (f->stat.st_mode);
3524 /* Output to OUT a quoted representation of the file name NAME,
3525 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3526 Store the number of screen columns occupied by NAME's quoted
3527 representation into WIDTH, if non-NULL. Return the number of bytes
3531 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3534 char smallbuf[BUFSIZ];
3535 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3537 size_t displayed_width IF_LINT (= 0);
3539 if (len < sizeof smallbuf)
3543 buf = alloca (len + 1);
3544 quotearg_buffer (buf, len + 1, name, -1, options);
3547 if (qmark_funny_chars)
3552 char const *p = buf;
3553 char const *plimit = buf + len;
3555 displayed_width = 0;
3560 case ' ': case '!': case '"': case '#': case '%':
3561 case '&': case '\'': case '(': case ')': case '*':
3562 case '+': case ',': case '-': case '.': case '/':
3563 case '0': case '1': case '2': case '3': case '4':
3564 case '5': case '6': case '7': case '8': case '9':
3565 case ':': case ';': case '<': case '=': case '>':
3567 case 'A': case 'B': case 'C': case 'D': case 'E':
3568 case 'F': case 'G': case 'H': case 'I': case 'J':
3569 case 'K': case 'L': case 'M': case 'N': case 'O':
3570 case 'P': case 'Q': case 'R': case 'S': case 'T':
3571 case 'U': case 'V': case 'W': case 'X': case 'Y':
3573 case '[': case '\\': case ']': case '^': case '_':
3574 case 'a': case 'b': case 'c': case 'd': case 'e':
3575 case 'f': case 'g': case 'h': case 'i': case 'j':
3576 case 'k': case 'l': case 'm': case 'n': case 'o':
3577 case 'p': case 'q': case 'r': case 's': case 't':
3578 case 'u': case 'v': case 'w': case 'x': case 'y':
3579 case 'z': case '{': case '|': case '}': case '~':
3580 /* These characters are printable ASCII characters. */
3582 displayed_width += 1;
3585 /* If we have a multibyte sequence, copy it until we
3586 reach its end, replacing each non-printable multibyte
3587 character with a single question mark. */
3590 memset (&mbstate, 0, sizeof mbstate);
3597 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3599 if (bytes == (size_t) -1)
3601 /* An invalid multibyte sequence was
3602 encountered. Skip one input byte, and
3603 put a question mark. */
3606 displayed_width += 1;
3610 if (bytes == (size_t) -2)
3612 /* An incomplete multibyte character
3613 at the end. Replace it entirely with
3617 displayed_width += 1;
3622 /* A null wide character was encountered. */
3628 /* A printable multibyte character.
3630 for (; bytes > 0; --bytes)
3632 displayed_width += w;
3636 /* An unprintable multibyte character.
3637 Replace it entirely with a question
3641 displayed_width += 1;
3644 while (! mbsinit (&mbstate));
3649 /* The buffer may have shrunk. */
3656 char const *plimit = buf + len;
3660 if (! ISPRINT (to_uchar (*p)))
3664 displayed_width = len;
3667 else if (width != NULL)
3671 displayed_width = mbsnwidth (buf, len, 0);
3675 char const *p = buf;
3676 char const *plimit = buf + len;
3678 displayed_width = 0;
3681 if (ISPRINT (to_uchar (*p)))
3689 fwrite (buf, 1, len, out);
3691 *width = displayed_width;
3696 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3697 struct obstack *stack)
3699 if (print_with_color)
3700 print_color_indicator (p, mode, linkok);
3703 PUSH_CURRENT_DIRED_POS (stack);
3705 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3708 PUSH_CURRENT_DIRED_POS (stack);
3710 if (print_with_color)
3713 prep_non_filename_text ();
3718 prep_non_filename_text (void)
3720 if (color_indicator[C_END].string != NULL)
3721 put_indicator (&color_indicator[C_END]);
3724 put_indicator (&color_indicator[C_LEFT]);
3725 put_indicator (&color_indicator[C_NORM]);
3726 put_indicator (&color_indicator[C_RIGHT]);
3730 /* Print the file name of `f' with appropriate quoting.
3731 Also print file size, inode number, and filetype indicator character,
3732 as requested by switches. */
3735 print_file_name_and_frills (const struct fileinfo *f)
3737 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3740 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3741 umaxtostr (f->stat.st_ino, buf));
3743 if (print_block_size)
3744 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3745 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3746 ST_NBLOCKSIZE, output_block_size));
3748 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3750 if (indicator_style != none)
3751 print_type_indicator (f->stat.st_mode);
3755 print_type_indicator (mode_t mode)
3761 if (indicator_style == classify && (mode & S_IXUGO))
3770 else if (indicator_style == slash)
3772 else if (S_ISLNK (mode))
3774 else if (S_ISFIFO (mode))
3776 else if (S_ISSOCK (mode))
3778 else if (S_ISDOOR (mode))
3789 print_color_indicator (const char *name, mode_t mode, int linkok)
3792 struct color_ext_type *ext; /* Color extension */
3793 size_t len; /* Length of name */
3795 /* Is this a nonexistent file? If so, linkok == -1. */
3797 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3806 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3807 type = C_STICKY_OTHER_WRITABLE;
3808 else if ((mode & S_IWOTH) != 0)
3809 type = C_OTHER_WRITABLE;
3810 else if ((mode & S_ISVTX) != 0)
3815 else if (S_ISLNK (mode))
3816 type = ((!linkok && color_indicator[C_ORPHAN].string)
3817 ? C_ORPHAN : C_LINK);
3818 else if (S_ISFIFO (mode))
3820 else if (S_ISSOCK (mode))
3822 else if (S_ISBLK (mode))
3824 else if (S_ISCHR (mode))
3826 else if (S_ISDOOR (mode))
3831 if ((mode & S_ISUID) != 0)
3833 else if ((mode & S_ISGID) != 0)
3835 else if ((mode & S_IXUGO) != 0)
3839 /* Check the file's suffix only if still classified as C_FILE. */
3843 /* Test if NAME has a recognized suffix. */
3845 len = strlen (name);
3846 name += len; /* Pointer to final \0. */
3847 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3849 if (ext->ext.len <= len
3850 && strncmp (name - ext->ext.len, ext->ext.string,
3857 put_indicator (&color_indicator[C_LEFT]);
3858 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3859 put_indicator (&color_indicator[C_RIGHT]);
3862 /* Output a color indicator (which may contain nulls). */
3864 put_indicator (const struct bin_str *ind)
3871 for (i = ind->len; i != 0; --i)
3876 length_of_file_name_and_frills (const struct fileinfo *f)
3880 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3883 len += 1 + (format == with_commas
3884 ? strlen (umaxtostr (f->stat.st_ino, buf))
3885 : inode_number_width);
3887 if (print_block_size)
3888 len += 1 + (format == with_commas
3889 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
3890 human_output_opts, ST_NBLOCKSIZE,
3892 : block_size_width);
3894 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3897 if (indicator_style != none)
3899 mode_t mode = f->stat.st_mode;
3901 len += (S_ISREG (mode)
3902 ? (indicator_style == classify && (mode & S_IXUGO))
3904 || (indicator_style != slash
3908 || S_ISDOOR (mode)))));
3915 print_many_per_line (void)
3917 size_t row; /* Current row. */
3918 size_t cols = calculate_columns (true);
3919 struct column_info const *line_fmt = &column_info[cols - 1];
3921 /* Calculate the number of rows that will be in each column except possibly
3922 for a short column on the right. */
3923 size_t rows = files_index / cols + (files_index % cols != 0);
3925 for (row = 0; row < rows; row++)
3928 size_t filesno = row;
3931 /* Print the next row. */
3934 size_t name_length = length_of_file_name_and_frills (files + filesno);
3935 size_t max_name_length = line_fmt->col_arr[col++];
3936 print_file_name_and_frills (files + filesno);
3939 if (filesno >= files_index)
3942 indent (pos + name_length, pos + max_name_length);
3943 pos += max_name_length;
3950 print_horizontal (void)
3954 size_t cols = calculate_columns (false);
3955 struct column_info const *line_fmt = &column_info[cols - 1];
3956 size_t name_length = length_of_file_name_and_frills (files);
3957 size_t max_name_length = line_fmt->col_arr[0];
3959 /* Print first entry. */
3960 print_file_name_and_frills (files);
3963 for (filesno = 1; filesno < files_index; ++filesno)
3965 size_t col = filesno % cols;
3974 indent (pos + name_length, pos + max_name_length);
3975 pos += max_name_length;
3978 print_file_name_and_frills (files + filesno);
3980 name_length = length_of_file_name_and_frills (files + filesno);
3981 max_name_length = line_fmt->col_arr[col];
3987 print_with_commas (void)
3992 for (filesno = 0; filesno < files_index; filesno++)
3994 size_t len = length_of_file_name_and_frills (files + filesno);
4000 if (pos + len + 2 < line_length)
4012 putchar (separator);
4015 print_file_name_and_frills (files + filesno);
4021 /* Assuming cursor is at position FROM, indent up to position TO.
4022 Use a TAB character instead of two or more spaces whenever possible. */
4025 indent (size_t from, size_t to)
4029 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4032 from += tabsize - from % tabsize;
4042 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4043 /* FIXME: maybe remove this function someday. See about using a
4044 non-malloc'ing version of file_name_concat. */
4047 attach (char *dest, const char *dirname, const char *name)
4049 const char *dirnamep = dirname;
4051 /* Copy dirname if it is not ".". */
4052 if (dirname[0] != '.' || dirname[1] != 0)
4055 *dest++ = *dirnamep++;
4056 /* Add '/' if `dirname' doesn't already end with it. */
4057 if (dirnamep > dirname && dirnamep[-1] != '/')
4065 /* Allocate enough column info suitable for the current number of
4066 files and display columns, and initialize the info to represent the
4067 narrowest possible columns. */
4070 init_column_info (void)
4073 size_t max_cols = MIN (max_idx, files_index);
4075 /* Currently allocated columns in column_info. */
4076 static size_t column_info_alloc;
4078 if (column_info_alloc < max_cols)
4080 size_t new_column_info_alloc;
4083 if (max_cols < max_idx / 2)
4085 /* The number of columns is far less than the display width
4086 allows. Grow the allocation, but only so that it's
4087 double the current requirements. If the display is
4088 extremely wide, this avoids allocating a lot of memory
4089 that is never needed. */
4090 column_info = xnrealloc (column_info, max_cols,
4091 2 * sizeof *column_info);
4092 new_column_info_alloc = 2 * max_cols;
4096 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4097 new_column_info_alloc = max_idx;
4100 /* Allocate the new size_t objects by computing the triangle
4101 formula n * (n + 1) / 2, except that we don't need to
4102 allocate the part of the triangle that we've already
4103 allocated. Check for address arithmetic overflow. */
4105 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4106 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4107 size_t t = s * column_info_growth;
4108 if (s < new_column_info_alloc || t / column_info_growth != s)
4110 p = xnmalloc (t / 2, sizeof *p);
4113 /* Grow the triangle by parceling out the cells just allocated. */
4114 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4116 column_info[i].col_arr = p;
4120 column_info_alloc = new_column_info_alloc;
4123 for (i = 0; i < max_cols; ++i)
4127 column_info[i].valid_len = true;
4128 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4129 for (j = 0; j <= i; ++j)
4130 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4134 /* Calculate the number of columns needed to represent the current set
4135 of files in the current display width. */
4138 calculate_columns (bool by_columns)
4140 size_t filesno; /* Index into files. */
4141 size_t cols; /* Number of files across. */
4143 /* Normally the maximum number of columns is determined by the
4144 screen width. But if few files are available this might limit it
4146 size_t max_cols = MIN (max_idx, files_index);
4148 init_column_info ();
4150 /* Compute the maximum number of possible columns. */
4151 for (filesno = 0; filesno < files_index; ++filesno)
4153 size_t name_length = length_of_file_name_and_frills (files + filesno);
4156 for (i = 0; i < max_cols; ++i)
4158 if (column_info[i].valid_len)
4160 size_t idx = (by_columns
4161 ? filesno / ((files_index + i) / (i + 1))
4162 : filesno % (i + 1));
4163 size_t real_length = name_length + (idx == i ? 0 : 2);
4165 if (column_info[i].col_arr[idx] < real_length)
4167 column_info[i].line_len += (real_length
4168 - column_info[i].col_arr[idx]);
4169 column_info[i].col_arr[idx] = real_length;
4170 column_info[i].valid_len = (column_info[i].line_len
4177 /* Find maximum allowed columns. */
4178 for (cols = max_cols; 1 < cols; --cols)
4180 if (column_info[cols - 1].valid_len)
4190 if (status != EXIT_SUCCESS)
4191 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4195 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4197 List information about the FILEs (the current directory by default).\n\
4198 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
4202 Mandatory arguments to long options are mandatory for short options too.\n\
4205 -a, --all do not ignore entries starting with .\n\
4206 -A, --almost-all do not list implied . and ..\n\
4207 --author with -l, print the author of each file\n\
4208 -b, --escape print octal escapes for nongraphic characters\n\
4211 --block-size=SIZE use SIZE-byte blocks\n\
4212 -B, --ignore-backups do not list implied entries ending with ~\n\
4213 -c with -lt: sort by, and show, ctime (time of last\n\
4214 modification of file status information)\n\
4215 with -l: show ctime and sort by name\n\
4216 otherwise: sort by ctime\n\
4219 -C list entries by columns\n\
4220 --color[=WHEN] control whether color is used to distinguish file\n\
4221 types. WHEN may be `never', `always', or `auto'\n\
4222 -d, --directory list directory entries instead of contents,\n\
4223 and do not dereference symbolic links\n\
4224 -D, --dired generate output designed for Emacs' dired mode\n\
4227 -f do not sort, enable -aU, disable -ls --color\n\
4228 -F, --classify append indicator (one of */=>@|) to entries\n\
4229 --file-type likewise, except do not append `*'\n\
4230 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4231 single-column -1, verbose -l, vertical -C\n\
4232 --full-time like -l --time-style=full-iso\n\
4235 -g like -l, but do not list owner\n\
4238 --group-directories-first\n\
4239 group directories before files\n\
4242 -G, --no-group like -l, but do not list group\n\
4243 -h, --human-readable with -l, print sizes in human readable format\n\
4244 (e.g., 1K 234M 2G)\n\
4245 --si likewise, but use powers of 1000 not 1024\n\
4246 -H, --dereference-command-line\n\
4247 follow symbolic links listed on the command line\n\
4248 --dereference-command-line-symlink-to-dir\n\
4249 follow each command line symbolic link\n\
4250 that points to a directory\n\
4251 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4252 (overridden by -a or -A)\n\
4255 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4256 none (default), slash (-p),\n\
4257 file-type (--file-type), classify (-F)\n\
4258 -i, --inode print the index number of each file\n\
4259 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4260 -k like --block-size=1K\n\
4263 -l use a long listing format\n\
4264 -L, --dereference when showing file information for a symbolic\n\
4265 link, show information for the file the link\n\
4266 references rather than for the link itself\n\
4267 -m fill width with a comma separated list of entries\n\
4270 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4271 -N, --literal print raw entry names (don't treat e.g. control\n\
4272 characters specially)\n\
4273 -o like -l, but do not list group information\n\
4274 -p, --indicator-style=slash\n\
4275 append / indicator to directories\n\
4278 -q, --hide-control-chars print ? instead of non graphic characters\n\
4279 --show-control-chars show non graphic characters as-is (default\n\
4280 unless program is `ls' and output is a terminal)\n\
4281 -Q, --quote-name enclose entry names in double quotes\n\
4282 --quoting-style=WORD use quoting style WORD for entry names:\n\
4283 literal, locale, shell, shell-always, c, escape\n\
4286 -r, --reverse reverse order while sorting\n\
4287 -R, --recursive list subdirectories recursively\n\
4288 -s, --size with -l, print size of each file, in blocks\n\
4291 -S sort by file size\n\
4292 --sort=WORD sort by WORD instead of name: none -U,\n\
4293 extension -X, size -S, time -t, version -v\n\
4294 --time=WORD with -l, show time as WORD instead of modification\n\
4295 time: atime -u, access -u, use -u, ctime -c,\n\
4296 or status -c; use specified time as sort key\n\
4300 --time-style=STYLE with -l, show times using style STYLE:\n\
4301 full-iso, long-iso, iso, locale, +FORMAT.\n\
4302 FORMAT is interpreted like `date'; if FORMAT is\n\
4303 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4304 non-recent files and FORMAT2 to recent files;\n\
4305 if STYLE is prefixed with `posix-', STYLE\n\
4306 takes effect only outside the POSIX locale\n\
4307 -t sort by modification time\n\
4308 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4311 -u with -lt: sort by, and show, access time\n\
4312 with -l: show access time and sort by name\n\
4313 otherwise: sort by access time\n\
4314 -U do not sort; list entries in directory order\n\
4315 -v sort by version\n\
4318 -w, --width=COLS assume screen width instead of current value\n\
4319 -x list entries by lines instead of by columns\n\
4320 -X sort alphabetically by entry extension\n\
4321 -1 list one file per line\n\
4323 fputs (HELP_OPTION_DESCRIPTION, stdout);
4324 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4326 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4327 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4331 By default, color is not used to distinguish types of files. That is\n\
4332 equivalent to using --color=none. Using the --color option without the\n\
4333 optional WHEN argument is equivalent to using --color=always. With\n\
4334 --color=auto, color codes are output only if standard output is connected\n\
4335 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4336 colors, and can be set easily by the dircolors command.\n\
4340 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4342 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);