1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2007 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 */
87 #include "filenamecat.h"
88 #include "hard-locale.h"
101 #include "stat-time.h"
102 #include "strftime.h"
103 #include "strverscmp.h"
106 #include "xreadlink.h"
108 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
109 : (ls_mode == LS_MULTI_COL \
112 #define AUTHORS "Richard Stallman", "David MacKenzie"
114 #define obstack_chunk_alloc malloc
115 #define obstack_chunk_free free
117 /* Return an int indicating the result of comparing two integers.
118 Subtracting doesn't always work, due to overflow. */
119 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
121 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
122 # define st_author st_uid
139 /* Display letters and indicators for each filetype.
140 Keep these in sync with enum filetype. */
141 static char const filetype_letter[] = "?pcdb-lswd";
143 /* Ensure that filetype and filetype_letter have the same
144 number of elements. */
145 verify (sizeof filetype_letter - 1 == arg_directory + 1);
147 #define FILETYPE_INDICATORS \
149 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
150 C_LINK, C_SOCK, C_FILE, C_DIR \
159 /* For symbolic link, name of the file linked to, otherwise zero. */
164 enum filetype filetype;
166 /* For symbolic link and long listing, st_mode of file linked to, otherwise
172 /* For symbolic link and color printing, true if linked-to file
173 exists, otherwise false. */
177 /* For long listings, true if the file has an access control list. */
183 # define FILE_HAS_ACL(F) ((F)->have_acl)
185 # define FILE_HAS_ACL(F) 0
188 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
190 /* Null is a valid character in a color indicator (think about Epson
191 printers, for example) so we have to use a length/buffer string
196 size_t len; /* Number of bytes */
197 const char *string; /* Pointer to the same */
204 # define tcgetpgrp(Fd) 0
207 static size_t quote_name (FILE *out, const char *name,
208 struct quoting_options const *options,
210 static char *make_link_name (char const *name, char const *linkname);
211 static int decode_switches (int argc, char **argv);
212 static bool file_ignored (char const *name);
213 static uintmax_t gobble_file (char const *name, enum filetype type,
214 ino_t inode, bool command_line_arg,
215 char const *dirname);
216 static void print_color_indicator (const char *name, mode_t mode, int linkok,
217 bool stat_ok, enum filetype type);
218 static void put_indicator (const struct bin_str *ind);
219 static void add_ignore_pattern (const char *pattern);
220 static void attach (char *dest, const char *dirname, const char *name);
221 static void clear_files (void);
222 static void extract_dirs_from_files (char const *dirname,
223 bool command_line_arg);
224 static void get_link_name (char const *filename, struct fileinfo *f,
225 bool command_line_arg);
226 static void indent (size_t from, size_t to);
227 static size_t calculate_columns (bool by_columns);
228 static void print_current_files (void);
229 static void print_dir (char const *name, char const *realname,
230 bool command_line_arg);
231 static void print_file_name_and_frills (const struct fileinfo *f);
232 static void print_horizontal (void);
233 static int format_user_width (uid_t u);
234 static int format_group_width (gid_t g);
235 static void print_long_format (const struct fileinfo *f);
236 static void print_many_per_line (void);
237 static void print_name_with_quoting (const char *p, mode_t mode,
238 int linkok, bool stat_ok,
240 struct obstack *stack);
241 static void prep_non_filename_text (void);
242 static void print_type_indicator (bool stat_ok, mode_t mode,
244 static void print_with_commas (void);
245 static void queue_directory (char const *name, char const *realname,
246 bool command_line_arg);
247 static void sort_files (void);
248 static void parse_ls_color (void);
249 void usage (int status);
251 /* The name this program was run with. */
254 /* Initial size of hash table.
255 Most hierarchies are likely to be shallower than this. */
256 #define INITIAL_TABLE_SIZE 30
258 /* The set of `active' directories, from the current command-line argument
259 to the level in the hierarchy at which files are being listed.
260 A directory is represented by its device and inode numbers (struct dev_ino).
261 A directory is added to this set when ls begins listing it or its
262 entries, and it is removed from the set just after ls has finished
263 processing it. This set is used solely to detect loops, e.g., with
264 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
265 static Hash_table *active_dir_set;
267 #define LOOP_DETECT (!!active_dir_set)
269 /* The table of files in the current directory:
271 `cwd_file' points to a vector of `struct fileinfo', one per file.
272 `cwd_n_alloc' is the number of elements space has been allocated for.
273 `cwd_n_used' is the number actually in use. */
275 /* Address of block containing the files that are described. */
276 static struct fileinfo *cwd_file;
278 /* Length of block that `cwd_file' points to, measured in files. */
279 static size_t cwd_n_alloc;
281 /* Index of first unused slot in `cwd_file'. */
282 static size_t cwd_n_used;
284 /* Vector of pointers to files, in proper sorted order, and the number
285 of entries allocated for it. */
286 static void **sorted_file;
287 static size_t sorted_file_alloc;
289 /* When true, in a color listing, color each symlink name according to the
290 type of file it points to. Otherwise, color them according to the `ln'
291 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
292 regardless. This is set when `ln=target' appears in LS_COLORS. */
294 static bool color_symlink_as_referent;
296 /* mode of appropriate file for colorization */
297 #define FILE_OR_LINK_MODE(File) \
298 ((color_symlink_as_referent & (File)->linkok) \
299 ? (File)->linkmode : (File)->stat.st_mode)
302 /* Record of one pending directory waiting to be listed. */
307 /* If the directory is actually the file pointed to by a symbolic link we
308 were told to list, `realname' will contain the name of the symbolic
309 link, otherwise zero. */
311 bool command_line_arg;
312 struct pending *next;
315 static struct pending *pending_dirs;
317 /* Current time in seconds and nanoseconds since 1970, updated as
318 needed when deciding whether a file is recent. */
320 static time_t current_time = TYPE_MINIMUM (time_t);
321 static int current_time_ns = -1;
323 /* Whether any of the files has an ACL. This affects the width of the
327 static bool any_has_acl;
329 enum { any_has_acl = false };
332 /* The number of columns to use for columns containing inode numbers,
333 block sizes, link counts, owners, groups, authors, major device
334 numbers, minor device numbers, and file sizes, respectively. */
336 static int inode_number_width;
337 static int block_size_width;
338 static int nlink_width;
339 static int owner_width;
340 static int group_width;
341 static int author_width;
342 static int major_device_number_width;
343 static int minor_device_number_width;
344 static int file_size_width;
348 /* long_format for lots of info, one per line.
349 one_per_line for just names, one per line.
350 many_per_line for just names, many per line, sorted vertically.
351 horizontal for just names, many per line, sorted horizontally.
352 with_commas for just names, many per line, separated by commas.
354 -l (and other options that imply -l), -1, -C, -x and -m control
359 long_format, /* -l and other options that imply -l */
360 one_per_line, /* -1 */
361 many_per_line, /* -C */
366 static enum format format;
368 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
369 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
370 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
373 full_iso_time_style, /* --time-style=full-iso */
374 long_iso_time_style, /* --time-style=long-iso */
375 iso_time_style, /* --time-style=iso */
376 locale_time_style /* --time-style=locale */
379 static char const *const time_style_args[] =
381 "full-iso", "long-iso", "iso", "locale", NULL
383 static enum time_style const time_style_types[] =
385 full_iso_time_style, long_iso_time_style, iso_time_style,
388 ARGMATCH_VERIFY (time_style_args, time_style_types);
390 /* Type of time to print or sort by. Controlled by -c and -u.
391 The values of each item of this enum are important since they are
392 used as indices in the sort functions array (see sort_files()). */
396 time_mtime, /* default */
399 time_numtypes /* the number of elements of this enum */
402 static enum time_type time_type;
404 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
405 The values of each item of this enum are important since they are
406 used as indices in the sort functions array (see sort_files()). */
410 sort_none = -1, /* -U */
411 sort_name, /* default */
412 sort_extension, /* -X */
414 sort_version, /* -v */
416 sort_numtypes /* the number of elements of this enum */
419 static enum sort_type sort_type;
421 /* Direction of sort.
422 false means highest first if numeric,
423 lowest first if alphabetic;
424 these are the defaults.
425 true means the opposite order in each case. -r */
427 static bool sort_reverse;
429 /* True means to display owner information. -g turns this off. */
431 static bool print_owner = true;
433 /* True means to display author information. */
435 static bool print_author;
437 /* True means to display group information. -G and -o turn this off. */
439 static bool print_group = true;
441 /* True means print the user and group id's as numbers rather
444 static bool numeric_ids;
446 /* True means mention the size in blocks of each file. -s */
448 static bool print_block_size;
450 /* Human-readable options for output. */
451 static int human_output_opts;
453 /* The units to use when printing sizes other than file sizes. */
454 static uintmax_t output_block_size;
456 /* Likewise, but for file sizes. */
457 static uintmax_t file_output_block_size = 1;
459 /* Follow the output with a special string. Using this format,
460 Emacs' dired mode starts up twice as fast, and can handle all
461 strange characters in file names. */
464 /* `none' means don't mention the type of files.
465 `slash' means mention directories only, with a '/'.
466 `file_type' means mention file types.
467 `classify' means mention file types and mark executables.
469 Controlled by -F, -p, and --indicator-style. */
473 none, /* --indicator-style=none */
474 slash, /* -p, --indicator-style=slash */
475 file_type, /* --indicator-style=file-type */
476 classify /* -F, --indicator-style=classify */
479 static enum indicator_style indicator_style;
481 /* Names of indicator styles. */
482 static char const *const indicator_style_args[] =
484 "none", "slash", "file-type", "classify", NULL
486 static enum indicator_style const indicator_style_types[] =
488 none, slash, file_type, classify
490 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
492 /* True means use colors to mark types. Also define the different
493 colors as well as the stuff for the LS_COLORS environment variable.
494 The LS_COLORS variable is now in a termcap-like format. */
496 static bool print_with_color;
500 color_never, /* 0: default or --color=never */
501 color_always, /* 1: --color=always */
502 color_if_tty /* 2: --color=tty */
505 enum Dereference_symlink
509 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
510 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
511 DEREF_ALWAYS /* -L */
516 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
517 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
518 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE
521 static const char *const indicator_name[]=
523 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
524 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
528 struct color_ext_type
530 struct bin_str ext; /* The extension we're looking for */
531 struct bin_str seq; /* The sequence to output when we do */
532 struct color_ext_type *next; /* Next in list */
535 static struct bin_str color_indicator[] =
537 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
538 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
539 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
540 { LEN_STR_PAIR ("0") }, /* no: Normal */
541 { LEN_STR_PAIR ("0") }, /* fi: File: default */
542 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
543 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
544 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
545 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
546 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
547 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
548 { 0, NULL }, /* mi: Missing file: undefined */
549 { 0, NULL }, /* or: Orphaned symlink: undefined */
550 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
551 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
552 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
553 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
554 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
555 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
556 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
560 static struct color_ext_type *color_ext_list = NULL;
562 /* Buffer for color sequences */
563 static char *color_buf;
565 /* True means to check for orphaned symbolic link, for displaying
568 static bool check_symlink_color;
570 /* True means mention the inode number of each file. -i */
572 static bool print_inode;
574 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
575 other options that imply -l), and -L. */
577 static enum Dereference_symlink dereference;
579 /* True means when a directory is found, display info on its
582 static bool recursive;
584 /* True means when an argument is a directory name, display info
587 static bool immediate_dirs;
589 /* True means that directories are grouped before files. */
591 static bool directories_first;
593 /* Which files to ignore. */
597 /* Ignore files whose names start with `.', and files specified by
598 --hide and --ignore. */
601 /* Ignore `.', `..', and files specified by --ignore. */
602 IGNORE_DOT_AND_DOTDOT,
604 /* Ignore only files specified by --ignore. */
608 /* A linked list of shell-style globbing patterns. If a non-argument
609 file name matches any of these patterns, it is ignored.
610 Controlled by -I. Multiple -I options accumulate.
611 The -B option adds `*~' and `.*~' to this list. */
613 struct ignore_pattern
616 struct ignore_pattern *next;
619 static struct ignore_pattern *ignore_patterns;
621 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
622 variable itself to be ignored. */
623 static struct ignore_pattern *hide_patterns;
625 /* True means output nongraphic chars in file names as `?'.
626 (-q, --hide-control-chars)
627 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
628 independent. The algorithm is: first, obey the quoting style to get a
629 string representing the file name; then, if qmark_funny_chars is set,
630 replace all nonprintable chars in that string with `?'. It's necessary
631 to replace nonprintable chars even in quoted strings, because we don't
632 want to mess up the terminal if control chars get sent to it, and some
633 quoting methods pass through control chars as-is. */
634 static bool qmark_funny_chars;
636 /* Quoting options for file and dir name output. */
638 static struct quoting_options *filename_quoting_options;
639 static struct quoting_options *dirname_quoting_options;
641 /* The number of chars per hardware tab stop. Setting this to zero
642 inhibits the use of TAB characters for separating columns. -T */
643 static size_t tabsize;
645 /* True means print each directory name before listing it. */
647 static bool print_dir_name;
649 /* The line length to use for breaking lines in many-per-line format.
650 Can be set with -w. */
652 static size_t line_length;
654 /* If true, the file listing format requires that stat be called on
657 static bool format_needs_stat;
659 /* Similar to `format_needs_stat', but set if only the file type is
662 static bool format_needs_type;
664 /* An arbitrary limit on the number of bytes in a printed time stamp.
665 This is set to a relatively small value to avoid the need to worry
666 about denial-of-service attacks on servers that run "ls" on behalf
667 of remote clients. 1000 bytes should be enough for any practical
668 time stamp format. */
670 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
672 /* strftime formats for non-recent and recent files, respectively, in
675 static char const *long_time_format[2] =
677 /* strftime format for non-recent files (older than 6 months), in
678 -l output. This should contain the year, month and day (at
679 least), in an order that is understood by people in your
680 locale's territory. Please try to keep the number of used
681 screen columns small, because many people work in windows with
682 only 80 columns. But make this as wide as the other string
683 below, for recent files. */
685 /* strftime format for recent files (younger than 6 months), in -l
686 output. This should contain the month, day and time (at
687 least), in an order that is understood by people in your
688 locale's territory. Please try to keep the number of used
689 screen columns small, because many people work in windows with
690 only 80 columns. But make this as wide as the other string
691 above, for non-recent files. */
695 /* The set of signals that are caught. */
697 static sigset_t caught_signals;
699 /* If nonzero, the value of the pending fatal signal. */
701 static sig_atomic_t volatile interrupt_signal;
703 /* A count of the number of pending stop signals that have been received. */
705 static sig_atomic_t volatile stop_signal_count;
707 /* Desired exit status. */
709 static int exit_status;
714 /* "ls" had a minor problem (e.g., it could not stat a directory
716 LS_MINOR_PROBLEM = 1,
718 /* "ls" had more serious trouble. */
722 /* For long options that have no equivalent short option, use a
723 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
726 AUTHOR_OPTION = CHAR_MAX + 1,
729 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
730 FILE_TYPE_INDICATOR_OPTION,
733 GROUP_DIRECTORIES_FIRST_OPTION,
735 INDICATOR_STYLE_OPTION,
737 /* FIXME: --kilobytes is deprecated (but not -k); remove in late 2006 */
738 KILOBYTES_LONG_OPTION,
740 QUOTING_STYLE_OPTION,
741 SHOW_CONTROL_CHARS_OPTION,
748 static struct option const long_options[] =
750 {"all", no_argument, NULL, 'a'},
751 {"escape", no_argument, NULL, 'b'},
752 {"directory", no_argument, NULL, 'd'},
753 {"dired", no_argument, NULL, 'D'},
754 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
755 {"group-directories-first", no_argument, NULL,
756 GROUP_DIRECTORIES_FIRST_OPTION},
757 {"human-readable", no_argument, NULL, 'h'},
758 {"inode", no_argument, NULL, 'i'},
759 {"kilobytes", no_argument, NULL, KILOBYTES_LONG_OPTION},
760 {"numeric-uid-gid", no_argument, NULL, 'n'},
761 {"no-group", no_argument, NULL, 'G'},
762 {"hide-control-chars", no_argument, NULL, 'q'},
763 {"reverse", no_argument, NULL, 'r'},
764 {"size", no_argument, NULL, 's'},
765 {"width", required_argument, NULL, 'w'},
766 {"almost-all", no_argument, NULL, 'A'},
767 {"ignore-backups", no_argument, NULL, 'B'},
768 {"classify", no_argument, NULL, 'F'},
769 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
770 {"si", no_argument, NULL, SI_OPTION},
771 {"dereference-command-line", no_argument, NULL, 'H'},
772 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
773 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
774 {"hide", required_argument, NULL, HIDE_OPTION},
775 {"ignore", required_argument, NULL, 'I'},
776 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
777 {"dereference", no_argument, NULL, 'L'},
778 {"literal", no_argument, NULL, 'N'},
779 {"quote-name", no_argument, NULL, 'Q'},
780 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
781 {"recursive", no_argument, NULL, 'R'},
782 {"format", required_argument, NULL, FORMAT_OPTION},
783 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
784 {"sort", required_argument, NULL, SORT_OPTION},
785 {"tabsize", required_argument, NULL, 'T'},
786 {"time", required_argument, NULL, TIME_OPTION},
787 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
788 {"color", optional_argument, NULL, COLOR_OPTION},
789 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
790 {"author", no_argument, NULL, AUTHOR_OPTION},
791 {GETOPT_HELP_OPTION_DECL},
792 {GETOPT_VERSION_OPTION_DECL},
796 static char const *const format_args[] =
798 "verbose", "long", "commas", "horizontal", "across",
799 "vertical", "single-column", NULL
801 static enum format const format_types[] =
803 long_format, long_format, with_commas, horizontal, horizontal,
804 many_per_line, one_per_line
806 ARGMATCH_VERIFY (format_args, format_types);
808 static char const *const sort_args[] =
810 "none", "time", "size", "extension", "version", NULL
812 static enum sort_type const sort_types[] =
814 sort_none, sort_time, sort_size, sort_extension, sort_version
816 ARGMATCH_VERIFY (sort_args, sort_types);
818 static char const *const time_args[] =
820 "atime", "access", "use", "ctime", "status", NULL
822 static enum time_type const time_types[] =
824 time_atime, time_atime, time_atime, time_ctime, time_ctime
826 ARGMATCH_VERIFY (time_args, time_types);
828 static char const *const color_args[] =
830 /* force and none are for compatibility with another color-ls version */
831 "always", "yes", "force",
832 "never", "no", "none",
833 "auto", "tty", "if-tty", NULL
835 static enum color_type const color_types[] =
837 color_always, color_always, color_always,
838 color_never, color_never, color_never,
839 color_if_tty, color_if_tty, color_if_tty
841 ARGMATCH_VERIFY (color_args, color_types);
843 /* Information about filling a column. */
851 /* Array with information about column filledness. */
852 static struct column_info *column_info;
854 /* Maximum number of columns ever possible for this display. */
855 static size_t max_idx;
857 /* The minimum width of a column is 3: 1 character for the name and 2
858 for the separating white space. */
859 #define MIN_COLUMN_WIDTH 3
862 /* This zero-based index is used solely with the --dired option.
863 When that option is in effect, this counter is incremented for each
864 byte of output generated by this program so that the beginning
865 and ending indices (in that output) of every file name can be recorded
866 and later output themselves. */
867 static size_t dired_pos;
869 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
871 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
872 #define DIRED_FPUTS(s, stream, s_len) \
873 do {fputs (s, stream); dired_pos += s_len;} while (0)
875 /* Like DIRED_FPUTS, but for use when S is a literal string. */
876 #define DIRED_FPUTS_LITERAL(s, stream) \
877 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
879 #define DIRED_INDENT() \
883 DIRED_FPUTS_LITERAL (" ", stdout); \
887 /* With --dired, store pairs of beginning and ending indices of filenames. */
888 static struct obstack dired_obstack;
890 /* With --dired, store pairs of beginning and ending indices of any
891 directory names that appear as headers (just before `total' line)
892 for lists of directory entries. Such directory names are seen when
893 listing hierarchies using -R and when a directory is listed with at
894 least one other command line argument. */
895 static struct obstack subdired_obstack;
897 /* Save the current index on the specified obstack, OBS. */
898 #define PUSH_CURRENT_DIRED_POS(obs) \
902 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
906 /* With -R, this stack is used to help detect directory cycles.
907 The device/inode pairs on this stack mirror the pairs in the
908 active_dir_set hash table. */
909 static struct obstack dev_ino_obstack;
911 /* Push a pair onto the device/inode stack. */
912 #define DEV_INO_PUSH(Dev, Ino) \
915 struct dev_ino *di; \
916 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
917 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
918 di->st_dev = (Dev); \
919 di->st_ino = (Ino); \
923 /* Pop a dev/ino struct off the global dev_ino_obstack
924 and return that struct. */
925 static struct dev_ino
928 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
929 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
930 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
933 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
938 assert (0 <= stat (Name, &sb)); \
939 assert (sb.st_dev == Di.st_dev); \
940 assert (sb.st_ino == Di.st_ino); \
945 /* Write to standard output PREFIX, followed by the quoting style and
946 a space-separated list of the integers stored in OS all on one line. */
949 dired_dump_obstack (const char *prefix, struct obstack *os)
953 n_pos = obstack_object_size (os) / sizeof (dired_pos);
959 pos = (size_t *) obstack_finish (os);
960 fputs (prefix, stdout);
961 for (i = 0; i < n_pos; i++)
962 printf (" %lu", (unsigned long int) pos[i]);
968 dev_ino_hash (void const *x, size_t table_size)
970 struct dev_ino const *p = x;
971 return (uintmax_t) p->st_ino % table_size;
975 dev_ino_compare (void const *x, void const *y)
977 struct dev_ino const *a = x;
978 struct dev_ino const *b = y;
979 return SAME_INODE (*a, *b) ? true : false;
983 dev_ino_free (void *x)
988 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
989 active directories. Return true if there is already a matching
990 entry in the table. */
993 visit_dir (dev_t dev, ino_t ino)
996 struct dev_ino *ent_from_table;
999 ent = xmalloc (sizeof *ent);
1003 /* Attempt to insert this entry into the table. */
1004 ent_from_table = hash_insert (active_dir_set, ent);
1006 if (ent_from_table == NULL)
1008 /* Insertion failed due to lack of memory. */
1012 found_match = (ent_from_table != ent);
1016 /* ent was not inserted, so free it. */
1024 free_pending_ent (struct pending *p)
1032 is_colored (enum indicator_no type)
1034 size_t len = color_indicator[type].len;
1035 char const *s = color_indicator[type].string;
1037 || (len == 1 && strncmp (s, "0", 1) == 0)
1038 || (len == 2 && strncmp (s, "00", 2) == 0));
1042 restore_default_color (void)
1044 put_indicator (&color_indicator[C_LEFT]);
1045 put_indicator (&color_indicator[C_RIGHT]);
1048 /* An ordinary signal was received; arrange for the program to exit. */
1051 sighandler (int sig)
1054 signal (sig, SIG_IGN);
1055 if (! interrupt_signal)
1056 interrupt_signal = sig;
1059 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1062 stophandler (int sig)
1065 signal (sig, stophandler);
1066 if (! interrupt_signal)
1067 stop_signal_count++;
1070 /* Process any pending signals. If signals are caught, this function
1071 should be called periodically. Ideally there should never be an
1072 unbounded amount of time when signals are not being processed.
1073 Signal handling can restore the default colors, so callers must
1074 immediately change colors after invoking this function. */
1077 process_signals (void)
1079 while (interrupt_signal | stop_signal_count)
1085 restore_default_color ();
1088 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1090 /* Reload interrupt_signal and stop_signal_count, in case a new
1091 signal was handled before sigprocmask took effect. */
1092 sig = interrupt_signal;
1093 stops = stop_signal_count;
1095 /* SIGTSTP is special, since the application can receive that signal
1096 more than once. In this case, don't set the signal handler to the
1097 default. Instead, just raise the uncatchable SIGSTOP. */
1100 stop_signal_count = stops - 1;
1104 signal (sig, SIG_DFL);
1106 /* Exit or suspend the program. */
1108 sigprocmask (SIG_SETMASK, &oldset, NULL);
1110 /* If execution reaches here, then the program has been
1111 continued (after being suspended). */
1116 main (int argc, char **argv)
1119 struct pending *thispend;
1122 /* The signals that are trapped, and the number of such signals. */
1123 static int const sig[] =
1125 /* This one is handled specially. */
1128 /* The usual suspects. */
1129 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1146 enum { nsigs = sizeof sig / sizeof sig[0] };
1149 bool caught_sig[nsigs];
1152 initialize_main (&argc, &argv);
1153 program_name = argv[0];
1154 setlocale (LC_ALL, "");
1155 bindtextdomain (PACKAGE, LOCALEDIR);
1156 textdomain (PACKAGE);
1158 initialize_exit_failure (LS_FAILURE);
1159 atexit (close_stdout);
1161 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1162 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1164 exit_status = EXIT_SUCCESS;
1165 print_dir_name = true;
1166 pending_dirs = NULL;
1168 i = decode_switches (argc, argv);
1170 if (print_with_color)
1173 /* Test print_with_color again, because the call to parse_ls_color
1174 may have just reset it -- e.g., if LS_COLORS is invalid. */
1175 if (print_with_color)
1177 /* Avoid following symbolic links when possible. */
1178 if (is_colored (C_ORPHAN)
1179 || is_colored (C_EXEC)
1180 || (is_colored (C_MISSING) && format == long_format))
1181 check_symlink_color = true;
1183 /* If the standard output is a controlling terminal, watch out
1184 for signals, so that the colors can be restored to the
1185 default state if "ls" is suspended or interrupted. */
1187 if (0 <= tcgetpgrp (STDOUT_FILENO))
1191 struct sigaction act;
1193 sigemptyset (&caught_signals);
1194 for (j = 0; j < nsigs; j++)
1196 sigaction (sig[j], NULL, &act);
1197 if (act.sa_handler != SIG_IGN)
1198 sigaddset (&caught_signals, sig[j]);
1201 act.sa_mask = caught_signals;
1202 act.sa_flags = SA_RESTART;
1204 for (j = 0; j < nsigs; j++)
1205 if (sigismember (&caught_signals, sig[j]))
1207 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1208 sigaction (sig[j], &act, NULL);
1211 for (j = 0; j < nsigs; j++)
1213 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1216 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1217 siginterrupt (sig[j], 0);
1223 prep_non_filename_text ();
1226 if (dereference == DEREF_UNDEFINED)
1227 dereference = ((immediate_dirs
1228 || indicator_style == classify
1229 || format == long_format)
1231 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1233 /* When using -R, initialize a data structure we'll use to
1234 detect any directory cycles. */
1237 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1241 if (active_dir_set == NULL)
1244 obstack_init (&dev_ino_obstack);
1247 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1248 || format == long_format
1249 || print_block_size;
1250 format_needs_type = (! format_needs_stat
1253 || indicator_style != none
1254 || directories_first));
1258 obstack_init (&dired_obstack);
1259 obstack_init (&subdired_obstack);
1263 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1273 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1275 queue_directory (".", NULL, true);
1279 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1285 if (!immediate_dirs)
1286 extract_dirs_from_files (NULL, true);
1287 /* `cwd_n_used' might be zero now. */
1290 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1291 (and not pending_dirs->name) because there may be no markers in the queue
1292 at this point. A marker may be enqueued when extract_dirs_from_files is
1293 called with a non-empty string or via print_dir. */
1296 print_current_files ();
1298 DIRED_PUTCHAR ('\n');
1300 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1301 print_dir_name = false;
1303 while (pending_dirs)
1305 thispend = pending_dirs;
1306 pending_dirs = pending_dirs->next;
1310 if (thispend->name == NULL)
1312 /* thispend->name == NULL means this is a marker entry
1313 indicating we've finished processing the directory.
1314 Use its dev/ino numbers to remove the corresponding
1315 entry from the active_dir_set hash table. */
1316 struct dev_ino di = dev_ino_pop ();
1317 struct dev_ino *found = hash_delete (active_dir_set, &di);
1318 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1320 dev_ino_free (found);
1321 free_pending_ent (thispend);
1326 print_dir (thispend->name, thispend->realname,
1327 thispend->command_line_arg);
1329 free_pending_ent (thispend);
1330 print_dir_name = true;
1333 if (print_with_color)
1337 restore_default_color ();
1340 /* Restore the default signal handling. */
1342 for (j = 0; j < nsigs; j++)
1343 if (sigismember (&caught_signals, sig[j]))
1344 signal (sig[j], SIG_DFL);
1346 for (j = 0; j < nsigs; j++)
1348 signal (sig[j], SIG_DFL);
1351 /* Act on any signals that arrived before the default was restored.
1352 This can process signals out of order, but there doesn't seem to
1353 be an easy way to do them in order, and the order isn't that
1354 important anyway. */
1355 for (j = stop_signal_count; j; j--)
1357 j = interrupt_signal;
1364 /* No need to free these since we're about to exit. */
1365 dired_dump_obstack ("//DIRED//", &dired_obstack);
1366 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1367 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1368 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1373 assert (hash_get_n_entries (active_dir_set) == 0);
1374 hash_free (active_dir_set);
1380 /* Set all the option flags according to the switches specified.
1381 Return the index of the first non-option argument. */
1384 decode_switches (int argc, char **argv)
1387 char *time_style_option = NULL;
1389 /* Record whether there is an option specifying sort type. */
1390 bool sort_type_specified = false;
1392 qmark_funny_chars = false;
1394 /* initialize all switches to default settings */
1399 /* This is for the `dir' program. */
1400 format = many_per_line;
1401 set_quoting_style (NULL, escape_quoting_style);
1404 case LS_LONG_FORMAT:
1405 /* This is for the `vdir' program. */
1406 format = long_format;
1407 set_quoting_style (NULL, escape_quoting_style);
1411 /* This is for the `ls' program. */
1412 if (isatty (STDOUT_FILENO))
1414 format = many_per_line;
1415 /* See description of qmark_funny_chars, above. */
1416 qmark_funny_chars = true;
1420 format = one_per_line;
1421 qmark_funny_chars = false;
1429 time_type = time_mtime;
1430 sort_type = sort_name;
1431 sort_reverse = false;
1432 numeric_ids = false;
1433 print_block_size = false;
1434 indicator_style = none;
1435 print_inode = false;
1436 dereference = DEREF_UNDEFINED;
1438 immediate_dirs = false;
1439 ignore_mode = IGNORE_DEFAULT;
1440 ignore_patterns = NULL;
1441 hide_patterns = NULL;
1443 /* FIXME: put this in a function. */
1445 char const *q_style = getenv ("QUOTING_STYLE");
1448 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1450 set_quoting_style (NULL, quoting_style_vals[i]);
1453 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1454 quotearg (q_style));
1459 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1460 human_output_opts = human_options (ls_block_size, false,
1461 &output_block_size);
1462 if (ls_block_size || getenv ("BLOCK_SIZE"))
1463 file_output_block_size = output_block_size;
1468 char const *p = getenv ("COLUMNS");
1471 unsigned long int tmp_ulong;
1472 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1473 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1475 line_length = tmp_ulong;
1480 _("ignoring invalid width in environment variable COLUMNS: %s"),
1490 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1491 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1492 line_length = ws.ws_col;
1497 char const *p = getenv ("TABSIZE");
1501 unsigned long int tmp_ulong;
1502 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1503 && tmp_ulong <= SIZE_MAX)
1505 tabsize = tmp_ulong;
1510 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1516 while ((c = getopt_long (argc, argv,
1517 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1518 long_options, NULL)) != -1)
1523 ignore_mode = IGNORE_MINIMAL;
1527 set_quoting_style (NULL, escape_quoting_style);
1531 time_type = time_ctime;
1535 immediate_dirs = true;
1539 /* Same as enabling -a -U and disabling -l -s. */
1540 ignore_mode = IGNORE_MINIMAL;
1541 sort_type = sort_none;
1542 sort_type_specified = true;
1544 if (format == long_format)
1545 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1546 print_block_size = false; /* disable -s */
1547 print_with_color = false; /* disable --color */
1550 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1551 indicator_style = file_type;
1555 format = long_format;
1556 print_owner = false;
1560 human_output_opts = human_autoscale | human_SI | human_base_1024;
1561 file_output_block_size = output_block_size = 1;
1568 case KILOBYTES_LONG_OPTION:
1570 _("the --kilobytes option is deprecated; use -k instead"));
1573 human_output_opts = 0;
1574 file_output_block_size = output_block_size = 1024;
1578 format = long_format;
1582 format = with_commas;
1587 format = long_format;
1590 case 'o': /* Just like -l, but don't display group info. */
1591 format = long_format;
1592 print_group = false;
1596 indicator_style = slash;
1600 qmark_funny_chars = true;
1604 sort_reverse = true;
1608 print_block_size = true;
1612 sort_type = sort_time;
1613 sort_type_specified = true;
1617 time_type = time_atime;
1621 sort_type = sort_version;
1622 sort_type_specified = true;
1627 unsigned long int tmp_ulong;
1628 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1629 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1630 error (LS_FAILURE, 0, _("invalid line width: %s"),
1632 line_length = tmp_ulong;
1637 format = horizontal;
1641 if (ignore_mode == IGNORE_DEFAULT)
1642 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1646 add_ignore_pattern ("*~");
1647 add_ignore_pattern (".*~");
1651 format = many_per_line;
1659 indicator_style = classify;
1662 case 'G': /* inhibit display of group info */
1663 print_group = false;
1667 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1670 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1671 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1675 add_ignore_pattern (optarg);
1679 dereference = DEREF_ALWAYS;
1683 set_quoting_style (NULL, literal_quoting_style);
1687 set_quoting_style (NULL, c_quoting_style);
1695 sort_type = sort_size;
1696 sort_type_specified = true;
1701 unsigned long int tmp_ulong;
1702 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1703 || SIZE_MAX < tmp_ulong)
1704 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1706 tabsize = tmp_ulong;
1711 sort_type = sort_none;
1712 sort_type_specified = true;
1716 sort_type = sort_extension;
1717 sort_type_specified = true;
1721 /* -1 has no effect after -l. */
1722 if (format != long_format)
1723 format = one_per_line;
1727 print_author = true;
1732 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1733 hide->pattern = optarg;
1734 hide->next = hide_patterns;
1735 hide_patterns = hide;
1740 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1741 sort_type_specified = true;
1744 case GROUP_DIRECTORIES_FIRST_OPTION:
1745 directories_first = true;
1749 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1753 format = XARGMATCH ("--format", optarg, format_args, format_types);
1756 case FULL_TIME_OPTION:
1757 format = long_format;
1758 time_style_option = "full-iso";
1765 i = XARGMATCH ("--color", optarg, color_args, color_types);
1767 /* Using --color with no argument is equivalent to using
1771 print_with_color = (i == color_always
1772 || (i == color_if_tty
1773 && isatty (STDOUT_FILENO)));
1775 if (print_with_color)
1777 /* Don't use TAB characters in output. Some terminal
1778 emulators can't handle the combination of tabs and
1779 color codes on the same line. */
1785 case INDICATOR_STYLE_OPTION:
1786 indicator_style = XARGMATCH ("--indicator-style", optarg,
1787 indicator_style_args,
1788 indicator_style_types);
1791 case QUOTING_STYLE_OPTION:
1792 set_quoting_style (NULL,
1793 XARGMATCH ("--quoting-style", optarg,
1795 quoting_style_vals));
1798 case TIME_STYLE_OPTION:
1799 time_style_option = optarg;
1802 case SHOW_CONTROL_CHARS_OPTION:
1803 qmark_funny_chars = false;
1806 case BLOCK_SIZE_OPTION:
1807 human_output_opts = human_options (optarg, true, &output_block_size);
1808 file_output_block_size = output_block_size;
1812 human_output_opts = human_autoscale | human_SI;
1813 file_output_block_size = output_block_size = 1;
1816 case_GETOPT_HELP_CHAR;
1818 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1825 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1827 filename_quoting_options = clone_quoting_options (NULL);
1828 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1829 set_char_quoting (filename_quoting_options, ' ', 1);
1830 if (file_type <= indicator_style)
1833 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1834 set_char_quoting (filename_quoting_options, *p, 1);
1837 dirname_quoting_options = clone_quoting_options (NULL);
1838 set_char_quoting (dirname_quoting_options, ':', 1);
1840 /* --dired is meaningful only with --format=long (-l).
1841 Otherwise, ignore it. FIXME: warn about this?
1842 Alternatively, make --dired imply --format=long? */
1843 if (dired && format != long_format)
1846 /* If -c or -u is specified and not -l (or any other option that implies -l),
1847 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1848 The behavior of ls when using either -c or -u but with neither -l nor -t
1849 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1850 sort by atime (this is the one that's not specified by the POSIX spec),
1851 -lu means show atime and sort by name, -lut means show atime and sort
1854 if ((time_type == time_ctime || time_type == time_atime)
1855 && !sort_type_specified && format != long_format)
1857 sort_type = sort_time;
1860 if (format == long_format)
1862 char *style = time_style_option;
1863 static char const posix_prefix[] = "posix-";
1866 if (! (style = getenv ("TIME_STYLE")))
1869 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1871 if (! hard_locale (LC_TIME))
1873 style += sizeof posix_prefix - 1;
1878 char *p0 = style + 1;
1879 char *p1 = strchr (p0, '\n');
1884 if (strchr (p1 + 1, '\n'))
1885 error (LS_FAILURE, 0, _("invalid time style format %s"),
1889 long_time_format[0] = p0;
1890 long_time_format[1] = p1;
1893 switch (XARGMATCH ("time style", style,
1897 case full_iso_time_style:
1898 long_time_format[0] = long_time_format[1] =
1899 "%Y-%m-%d %H:%M:%S.%N %z";
1902 case long_iso_time_style:
1903 case_long_iso_time_style:
1904 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1907 case iso_time_style:
1908 long_time_format[0] = "%Y-%m-%d ";
1909 long_time_format[1] = "%m-%d %H:%M";
1912 case locale_time_style:
1913 if (hard_locale (LC_TIME))
1915 /* Ensure that the locale has translations for both
1916 formats. If not, fall back on long-iso format. */
1918 for (i = 0; i < 2; i++)
1920 char const *locale_format =
1921 dcgettext (NULL, long_time_format[i], LC_TIME);
1922 if (locale_format == long_time_format[i])
1923 goto case_long_iso_time_style;
1924 long_time_format[i] = locale_format;
1933 /* Parse a string as part of the LS_COLORS variable; this may involve
1934 decoding all kinds of escape characters. If equals_end is set an
1935 unescaped equal sign ends the string, otherwise only a : or \0
1936 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1939 The resulting string is *not* null-terminated, but may contain
1942 Note that both dest and src are char **; on return they point to
1943 the first free byte after the array and the character that ended
1944 the input string, respectively. */
1947 get_funky_string (char **dest, const char **src, bool equals_end,
1948 size_t *output_count)
1950 char num; /* For numerical codes */
1951 size_t count; /* Something to count with */
1953 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1958 p = *src; /* We don't want to double-indirect */
1959 q = *dest; /* the whole darn time. */
1961 count = 0; /* No characters counted in yet. */
1964 state = ST_GND; /* Start in ground state. */
1965 while (state < ST_END)
1969 case ST_GND: /* Ground state (no escapes) */
1974 state = ST_END; /* End of string */
1977 state = ST_BACKSLASH; /* Backslash scape sequence */
1981 state = ST_CARET; /* Caret escape */
1987 state = ST_END; /* End */
1990 /* else fall through */
1998 case ST_BACKSLASH: /* Backslash escaped character */
2009 state = ST_OCTAL; /* Octal sequence */
2014 state = ST_HEX; /* Hex sequence */
2017 case 'a': /* Bell */
2020 case 'b': /* Backspace */
2023 case 'e': /* Escape */
2026 case 'f': /* Form feed */
2029 case 'n': /* Newline */
2032 case 'r': /* Carriage return */
2038 case 'v': /* Vtab */
2041 case '?': /* Delete */
2044 case '_': /* Space */
2047 case '\0': /* End of string */
2048 state = ST_ERROR; /* Error! */
2050 default: /* Escaped character like \ ^ : = */
2054 if (state == ST_BACKSLASH)
2063 case ST_OCTAL: /* Octal sequence */
2064 if (*p < '0' || *p > '7')
2071 num = (num << 3) + (*(p++) - '0');
2074 case ST_HEX: /* Hex sequence */
2087 num = (num << 4) + (*(p++) - '0');
2095 num = (num << 4) + (*(p++) - 'a') + 10;
2103 num = (num << 4) + (*(p++) - 'A') + 10;
2113 case ST_CARET: /* Caret escape */
2114 state = ST_GND; /* Should be the next state... */
2115 if (*p >= '@' && *p <= '~')
2117 *(q++) = *(p++) & 037;
2136 *output_count = count;
2138 return state != ST_ERROR;
2142 parse_ls_color (void)
2144 const char *p; /* Pointer to character being parsed */
2145 char *buf; /* color_buf buffer pointer */
2146 int state; /* State of parser */
2147 int ind_no; /* Indicator number */
2148 char label[3]; /* Indicator label */
2149 struct color_ext_type *ext; /* Extension we are working on */
2151 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2155 strcpy (label, "??");
2157 /* This is an overly conservative estimate, but any possible
2158 LS_COLORS string will *not* generate a color_buf longer than
2159 itself, so it is a safe way of allocating a buffer in
2161 buf = color_buf = xstrdup (p);
2168 case 1: /* First label character */
2176 /* Allocate new extension block and add to head of
2177 linked list (this way a later definition will
2178 override an earlier one, which can be useful for
2179 having terminal-specific defs override global). */
2181 ext = xmalloc (sizeof *ext);
2182 ext->next = color_ext_list;
2183 color_ext_list = ext;
2186 ext->ext.string = buf;
2188 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2193 state = 0; /* Done! */
2196 default: /* Assume it is file type label */
2203 case 2: /* Second label character */
2210 state = -1; /* Error */
2213 case 3: /* Equal sign after indicator label */
2214 state = -1; /* Assume failure... */
2215 if (*(p++) == '=')/* It *should* be... */
2217 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2219 if (STREQ (label, indicator_name[ind_no]))
2221 color_indicator[ind_no].string = buf;
2222 state = (get_funky_string (&buf, &p, false,
2223 &color_indicator[ind_no].len)
2229 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2233 case 4: /* Equal sign after *.ext */
2236 ext->seq.string = buf;
2237 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2248 struct color_ext_type *e;
2249 struct color_ext_type *e2;
2252 _("unparsable value for LS_COLORS environment variable"));
2254 for (e = color_ext_list; e != NULL; /* empty */)
2260 print_with_color = false;
2263 if (color_indicator[C_LINK].len == 6
2264 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2265 color_symlink_as_referent = true;
2268 /* Set the exit status to report a failure. If SERIOUS, it is a
2269 serious failure; otherwise, it is merely a minor problem. */
2272 set_exit_status (bool serious)
2275 exit_status = LS_FAILURE;
2276 else if (exit_status == EXIT_SUCCESS)
2277 exit_status = LS_MINOR_PROBLEM;
2280 /* Assuming a failure is serious if SERIOUS, use the printf-style
2281 MESSAGE to report the failure to access a file named FILE. Assume
2282 errno is set appropriately for the failure. */
2285 file_failure (bool serious, char const *message, char const *file)
2287 error (0, errno, message, quotearg_colon (file));
2288 set_exit_status (serious);
2291 /* Request that the directory named NAME have its contents listed later.
2292 If REALNAME is nonzero, it will be used instead of NAME when the
2293 directory name is printed. This allows symbolic links to directories
2294 to be treated as regular directories but still be listed under their
2295 real names. NAME == NULL is used to insert a marker entry for the
2296 directory named in REALNAME.
2297 If NAME is non-NULL, we use its dev/ino information to save
2298 a call to stat -- when doing a recursive (-R) traversal.
2299 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2302 queue_directory (char const *name, char const *realname, bool command_line_arg)
2304 struct pending *new = xmalloc (sizeof *new);
2305 new->realname = realname ? xstrdup (realname) : NULL;
2306 new->name = name ? xstrdup (name) : NULL;
2307 new->command_line_arg = command_line_arg;
2308 new->next = pending_dirs;
2312 /* Read directory NAME, and list the files in it.
2313 If REALNAME is nonzero, print its name instead of NAME;
2314 this is used for symbolic links to directories.
2315 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2318 print_dir (char const *name, char const *realname, bool command_line_arg)
2321 struct dirent *next;
2322 uintmax_t total_blocks = 0;
2323 static bool first = true;
2326 dirp = opendir (name);
2329 file_failure (command_line_arg, _("cannot open directory %s"), name);
2335 struct stat dir_stat;
2336 int fd = dirfd (dirp);
2338 /* If dirfd failed, endure the overhead of using stat. */
2340 ? fstat (fd, &dir_stat)
2341 : stat (name, &dir_stat)) < 0)
2343 file_failure (command_line_arg,
2344 _("cannot determine device and inode of %s"), name);
2349 /* If we've already visited this dev/inode pair, warn that
2350 we've found a loop, and do not process this directory. */
2351 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2353 error (0, 0, _("%s: not listing already-listed directory"),
2354 quotearg_colon (name));
2359 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2362 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2369 /* Set errno to zero so we can distinguish between a readdir failure
2370 and when readdir simply finds that there are no more entries. */
2372 next = readdir (dirp);
2375 if (! file_ignored (next->d_name))
2377 enum filetype type = unknown;
2379 #if HAVE_STRUCT_DIRENT_D_TYPE
2380 switch (next->d_type)
2382 case DT_BLK: type = blockdev; break;
2383 case DT_CHR: type = chardev; break;
2384 case DT_DIR: type = directory; break;
2385 case DT_FIFO: type = fifo; break;
2386 case DT_LNK: type = symbolic_link; break;
2387 case DT_REG: type = normal; break;
2388 case DT_SOCK: type = sock; break;
2390 case DT_WHT: type = whiteout; break;
2394 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2398 else if (errno != 0)
2400 file_failure (command_line_arg, _("reading directory %s"), name);
2401 if (errno != EOVERFLOW)
2408 if (closedir (dirp) != 0)
2410 file_failure (command_line_arg, _("closing directory %s"), name);
2411 /* Don't return; print whatever we got. */
2414 /* Sort the directory contents. */
2417 /* If any member files are subdirectories, perhaps they should have their
2418 contents listed rather than being mentioned here as files. */
2421 extract_dirs_from_files (name, command_line_arg);
2423 if (recursive | print_dir_name)
2426 DIRED_PUTCHAR ('\n');
2429 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2430 dired_pos += quote_name (stdout, realname ? realname : name,
2431 dirname_quoting_options, NULL);
2432 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2433 DIRED_FPUTS_LITERAL (":\n", stdout);
2436 if (format == long_format || print_block_size)
2439 char buf[LONGEST_HUMAN_READABLE + 1];
2443 DIRED_FPUTS (p, stdout, strlen (p));
2444 DIRED_PUTCHAR (' ');
2445 p = human_readable (total_blocks, buf, human_output_opts,
2446 ST_NBLOCKSIZE, output_block_size);
2447 DIRED_FPUTS (p, stdout, strlen (p));
2448 DIRED_PUTCHAR ('\n');
2452 print_current_files ();
2455 /* Add `pattern' to the list of patterns for which files that match are
2459 add_ignore_pattern (const char *pattern)
2461 struct ignore_pattern *ignore;
2463 ignore = xmalloc (sizeof *ignore);
2464 ignore->pattern = pattern;
2465 /* Add it to the head of the linked list. */
2466 ignore->next = ignore_patterns;
2467 ignore_patterns = ignore;
2470 /* Return true if one of the PATTERNS matches FILE. */
2473 patterns_match (struct ignore_pattern const *patterns, char const *file)
2475 struct ignore_pattern const *p;
2476 for (p = patterns; p; p = p->next)
2477 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2482 /* Return true if FILE should be ignored. */
2485 file_ignored (char const *name)
2487 return ((ignore_mode != IGNORE_MINIMAL
2489 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2490 || (ignore_mode == IGNORE_DEFAULT
2491 && patterns_match (hide_patterns, name))
2492 || patterns_match (ignore_patterns, name));
2495 /* POSIX requires that a file size be printed without a sign, even
2496 when negative. Assume the typical case where negative sizes are
2497 actually positive values that have wrapped around. */
2500 unsigned_file_size (off_t size)
2502 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2505 /* Enter and remove entries in the table `cwd_file'. */
2507 /* Empty the table of files. */
2514 for (i = 0; i < cwd_n_used; i++)
2516 struct fileinfo *f = sorted_file[i];
2523 any_has_acl = false;
2525 inode_number_width = 0;
2526 block_size_width = 0;
2531 major_device_number_width = 0;
2532 minor_device_number_width = 0;
2533 file_size_width = 0;
2536 /* Add a file to the current table of files.
2537 Verify that the file exists, and print an error message if it does not.
2538 Return the number of blocks that the file occupies. */
2541 gobble_file (char const *name, enum filetype type, ino_t inode,
2542 bool command_line_arg, char const *dirname)
2544 uintmax_t blocks = 0;
2547 /* An inode value prior to gobble_file necessarily came from readdir,
2548 which is not used for command line arguments. */
2549 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2551 if (cwd_n_used == cwd_n_alloc)
2553 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2557 f = &cwd_file[cwd_n_used];
2558 memset (f, '\0', sizeof *f);
2559 f->stat.st_ino = inode;
2562 if (command_line_arg
2563 || format_needs_stat
2564 /* When coloring a directory (we may know the type from
2565 direct.d_type), we have to stat it in order to indicate
2566 sticky and/or other-writable attributes. */
2567 || (type == directory && print_with_color)
2568 /* When dereferencing symlinks, the inode and type must come from
2569 stat, but readdir provides the inode and type of lstat. */
2570 || ((print_inode || format_needs_type)
2571 && (type == symbolic_link || type == unknown)
2572 && (dereference == DEREF_ALWAYS
2573 || (command_line_arg && dereference != DEREF_NEVER)))
2574 /* Command line dereferences are already taken care of by the above
2575 assertion that the inode number is not yet known. */
2576 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2577 || (format_needs_type
2578 && (type == unknown || command_line_arg
2579 /* --indicator-style=classify (aka -F)
2580 requires that we stat each regular file
2581 to see if it's executable. */
2582 || (type == normal && (indicator_style == classify
2583 /* This is so that --color ends up
2584 highlighting files with the executable
2585 bit set even when options like -F are
2587 || (print_with_color
2588 && is_colored (C_EXEC))
2592 /* Absolute name of this file. */
2593 char *absolute_name;
2597 if (name[0] == '/' || dirname[0] == 0)
2598 absolute_name = (char *) name;
2601 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2602 attach (absolute_name, dirname, name);
2605 switch (dereference)
2608 err = stat (absolute_name, &f->stat);
2611 case DEREF_COMMAND_LINE_ARGUMENTS:
2612 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2613 if (command_line_arg)
2616 err = stat (absolute_name, &f->stat);
2618 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2621 need_lstat = (err < 0
2623 : ! S_ISDIR (f->stat.st_mode));
2627 /* stat failed because of ENOENT, maybe indicating a dangling
2628 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2629 directory, and --dereference-command-line-symlink-to-dir is
2630 in effect. Fall through so that we call lstat instead. */
2633 default: /* DEREF_NEVER */
2634 err = lstat (absolute_name, &f->stat);
2640 /* Failure to stat a command line argument leads to
2641 an exit status of 2. For other files, stat failure
2642 provokes an exit status of 1. */
2643 file_failure (command_line_arg,
2644 _("cannot access %s"), absolute_name);
2645 if (command_line_arg)
2648 f->name = xstrdup (name);
2657 if (format == long_format)
2659 int n = file_has_acl (absolute_name, &f->stat);
2660 f->have_acl = (0 < n);
2661 any_has_acl |= f->have_acl;
2663 error (0, errno, "%s", quotearg_colon (absolute_name));
2667 if (S_ISLNK (f->stat.st_mode)
2668 && (format == long_format || check_symlink_color))
2671 struct stat linkstats;
2673 get_link_name (absolute_name, f, command_line_arg);
2674 linkname = make_link_name (absolute_name, f->linkname);
2676 /* Avoid following symbolic links when possible, ie, when
2677 they won't be traced and when no indicator is needed. */
2679 && (file_type <= indicator_style || check_symlink_color)
2680 && stat (linkname, &linkstats) == 0)
2684 /* Symbolic links to directories that are mentioned on the
2685 command line are automatically traced if not being
2687 if (!command_line_arg || format == long_format
2688 || !S_ISDIR (linkstats.st_mode))
2690 /* Get the linked-to file's mode for the filetype indicator
2691 in long listings. */
2692 f->linkmode = linkstats.st_mode;
2698 if (S_ISLNK (f->stat.st_mode))
2699 f->filetype = symbolic_link;
2700 else if (S_ISDIR (f->stat.st_mode))
2702 if (command_line_arg & !immediate_dirs)
2703 f->filetype = arg_directory;
2705 f->filetype = directory;
2708 f->filetype = normal;
2710 blocks = ST_NBLOCKS (f->stat);
2712 char buf[LONGEST_HUMAN_READABLE + 1];
2713 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2714 ST_NBLOCKSIZE, output_block_size),
2716 if (block_size_width < len)
2717 block_size_width = len;
2722 int len = format_user_width (f->stat.st_uid);
2723 if (owner_width < len)
2729 int len = format_group_width (f->stat.st_gid);
2730 if (group_width < len)
2736 int len = format_user_width (f->stat.st_author);
2737 if (author_width < len)
2742 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2743 int len = strlen (umaxtostr (f->stat.st_nlink, buf));
2744 if (nlink_width < len)
2748 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2750 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2751 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2752 if (major_device_number_width < len)
2753 major_device_number_width = len;
2754 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2755 if (minor_device_number_width < len)
2756 minor_device_number_width = len;
2757 len = major_device_number_width + 2 + minor_device_number_width;
2758 if (file_size_width < len)
2759 file_size_width = len;
2763 char buf[LONGEST_HUMAN_READABLE + 1];
2764 uintmax_t size = unsigned_file_size (f->stat.st_size);
2765 int len = mbswidth (human_readable (size, buf, human_output_opts,
2766 1, file_output_block_size),
2768 if (file_size_width < len)
2769 file_size_width = len;
2775 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2776 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2777 if (inode_number_width < len)
2778 inode_number_width = len;
2781 f->name = xstrdup (name);
2787 /* Return true if F refers to a directory. */
2789 is_directory (const struct fileinfo *f)
2791 return f->filetype == directory || f->filetype == arg_directory;
2794 /* Put the name of the file that FILENAME is a symbolic link to
2795 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2796 FILENAME is a command-line argument. */
2799 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2801 f->linkname = xreadlink_with_size (filename, f->stat.st_size);
2802 if (f->linkname == NULL)
2803 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2807 /* If `linkname' is a relative name and `name' contains one or more
2808 leading directories, return `linkname' with those directories
2809 prepended; otherwise, return a copy of `linkname'.
2810 If `linkname' is zero, return zero. */
2813 make_link_name (char const *name, char const *linkname)
2821 if (*linkname == '/')
2822 return xstrdup (linkname);
2824 /* The link is to a relative name. Prepend any leading directory
2825 in `name' to the link name. */
2826 linkbuf = strrchr (name, '/');
2828 return xstrdup (linkname);
2830 bufsiz = linkbuf - name + 1;
2831 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2832 strncpy (linkbuf, name, bufsiz);
2833 strcpy (linkbuf + bufsiz, linkname);
2837 /* Return true if the last component of NAME is `.' or `..'
2838 This is so we don't try to recurse on `././././. ...' */
2841 basename_is_dot_or_dotdot (const char *name)
2843 char const *base = last_component (name);
2844 return dot_or_dotdot (base);
2847 /* Remove any entries from CWD_FILE that are for directories,
2848 and queue them to be listed as directories instead.
2849 DIRNAME is the prefix to prepend to each dirname
2850 to make it correct relative to ls's working dir;
2851 if it is null, no prefix is needed and "." and ".." should not be ignored.
2852 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2853 This is desirable when processing directories recursively. */
2856 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2860 bool ignore_dot_and_dot_dot = (dirname != NULL);
2862 if (dirname && LOOP_DETECT)
2864 /* Insert a marker entry first. When we dequeue this marker entry,
2865 we'll know that DIRNAME has been processed and may be removed
2866 from the set of active directories. */
2867 queue_directory (NULL, dirname, false);
2870 /* Queue the directories last one first, because queueing reverses the
2872 for (i = cwd_n_used; i-- != 0; )
2874 struct fileinfo *f = sorted_file[i];
2876 if (is_directory (f)
2877 && (! ignore_dot_and_dot_dot
2878 || ! basename_is_dot_or_dotdot (f->name)))
2880 if (!dirname || f->name[0] == '/')
2881 queue_directory (f->name, f->linkname, command_line_arg);
2884 char *name = file_name_concat (dirname, f->name, NULL);
2885 queue_directory (name, f->linkname, command_line_arg);
2888 if (f->filetype == arg_directory)
2893 /* Now delete the directories from the table, compacting all the remaining
2896 for (i = 0, j = 0; i < cwd_n_used; i++)
2898 struct fileinfo *f = sorted_file[i];
2900 j += (f->filetype != arg_directory);
2905 /* Use strcoll to compare strings in this locale. If an error occurs,
2906 report an error and longjmp to failed_strcoll. */
2908 static jmp_buf failed_strcoll;
2911 xstrcoll (char const *a, char const *b)
2915 diff = strcoll (a, b);
2918 error (0, errno, _("cannot compare file names %s and %s"),
2919 quote_n (0, a), quote_n (1, b));
2920 set_exit_status (false);
2921 longjmp (failed_strcoll, 1);
2926 /* Comparison routines for sorting the files. */
2928 typedef void const *V;
2929 typedef int (*qsortFunc)(V a, V b);
2931 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
2932 The do { ... } while(0) makes it possible to use the macro more like
2933 a statement, without violating C89 rules: */
2934 #define DIRFIRST_CHECK(a, b) \
2937 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
2938 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
2939 if (a_is_dir && !b_is_dir) \
2940 return -1; /* a goes before b */ \
2941 if (!a_is_dir && b_is_dir) \
2942 return 1; /* b goes before a */ \
2946 /* Define the 8 different sort function variants required for each sortkey.
2947 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
2948 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
2949 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
2950 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
2951 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
2952 /* direct, non-dirfirst versions */ \
2953 static int xstrcoll_##key_name (V a, V b) \
2954 { return key_cmp_func (a, b, xstrcoll); } \
2955 static int strcmp_##key_name (V a, V b) \
2956 { return key_cmp_func (a, b, strcmp); } \
2958 /* reverse, non-dirfirst versions */ \
2959 static int rev_xstrcoll_##key_name (V a, V b) \
2960 { return key_cmp_func (b, a, xstrcoll); } \
2961 static int rev_strcmp_##key_name (V a, V b) \
2962 { return key_cmp_func (b, a, strcmp); } \
2964 /* direct, dirfirst versions */ \
2965 static int xstrcoll_df_##key_name (V a, V b) \
2966 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
2967 static int strcmp_df_##key_name (V a, V b) \
2968 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
2970 /* reverse, dirfirst versions */ \
2971 static int rev_xstrcoll_df_##key_name (V a, V b) \
2972 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
2973 static int rev_strcmp_df_##key_name (V a, V b) \
2974 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
2977 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2978 int (*cmp) (char const *, char const *))
2980 int diff = timespec_cmp (get_stat_ctime (&b->stat),
2981 get_stat_ctime (&a->stat));
2982 return diff ? diff : cmp (a->name, b->name);
2986 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2987 int (*cmp) (char const *, char const *))
2989 int diff = timespec_cmp (get_stat_mtime (&b->stat),
2990 get_stat_mtime (&a->stat));
2991 return diff ? diff : cmp (a->name, b->name);
2995 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2996 int (*cmp) (char const *, char const *))
2998 int diff = timespec_cmp (get_stat_atime (&b->stat),
2999 get_stat_atime (&a->stat));
3000 return diff ? diff : cmp (a->name, b->name);
3004 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3005 int (*cmp) (char const *, char const *))
3007 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3008 return diff ? diff : cmp (a->name, b->name);
3012 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3013 int (*cmp) (char const *, char const *))
3015 return cmp (a->name, b->name);
3018 /* Compare file extensions. Files with no extension are `smallest'.
3019 If extensions are the same, compare by filenames instead. */
3022 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3023 int (*cmp) (char const *, char const *))
3025 char const *base1 = strrchr (a->name, '.');
3026 char const *base2 = strrchr (b->name, '.');
3027 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3028 return diff ? diff : cmp (a->name, b->name);
3031 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3032 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3033 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3034 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3035 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3036 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3038 /* Compare file versions.
3039 Unlike all other compare functions above, cmp_version depends only
3040 on strverscmp, which does not fail (even for locale reasons), and does not
3041 need a secondary sort key.
3042 All the other sort options, in fact, need xstrcoll and strcmp variants,
3043 because they all use a string comparison (either as the primary or secondary
3044 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3045 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3046 thanks to the gnulib library. */
3048 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3050 return strverscmp (a->name, b->name);
3053 static int xstrcoll_version (V a, V b)
3054 { return cmp_version (a, b); }
3055 static int rev_xstrcoll_version (V a, V b)
3056 { return cmp_version (b, a); }
3057 static int xstrcoll_df_version (V a, V b)
3058 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3059 static int rev_xstrcoll_df_version (V a, V b)
3060 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3063 /* We have 2^3 different variants for each sortkey function
3064 (for 3 independent sort modes).
3065 The function pointers stored in this array must be dereferenced as:
3067 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3069 Note that the order in which sortkeys are listed in the function pointer
3070 array below is defined by the order of the elements in the time_type and
3073 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3076 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3077 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3080 { strcmp_##key_name, strcmp_df_##key_name }, \
3081 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3085 static qsortFunc sort_functions[][2][2][2] =
3087 LIST_SORTFUNCTION_VARIANTS (name),
3088 LIST_SORTFUNCTION_VARIANTS (extension),
3089 LIST_SORTFUNCTION_VARIANTS (size),
3093 { xstrcoll_version, xstrcoll_df_version },
3094 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3097 /* We use NULL for the strcmp variants of version comparison
3098 since as explained in cmp_version definition, version comparison
3099 does not rely on xstrcoll, so it will never longjmp, and never
3100 need to try the strcmp fallback. */
3107 /* last are time sort functions */
3108 LIST_SORTFUNCTION_VARIANTS (mtime),
3109 LIST_SORTFUNCTION_VARIANTS (ctime),
3110 LIST_SORTFUNCTION_VARIANTS (atime)
3113 /* The number of sortkeys is calculated as
3114 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3115 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3116 This is because when sort_type==sort_time, we have up to
3117 time_numtypes possible sortkeys.
3119 This line verifies at compile-time that the array of sort functions has been
3120 initialized for all possible sortkeys. */
3121 verify (ARRAY_CARDINALITY (sort_functions)
3122 == sort_numtypes + time_numtypes - 1 );
3124 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3127 initialize_ordering_vector (void)
3130 for (i = 0; i < cwd_n_used; i++)
3131 sorted_file[i] = &cwd_file[i];
3134 /* Sort the files now in the table. */
3141 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3144 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3145 sorted_file_alloc = 3 * cwd_n_used;
3148 initialize_ordering_vector ();
3150 if (sort_type == sort_none)
3153 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3154 ignore strcoll failures, as a failing strcoll might be a
3155 comparison function that is not a total order, and if we ignored
3156 the failure this might cause qsort to dump core. */
3158 if (! setjmp (failed_strcoll))
3159 use_strcmp = false; /* strcoll() succeeded */
3163 assert (sort_type != sort_version);
3164 initialize_ordering_vector ();
3167 /* When sort_type == sort_time, use time_type as subindex. */
3168 mpsort ((void const **) sorted_file, cwd_n_used,
3169 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3170 [use_strcmp][sort_reverse]
3171 [directories_first]);
3174 /* List all the files now in the table. */
3177 print_current_files (void)
3184 for (i = 0; i < cwd_n_used; i++)
3186 print_file_name_and_frills (sorted_file[i]);
3192 print_many_per_line ();
3196 print_horizontal ();
3200 print_with_commas ();
3204 for (i = 0; i < cwd_n_used; i++)
3206 print_long_format (sorted_file[i]);
3207 DIRED_PUTCHAR ('\n');
3213 /* Return the expected number of columns in a long-format time stamp,
3214 or zero if it cannot be calculated. */
3217 long_time_expected_width (void)
3219 static int width = -1;
3224 struct tm const *tm = localtime (&epoch);
3225 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3227 /* In case you're wondering if localtime can fail with an input time_t
3228 value of 0, let's just say it's very unlikely, but not inconceivable.
3229 The TZ environment variable would have to specify a time zone that
3230 is 2**31-1900 years or more ahead of UTC. This could happen only on
3231 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3232 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3233 their implementations limit the offset to 167:59 and 24:00, resp. */
3237 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3239 width = mbsnwidth (buf, len, 0);
3249 /* Get the current time. */
3252 get_current_time (void)
3254 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
3256 struct timespec timespec;
3257 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
3259 current_time = timespec.tv_sec;
3260 current_time_ns = timespec.tv_nsec;
3266 /* The clock does not have nanosecond resolution, so get the maximum
3267 possible value for the current time that is consistent with the
3268 reported clock. That way, files are not considered to be in the
3269 future merely because their time stamps have higher resolution
3270 than the clock resolution. */
3272 #if HAVE_GETTIMEOFDAY
3274 struct timeval timeval;
3275 gettimeofday (&timeval, NULL);
3276 current_time = timeval.tv_sec;
3277 current_time_ns = timeval.tv_usec * 1000 + 999;
3280 current_time = time (NULL);
3281 current_time_ns = 999999999;
3285 /* Print the user or group name NAME, with numeric id ID, using a
3286 print width of WIDTH columns. */
3289 format_user_or_group (char const *name, unsigned long int id, int width)
3295 int width_gap = width - mbswidth (name, 0);
3296 int pad = MAX (0, width_gap);
3297 fputs (name, stdout);
3298 len = strlen (name) + pad;
3306 printf ("%*lu ", width, id);
3310 dired_pos += len + 1;
3313 /* Print the name or id of the user with id U, using a print width of
3317 format_user (uid_t u, int width, bool stat_ok)
3319 format_user_or_group (! stat_ok ? "?" :
3320 (numeric_ids ? NULL : getuser (u)), u, width);
3323 /* Likewise, for groups. */
3326 format_group (gid_t g, int width, bool stat_ok)
3328 format_user_or_group (! stat_ok ? "?" :
3329 (numeric_ids ? NULL : getgroup (g)), g, width);
3332 /* Return the number of columns that format_user_or_group will print. */
3335 format_user_or_group_width (char const *name, unsigned long int id)
3339 int len = mbswidth (name, 0);
3340 return MAX (0, len);
3344 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3345 sprintf (buf, "%lu", id);
3346 return strlen (buf);
3350 /* Return the number of columns that format_user will print. */
3353 format_user_width (uid_t u)
3355 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3358 /* Likewise, for groups. */
3361 format_group_width (gid_t g)
3363 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3367 /* Print information about F in long format. */
3370 print_long_format (const struct fileinfo *f)
3374 [LONGEST_HUMAN_READABLE + 1 /* inode */
3375 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3376 + sizeof (modebuf) - 1 + 1 /* mode string */
3377 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3378 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3379 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3380 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3386 struct timespec when_timespec;
3387 struct tm *when_local;
3389 /* Compute the mode string, except remove the trailing space if no
3390 files in this directory have ACLs. */
3392 filemodestring (&f->stat, modebuf);
3395 modebuf[0] = filetype_letter[f->filetype];
3396 memset (modebuf + 1, '?', 10);
3401 else if (FILE_HAS_ACL (f))
3407 when_timespec = get_stat_ctime (&f->stat);
3410 when_timespec = get_stat_mtime (&f->stat);
3413 when_timespec = get_stat_atime (&f->stat);
3419 when = when_timespec.tv_sec;
3420 when_ns = when_timespec.tv_nsec;
3426 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3427 sprintf (p, "%*s ", inode_number_width,
3428 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3430 : umaxtostr (f->stat.st_ino, hbuf)));
3431 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3432 The latter is wrong when inode_number_width is zero. */
3436 if (print_block_size)
3438 char hbuf[LONGEST_HUMAN_READABLE + 1];
3439 char const *blocks =
3442 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3443 ST_NBLOCKSIZE, output_block_size));
3445 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3447 while ((*p++ = *blocks++))
3452 /* The last byte of the mode string is the POSIX
3453 "optional alternate access method flag". */
3455 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3456 sprintf (p, "%s %*s ", modebuf, nlink_width,
3457 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3459 /* Increment by strlen (p) here, rather than by, e.g.,
3460 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3461 The latter is wrong when nlink_width is zero. */
3466 if (print_owner | print_group | print_author)
3468 DIRED_FPUTS (buf, stdout, p - buf);
3471 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3474 format_group (f->stat.st_gid, group_width, f->stat_ok);
3477 format_user (f->stat.st_author, author_width, f->stat_ok);
3483 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3485 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3486 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3487 int blanks_width = (file_size_width
3488 - (major_device_number_width + 2
3489 + minor_device_number_width));
3490 sprintf (p, "%*s, %*s ",
3491 major_device_number_width + MAX (0, blanks_width),
3492 umaxtostr (major (f->stat.st_rdev), majorbuf),
3493 minor_device_number_width,
3494 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3495 p += file_size_width + 1;
3499 char hbuf[LONGEST_HUMAN_READABLE + 1];
3503 : human_readable (unsigned_file_size (f->stat.st_size),
3504 hbuf, human_output_opts, 1, file_output_block_size));
3506 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3508 while ((*p++ = *size++))
3513 when_local = localtime (&when_timespec.tv_sec);
3517 if (f->stat_ok && when_local)
3519 time_t six_months_ago;
3523 /* If the file appears to be in the future, update the current
3524 time, in case the file happens to have been modified since
3525 the last time we checked the clock. */
3526 if (current_time < when
3527 || (current_time == when && current_time_ns < when_ns))
3529 /* Note that get_current_time calls gettimeofday which, on some non-
3530 compliant systems, clobbers the buffer used for localtime's result.
3531 But it's ok here, because we use a gettimeofday wrapper that
3532 saves and restores the buffer around the gettimeofday call. */
3533 get_current_time ();
3536 /* Consider a time to be recent if it is within the past six
3537 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3538 31556952 seconds on the average. Write this value as an
3539 integer constant to avoid floating point hassles. */
3540 six_months_ago = current_time - 31556952 / 2;
3541 recent = (six_months_ago <= when
3542 && (when < current_time
3543 || (when == current_time && when_ns <= current_time_ns)));
3544 fmt = long_time_format[recent];
3546 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3547 when_local, 0, when_ns);
3555 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3560 /* The time cannot be converted using the desired format, so
3561 print it as a huge integer number of seconds. */
3562 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3563 sprintf (p, "%*s ", long_time_expected_width (),
3566 : (TYPE_SIGNED (time_t)
3567 ? imaxtostr (when, hbuf)
3568 : umaxtostr (when, hbuf))));
3572 DIRED_FPUTS (buf, stdout, p - buf);
3573 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3574 f->stat_ok, f->filetype, &dired_obstack);
3576 if (f->filetype == symbolic_link)
3580 DIRED_FPUTS_LITERAL (" -> ", stdout);
3581 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3582 f->stat_ok, f->filetype, NULL);
3583 if (indicator_style != none)
3584 print_type_indicator (true, f->linkmode, unknown);
3587 else if (indicator_style != none)
3588 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3591 /* Output to OUT a quoted representation of the file name NAME,
3592 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3593 Store the number of screen columns occupied by NAME's quoted
3594 representation into WIDTH, if non-NULL. Return the number of bytes
3598 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3601 char smallbuf[BUFSIZ];
3602 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3604 size_t displayed_width IF_LINT (= 0);
3606 if (len < sizeof smallbuf)
3610 buf = alloca (len + 1);
3611 quotearg_buffer (buf, len + 1, name, -1, options);
3614 if (qmark_funny_chars)
3619 char const *p = buf;
3620 char const *plimit = buf + len;
3622 displayed_width = 0;
3627 case ' ': case '!': case '"': case '#': case '%':
3628 case '&': case '\'': case '(': case ')': case '*':
3629 case '+': case ',': case '-': case '.': case '/':
3630 case '0': case '1': case '2': case '3': case '4':
3631 case '5': case '6': case '7': case '8': case '9':
3632 case ':': case ';': case '<': case '=': case '>':
3634 case 'A': case 'B': case 'C': case 'D': case 'E':
3635 case 'F': case 'G': case 'H': case 'I': case 'J':
3636 case 'K': case 'L': case 'M': case 'N': case 'O':
3637 case 'P': case 'Q': case 'R': case 'S': case 'T':
3638 case 'U': case 'V': case 'W': case 'X': case 'Y':
3640 case '[': case '\\': case ']': case '^': case '_':
3641 case 'a': case 'b': case 'c': case 'd': case 'e':
3642 case 'f': case 'g': case 'h': case 'i': case 'j':
3643 case 'k': case 'l': case 'm': case 'n': case 'o':
3644 case 'p': case 'q': case 'r': case 's': case 't':
3645 case 'u': case 'v': case 'w': case 'x': case 'y':
3646 case 'z': case '{': case '|': case '}': case '~':
3647 /* These characters are printable ASCII characters. */
3649 displayed_width += 1;
3652 /* If we have a multibyte sequence, copy it until we
3653 reach its end, replacing each non-printable multibyte
3654 character with a single question mark. */
3656 mbstate_t mbstate = { 0, };
3663 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3665 if (bytes == (size_t) -1)
3667 /* An invalid multibyte sequence was
3668 encountered. Skip one input byte, and
3669 put a question mark. */
3672 displayed_width += 1;
3676 if (bytes == (size_t) -2)
3678 /* An incomplete multibyte character
3679 at the end. Replace it entirely with
3683 displayed_width += 1;
3688 /* A null wide character was encountered. */
3694 /* A printable multibyte character.
3696 for (; bytes > 0; --bytes)
3698 displayed_width += w;
3702 /* An unprintable multibyte character.
3703 Replace it entirely with a question
3707 displayed_width += 1;
3710 while (! mbsinit (&mbstate));
3715 /* The buffer may have shrunk. */
3722 char const *plimit = buf + len;
3726 if (! isprint (to_uchar (*p)))
3730 displayed_width = len;
3733 else if (width != NULL)
3737 displayed_width = mbsnwidth (buf, len, 0);
3741 char const *p = buf;
3742 char const *plimit = buf + len;
3744 displayed_width = 0;
3747 if (isprint (to_uchar (*p)))
3755 fwrite (buf, 1, len, out);
3757 *width = displayed_width;
3762 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3763 bool stat_ok, enum filetype type,
3764 struct obstack *stack)
3766 if (print_with_color)
3767 print_color_indicator (p, mode, linkok, stat_ok, type);
3770 PUSH_CURRENT_DIRED_POS (stack);
3772 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3775 PUSH_CURRENT_DIRED_POS (stack);
3777 if (print_with_color)
3780 prep_non_filename_text ();
3785 prep_non_filename_text (void)
3787 if (color_indicator[C_END].string != NULL)
3788 put_indicator (&color_indicator[C_END]);
3791 put_indicator (&color_indicator[C_LEFT]);
3792 put_indicator (&color_indicator[C_NORM]);
3793 put_indicator (&color_indicator[C_RIGHT]);
3797 /* Print the file name of `f' with appropriate quoting.
3798 Also print file size, inode number, and filetype indicator character,
3799 as requested by switches. */
3802 print_file_name_and_frills (const struct fileinfo *f)
3804 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3807 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3808 umaxtostr (f->stat.st_ino, buf));
3810 if (print_block_size)
3811 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3812 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3813 ST_NBLOCKSIZE, output_block_size));
3815 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3816 f->stat_ok, f->filetype, NULL);
3818 if (indicator_style != none)
3819 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3822 /* Given these arguments describing a file, return the single-byte
3823 type indicator, or 0. */
3825 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3829 if (stat_ok ? S_ISREG (mode) : type == normal)
3831 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3838 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3840 else if (indicator_style == slash)
3842 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3844 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3846 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3848 else if (stat_ok && S_ISDOOR (mode))
3857 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3859 char c = get_type_indicator (stat_ok, mode, type);
3865 print_color_indicator (const char *name, mode_t mode, int linkok,
3866 bool stat_ok, enum filetype filetype)
3869 struct color_ext_type *ext; /* Color extension */
3870 size_t len; /* Length of name */
3872 /* Is this a nonexistent file? If so, linkok == -1. */
3874 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3878 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3879 type = filetype_indicator[filetype];
3886 if ((mode & S_ISUID) != 0)
3888 else if ((mode & S_ISGID) != 0)
3890 else if ((mode & S_IXUGO) != 0)
3893 else if (S_ISDIR (mode))
3895 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3896 type = C_STICKY_OTHER_WRITABLE;
3897 else if ((mode & S_IWOTH) != 0)
3898 type = C_OTHER_WRITABLE;
3899 else if ((mode & S_ISVTX) != 0)
3904 else if (S_ISLNK (mode))
3905 type = ((!linkok && color_indicator[C_ORPHAN].string)
3906 ? C_ORPHAN : C_LINK);
3907 else if (S_ISFIFO (mode))
3909 else if (S_ISSOCK (mode))
3911 else if (S_ISBLK (mode))
3913 else if (S_ISCHR (mode))
3915 else if (S_ISDOOR (mode))
3919 /* Classify a file of some other type as C_ORPHAN. */
3924 /* Check the file's suffix only if still classified as C_FILE. */
3928 /* Test if NAME has a recognized suffix. */
3930 len = strlen (name);
3931 name += len; /* Pointer to final \0. */
3932 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3934 if (ext->ext.len <= len
3935 && strncmp (name - ext->ext.len, ext->ext.string,
3941 put_indicator (&color_indicator[C_LEFT]);
3942 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3943 put_indicator (&color_indicator[C_RIGHT]);
3946 /* Output a color indicator (which may contain nulls). */
3948 put_indicator (const struct bin_str *ind)
3955 for (i = ind->len; i != 0; --i)
3960 length_of_file_name_and_frills (const struct fileinfo *f)
3964 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3967 len += 1 + (format == with_commas
3968 ? strlen (umaxtostr (f->stat.st_ino, buf))
3969 : inode_number_width);
3971 if (print_block_size)
3972 len += 1 + (format == with_commas
3973 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
3974 human_output_opts, ST_NBLOCKSIZE,
3976 : block_size_width);
3978 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3981 if (indicator_style != none)
3983 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3991 print_many_per_line (void)
3993 size_t row; /* Current row. */
3994 size_t cols = calculate_columns (true);
3995 struct column_info const *line_fmt = &column_info[cols - 1];
3997 /* Calculate the number of rows that will be in each column except possibly
3998 for a short column on the right. */
3999 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4001 for (row = 0; row < rows; row++)
4004 size_t filesno = row;
4007 /* Print the next row. */
4010 struct fileinfo const *f = sorted_file[filesno];
4011 size_t name_length = length_of_file_name_and_frills (f);
4012 size_t max_name_length = line_fmt->col_arr[col++];
4013 print_file_name_and_frills (f);
4016 if (filesno >= cwd_n_used)
4019 indent (pos + name_length, pos + max_name_length);
4020 pos += max_name_length;
4027 print_horizontal (void)
4031 size_t cols = calculate_columns (false);
4032 struct column_info const *line_fmt = &column_info[cols - 1];
4033 size_t name_length = length_of_file_name_and_frills (cwd_file);
4034 size_t max_name_length = line_fmt->col_arr[0];
4036 /* Print first entry. */
4037 print_file_name_and_frills (cwd_file);
4040 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4042 struct fileinfo const *f;
4043 size_t col = filesno % cols;
4052 indent (pos + name_length, pos + max_name_length);
4053 pos += max_name_length;
4056 f = sorted_file[filesno];
4057 print_file_name_and_frills (f);
4059 name_length = length_of_file_name_and_frills (f);
4060 max_name_length = line_fmt->col_arr[col];
4066 print_with_commas (void)
4071 for (filesno = 0; filesno < cwd_n_used; filesno++)
4073 struct fileinfo const *f = sorted_file[filesno];
4074 size_t len = length_of_file_name_and_frills (f);
4080 if (pos + len + 2 < line_length)
4092 putchar (separator);
4095 print_file_name_and_frills (f);
4101 /* Assuming cursor is at position FROM, indent up to position TO.
4102 Use a TAB character instead of two or more spaces whenever possible. */
4105 indent (size_t from, size_t to)
4109 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4112 from += tabsize - from % tabsize;
4122 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4123 /* FIXME: maybe remove this function someday. See about using a
4124 non-malloc'ing version of file_name_concat. */
4127 attach (char *dest, const char *dirname, const char *name)
4129 const char *dirnamep = dirname;
4131 /* Copy dirname if it is not ".". */
4132 if (dirname[0] != '.' || dirname[1] != 0)
4135 *dest++ = *dirnamep++;
4136 /* Add '/' if `dirname' doesn't already end with it. */
4137 if (dirnamep > dirname && dirnamep[-1] != '/')
4145 /* Allocate enough column info suitable for the current number of
4146 files and display columns, and initialize the info to represent the
4147 narrowest possible columns. */
4150 init_column_info (void)
4153 size_t max_cols = MIN (max_idx, cwd_n_used);
4155 /* Currently allocated columns in column_info. */
4156 static size_t column_info_alloc;
4158 if (column_info_alloc < max_cols)
4160 size_t new_column_info_alloc;
4163 if (max_cols < max_idx / 2)
4165 /* The number of columns is far less than the display width
4166 allows. Grow the allocation, but only so that it's
4167 double the current requirements. If the display is
4168 extremely wide, this avoids allocating a lot of memory
4169 that is never needed. */
4170 column_info = xnrealloc (column_info, max_cols,
4171 2 * sizeof *column_info);
4172 new_column_info_alloc = 2 * max_cols;
4176 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4177 new_column_info_alloc = max_idx;
4180 /* Allocate the new size_t objects by computing the triangle
4181 formula n * (n + 1) / 2, except that we don't need to
4182 allocate the part of the triangle that we've already
4183 allocated. Check for address arithmetic overflow. */
4185 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4186 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4187 size_t t = s * column_info_growth;
4188 if (s < new_column_info_alloc || t / column_info_growth != s)
4190 p = xnmalloc (t / 2, sizeof *p);
4193 /* Grow the triangle by parceling out the cells just allocated. */
4194 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4196 column_info[i].col_arr = p;
4200 column_info_alloc = new_column_info_alloc;
4203 for (i = 0; i < max_cols; ++i)
4207 column_info[i].valid_len = true;
4208 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4209 for (j = 0; j <= i; ++j)
4210 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4214 /* Calculate the number of columns needed to represent the current set
4215 of files in the current display width. */
4218 calculate_columns (bool by_columns)
4220 size_t filesno; /* Index into cwd_file. */
4221 size_t cols; /* Number of files across. */
4223 /* Normally the maximum number of columns is determined by the
4224 screen width. But if few files are available this might limit it
4226 size_t max_cols = MIN (max_idx, cwd_n_used);
4228 init_column_info ();
4230 /* Compute the maximum number of possible columns. */
4231 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4233 struct fileinfo const *f = sorted_file[filesno];
4234 size_t name_length = length_of_file_name_and_frills (f);
4237 for (i = 0; i < max_cols; ++i)
4239 if (column_info[i].valid_len)
4241 size_t idx = (by_columns
4242 ? filesno / ((cwd_n_used + i) / (i + 1))
4243 : filesno % (i + 1));
4244 size_t real_length = name_length + (idx == i ? 0 : 2);
4246 if (column_info[i].col_arr[idx] < real_length)
4248 column_info[i].line_len += (real_length
4249 - column_info[i].col_arr[idx]);
4250 column_info[i].col_arr[idx] = real_length;
4251 column_info[i].valid_len = (column_info[i].line_len
4258 /* Find maximum allowed columns. */
4259 for (cols = max_cols; 1 < cols; --cols)
4261 if (column_info[cols - 1].valid_len)
4271 if (status != EXIT_SUCCESS)
4272 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4276 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4278 List information about the FILEs (the current directory by default).\n\
4279 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4283 Mandatory arguments to long options are mandatory for short options too.\n\
4286 -a, --all do not ignore entries starting with .\n\
4287 -A, --almost-all do not list implied . and ..\n\
4288 --author with -l, print the author of each file\n\
4289 -b, --escape print octal escapes for nongraphic characters\n\
4292 --block-size=SIZE use SIZE-byte blocks\n\
4293 -B, --ignore-backups do not list implied entries ending with ~\n\
4294 -c with -lt: sort by, and show, ctime (time of last\n\
4295 modification of file status information)\n\
4296 with -l: show ctime and sort by name\n\
4297 otherwise: sort by ctime\n\
4300 -C list entries by columns\n\
4301 --color[=WHEN] control whether color is used to distinguish file\n\
4302 types. WHEN may be `never', `always', or `auto'\n\
4303 -d, --directory list directory entries instead of contents,\n\
4304 and do not dereference symbolic links\n\
4305 -D, --dired generate output designed for Emacs' dired mode\n\
4308 -f do not sort, enable -aU, disable -ls --color\n\
4309 -F, --classify append indicator (one of */=>@|) to entries\n\
4310 --file-type likewise, except do not append `*'\n\
4311 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4312 single-column -1, verbose -l, vertical -C\n\
4313 --full-time like -l --time-style=full-iso\n\
4316 -g like -l, but do not list owner\n\
4319 --group-directories-first\n\
4320 group directories before files\n\
4323 -G, --no-group in a long listing, don't print group names\n\
4324 -h, --human-readable with -l, print sizes in human readable format\n\
4325 (e.g., 1K 234M 2G)\n\
4326 --si likewise, but use powers of 1000 not 1024\n\
4329 -H, --dereference-command-line\n\
4330 follow symbolic links listed on the command line\n\
4331 --dereference-command-line-symlink-to-dir\n\
4332 follow each command line symbolic link\n\
4333 that points to a directory\n\
4334 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4335 (overridden by -a or -A)\n\
4338 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4339 none (default), slash (-p),\n\
4340 file-type (--file-type), classify (-F)\n\
4341 -i, --inode print the index number of each file\n\
4342 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4343 -k like --block-size=1K\n\
4346 -l use a long listing format\n\
4347 -L, --dereference when showing file information for a symbolic\n\
4348 link, show information for the file the link\n\
4349 references rather than for the link itself\n\
4350 -m fill width with a comma separated list of entries\n\
4353 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4354 -N, --literal print raw entry names (don't treat e.g. control\n\
4355 characters specially)\n\
4356 -o like -l, but do not list group information\n\
4357 -p, --indicator-style=slash\n\
4358 append / indicator to directories\n\
4361 -q, --hide-control-chars print ? instead of non graphic characters\n\
4362 --show-control-chars show non graphic characters as-is (default\n\
4363 unless program is `ls' and output is a terminal)\n\
4364 -Q, --quote-name enclose entry names in double quotes\n\
4365 --quoting-style=WORD use quoting style WORD for entry names:\n\
4366 literal, locale, shell, shell-always, c, escape\n\
4369 -r, --reverse reverse order while sorting\n\
4370 -R, --recursive list subdirectories recursively\n\
4371 -s, --size print the size of each file, in blocks\n\
4374 -S sort by file size\n\
4375 --sort=WORD sort by WORD instead of name: none -U,\n\
4376 extension -X, size -S, time -t, version -v\n\
4377 --time=WORD with -l, show time as WORD instead of modification\n\
4378 time: atime -u, access -u, use -u, ctime -c,\n\
4379 or status -c; use specified time as sort key\n\
4383 --time-style=STYLE with -l, show times using style STYLE:\n\
4384 full-iso, long-iso, iso, locale, +FORMAT.\n\
4385 FORMAT is interpreted like `date'; if FORMAT is\n\
4386 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4387 non-recent files and FORMAT2 to recent files;\n\
4388 if STYLE is prefixed with `posix-', STYLE\n\
4389 takes effect only outside the POSIX locale\n\
4392 -t sort by modification time\n\
4393 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4396 -u with -lt: sort by, and show, access time\n\
4397 with -l: show access time and sort by name\n\
4398 otherwise: sort by access time\n\
4399 -U do not sort; list entries in directory order\n\
4400 -v sort by version\n\
4403 -w, --width=COLS assume screen width instead of current value\n\
4404 -x list entries by lines instead of by columns\n\
4405 -X sort alphabetically by entry extension\n\
4406 -1 list one file per line\n\
4408 fputs (HELP_OPTION_DESCRIPTION, stdout);
4409 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4411 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4412 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4416 By default, color is not used to distinguish types of files. That is\n\
4417 equivalent to using --color=none. Using the --color option without the\n\
4418 optional WHEN argument is equivalent to using --color=always. With\n\
4419 --color=auto, color codes are output only if standard output is connected\n\
4420 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4421 colors, and can be set easily by the dircolors command.\n\
4425 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4427 emit_bug_reporting_address ();