1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2003 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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>
46 #ifdef GWINSZ_IN_SYS_IOCTL
47 # include <sys/ioctl.h>
50 #ifdef WINSIZE_IN_PTEM
51 # include <sys/stream.h>
52 # include <sys/ptem.h>
63 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
72 #if !defined iswprint && !HAVE_ISWPRINT
73 # define iswprint(wc) 1
76 #ifndef HAVE_DECL_WCWIDTH
77 "this configure-time declaration test was not run"
79 #if !HAVE_DECL_WCWIDTH
83 /* If wcwidth() doesn't exist, assume all printable characters have
87 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
100 #include "full-write.h"
101 #include "hard-locale.h"
104 #include "filemode.h"
105 #include "inttostr.h"
107 #include "mbswidth.h"
109 #include "path-concat.h"
111 #include "quotearg.h"
113 #include "strftime.h"
114 #include "strverscmp.h"
116 #include "xreadlink.h"
118 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
119 : (ls_mode == LS_MULTI_COL \
122 #define WRITTEN_BY _("Written by Richard Stallman and David MacKenzie.")
124 #define obstack_chunk_alloc malloc
125 #define obstack_chunk_free free
127 /* Return an int indicating the result of comparing two integers.
128 Subtracting doesn't always work, due to overflow. */
129 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
131 /* The field width for inode numbers. On some hosts inode numbers are
132 64 bits, so columns won't line up exactly when a huge inode number
133 is encountered, but in practice 7 digits is usually enough. */
135 # define INODE_DIGITS 7
138 /* Arrange to make lstat calls go through the wrapper function
139 on systems with an lstat function that does not dereference symlinks
140 that are specified with a trailing slash. */
141 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
142 int rpl_lstat (const char *, struct stat *);
144 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
147 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
148 # define DT_INIT(Val) = Val
150 # define DT_INIT(Val) /* empty */
154 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
156 # define TIMESPEC_NS(timespec) 0
159 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
160 # define st_author st_uid
163 /* Cray/Unicos DMF: use the file's migrated, not real, status */
165 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
167 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
170 #ifndef LOGIN_NAME_MAX
171 # if _POSIX_LOGIN_NAME_MAX
172 # define LOGIN_NAME_MAX _POSIX_LOGIN_NAME_MAX
174 # define LOGIN_NAME_MAX 17
178 /* The maximum length of a string representation of a user or group ID,
179 not counting any terminating NUL byte. */
180 #define ID_LENGTH_MAX \
181 MAX (LOGIN_NAME_MAX - 1, LONGEST_HUMAN_READABLE)
185 unknown DT_INIT (DT_UNKNOWN),
186 fifo DT_INIT (DT_FIFO),
187 chardev DT_INIT (DT_CHR),
188 directory DT_INIT (DT_DIR),
189 blockdev DT_INIT (DT_BLK),
190 normal DT_INIT (DT_REG),
191 symbolic_link DT_INIT (DT_LNK),
192 sock DT_INIT (DT_SOCK),
193 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
194 | DT_REG | DT_LNK | DT_SOCK))
204 /* For symbolic link, name of the file linked to, otherwise zero. */
207 /* For symbolic link and long listing, st_mode of file linked to, otherwise
211 /* For symbolic link and color printing, 1 if linked-to file
212 exists, otherwise 0. */
215 enum filetype filetype;
218 /* For long listings, true if the file has an access control list. */
224 # define FILE_HAS_ACL(F) ((F)->have_acl)
226 # define FILE_HAS_ACL(F) 0
229 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
231 /* Null is a valid character in a color indicator (think about Epson
232 printers, for example) so we have to use a length/buffer string
237 int len; /* Number of bytes */
238 const char *string; /* Pointer to the same */
248 static size_t quote_name (FILE *out, const char *name,
249 struct quoting_options const *options,
251 static char *make_link_path (const char *path, const char *linkname);
252 static int decode_switches (int argc, char **argv);
253 static int file_interesting (const struct dirent *next);
254 static uintmax_t gobble_file (const char *name, enum filetype type,
255 int explicit_arg, const char *dirname);
256 static void print_color_indicator (const char *name, mode_t mode, int linkok);
257 static void put_indicator (const struct bin_str *ind);
258 static int put_indicator_direct (const struct bin_str *ind);
259 static int length_of_file_name_and_frills (const struct fileinfo *f);
260 static void add_ignore_pattern (const char *pattern);
261 static void attach (char *dest, const char *dirname, const char *name);
262 static void clear_files (void);
263 static void extract_dirs_from_files (const char *dirname,
264 int ignore_dot_and_dot_dot);
265 static void get_link_name (const char *filename, struct fileinfo *f);
266 static void indent (int from, int to);
267 static void init_column_info (void);
268 static void print_current_files (void);
269 static void print_dir (const char *name, const char *realname);
270 static void print_file_name_and_frills (const struct fileinfo *f);
271 static void print_horizontal (void);
272 static void print_long_format (const struct fileinfo *f);
273 static void print_many_per_line (void);
274 static void print_name_with_quoting (const char *p, mode_t mode,
276 struct obstack *stack);
277 static void prep_non_filename_text (void);
278 static void print_type_indicator (mode_t mode);
279 static void print_with_commas (void);
280 static void queue_directory (const char *name, const char *realname);
281 static void sort_files (void);
282 static void parse_ls_color (void);
283 void usage (int status);
285 /* The name the program was run with, stripped of any leading path. */
288 /* Initial size of hash table.
289 Most hierarchies are likely to be shallower than this. */
290 #define INITIAL_TABLE_SIZE 30
292 /* The set of `active' directories, from the current command-line argument
293 to the level in the hierarchy at which files are being listed.
294 A directory is represented by its device and inode numbers (struct dev_ino).
295 A directory is added to this set when ls begins listing it or its
296 entries, and it is removed from the set just after ls has finished
297 processing it. This set is used solely to detect loops, e.g., with
298 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
299 static Hash_table *active_dir_set;
301 #define LOOP_DETECT (!!active_dir_set)
303 /* The table of files in the current directory:
305 `files' points to a vector of `struct fileinfo', one per file.
306 `nfiles' is the number of elements space has been allocated for.
307 `files_index' is the number actually in use. */
309 /* Address of block containing the files that are described. */
310 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
312 /* Length of block that `files' points to, measured in files. */
313 static int nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
315 /* Index of first unused in `files'. */
316 static int files_index; /* FIXME: rename this to e.g. cwd_n_used */
318 /* When nonzero, in a color listing, color each symlink name according to the
319 type of file it points to. Otherwise, color them according to the `ln'
320 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
321 regardless. This is set when `ln=target' appears in LS_COLORS. */
323 static int color_symlink_as_referent;
325 /* mode of appropriate file for colorization */
326 #define FILE_OR_LINK_MODE(File) \
327 ((color_symlink_as_referent && (File)->linkok) \
328 ? (File)->linkmode : (File)->stat.st_mode)
331 /* Record of one pending directory waiting to be listed. */
336 /* If the directory is actually the file pointed to by a symbolic link we
337 were told to list, `realname' will contain the name of the symbolic
338 link, otherwise zero. */
340 struct pending *next;
343 static struct pending *pending_dirs;
345 /* Current time in seconds and nanoseconds since 1970, updated as
346 needed when deciding whether a file is recent. */
348 static time_t current_time = TYPE_MINIMUM (time_t);
349 static int current_time_ns = -1;
351 /* The number of digits to use for block sizes.
352 4, or more if needed for bigger numbers. */
354 static int block_size_size;
358 /* long_format for lots of info, one per line.
359 one_per_line for just names, one per line.
360 many_per_line for just names, many per line, sorted vertically.
361 horizontal for just names, many per line, sorted horizontally.
362 with_commas for just names, many per line, separated by commas.
364 -l (and other options that imply -l), -1, -C, -x and -m control
369 long_format, /* -l and other options that imply -l */
370 one_per_line, /* -1 */
371 many_per_line, /* -C */
376 static enum format format;
378 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
379 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
380 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
383 full_iso_time_style, /* --time-style=full-iso */
384 long_iso_time_style, /* --time-style=long-iso */
385 iso_time_style, /* --time-style=iso */
386 locale_time_style /* --time-style=locale */
389 static char const *const time_style_args[] =
391 "full-iso", "long-iso", "iso", "locale", 0
394 static enum time_style const time_style_types[] =
396 full_iso_time_style, long_iso_time_style, iso_time_style,
400 /* Type of time to print or sort by. Controlled by -c and -u. */
404 time_mtime, /* default */
409 static enum time_type time_type;
411 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
416 sort_name, /* default */
417 sort_extension, /* -X */
420 sort_version /* -v */
423 static enum sort_type sort_type;
425 /* Direction of sort.
426 0 means highest first if numeric,
427 lowest first if alphabetic;
428 these are the defaults.
429 1 means the opposite order in each case. -r */
431 static int sort_reverse;
433 /* Nonzero means to display owner information. -g turns this off. */
435 static int print_owner = 1;
437 /* Nonzero means to display author information. */
439 static bool print_author;
441 /* Nonzero means to display group information. -G and -o turn this off. */
443 static int print_group = 1;
445 /* Nonzero means print the user and group id's as numbers rather
448 static int numeric_ids;
450 /* Nonzero means mention the size in blocks of each file. -s */
452 static int print_block_size;
454 /* Human-readable options for output. */
455 static int human_output_opts;
457 /* The units to use when printing sizes other than file sizes. */
458 static uintmax_t output_block_size;
460 /* Likewise, but for file sizes. */
461 static uintmax_t file_output_block_size = 1;
463 /* Precede each line of long output (per file) with a string like `m,n:'
464 where M is the number of characters after the `:' and before the
465 filename and N is the length of the filename. Using this format,
466 Emacs' dired mode starts up twice as fast, and can handle all
467 strange characters in file names. */
470 /* `none' means don't mention the type of files.
471 `classify' means mention file types and mark executables.
472 `file_type' means mention only file types.
474 Controlled by -F, -p, and --indicator-style. */
478 none, /* --indicator-style=none */
479 classify, /* -F, --indicator-style=classify */
480 file_type /* -p, --indicator-style=file-type */
483 static enum indicator_style indicator_style;
485 /* Names of indicator styles. */
486 static char const *const indicator_style_args[] =
488 "none", "classify", "file-type", 0
491 static enum indicator_style const indicator_style_types[]=
493 none, classify, file_type
496 /* Nonzero means use colors to mark types. Also define the different
497 colors as well as the stuff for the LS_COLORS environment variable.
498 The LS_COLORS variable is now in a termcap-like format. */
500 static int print_with_color;
504 color_never, /* 0: default or --color=never */
505 color_always, /* 1: --color=always */
506 color_if_tty /* 2: --color=tty */
509 enum Dereference_symlink
513 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
514 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
515 DEREF_ALWAYS /* -L */
520 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
521 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
524 static const char *const indicator_name[]=
526 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
527 "bd", "cd", "mi", "or", "ex", "do", NULL
530 struct color_ext_type
532 struct bin_str ext; /* The extension we're looking for */
533 struct bin_str seq; /* The sequence to output when we do */
534 struct color_ext_type *next; /* Next in list */
537 static struct bin_str color_indicator[] =
539 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
540 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
541 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
542 { LEN_STR_PAIR ("0") }, /* no: Normal */
543 { LEN_STR_PAIR ("0") }, /* fi: File: default */
544 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
545 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
546 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
547 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
548 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
549 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
550 { 0, NULL }, /* mi: Missing file: undefined */
551 { 0, NULL }, /* or: Orphanned symlink: undefined */
552 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
553 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
557 static struct color_ext_type *color_ext_list = NULL;
559 /* Buffer for color sequences */
560 static char *color_buf;
562 /* Nonzero means to check for orphaned symbolic link, for displaying
565 static int check_symlink_color;
567 /* Nonzero means mention the inode number of each file. -i */
569 static int print_inode;
571 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
572 other options that imply -l), and -L. */
574 static enum Dereference_symlink dereference;
576 /* Nonzero means when a directory is found, display info on its
579 static int recursive;
581 /* Nonzero means when an argument is a directory name, display info
584 static int immediate_dirs;
586 /* Nonzero means don't omit files whose names start with `.'. -A */
588 static int all_files;
590 /* Nonzero means don't omit files `.' and `..'
591 This flag implies `all_files'. -a */
593 static int really_all_files;
595 /* A linked list of shell-style globbing patterns. If a non-argument
596 file name matches any of these patterns, it is omitted.
597 Controlled by -I. Multiple -I options accumulate.
598 The -B option adds `*~' and `.*~' to this list. */
600 struct ignore_pattern
603 struct ignore_pattern *next;
606 static struct ignore_pattern *ignore_patterns;
608 /* Nonzero means output nongraphic chars in file names as `?'.
609 (-q, --hide-control-chars)
610 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
611 independent. The algorithm is: first, obey the quoting style to get a
612 string representing the file name; then, if qmark_funny_chars is set,
613 replace all nonprintable chars in that string with `?'. It's necessary
614 to replace nonprintable chars even in quoted strings, because we don't
615 want to mess up the terminal if control chars get sent to it, and some
616 quoting methods pass through control chars as-is. */
617 static int qmark_funny_chars;
619 /* Quoting options for file and dir name output. */
621 static struct quoting_options *filename_quoting_options;
622 static struct quoting_options *dirname_quoting_options;
624 /* The number of chars per hardware tab stop. Setting this to zero
625 inhibits the use of TAB characters for separating columns. -T */
628 /* Nonzero means we are listing the working directory because no
629 non-option arguments were given. */
631 static int dir_defaulted;
633 /* Nonzero means print each directory name before listing it. */
635 static int print_dir_name;
637 /* The line length to use for breaking lines in many-per-line format.
638 Can be set with -w. */
640 static int line_length;
642 /* If nonzero, the file listing format requires that stat be called on
645 static int format_needs_stat;
647 /* Similar to `format_needs_stat', but set if only the file type is
650 static int format_needs_type;
652 /* strftime formats for non-recent and recent files, respectively, in
655 static char const *long_time_format[2] =
657 /* strftime format for non-recent files (older than 6 months), in
658 -l output when --time-style=locale is specified. This should
659 contain the year, month and day (at least), in an order that is
660 understood by people in your locale's territory.
661 Please try to keep the number of used screen columns small,
662 because many people work in windows with only 80 columns. But
663 make this as wide as the other string below, for recent files. */
665 /* strftime format for recent files (younger than 6 months), in
666 -l output when --time-style=locale is specified. This should
667 contain the month, day and time (at least), in an order that is
668 understood by people in your locale's territory.
669 Please try to keep the number of used screen columns small,
670 because many people work in windows with only 80 columns. But
671 make this as wide as the other string above, for non-recent files. */
675 /* The exit status to use if we don't get any fatal errors. */
677 static int exit_status;
679 /* For long options that have no equivalent short option, use a
680 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
683 AUTHOR_OPTION = CHAR_MAX + 1,
686 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
689 INDICATOR_STYLE_OPTION,
690 QUOTING_STYLE_OPTION,
691 SHOW_CONTROL_CHARS_OPTION,
698 static struct option const long_options[] =
700 {"all", no_argument, 0, 'a'},
701 {"escape", no_argument, 0, 'b'},
702 {"directory", no_argument, 0, 'd'},
703 {"dired", no_argument, 0, 'D'},
704 {"full-time", no_argument, 0, FULL_TIME_OPTION},
705 {"human-readable", no_argument, 0, 'h'},
706 {"inode", no_argument, 0, 'i'},
707 {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
708 {"numeric-uid-gid", no_argument, 0, 'n'},
709 {"no-group", no_argument, 0, 'G'},
710 {"hide-control-chars", no_argument, 0, 'q'},
711 {"reverse", no_argument, 0, 'r'},
712 {"size", no_argument, 0, 's'},
713 {"width", required_argument, 0, 'w'},
714 {"almost-all", no_argument, 0, 'A'},
715 {"ignore-backups", no_argument, 0, 'B'},
716 {"classify", no_argument, 0, 'F'},
717 {"file-type", no_argument, 0, 'p'},
718 {"si", no_argument, 0, SI_OPTION},
719 {"dereference-command-line", no_argument, 0, 'H'},
720 {"dereference-command-line-symlink-to-dir", no_argument, 0,
721 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
722 {"ignore", required_argument, 0, 'I'},
723 {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
724 {"dereference", no_argument, 0, 'L'},
725 {"literal", no_argument, 0, 'N'},
726 {"quote-name", no_argument, 0, 'Q'},
727 {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
728 {"recursive", no_argument, 0, 'R'},
729 {"format", required_argument, 0, FORMAT_OPTION},
730 {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
731 {"sort", required_argument, 0, SORT_OPTION},
732 {"tabsize", required_argument, 0, 'T'},
733 {"time", required_argument, 0, TIME_OPTION},
734 {"time-style", required_argument, 0, TIME_STYLE_OPTION},
735 {"color", optional_argument, 0, COLOR_OPTION},
736 {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
737 {"author", no_argument, 0, AUTHOR_OPTION},
738 {GETOPT_HELP_OPTION_DECL},
739 {GETOPT_VERSION_OPTION_DECL},
743 static char const *const format_args[] =
745 "verbose", "long", "commas", "horizontal", "across",
746 "vertical", "single-column", 0
749 static enum format const format_types[] =
751 long_format, long_format, with_commas, horizontal, horizontal,
752 many_per_line, one_per_line
755 static char const *const sort_args[] =
757 "none", "time", "size", "extension", "version", 0
760 static enum sort_type const sort_types[] =
762 sort_none, sort_time, sort_size, sort_extension, sort_version
765 static char const *const time_args[] =
767 "atime", "access", "use", "ctime", "status", 0
770 static enum time_type const time_types[] =
772 time_atime, time_atime, time_atime, time_ctime, time_ctime
775 static char const *const color_args[] =
777 /* force and none are for compatibility with another color-ls version */
778 "always", "yes", "force",
779 "never", "no", "none",
780 "auto", "tty", "if-tty", 0
783 static enum color_type const color_types[] =
785 color_always, color_always, color_always,
786 color_never, color_never, color_never,
787 color_if_tty, color_if_tty, color_if_tty
790 /* Information about filling a column. */
798 /* Array with information about column filledness. */
799 static struct column_info *column_info;
801 /* Maximum number of columns ever possible for this display. */
804 /* The minimum width of a colum is 3: 1 character for the name and 2
805 for the separating white space. */
806 #define MIN_COLUMN_WIDTH 3
809 /* This zero-based index is used solely with the --dired option.
810 When that option is in effect, this counter is incremented for each
811 character of output generated by this program so that the beginning
812 and ending indices (in that output) of every file name can be recorded
813 and later output themselves. */
814 static size_t dired_pos;
816 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
818 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
819 #define DIRED_FPUTS(s, stream, s_len) \
820 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
822 /* Like DIRED_FPUTS, but for use when S is a literal string. */
823 #define DIRED_FPUTS_LITERAL(s, stream) \
824 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
826 #define DIRED_INDENT() \
830 DIRED_FPUTS_LITERAL (" ", stdout); \
834 /* With --dired, store pairs of beginning and ending indices of filenames. */
835 static struct obstack dired_obstack;
837 /* With --dired, store pairs of beginning and ending indices of any
838 directory names that appear as headers (just before `total' line)
839 for lists of directory entries. Such directory names are seen when
840 listing hierarchies using -R and when a directory is listed with at
841 least one other command line argument. */
842 static struct obstack subdired_obstack;
844 /* Save the current index on the specified obstack, OBS. */
845 #define PUSH_CURRENT_DIRED_POS(obs) \
849 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
853 /* With -R, this stack is used to help detect directory cycles.
854 The device/inode pairs on this stack mirror the pairs in the
855 active_dir_set hash table. */
856 static struct obstack dev_ino_obstack;
858 /* Push a pair onto the device/inode stack. */
859 #define DEV_INO_PUSH(Dev, Ino) \
862 struct dev_ino *di; \
863 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
864 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
865 di->st_dev = (Dev); \
866 di->st_ino = (Ino); \
870 /* Pop a dev/ino struct off the global dev_ino_obstack
871 and return that struct. */
872 static struct dev_ino
875 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
876 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
877 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
880 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
885 assert (0 <= stat (Name, &sb)); \
886 assert (sb.st_dev == Di.st_dev); \
887 assert (sb.st_ino == Di.st_ino); \
892 /* Write to standard output PREFIX, followed by the quoting style and
893 a space-separated list of the integers stored in OS all on one line. */
896 dired_dump_obstack (const char *prefix, struct obstack *os)
900 n_pos = obstack_object_size (os) / sizeof (dired_pos);
906 pos = (size_t *) obstack_finish (os);
907 fputs (prefix, stdout);
908 for (i = 0; i < n_pos; i++)
909 printf (" %lu", (unsigned long) pos[i]);
915 dev_ino_hash (void const *x, unsigned int table_size)
917 struct dev_ino const *p = x;
918 return (uintmax_t) p->st_ino % table_size;
922 dev_ino_compare (void const *x, void const *y)
924 struct dev_ino const *a = x;
925 struct dev_ino const *b = y;
926 return SAME_INODE (*a, *b) ? true : false;
930 dev_ino_free (void *x)
935 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
936 active directories. Return nonzero if there is already a matching
937 entry in the table. Otherwise, return zero. */
940 visit_dir (dev_t dev, ino_t ino)
943 struct dev_ino *ent_from_table;
946 ent = XMALLOC (struct dev_ino, 1);
950 /* Attempt to insert this entry into the table. */
951 ent_from_table = hash_insert (active_dir_set, ent);
953 if (ent_from_table == NULL)
955 /* Insertion failed due to lack of memory. */
959 found_match = (ent_from_table != ent);
963 /* ent was not inserted, so free it. */
971 free_pending_ent (struct pending *p)
981 restore_default_color (void)
983 if (put_indicator_direct (&color_indicator[C_LEFT]) == 0)
984 put_indicator_direct (&color_indicator[C_RIGHT]);
987 /* Upon interrupt, suspend, hangup, etc. ensure that the
988 terminal text color is restored to the default. */
993 signal (sig, SIG_IGN);
996 restore_default_color ();
998 /* SIGTSTP is special, since the application can receive that signal more
999 than once. In this case, don't set the signal handler to the default.
1000 Instead, just raise the uncatchable SIGSTOP. */
1008 struct sigaction sigact;
1010 sigact.sa_handler = SIG_DFL;
1011 sigemptyset (&sigact.sa_mask);
1012 sigact.sa_flags = 0;
1013 sigaction (sig, &sigact, NULL);
1015 signal (sig, SIG_DFL);
1023 main (int argc, char **argv)
1026 register struct pending *thispend;
1027 unsigned int n_files;
1029 initialize_main (&argc, &argv);
1030 program_name = argv[0];
1031 setlocale (LC_ALL, "");
1032 bindtextdomain (PACKAGE, LOCALEDIR);
1033 textdomain (PACKAGE);
1035 atexit (close_stdout);
1037 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1038 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1045 i = decode_switches (argc, argv);
1047 if (print_with_color)
1050 /* Test print_with_color again, because the call to parse_ls_color
1051 may have just reset it -- e.g., if LS_COLORS is invalid. */
1052 if (print_with_color)
1054 prep_non_filename_text ();
1055 /* Avoid following symbolic links when possible. */
1056 if (color_indicator[C_ORPHAN].string != NULL
1057 || (color_indicator[C_MISSING].string != NULL
1058 && format == long_format))
1059 check_symlink_color = 1;
1063 static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE,
1064 SIGQUIT, SIGTERM, SIGTSTP };
1065 unsigned nsigs = sizeof sigs / sizeof *sigs;
1067 struct sigaction oldact, newact;
1068 sigset_t caught_signals;
1070 sigemptyset (&caught_signals);
1071 for (j = 0; j < nsigs; j++)
1072 sigaddset (&caught_signals, sigs[j]);
1073 newact.sa_handler = sighandler;
1074 newact.sa_mask = caught_signals;
1075 newact.sa_flags = 0;
1078 for (j = 0; j < nsigs; j++)
1082 sigaction (sig, NULL, &oldact);
1083 if (oldact.sa_handler != SIG_IGN)
1084 sigaction (sig, &newact, NULL);
1086 if (signal (sig, SIG_IGN) != SIG_IGN)
1087 signal (sig, sighandler);
1093 if (dereference == DEREF_UNDEFINED)
1094 dereference = ((immediate_dirs
1095 || indicator_style == classify
1096 || format == long_format)
1098 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1100 /* When using -R, initialize a data structure we'll use to
1101 detect any directory cycles. */
1104 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1108 if (active_dir_set == NULL)
1111 obstack_init (&dev_ino_obstack);
1114 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1115 || format == long_format
1116 || dereference == DEREF_ALWAYS
1117 || print_block_size || print_inode;
1118 format_needs_type = (format_needs_stat == 0
1119 && (recursive || print_with_color
1120 || indicator_style != none));
1124 obstack_init (&dired_obstack);
1125 obstack_init (&subdired_obstack);
1129 files = XMALLOC (struct fileinfo, nfiles);
1138 for (; i < argc; i++)
1140 gobble_file (argv[i], unknown, 1, "");
1146 gobble_file (".", directory, 1, "");
1148 queue_directory (".", 0);
1154 if (!immediate_dirs)
1155 extract_dirs_from_files ("", 0);
1156 /* `files_index' might be zero now. */
1159 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1160 (and not pending_dirs->name) because there may be no markers in the queue
1161 at this point. A marker may be enqueued when extract_dirs_from_files is
1162 called with a non-empty string or via print_dir. */
1165 print_current_files ();
1167 DIRED_PUTCHAR ('\n');
1169 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1172 while (pending_dirs)
1174 thispend = pending_dirs;
1175 pending_dirs = pending_dirs->next;
1179 if (thispend->name == NULL)
1181 /* thispend->name == NULL means this is a marker entry
1182 indicating we've finished processing the directory.
1183 Use its dev/ino numbers to remove the corresponding
1184 entry from the active_dir_set hash table. */
1185 struct dev_ino di = dev_ino_pop ();
1186 struct dev_ino *found = hash_delete (active_dir_set, &di);
1187 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1189 dev_ino_free (found);
1190 free_pending_ent (thispend);
1195 print_dir (thispend->name, thispend->realname);
1197 free_pending_ent (thispend);
1203 /* No need to free these since we're about to exit. */
1204 dired_dump_obstack ("//DIRED//", &dired_obstack);
1205 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1206 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1207 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1210 /* Restore default color before exiting */
1211 if (print_with_color)
1213 put_indicator (&color_indicator[C_LEFT]);
1214 put_indicator (&color_indicator[C_RIGHT]);
1219 assert (hash_get_n_entries (active_dir_set) == 0);
1220 hash_free (active_dir_set);
1226 /* Set all the option flags according to the switches specified.
1227 Return the index of the first non-option argument. */
1230 decode_switches (int argc, char **argv)
1233 char *time_style_option = 0;
1235 /* Record whether there is an option specifying sort type. */
1236 int sort_type_specified = 0;
1238 qmark_funny_chars = 0;
1240 /* initialize all switches to default settings */
1245 /* This is for the `dir' program. */
1246 format = many_per_line;
1247 set_quoting_style (NULL, escape_quoting_style);
1250 case LS_LONG_FORMAT:
1251 /* This is for the `vdir' program. */
1252 format = long_format;
1253 set_quoting_style (NULL, escape_quoting_style);
1257 /* This is for the `ls' program. */
1258 if (isatty (STDOUT_FILENO))
1260 format = many_per_line;
1261 /* See description of qmark_funny_chars, above. */
1262 qmark_funny_chars = 1;
1266 format = one_per_line;
1267 qmark_funny_chars = 0;
1275 time_type = time_mtime;
1276 sort_type = sort_name;
1279 print_block_size = 0;
1280 indicator_style = none;
1282 dereference = DEREF_UNDEFINED;
1286 really_all_files = 0;
1287 ignore_patterns = 0;
1289 /* FIXME: put this in a function. */
1291 char const *q_style = getenv ("QUOTING_STYLE");
1294 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1296 set_quoting_style (NULL, quoting_style_vals[i]);
1299 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1300 quotearg (q_style));
1305 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1306 human_output_opts = human_options (ls_block_size, false,
1307 &output_block_size);
1308 if (ls_block_size || getenv ("BLOCK_SIZE"))
1309 file_output_block_size = output_block_size;
1314 char const *p = getenv ("COLUMNS");
1318 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1319 && 0 < tmp_long && tmp_long <= INT_MAX)
1321 line_length = (int) tmp_long;
1326 _("ignoring invalid width in environment variable COLUMNS: %s"),
1336 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
1337 line_length = ws.ws_col;
1341 /* Using the TABSIZE environment variable is not POSIX-approved.
1342 Ignore it when POSIXLY_CORRECT is set. */
1346 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1349 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1350 && 0 <= tmp_long && tmp_long <= INT_MAX)
1352 tabsize = (int) tmp_long;
1357 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1363 while ((c = getopt_long (argc, argv,
1364 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1365 long_options, NULL)) != -1)
1374 really_all_files = 1;
1378 set_quoting_style (NULL, escape_quoting_style);
1382 time_type = time_ctime;
1390 /* Same as enabling -a -U and disabling -l -s. */
1392 really_all_files = 1;
1393 sort_type = sort_none;
1394 sort_type_specified = 1;
1396 if (format == long_format)
1397 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1398 print_block_size = 0; /* disable -s */
1399 print_with_color = 0; /* disable --color */
1403 format = long_format;
1408 human_output_opts = human_autoscale | human_SI | human_base_1024;
1409 file_output_block_size = output_block_size = 1;
1417 human_output_opts = 0;
1418 file_output_block_size = output_block_size = 1024;
1422 format = long_format;
1426 format = with_commas;
1431 format = long_format;
1434 case 'o': /* Just like -l, but don't display group info. */
1435 format = long_format;
1440 indicator_style = file_type;
1444 qmark_funny_chars = 1;
1452 print_block_size = 1;
1456 sort_type = sort_time;
1457 sort_type_specified = 1;
1461 time_type = time_atime;
1465 sort_type = sort_version;
1466 sort_type_specified = 1;
1472 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1473 || tmp_long <= 0 || tmp_long > INT_MAX)
1474 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1476 line_length = (int) tmp_long;
1481 format = horizontal;
1485 really_all_files = 0;
1490 add_ignore_pattern ("*~");
1491 add_ignore_pattern (".*~");
1495 format = many_per_line;
1503 indicator_style = classify;
1506 case 'G': /* inhibit display of group info */
1511 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1514 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1515 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1519 add_ignore_pattern (optarg);
1523 dereference = DEREF_ALWAYS;
1527 set_quoting_style (NULL, literal_quoting_style);
1531 set_quoting_style (NULL, c_quoting_style);
1539 sort_type = sort_size;
1540 sort_type_specified = 1;
1546 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1547 || tmp_long < 0 || tmp_long > INT_MAX)
1548 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1550 tabsize = (int) tmp_long;
1555 sort_type = sort_none;
1556 sort_type_specified = 1;
1560 sort_type = sort_extension;
1561 sort_type_specified = 1;
1565 /* -1 has no effect after -l. */
1566 if (format != long_format)
1567 format = one_per_line;
1571 print_author = true;
1575 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1576 sort_type_specified = 1;
1580 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1584 format = XARGMATCH ("--format", optarg, format_args, format_types);
1587 case FULL_TIME_OPTION:
1588 format = long_format;
1589 time_style_option = "full-iso";
1596 i = XARGMATCH ("--color", optarg, color_args, color_types);
1598 /* Using --color with no argument is equivalent to using
1602 print_with_color = (i == color_always
1603 || (i == color_if_tty
1604 && isatty (STDOUT_FILENO)));
1606 if (print_with_color)
1608 /* Don't use TAB characters in output. Some terminal
1609 emulators can't handle the combination of tabs and
1610 color codes on the same line. */
1616 case INDICATOR_STYLE_OPTION:
1617 indicator_style = XARGMATCH ("--indicator-style", optarg,
1618 indicator_style_args,
1619 indicator_style_types);
1622 case QUOTING_STYLE_OPTION:
1623 set_quoting_style (NULL,
1624 XARGMATCH ("--quoting-style", optarg,
1626 quoting_style_vals));
1629 case TIME_STYLE_OPTION:
1630 time_style_option = optarg;
1633 case SHOW_CONTROL_CHARS_OPTION:
1634 qmark_funny_chars = 0;
1637 case BLOCK_SIZE_OPTION:
1638 human_output_opts = human_options (optarg, true, &output_block_size);
1639 file_output_block_size = output_block_size;
1643 human_output_opts = human_autoscale | human_SI;
1644 file_output_block_size = output_block_size = 1;
1647 case_GETOPT_HELP_CHAR;
1649 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
1652 usage (EXIT_FAILURE);
1656 filename_quoting_options = clone_quoting_options (NULL);
1657 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1658 set_char_quoting (filename_quoting_options, ' ', 1);
1659 if (indicator_style != none)
1662 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1663 set_char_quoting (filename_quoting_options, *p, 1);
1666 dirname_quoting_options = clone_quoting_options (NULL);
1667 set_char_quoting (dirname_quoting_options, ':', 1);
1669 /* --dired is meaningful only with --format=long (-l).
1670 Otherwise, ignore it. FIXME: warn about this?
1671 Alternatively, make --dired imply --format=long? */
1672 if (dired && format != long_format)
1675 /* If -c or -u is specified and not -l (or any other option that implies -l),
1676 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1677 The behavior of ls when using either -c or -u but with neither -l nor -t
1678 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1679 sort by atime (this is the one that's not specified by the POSIX spec),
1680 -lu means show atime and sort by name, -lut means show atime and sort
1683 if ((time_type == time_ctime || time_type == time_atime)
1684 && !sort_type_specified && format != long_format)
1686 sort_type = sort_time;
1689 if (format == long_format)
1691 char *style = time_style_option;
1692 static char const posix_prefix[] = "posix-";
1695 if (! (style = getenv ("TIME_STYLE")))
1696 style = "posix-long-iso";
1698 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1700 if (! hard_locale (LC_TIME))
1702 style += sizeof posix_prefix - 1;
1707 char *p0 = style + 1;
1708 char *p1 = strchr (p0, '\n');
1713 if (strchr (p1 + 1, '\n'))
1714 error (EXIT_FAILURE, 0, _("invalid time style format %s"),
1718 long_time_format[0] = p0;
1719 long_time_format[1] = p1;
1722 switch (XARGMATCH ("time style", style,
1726 case full_iso_time_style:
1727 long_time_format[0] = long_time_format[1] =
1728 "%Y-%m-%d %H:%M:%S.%N %z";
1731 case long_iso_time_style:
1732 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1735 case iso_time_style:
1736 long_time_format[0] = "%Y-%m-%d ";
1737 long_time_format[1] = "%m-%d %H:%M";
1740 case locale_time_style:
1741 if (hard_locale (LC_TIME))
1744 for (i = 0; i < 2; i++)
1745 long_time_format[i] =
1746 dcgettext (NULL, long_time_format[i], LC_TIME);
1754 /* Parse a string as part of the LS_COLORS variable; this may involve
1755 decoding all kinds of escape characters. If equals_end is set an
1756 unescaped equal sign ends the string, otherwise only a : or \0
1757 does. Returns the number of characters output, or -1 on failure.
1759 The resulting string is *not* null-terminated, but may contain
1762 Note that both dest and src are char **; on return they point to
1763 the first free byte after the array and the character that ended
1764 the input string, respectively. */
1767 get_funky_string (char **dest, const char **src, int equals_end)
1769 int num; /* For numerical codes */
1770 int count; /* Something to count with */
1772 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1777 p = *src; /* We don't want to double-indirect */
1778 q = *dest; /* the whole darn time. */
1780 count = 0; /* No characters counted in yet. */
1783 state = ST_GND; /* Start in ground state. */
1784 while (state < ST_END)
1788 case ST_GND: /* Ground state (no escapes) */
1793 state = ST_END; /* End of string */
1796 state = ST_BACKSLASH; /* Backslash scape sequence */
1800 state = ST_CARET; /* Caret escape */
1806 state = ST_END; /* End */
1809 /* else fall through */
1817 case ST_BACKSLASH: /* Backslash escaped character */
1828 state = ST_OCTAL; /* Octal sequence */
1833 state = ST_HEX; /* Hex sequence */
1836 case 'a': /* Bell */
1837 num = 7; /* Not all C compilers know what \a means */
1839 case 'b': /* Backspace */
1842 case 'e': /* Escape */
1845 case 'f': /* Form feed */
1848 case 'n': /* Newline */
1851 case 'r': /* Carriage return */
1857 case 'v': /* Vtab */
1860 case '?': /* Delete */
1863 case '_': /* Space */
1866 case '\0': /* End of string */
1867 state = ST_ERROR; /* Error! */
1869 default: /* Escaped character like \ ^ : = */
1873 if (state == ST_BACKSLASH)
1882 case ST_OCTAL: /* Octal sequence */
1883 if (*p < '0' || *p > '7')
1890 num = (num << 3) + (*(p++) - '0');
1893 case ST_HEX: /* Hex sequence */
1906 num = (num << 4) + (*(p++) - '0');
1914 num = (num << 4) + (*(p++) - 'a') + 10;
1922 num = (num << 4) + (*(p++) - 'A') + 10;
1932 case ST_CARET: /* Caret escape */
1933 state = ST_GND; /* Should be the next state... */
1934 if (*p >= '@' && *p <= '~')
1936 *(q++) = *(p++) & 037;
1956 return state == ST_ERROR ? -1 : count;
1960 parse_ls_color (void)
1962 const char *p; /* Pointer to character being parsed */
1963 char *buf; /* color_buf buffer pointer */
1964 int state; /* State of parser */
1965 int ind_no; /* Indicator number */
1966 char label[3]; /* Indicator label */
1967 struct color_ext_type *ext; /* Extension we are working on */
1969 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1973 strcpy (label, "??");
1975 /* This is an overly conservative estimate, but any possible
1976 LS_COLORS string will *not* generate a color_buf longer than
1977 itself, so it is a safe way of allocating a buffer in
1979 buf = color_buf = xstrdup (p);
1986 case 1: /* First label character */
1994 /* Allocate new extension block and add to head of
1995 linked list (this way a later definition will
1996 override an earlier one, which can be useful for
1997 having terminal-specific defs override global). */
1999 ext = XMALLOC (struct color_ext_type, 1);
2000 ext->next = color_ext_list;
2001 color_ext_list = ext;
2004 ext->ext.string = buf;
2006 state = (ext->ext.len =
2007 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
2011 state = 0; /* Done! */
2014 default: /* Assume it is file type label */
2021 case 2: /* Second label character */
2028 state = -1; /* Error */
2031 case 3: /* Equal sign after indicator label */
2032 state = -1; /* Assume failure... */
2033 if (*(p++) == '=')/* It *should* be... */
2035 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2037 if (STREQ (label, indicator_name[ind_no]))
2039 color_indicator[ind_no].string = buf;
2040 state = ((color_indicator[ind_no].len =
2041 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
2046 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2050 case 4: /* Equal sign after *.ext */
2053 ext->seq.string = buf;
2054 state = (ext->seq.len =
2055 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
2065 struct color_ext_type *e;
2066 struct color_ext_type *e2;
2069 _("unparsable value for LS_COLORS environment variable"));
2071 for (e = color_ext_list; e != NULL; /* empty */)
2077 print_with_color = 0;
2080 if (color_indicator[C_LINK].len == 6
2081 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2082 color_symlink_as_referent = 1;
2085 /* Request that the directory named NAME have its contents listed later.
2086 If REALNAME is nonzero, it will be used instead of NAME when the
2087 directory name is printed. This allows symbolic links to directories
2088 to be treated as regular directories but still be listed under their
2089 real names. NAME == NULL is used to insert a marker entry for the
2090 directory named in REALNAME.
2091 If F is non-NULL, we use its dev/ino information to save
2092 a call to stat -- when doing a recursive (-R) traversal. */
2095 queue_directory (const char *name, const char *realname)
2097 struct pending *new;
2099 new = XMALLOC (struct pending, 1);
2100 new->realname = realname ? xstrdup (realname) : NULL;
2101 new->name = name ? xstrdup (name) : NULL;
2102 new->next = pending_dirs;
2106 /* Read directory `name', and list the files in it.
2107 If `realname' is nonzero, print its name instead of `name';
2108 this is used for symbolic links to directories. */
2111 print_dir (const char *name, const char *realname)
2114 register struct dirent *next;
2115 register uintmax_t total_blocks = 0;
2116 static int first = 1;
2119 dirp = opendir (name);
2122 error (0, errno, "%s", quotearg_colon (name));
2129 struct stat dir_stat;
2130 int fd = dirfd (dirp);
2132 /* If dirfd failed, endure the overhead of using stat. */
2134 ? fstat (fd, &dir_stat)
2135 : stat (name, &dir_stat)) < 0)
2137 error (0, errno, _("cannot determine device and inode of %s"),
2138 quotearg_colon (name));
2143 /* If we've already visited this dev/inode pair, warn that
2144 we've found a loop, and do not process this directory. */
2145 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2147 error (0, 0, _("not listing already-listed directory: %s"),
2148 quotearg_colon (name));
2152 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2155 /* Read the directory entries, and insert the subfiles into the `files'
2162 /* Set errno to zero so we can distinguish between a readdir failure
2163 and when readdir simply finds that there are no more entries. */
2165 if ((next = readdir (dirp)) == NULL)
2169 /* Save/restore errno across closedir call. */
2174 /* Arrange to give a diagnostic after exiting this loop. */
2180 if (file_interesting (next))
2182 enum filetype type = unknown;
2184 #if HAVE_STRUCT_DIRENT_D_TYPE
2185 if (next->d_type == DT_BLK
2186 || next->d_type == DT_CHR
2187 || next->d_type == DT_DIR
2188 || next->d_type == DT_FIFO
2189 || next->d_type == DT_LNK
2190 || next->d_type == DT_REG
2191 || next->d_type == DT_SOCK)
2192 type = next->d_type;
2194 total_blocks += gobble_file (next->d_name, type, 0, name);
2198 if (dirp == NULL || CLOSEDIR (dirp))
2200 error (0, errno, _("reading directory %s"), quotearg_colon (name));
2202 /* Don't return; print whatever we got. */
2205 /* Sort the directory contents. */
2208 /* If any member files are subdirectories, perhaps they should have their
2209 contents listed rather than being mentioned here as files. */
2212 extract_dirs_from_files (name, 1);
2214 if (recursive || print_dir_name)
2217 DIRED_PUTCHAR ('\n');
2220 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2221 dired_pos += quote_name (stdout, realname ? realname : name,
2222 dirname_quoting_options, NULL);
2223 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2224 DIRED_FPUTS_LITERAL (":\n", stdout);
2227 if (format == long_format || print_block_size)
2230 char buf[LONGEST_HUMAN_READABLE + 1];
2234 DIRED_FPUTS (p, stdout, strlen (p));
2235 DIRED_PUTCHAR (' ');
2236 p = human_readable (total_blocks, buf, human_output_opts,
2237 ST_NBLOCKSIZE, output_block_size);
2238 DIRED_FPUTS (p, stdout, strlen (p));
2239 DIRED_PUTCHAR ('\n');
2243 print_current_files ();
2246 /* Add `pattern' to the list of patterns for which files that match are
2250 add_ignore_pattern (const char *pattern)
2252 register struct ignore_pattern *ignore;
2254 ignore = XMALLOC (struct ignore_pattern, 1);
2255 ignore->pattern = pattern;
2256 /* Add it to the head of the linked list. */
2257 ignore->next = ignore_patterns;
2258 ignore_patterns = ignore;
2261 /* Return nonzero if the file in `next' should be listed. */
2264 file_interesting (const struct dirent *next)
2266 register struct ignore_pattern *ignore;
2268 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2269 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2272 if (really_all_files
2273 || next->d_name[0] != '.'
2275 && next->d_name[1] != '\0'
2276 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2282 /* Enter and remove entries in the table `files'. */
2284 /* Empty the table of files. */
2291 for (i = 0; i < files_index; i++)
2293 free (files[i].name);
2294 if (files[i].linkname)
2295 free (files[i].linkname);
2299 block_size_size = 4;
2302 /* Add a file to the current table of files.
2303 Verify that the file exists, and print an error message if it does not.
2304 Return the number of blocks that the file occupies. */
2307 gobble_file (const char *name, enum filetype type, int explicit_arg,
2308 const char *dirname)
2310 register uintmax_t blocks;
2311 register char *path;
2313 if (files_index == nfiles)
2316 files = XREALLOC (files, struct fileinfo, nfiles);
2319 files[files_index].linkname = 0;
2320 files[files_index].linkmode = 0;
2321 files[files_index].linkok = 0;
2324 || format_needs_stat
2325 || (format_needs_type
2328 /* FIXME: remove this disjunct.
2329 I don't think we care about symlinks here, but for now
2330 this won't make a big performance difference. */
2331 || type == symbolic_link
2333 /* --indicator-style=classify (aka -F)
2334 requires that we stat each regular file
2335 to see if it's executable. */
2336 || (type == normal && (indicator_style == classify
2337 /* This is so that --color ends up
2338 highlighting files with the executable
2339 bit set even when options like -F are
2341 || print_with_color)))))
2344 /* `path' is the absolute pathname of this file. */
2347 if (name[0] == '/' || dirname[0] == 0)
2348 path = (char *) name;
2351 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
2352 attach (path, dirname, name);
2355 switch (dereference)
2358 err = stat (path, &files[files_index].stat);
2361 case DEREF_COMMAND_LINE_ARGUMENTS:
2362 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2366 err = stat (path, &files[files_index].stat);
2368 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2371 need_lstat = (err < 0
2373 : ! S_ISDIR (files[files_index].stat.st_mode));
2377 /* stat failed because of ENOENT, maybe indicating a dangling
2378 symlink. Or stat succeeded, PATH does not refer to a
2379 directory, and --dereference-command-line-symlink-to-dir is
2380 in effect. Fall through so that we call lstat instead. */
2383 default: /* DEREF_NEVER */
2384 err = lstat (path, &files[files_index].stat);
2390 error (0, errno, "%s", quotearg_colon (path));
2396 if (format == long_format)
2398 int n = file_has_acl (path, &files[files_index].stat);
2399 files[files_index].have_acl = (0 < n);
2401 error (0, errno, "%s", quotearg_colon (path));
2405 if (S_ISLNK (files[files_index].stat.st_mode)
2406 && (format == long_format || check_symlink_color))
2409 struct stat linkstats;
2411 get_link_name (path, &files[files_index]);
2412 linkpath = make_link_path (path, files[files_index].linkname);
2414 /* Avoid following symbolic links when possible, ie, when
2415 they won't be traced and when no indicator is needed. */
2417 && (indicator_style != none || check_symlink_color)
2418 && stat (linkpath, &linkstats) == 0)
2420 files[files_index].linkok = 1;
2422 /* Symbolic links to directories that are mentioned on the
2423 command line are automatically traced if not being
2425 if (!explicit_arg || format == long_format
2426 || !S_ISDIR (linkstats.st_mode))
2428 /* Get the linked-to file's mode for the filetype indicator
2429 in long listings. */
2430 files[files_index].linkmode = linkstats.st_mode;
2431 files[files_index].linkok = 1;
2438 if (S_ISLNK (files[files_index].stat.st_mode))
2439 files[files_index].filetype = symbolic_link;
2440 else if (S_ISDIR (files[files_index].stat.st_mode))
2442 if (explicit_arg && !immediate_dirs)
2443 files[files_index].filetype = arg_directory;
2445 files[files_index].filetype = directory;
2448 files[files_index].filetype = normal;
2450 blocks = ST_NBLOCKS (files[files_index].stat);
2452 char buf[LONGEST_HUMAN_READABLE + 1];
2453 int len = strlen (human_readable (blocks, buf, human_output_opts,
2454 ST_NBLOCKSIZE, output_block_size));
2455 if (block_size_size < len)
2456 block_size_size = len < 7 ? len : 7;
2461 files[files_index].filetype = type;
2462 #if HAVE_STRUCT_DIRENT_D_TYPE
2463 files[files_index].stat.st_mode = DTTOIF (type);
2468 files[files_index].name = xstrdup (name);
2476 /* Put the name of the file that `filename' is a symbolic link to
2477 into the `linkname' field of `f'. */
2480 get_link_name (const char *filename, struct fileinfo *f)
2482 f->linkname = xreadlink (filename);
2483 if (f->linkname == NULL)
2485 error (0, errno, _("cannot read symbolic link %s"),
2486 quotearg_colon (filename));
2491 /* If `linkname' is a relative path and `path' contains one or more
2492 leading directories, return `linkname' with those directories
2493 prepended; otherwise, return a copy of `linkname'.
2494 If `linkname' is zero, return zero. */
2497 make_link_path (const char *path, const char *linkname)
2505 if (*linkname == '/')
2506 return xstrdup (linkname);
2508 /* The link is to a relative path. Prepend any leading path
2509 in `path' to the link name. */
2510 linkbuf = strrchr (path, '/');
2512 return xstrdup (linkname);
2514 bufsiz = linkbuf - path + 1;
2515 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2516 strncpy (linkbuf, path, bufsiz);
2517 strcpy (linkbuf + bufsiz, linkname);
2522 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2523 This is so we don't try to recurse on `././././. ...' */
2526 basename_is_dot_or_dotdot (const char *name)
2528 char const *base = base_name (name);
2529 return DOT_OR_DOTDOT (base);
2532 /* Remove any entries from `files' that are for directories,
2533 and queue them to be listed as directories instead.
2534 `dirname' is the prefix to prepend to each dirname
2535 to make it correct relative to ls's working dir.
2536 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2537 This is desirable when processing directories recursively. */
2540 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2544 if (*dirname && LOOP_DETECT)
2546 /* Insert a marker entry first. When we dequeue this marker entry,
2547 we'll know that DIRNAME has been processed and may be removed
2548 from the set of active directories. */
2549 queue_directory (NULL, dirname);
2552 /* Queue the directories last one first, because queueing reverses the
2554 for (i = files_index - 1; i >= 0; i--)
2555 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2556 && (!ignore_dot_and_dot_dot
2557 || !basename_is_dot_or_dotdot (files[i].name)))
2559 if (files[i].name[0] == '/' || dirname[0] == 0)
2561 queue_directory (files[i].name, files[i].linkname);
2565 char *path = path_concat (dirname, files[i].name, NULL);
2566 queue_directory (path, files[i].linkname);
2569 if (files[i].filetype == arg_directory)
2570 free (files[i].name);
2573 /* Now delete the directories from the table, compacting all the remaining
2576 for (i = 0, j = 0; i < files_index; i++)
2577 if (files[i].filetype != arg_directory)
2578 files[j++] = files[i];
2582 /* Use strcoll to compare strings in this locale. If an error occurs,
2583 report an error and longjmp to failed_strcoll. */
2585 static jmp_buf failed_strcoll;
2588 xstrcoll (char const *a, char const *b)
2592 diff = strcoll (a, b);
2595 error (0, errno, _("cannot compare file names %s and %s"),
2596 quote_n (0, a), quote_n (1, b));
2598 longjmp (failed_strcoll, 1);
2603 /* Comparison routines for sorting the files. */
2605 typedef void const *V;
2608 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2609 int (*cmp) (char const *, char const *))
2611 int diff = CTIME_CMP (b->stat, a->stat);
2612 return diff ? diff : cmp (a->name, b->name);
2614 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2615 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2616 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2617 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2620 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2621 int (*cmp) (char const *, char const *))
2623 int diff = MTIME_CMP (b->stat, a->stat);
2624 return diff ? diff : cmp (a->name, b->name);
2626 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2627 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2628 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2629 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2632 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2633 int (*cmp) (char const *, char const *))
2635 int diff = ATIME_CMP (b->stat, a->stat);
2636 return diff ? diff : cmp (a->name, b->name);
2638 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2639 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2640 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2641 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2644 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2645 int (*cmp) (char const *, char const *))
2647 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2648 return diff ? diff : cmp (a->name, b->name);
2650 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2651 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2652 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2653 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2656 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2658 return strverscmp (a->name, b->name);
2660 static int compare_version (V a, V b) { return cmp_version (a, b); }
2661 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2664 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2665 int (*cmp) (char const *, char const *))
2667 return cmp (a->name, b->name);
2669 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2670 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2671 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2672 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2674 /* Compare file extensions. Files with no extension are `smallest'.
2675 If extensions are the same, compare by filenames instead. */
2678 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2679 int (*cmp) (char const *, char const *))
2681 char const *base1 = strrchr (a->name, '.');
2682 char const *base2 = strrchr (b->name, '.');
2683 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2684 return diff ? diff : cmp (a->name, b->name);
2686 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2687 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2688 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2689 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2691 /* Sort the files now in the table. */
2696 /* `func' must be `volatile', so it can't be
2697 clobbered by a `longjmp' into this function. */
2698 int (* volatile func) (V, V);
2708 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2711 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2714 func = sort_reverse ? rev_cmp_atime : compare_atime;
2721 func = sort_reverse ? rev_cmp_name : compare_name;
2723 case sort_extension:
2724 func = sort_reverse ? rev_cmp_extension : compare_extension;
2727 func = sort_reverse ? rev_cmp_size : compare_size;
2730 func = sort_reverse ? rev_cmp_version : compare_version;
2736 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2737 ignore strcoll failures, as a failing strcoll might be a
2738 comparison function that is not a total order, and if we ignored
2739 the failure this might cause qsort to dump core. */
2741 if (setjmp (failed_strcoll))
2749 func = sort_reverse ? rev_str_ctime : compstr_ctime;
2752 func = sort_reverse ? rev_str_mtime : compstr_mtime;
2755 func = sort_reverse ? rev_str_atime : compstr_atime;
2762 func = sort_reverse ? rev_str_name : compstr_name;
2764 case sort_extension:
2765 func = sort_reverse ? rev_str_extension : compstr_extension;
2768 func = sort_reverse ? rev_str_size : compstr_size;
2775 qsort (files, files_index, sizeof (struct fileinfo), func);
2778 /* List all the files now in the table. */
2781 print_current_files (void)
2788 for (i = 0; i < files_index; i++)
2790 print_file_name_and_frills (files + i);
2796 init_column_info ();
2797 print_many_per_line ();
2801 init_column_info ();
2802 print_horizontal ();
2806 print_with_commas ();
2810 for (i = 0; i < files_index; i++)
2812 print_long_format (files + i);
2813 DIRED_PUTCHAR ('\n');
2819 /* Return the expected number of columns in a long-format time stamp,
2820 or zero if it cannot be calculated. */
2823 long_time_expected_width (void)
2825 static int width = -1;
2830 struct tm const *tm = localtime (&epoch);
2831 char const *fmt = long_time_format[0];
2833 char *buf = initbuf;
2834 size_t bufsize = sizeof initbuf;
2840 len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2843 buf = alloca (bufsize *= 2);
2846 width = mbsnwidth (buf, len, 0);
2854 /* Get the current time. */
2857 get_current_time (void)
2859 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2861 struct timespec timespec;
2862 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
2864 current_time = timespec.tv_sec;
2865 current_time_ns = timespec.tv_nsec;
2871 /* The clock does not have nanosecond resolution, so get the maximum
2872 possible value for the current time that is consistent with the
2873 reported clock. That way, files are not considered to be in the
2874 future merely because their time stamps have higher resolution
2875 than the clock resolution. */
2877 #if HAVE_GETTIMEOFDAY
2879 struct timeval timeval;
2880 if (gettimeofday (&timeval, NULL) == 0)
2882 current_time = timeval.tv_sec;
2883 current_time_ns = timeval.tv_usec * 1000 + 999;
2889 current_time = time (NULL);
2890 current_time_ns = 999999999;
2893 /* Format into BUFFER the name or id of the user with id U. Return
2894 the length of the formatted buffer, not counting the terminating
2898 format_user (char *buffer, uid_t u)
2900 char const *name = (numeric_ids ? NULL : getuser (u));
2902 sprintf (buffer, "%-8s ", name);
2904 sprintf (buffer, "%-8lu ", (unsigned long) u);
2905 return strlen (buffer);
2908 /* Print information about F in long format. */
2911 print_long_format (const struct fileinfo *f)
2915 [LONGEST_HUMAN_READABLE + 1 /* inode */
2916 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
2917 + sizeof (modebuf) - 1 + 1 /* mode string */
2918 + LONGEST_HUMAN_READABLE + 1 /* st_nlink */
2919 + ID_LENGTH_MAX + 1 /* owner name */
2920 + ID_LENGTH_MAX + 1 /* group name */
2921 + ID_LENGTH_MAX + 1 /* author name */
2922 + LONGEST_HUMAN_READABLE + 1 /* major device number */
2923 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
2924 + 35 + 1 /* usual length of time/date -- may be longer; see below */
2926 char *buf = init_bigbuf;
2927 size_t bufsize = sizeof (init_bigbuf);
2931 int when_ns IF_LINT (= 0);
2932 struct tm *when_local;
2934 /* Compute mode string. On most systems, it's based on st_mode.
2935 On systems with migration (via the stat.st_dm_mode field), use
2936 the file's migrated status. */
2937 mode_string (ST_DM_MODE (f->stat), modebuf);
2939 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2945 when = f->stat.st_ctime;
2946 when_ns = TIMESPEC_NS (f->stat.st_ctim);
2949 when = f->stat.st_mtime;
2950 when_ns = TIMESPEC_NS (f->stat.st_mtim);
2953 when = f->stat.st_atime;
2954 when_ns = TIMESPEC_NS (f->stat.st_atim);
2962 char hbuf[LONGEST_HUMAN_READABLE + 1];
2963 sprintf (p, "%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, hbuf));
2967 if (print_block_size)
2969 char hbuf[LONGEST_HUMAN_READABLE + 1];
2970 sprintf (p, "%*s ", block_size_size,
2971 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
2972 ST_NBLOCKSIZE, output_block_size));
2976 /* The last byte of the mode string is the POSIX
2977 "optional alternate access method flag". */
2978 sprintf (p, "%s %3lu ", modebuf, (unsigned long) f->stat.st_nlink);
2982 p += format_user (p, f->stat.st_uid);
2986 char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2988 sprintf (p, "%-8s ", group_name);
2990 sprintf (p, "%-8lu ", (unsigned long) f->stat.st_gid);
2995 p += format_user (p, f->stat.st_author);
2997 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2998 sprintf (p, "%3lu, %3lu ",
2999 (unsigned long) major (f->stat.st_rdev),
3000 (unsigned long) minor (f->stat.st_rdev));
3003 char hbuf[LONGEST_HUMAN_READABLE + 1];
3004 uintmax_t size = f->stat.st_size;
3006 /* POSIX requires that the size be printed without a sign, even
3007 when negative. Assume the typical case where negative sizes
3008 are actually positive values that have wrapped around. */
3009 size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3012 human_readable (size, hbuf, human_output_opts,
3013 1, file_output_block_size));
3018 if ((when_local = localtime (&when)))
3020 time_t six_months_ago;
3024 /* If the file appears to be in the future, update the current
3025 time, in case the file happens to have been modified since
3026 the last time we checked the clock. */
3027 if (current_time < when
3028 || (current_time == when && current_time_ns < when_ns))
3030 /* Note that get_current_time calls gettimeofday which, on some non-
3031 compliant systems, clobbers the buffer used for localtime's result.
3032 But it's ok here, because we use a gettimeofday wrapper that
3033 saves and restores the buffer around the gettimeofday call. */
3034 get_current_time ();
3037 /* Consider a time to be recent if it is within the past six
3038 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3039 31556952 seconds on the average. Write this value as an
3040 integer constant to avoid floating point hassles. */
3041 six_months_ago = current_time - 31556952 / 2;
3042 recent = (six_months_ago <= when
3043 && (when < current_time
3044 || (when == current_time && when_ns <= current_time_ns)));
3045 fmt = long_time_format[recent];
3051 s = nstrftime (p, buf + bufsize - p - 1, fmt,
3052 when_local, 0, when_ns);
3055 newbuf = alloca (bufsize *= 2);
3056 memcpy (newbuf, buf, p - buf);
3057 p = newbuf + (p - buf);
3064 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3069 /* The time cannot be represented as a local time;
3070 print it as a huge integer number of seconds. */
3071 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3072 sprintf (p, "%*s ", long_time_expected_width (),
3073 (TYPE_SIGNED (time_t)
3074 ? imaxtostr (when, hbuf)
3075 : umaxtostr (when, hbuf)));
3080 DIRED_FPUTS (buf, stdout, p - buf);
3081 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3084 if (f->filetype == symbolic_link)
3088 DIRED_FPUTS_LITERAL (" -> ", stdout);
3089 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3091 if (indicator_style != none)
3092 print_type_indicator (f->linkmode);
3095 else if (indicator_style != none)
3096 print_type_indicator (f->stat.st_mode);
3099 /* Output to OUT a quoted representation of the file name NAME,
3100 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3101 Store the number of screen columns occupied by NAME's quoted
3102 representation into WIDTH, if non-NULL. Return the number of bytes
3106 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3109 char smallbuf[BUFSIZ];
3110 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3112 size_t displayed_width IF_LINT (= 0);
3114 if (len < sizeof smallbuf)
3118 buf = (char *) alloca (len + 1);
3119 quotearg_buffer (buf, len + 1, name, -1, options);
3122 if (qmark_funny_chars)
3127 char const *p = buf;
3128 char const *plimit = buf + len;
3130 displayed_width = 0;
3135 case ' ': case '!': case '"': case '#': case '%':
3136 case '&': case '\'': case '(': case ')': case '*':
3137 case '+': case ',': case '-': case '.': case '/':
3138 case '0': case '1': case '2': case '3': case '4':
3139 case '5': case '6': case '7': case '8': case '9':
3140 case ':': case ';': case '<': case '=': case '>':
3142 case 'A': case 'B': case 'C': case 'D': case 'E':
3143 case 'F': case 'G': case 'H': case 'I': case 'J':
3144 case 'K': case 'L': case 'M': case 'N': case 'O':
3145 case 'P': case 'Q': case 'R': case 'S': case 'T':
3146 case 'U': case 'V': case 'W': case 'X': case 'Y':
3148 case '[': case '\\': case ']': case '^': case '_':
3149 case 'a': case 'b': case 'c': case 'd': case 'e':
3150 case 'f': case 'g': case 'h': case 'i': case 'j':
3151 case 'k': case 'l': case 'm': case 'n': case 'o':
3152 case 'p': case 'q': case 'r': case 's': case 't':
3153 case 'u': case 'v': case 'w': case 'x': case 'y':
3154 case 'z': case '{': case '|': case '}': case '~':
3155 /* These characters are printable ASCII characters. */
3157 displayed_width += 1;
3160 /* If we have a multibyte sequence, copy it until we
3161 reach its end, replacing each non-printable multibyte
3162 character with a single question mark. */
3165 memset (&mbstate, 0, sizeof mbstate);
3172 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3174 if (bytes == (size_t) -1)
3176 /* An invalid multibyte sequence was
3177 encountered. Skip one input byte, and
3178 put a question mark. */
3181 displayed_width += 1;
3185 if (bytes == (size_t) -2)
3187 /* An incomplete multibyte character
3188 at the end. Replace it entirely with
3192 displayed_width += 1;
3197 /* A null wide character was encountered. */
3203 /* A printable multibyte character.
3205 for (; bytes > 0; --bytes)
3207 displayed_width += w;
3211 /* An unprintable multibyte character.
3212 Replace it entirely with a question
3216 displayed_width += 1;
3219 while (! mbsinit (&mbstate));
3224 /* The buffer may have shrunk. */
3231 char const *plimit = buf + len;
3235 if (! ISPRINT ((unsigned char) *p))
3239 displayed_width = len;
3242 else if (width != NULL)
3246 displayed_width = mbsnwidth (buf, len, 0);
3250 char const *p = buf;
3251 char const *plimit = buf + len;
3253 displayed_width = 0;
3256 if (ISPRINT ((unsigned char) *p))
3264 fwrite (buf, 1, len, out);
3266 *width = displayed_width;
3271 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3272 struct obstack *stack)
3274 if (print_with_color)
3275 print_color_indicator (p, mode, linkok);
3278 PUSH_CURRENT_DIRED_POS (stack);
3280 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3283 PUSH_CURRENT_DIRED_POS (stack);
3285 if (print_with_color)
3286 prep_non_filename_text ();
3290 prep_non_filename_text (void)
3292 if (color_indicator[C_END].string != NULL)
3293 put_indicator (&color_indicator[C_END]);
3296 put_indicator (&color_indicator[C_LEFT]);
3297 put_indicator (&color_indicator[C_NORM]);
3298 put_indicator (&color_indicator[C_RIGHT]);
3302 /* Print the file name of `f' with appropriate quoting.
3303 Also print file size, inode number, and filetype indicator character,
3304 as requested by switches. */
3307 print_file_name_and_frills (const struct fileinfo *f)
3309 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3312 printf ("%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, buf));
3314 if (print_block_size)
3315 printf ("%*s ", block_size_size,
3316 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3317 ST_NBLOCKSIZE, output_block_size));
3319 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3321 if (indicator_style != none)
3322 print_type_indicator (f->stat.st_mode);
3326 print_type_indicator (mode_t mode)
3332 if (indicator_style == classify && (mode & S_IXUGO))
3341 else if (S_ISLNK (mode))
3343 else if (S_ISFIFO (mode))
3345 else if (S_ISSOCK (mode))
3347 else if (S_ISDOOR (mode))
3358 print_color_indicator (const char *name, mode_t mode, int linkok)
3361 struct color_ext_type *ext; /* Color extension */
3362 size_t len; /* Length of name */
3364 /* Is this a nonexistent file? If so, linkok == -1. */
3366 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3375 else if (S_ISLNK (mode))
3376 type = ((!linkok && color_indicator[C_ORPHAN].string)
3377 ? C_ORPHAN : C_LINK);
3378 else if (S_ISFIFO (mode))
3380 else if (S_ISSOCK (mode))
3382 else if (S_ISBLK (mode))
3384 else if (S_ISCHR (mode))
3386 else if (S_ISDOOR (mode))
3389 if (type == C_FILE && (mode & S_IXUGO) != 0)
3392 /* Check the file's suffix only if still classified as C_FILE. */
3396 /* Test if NAME has a recognized suffix. */
3398 len = strlen (name);
3399 name += len; /* Pointer to final \0. */
3400 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3402 if ((size_t) ext->ext.len <= len
3403 && strncmp (name - ext->ext.len, ext->ext.string,
3410 put_indicator (&color_indicator[C_LEFT]);
3411 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3412 put_indicator (&color_indicator[C_RIGHT]);
3415 /* Output a color indicator (which may contain nulls). */
3417 put_indicator (const struct bin_str *ind)
3420 register const char *p;
3424 for (i = ind->len; i > 0; --i)
3428 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3429 Return zero if the write is successful or if the string length is zero.
3430 Return nonzero if the write fails. */
3432 put_indicator_direct (const struct bin_str *ind)
3439 return (full_write (STDOUT_FILENO, ind->string, len) != len);
3443 length_of_file_name_and_frills (const struct fileinfo *f)
3445 register int len = 0;
3449 len += INODE_DIGITS + 1;
3451 if (print_block_size)
3452 len += 1 + block_size_size;
3454 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3457 if (indicator_style != none)
3459 mode_t filetype = f->stat.st_mode;
3461 if (S_ISREG (filetype))
3463 if (indicator_style == classify
3464 && (f->stat.st_mode & S_IXUGO))
3467 else if (S_ISDIR (filetype)
3468 || S_ISLNK (filetype)
3469 || S_ISFIFO (filetype)
3470 || S_ISSOCK (filetype)
3471 || S_ISDOOR (filetype)
3480 print_many_per_line (void)
3482 struct column_info *line_fmt;
3483 int filesno; /* Index into files. */
3484 int row; /* Current row. */
3485 int max_name_length; /* Length of longest file name + frills. */
3486 int name_length; /* Length of each file name + frills. */
3487 int pos; /* Current character column. */
3488 int cols; /* Number of files across. */
3489 int rows; /* Maximum number of files down. */
3492 /* Normally the maximum number of columns is determined by the
3493 screen width. But if few files are available this might limit it
3495 max_cols = max_idx > files_index ? files_index : max_idx;
3497 /* Compute the maximum number of possible columns. */
3498 for (filesno = 0; filesno < files_index; ++filesno)
3502 name_length = length_of_file_name_and_frills (files + filesno);
3504 for (i = 0; i < max_cols; ++i)
3506 if (column_info[i].valid_len)
3508 int idx = filesno / ((files_index + i) / (i + 1));
3509 int real_length = name_length + (idx == i ? 0 : 2);
3511 if (real_length > column_info[i].col_arr[idx])
3513 column_info[i].line_len += (real_length
3514 - column_info[i].col_arr[idx]);
3515 column_info[i].col_arr[idx] = real_length;
3516 column_info[i].valid_len = column_info[i].line_len < line_length;
3522 /* Find maximum allowed columns. */
3523 for (cols = max_cols; cols > 1; --cols)
3525 if (column_info[cols - 1].valid_len)
3529 line_fmt = &column_info[cols - 1];
3531 /* Calculate the number of rows that will be in each column except possibly
3532 for a short column on the right. */
3533 rows = files_index / cols + (files_index % cols != 0);
3535 for (row = 0; row < rows; row++)
3540 /* Print the next row. */
3543 print_file_name_and_frills (files + filesno);
3544 name_length = length_of_file_name_and_frills (files + filesno);
3545 max_name_length = line_fmt->col_arr[col++];
3548 if (filesno >= files_index)
3551 indent (pos + name_length, pos + max_name_length);
3552 pos += max_name_length;
3559 print_horizontal (void)
3561 struct column_info *line_fmt;
3563 int max_name_length;
3569 /* Normally the maximum number of columns is determined by the
3570 screen width. But if few files are available this might limit it
3572 max_cols = max_idx > files_index ? files_index : max_idx;
3574 /* Compute the maximum file name length. */
3575 max_name_length = 0;
3576 for (filesno = 0; filesno < files_index; ++filesno)
3580 name_length = length_of_file_name_and_frills (files + filesno);
3582 for (i = 0; i < max_cols; ++i)
3584 if (column_info[i].valid_len)
3586 int idx = filesno % (i + 1);
3587 int real_length = name_length + (idx == i ? 0 : 2);
3589 if (real_length > column_info[i].col_arr[idx])
3591 column_info[i].line_len += (real_length
3592 - column_info[i].col_arr[idx]);
3593 column_info[i].col_arr[idx] = real_length;
3594 column_info[i].valid_len = column_info[i].line_len < line_length;
3600 /* Find maximum allowed columns. */
3601 for (cols = max_cols; cols > 1; --cols)
3603 if (column_info[cols - 1].valid_len)
3607 line_fmt = &column_info[cols - 1];
3611 /* Print first entry. */
3612 print_file_name_and_frills (files);
3613 name_length = length_of_file_name_and_frills (files);
3614 max_name_length = line_fmt->col_arr[0];
3617 for (filesno = 1; filesno < files_index; ++filesno)
3619 int col = filesno % cols;
3628 indent (pos + name_length, pos + max_name_length);
3629 pos += max_name_length;
3632 print_file_name_and_frills (files + filesno);
3634 name_length = length_of_file_name_and_frills (files + filesno);
3635 max_name_length = line_fmt->col_arr[col];
3641 print_with_commas (void)
3648 for (filesno = 0; filesno < files_index; filesno++)
3652 pos += length_of_file_name_and_frills (files + filesno);
3653 if (filesno + 1 < files_index)
3654 pos += 2; /* For the comma and space */
3656 if (old_pos != 0 && pos >= line_length)
3662 print_file_name_and_frills (files + filesno);
3663 if (filesno + 1 < files_index)
3672 /* Assuming cursor is at position FROM, indent up to position TO.
3673 Use a TAB character instead of two or more spaces whenever possible. */
3676 indent (int from, int to)
3680 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
3683 from += tabsize - from % tabsize;
3693 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3694 /* FIXME: maybe remove this function someday. See about using a
3695 non-malloc'ing version of path_concat. */
3698 attach (char *dest, const char *dirname, const char *name)
3700 const char *dirnamep = dirname;
3702 /* Copy dirname if it is not ".". */
3703 if (dirname[0] != '.' || dirname[1] != 0)
3706 *dest++ = *dirnamep++;
3707 /* Add '/' if `dirname' doesn't already end with it. */
3708 if (dirnamep > dirname && dirnamep[-1] != '/')
3717 init_column_info (void)
3722 max_idx = line_length / MIN_COLUMN_WIDTH;
3726 if (column_info == NULL)
3728 column_info = XMALLOC (struct column_info, max_idx);
3732 for (i = 0; i < max_idx; ++i)
3736 column_info[i].valid_len = 1;
3737 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3740 column_info[i].col_arr = XMALLOC (int, i + 1);
3742 for (j = 0; j <= i; ++j)
3743 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3751 fprintf (stderr, _("Try `%s --help' for more information.\n"),
3755 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3757 List information about the FILEs (the current directory by default).\n\
3758 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3762 Mandatory arguments to long options are mandatory for short options too.\n\
3765 -a, --all do not hide entries starting with .\n\
3766 -A, --almost-all do not list implied . and ..\n\
3767 --author print the author of each file\n\
3768 -b, --escape print octal escapes for nongraphic characters\n\
3771 --block-size=SIZE use SIZE-byte blocks\n\
3772 -B, --ignore-backups do not list implied entries ending with ~\n\
3773 -c with -lt: sort by, and show, ctime (time of last\n\
3774 modification of file status information)\n\
3775 with -l: show ctime and sort by name\n\
3776 otherwise: sort by ctime\n\
3779 -C list entries by columns\n\
3780 --color[=WHEN] control whether color is used to distinguish file\n\
3781 types. WHEN may be `never', `always', or `auto'\n\
3782 -d, --directory list directory entries instead of contents,\n\
3783 and do not dereference symbolic links\n\
3784 -D, --dired generate output designed for Emacs' dired mode\n\
3787 -f do not sort, enable -aU, disable -lst\n\
3788 -F, --classify append indicator (one of */=@|) to entries\n\
3789 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3790 single-column -1, verbose -l, vertical -C\n\
3791 --full-time like -l --time-style=full-iso\n\
3794 -g like -l, but do not list owner\n\
3795 -G, --no-group inhibit display of group information\n\
3796 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3797 --si likewise, but use powers of 1000 not 1024\n\
3798 -H, --dereference-command-line\n\
3799 follow symbolic links listed on the command line\n\
3800 --dereference-command-line-symlink-to-dir\n\
3801 follow each command line symbolic link\n\
3802 that points to a directory\n\
3805 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3806 none (default), classify (-F), file-type (-p)\n\
3807 -i, --inode print index number of each file\n\
3808 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3809 -k like --block-size=1K\n\
3812 -l use a long listing format\n\
3813 -L, --dereference when showing file information for a symbolic\n\
3814 link, show information for the file the link\n\
3815 references rather than for the link itself\n\
3816 -m fill width with a comma separated list of entries\n\
3819 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3820 -N, --literal print raw entry names (don't treat e.g. control\n\
3821 characters specially)\n\
3822 -o like -l, but do not list group information\n\
3823 -p, --file-type append indicator (one of /=@|) to entries\n\
3826 -q, --hide-control-chars print ? instead of non graphic characters\n\
3827 --show-control-chars show non graphic characters as-is (default\n\
3828 unless program is `ls' and output is a terminal)\n\
3829 -Q, --quote-name enclose entry names in double quotes\n\
3830 --quoting-style=WORD use quoting style WORD for entry names:\n\
3831 literal, locale, shell, shell-always, c, escape\n\
3834 -r, --reverse reverse order while sorting\n\
3835 -R, --recursive list subdirectories recursively\n\
3836 -s, --size print size of each file, in blocks\n\
3839 -S sort by file size\n\
3840 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3842 status -c, time -t, atime -u, access -u, use -u\n\
3843 --time=WORD show time as WORD instead of modification time:\n\
3844 atime, access, use, ctime or status; use\n\
3845 specified time as sort key if --sort=time\n\
3848 --time-style=STYLE show times using style STYLE:\n\
3849 full-iso, long-iso, iso, locale, +FORMAT\n\
3850 FORMAT is interpreted like `date'; if FORMAT is\n\
3851 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
3852 non-recent files and FORMAT2 to recent files;\n\
3853 if STYLE is prefixed with `posix-', STYLE\n\
3854 takes effect only outside the POSIX locale\n\
3855 -t sort by modification time\n\
3856 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
3859 -u with -lt: sort by, and show, access time\n\
3860 with -l: show access time and sort by name\n\
3861 otherwise: sort by access time\n\
3862 -U do not sort; list entries in directory order\n\
3863 -v sort by version\n\
3866 -w, --width=COLS assume screen width instead of current value\n\
3867 -x list entries by lines instead of by columns\n\
3868 -X sort alphabetically by entry extension\n\
3869 -1 list one file per line\n\
3871 fputs (HELP_OPTION_DESCRIPTION, stdout);
3872 fputs (VERSION_OPTION_DESCRIPTION, stdout);
3874 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3875 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
3879 By default, color is not used to distinguish types of files. That is\n\
3880 equivalent to using --color=none. Using the --color option without the\n\
3881 optional WHEN argument is equivalent to using --color=always. With\n\
3882 --color=auto, color codes are output only if standard output is connected\n\
3883 to a terminal (tty).\n\
3885 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);