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>. */
44 #include <sys/types.h>
50 #ifdef GWINSZ_IN_SYS_IOCTL
51 # include <sys/ioctl.h>
54 #ifdef WINSIZE_IN_PTEM
55 # include <sys/stream.h>
56 # include <sys/ptem.h>
70 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
79 #if !defined iswprint && !HAVE_ISWPRINT
80 # define iswprint(wc) 1
83 #ifndef HAVE_DECL_WCWIDTH
84 "this configure-time declaration test was not run"
86 #if !HAVE_DECL_WCWIDTH
90 /* If wcwidth() doesn't exist, assume all printable characters have
94 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
102 #include "argmatch.h"
107 #include "full-write.h"
108 #include "hard-locale.h"
111 #include "filemode.h"
112 #include "inttostr.h"
114 #include "mbswidth.h"
116 #include "path-concat.h"
118 #include "quotearg.h"
120 #include "strftime.h"
121 #include "strverscmp.h"
123 #include "xreadlink.h"
125 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
126 : (ls_mode == LS_MULTI_COL \
129 #define AUTHORS N_ ("Richard Stallman and David MacKenzie")
131 #define obstack_chunk_alloc malloc
132 #define obstack_chunk_free free
134 /* Return an int indicating the result of comparing two integers.
135 Subtracting doesn't always work, due to overflow. */
136 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
138 /* The field width for inode numbers. On some hosts inode numbers are
139 64 bits, so columns won't line up exactly when a huge inode number
140 is encountered, but in practice 7 digits is usually enough. */
142 # define INODE_DIGITS 7
145 /* Arrange to make lstat calls go through the wrapper function
146 on systems with an lstat function that does not dereference symlinks
147 that are specified with a trailing slash. */
148 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
149 int rpl_lstat (const char *, struct stat *);
151 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
154 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
155 # define DT_INIT(Val) = Val
157 # define DT_INIT(Val) /* empty */
161 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
163 # define TIMESPEC_NS(timespec) 0
166 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
167 # define st_author st_uid
170 /* Cray/Unicos DMF: use the file's migrated, not real, status */
172 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
174 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
177 #ifndef LOGIN_NAME_MAX
178 # if _POSIX_LOGIN_NAME_MAX
179 # define LOGIN_NAME_MAX _POSIX_LOGIN_NAME_MAX
181 # define LOGIN_NAME_MAX 17
185 /* The maximum length of a string representation of a user or group ID,
186 not counting any terminating NUL byte. */
187 #define ID_LENGTH_MAX \
188 MAX (LOGIN_NAME_MAX - 1, LONGEST_HUMAN_READABLE)
192 unknown DT_INIT (DT_UNKNOWN),
193 fifo DT_INIT (DT_FIFO),
194 chardev DT_INIT (DT_CHR),
195 directory DT_INIT (DT_DIR),
196 blockdev DT_INIT (DT_BLK),
197 normal DT_INIT (DT_REG),
198 symbolic_link DT_INIT (DT_LNK),
199 sock DT_INIT (DT_SOCK),
200 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
201 | DT_REG | DT_LNK | DT_SOCK))
211 /* For symbolic link, name of the file linked to, otherwise zero. */
214 /* For symbolic link and long listing, st_mode of file linked to, otherwise
218 /* For symbolic link and color printing, 1 if linked-to file
219 exists, otherwise 0. */
222 enum filetype filetype;
225 /* For long listings, true if the file has an access control list. */
231 # define FILE_HAS_ACL(F) ((F)->have_acl)
233 # define FILE_HAS_ACL(F) 0
236 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
238 /* Null is a valid character in a color indicator (think about Epson
239 printers, for example) so we have to use a length/buffer string
244 int len; /* Number of bytes */
245 const char *string; /* Pointer to the same */
255 static size_t quote_name (FILE *out, const char *name,
256 struct quoting_options const *options,
258 static char *make_link_path (const char *path, const char *linkname);
259 static int decode_switches (int argc, char **argv);
260 static int file_interesting (const struct dirent *next);
261 static uintmax_t gobble_file (const char *name, enum filetype type,
262 int explicit_arg, const char *dirname);
263 static void print_color_indicator (const char *name, mode_t mode, int linkok);
264 static void put_indicator (const struct bin_str *ind);
265 static int put_indicator_direct (const struct bin_str *ind);
266 static int length_of_file_name_and_frills (const struct fileinfo *f);
267 static void add_ignore_pattern (const char *pattern);
268 static void attach (char *dest, const char *dirname, const char *name);
269 static void clear_files (void);
270 static void extract_dirs_from_files (const char *dirname,
271 int ignore_dot_and_dot_dot);
272 static void get_link_name (const char *filename, struct fileinfo *f);
273 static void indent (int from, int to);
274 static void init_column_info (void);
275 static void print_current_files (void);
276 static void print_dir (const char *name, const char *realname);
277 static void print_file_name_and_frills (const struct fileinfo *f);
278 static void print_horizontal (void);
279 static void print_long_format (const struct fileinfo *f);
280 static void print_many_per_line (void);
281 static void print_name_with_quoting (const char *p, mode_t mode,
283 struct obstack *stack);
284 static void prep_non_filename_text (void);
285 static void print_type_indicator (mode_t mode);
286 static void print_with_commas (void);
287 static void queue_directory (const char *name, const char *realname);
288 static void sort_files (void);
289 static void parse_ls_color (void);
290 void usage (int status);
292 /* The name the program was run with, stripped of any leading path. */
295 /* Initial size of hash table.
296 Most hierarchies are likely to be shallower than this. */
297 #define INITIAL_TABLE_SIZE 30
299 /* The set of `active' directories, from the current command-line argument
300 to the level in the hierarchy at which files are being listed.
301 A directory is represented by its device and inode numbers (struct dev_ino).
302 A directory is added to this set when ls begins listing it or its
303 entries, and it is removed from the set just after ls has finished
304 processing it. This set is used solely to detect loops, e.g., with
305 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
306 static Hash_table *active_dir_set;
308 #define LOOP_DETECT (!!active_dir_set)
310 /* The table of files in the current directory:
312 `files' points to a vector of `struct fileinfo', one per file.
313 `nfiles' is the number of elements space has been allocated for.
314 `files_index' is the number actually in use. */
316 /* Address of block containing the files that are described. */
317 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
319 /* Length of block that `files' points to, measured in files. */
320 static int nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
322 /* Index of first unused in `files'. */
323 static int files_index; /* FIXME: rename this to e.g. cwd_n_used */
325 /* When nonzero, in a color listing, color each symlink name according to the
326 type of file it points to. Otherwise, color them according to the `ln'
327 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
328 regardless. This is set when `ln=target' appears in LS_COLORS. */
330 static int color_symlink_as_referent;
332 /* mode of appropriate file for colorization */
333 #define FILE_OR_LINK_MODE(File) \
334 ((color_symlink_as_referent && (File)->linkok) \
335 ? (File)->linkmode : (File)->stat.st_mode)
338 /* Record of one pending directory waiting to be listed. */
343 /* If the directory is actually the file pointed to by a symbolic link we
344 were told to list, `realname' will contain the name of the symbolic
345 link, otherwise zero. */
347 struct pending *next;
350 static struct pending *pending_dirs;
352 /* Current time in seconds and nanoseconds since 1970, updated as
353 needed when deciding whether a file is recent. */
355 static time_t current_time = TYPE_MINIMUM (time_t);
356 static int current_time_ns = -1;
358 /* The number of digits to use for block sizes.
359 4, or more if needed for bigger numbers. */
361 static int block_size_size;
365 /* long_format for lots of info, one per line.
366 one_per_line for just names, one per line.
367 many_per_line for just names, many per line, sorted vertically.
368 horizontal for just names, many per line, sorted horizontally.
369 with_commas for just names, many per line, separated by commas.
371 -l (and other options that imply -l), -1, -C, -x and -m control
376 long_format, /* -l and other options that imply -l */
377 one_per_line, /* -1 */
378 many_per_line, /* -C */
383 static enum format format;
385 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
386 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
387 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
390 full_iso_time_style, /* --time-style=full-iso */
391 long_iso_time_style, /* --time-style=long-iso */
392 iso_time_style, /* --time-style=iso */
393 locale_time_style /* --time-style=locale */
396 static char const *const time_style_args[] =
398 "full-iso", "long-iso", "iso", "locale", 0
401 static enum time_style const time_style_types[] =
403 full_iso_time_style, long_iso_time_style, iso_time_style,
407 /* Type of time to print or sort by. Controlled by -c and -u. */
411 time_mtime, /* default */
416 static enum time_type time_type;
418 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
423 sort_name, /* default */
424 sort_extension, /* -X */
427 sort_version /* -v */
430 static enum sort_type sort_type;
432 /* Direction of sort.
433 0 means highest first if numeric,
434 lowest first if alphabetic;
435 these are the defaults.
436 1 means the opposite order in each case. -r */
438 static int sort_reverse;
440 /* Nonzero means to display owner information. -g turns this off. */
442 static int print_owner = 1;
444 /* Nonzero means to display author information. */
446 static bool print_author;
448 /* Nonzero means to display group information. -G and -o turn this off. */
450 static int print_group = 1;
452 /* Nonzero means print the user and group id's as numbers rather
455 static int numeric_ids;
457 /* Nonzero means mention the size in blocks of each file. -s */
459 static int print_block_size;
461 /* Human-readable options for output. */
462 static int human_output_opts;
464 /* The units to use when printing sizes other than file sizes. */
465 static uintmax_t output_block_size;
467 /* Likewise, but for file sizes. */
468 static uintmax_t file_output_block_size = 1;
470 /* Precede each line of long output (per file) with a string like `m,n:'
471 where M is the number of characters after the `:' and before the
472 filename and N is the length of the filename. Using this format,
473 Emacs' dired mode starts up twice as fast, and can handle all
474 strange characters in file names. */
477 /* `none' means don't mention the type of files.
478 `classify' means mention file types and mark executables.
479 `file_type' means mention only file types.
481 Controlled by -F, -p, and --indicator-style. */
485 none, /* --indicator-style=none */
486 classify, /* -F, --indicator-style=classify */
487 file_type /* -p, --indicator-style=file-type */
490 static enum indicator_style indicator_style;
492 /* Names of indicator styles. */
493 static char const *const indicator_style_args[] =
495 "none", "classify", "file-type", 0
498 static enum indicator_style const indicator_style_types[]=
500 none, classify, file_type
503 /* Nonzero means use colors to mark types. Also define the different
504 colors as well as the stuff for the LS_COLORS environment variable.
505 The LS_COLORS variable is now in a termcap-like format. */
507 static int print_with_color;
511 color_never, /* 0: default or --color=never */
512 color_always, /* 1: --color=always */
513 color_if_tty /* 2: --color=tty */
516 enum Dereference_symlink
520 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
521 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
522 DEREF_ALWAYS /* -L */
527 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
528 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
531 static const char *const indicator_name[]=
533 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
534 "bd", "cd", "mi", "or", "ex", "do", NULL
537 struct color_ext_type
539 struct bin_str ext; /* The extension we're looking for */
540 struct bin_str seq; /* The sequence to output when we do */
541 struct color_ext_type *next; /* Next in list */
544 static struct bin_str color_indicator[] =
546 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
547 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
548 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
549 { LEN_STR_PAIR ("0") }, /* no: Normal */
550 { LEN_STR_PAIR ("0") }, /* fi: File: default */
551 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
552 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
553 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
554 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
555 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
556 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
557 { 0, NULL }, /* mi: Missing file: undefined */
558 { 0, NULL }, /* or: Orphanned symlink: undefined */
559 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
560 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
564 static struct color_ext_type *color_ext_list = NULL;
566 /* Buffer for color sequences */
567 static char *color_buf;
569 /* Nonzero means to check for orphaned symbolic link, for displaying
572 static int check_symlink_color;
574 /* Nonzero means mention the inode number of each file. -i */
576 static int print_inode;
578 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
579 other options that imply -l), and -L. */
581 static enum Dereference_symlink dereference;
583 /* Nonzero means when a directory is found, display info on its
586 static int recursive;
588 /* Nonzero means when an argument is a directory name, display info
591 static int immediate_dirs;
593 /* Nonzero means don't omit files whose names start with `.'. -A */
595 static int all_files;
597 /* Nonzero means don't omit files `.' and `..'
598 This flag implies `all_files'. -a */
600 static int really_all_files;
602 /* A linked list of shell-style globbing patterns. If a non-argument
603 file name matches any of these patterns, it is omitted.
604 Controlled by -I. Multiple -I options accumulate.
605 The -B option adds `*~' and `.*~' to this list. */
607 struct ignore_pattern
610 struct ignore_pattern *next;
613 static struct ignore_pattern *ignore_patterns;
615 /* Nonzero means output nongraphic chars in file names as `?'.
616 (-q, --hide-control-chars)
617 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
618 independent. The algorithm is: first, obey the quoting style to get a
619 string representing the file name; then, if qmark_funny_chars is set,
620 replace all nonprintable chars in that string with `?'. It's necessary
621 to replace nonprintable chars even in quoted strings, because we don't
622 want to mess up the terminal if control chars get sent to it, and some
623 quoting methods pass through control chars as-is. */
624 static int qmark_funny_chars;
626 /* Quoting options for file and dir name output. */
628 static struct quoting_options *filename_quoting_options;
629 static struct quoting_options *dirname_quoting_options;
631 /* The number of chars per hardware tab stop. Setting this to zero
632 inhibits the use of TAB characters for separating columns. -T */
635 /* Nonzero means we are listing the working directory because no
636 non-option arguments were given. */
638 static int dir_defaulted;
640 /* Nonzero means print each directory name before listing it. */
642 static int print_dir_name;
644 /* The line length to use for breaking lines in many-per-line format.
645 Can be set with -w. */
647 static int line_length;
649 /* If nonzero, the file listing format requires that stat be called on
652 static int format_needs_stat;
654 /* Similar to `format_needs_stat', but set if only the file type is
657 static int format_needs_type;
659 /* strftime formats for non-recent and recent files, respectively, in
662 static char const *long_time_format[2] =
664 /* strftime format for non-recent files (older than 6 months), in
665 -l output when --time-style=locale is specified. This should
666 contain the year, month and day (at least), in an order that is
667 understood by people in your locale's territory.
668 Please try to keep the number of used screen columns small,
669 because many people work in windows with only 80 columns. But
670 make this as wide as the other string below, for recent files. */
672 /* strftime format for recent files (younger than 6 months), in
673 -l output when --time-style=locale is specified. This should
674 contain the month, day and time (at least), in an order that is
675 understood by people in your locale's territory.
676 Please try to keep the number of used screen columns small,
677 because many people work in windows with only 80 columns. But
678 make this as wide as the other string above, for non-recent files. */
682 /* The exit status to use if we don't get any fatal errors. */
684 static int exit_status;
686 /* For long options that have no equivalent short option, use a
687 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
690 AUTHOR_OPTION = CHAR_MAX + 1,
693 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
696 INDICATOR_STYLE_OPTION,
697 QUOTING_STYLE_OPTION,
698 SHOW_CONTROL_CHARS_OPTION,
705 static struct option const long_options[] =
707 {"all", no_argument, 0, 'a'},
708 {"escape", no_argument, 0, 'b'},
709 {"directory", no_argument, 0, 'd'},
710 {"dired", no_argument, 0, 'D'},
711 {"full-time", no_argument, 0, FULL_TIME_OPTION},
712 {"human-readable", no_argument, 0, 'h'},
713 {"inode", no_argument, 0, 'i'},
714 {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
715 {"numeric-uid-gid", no_argument, 0, 'n'},
716 {"no-group", no_argument, 0, 'G'},
717 {"hide-control-chars", no_argument, 0, 'q'},
718 {"reverse", no_argument, 0, 'r'},
719 {"size", no_argument, 0, 's'},
720 {"width", required_argument, 0, 'w'},
721 {"almost-all", no_argument, 0, 'A'},
722 {"ignore-backups", no_argument, 0, 'B'},
723 {"classify", no_argument, 0, 'F'},
724 {"file-type", no_argument, 0, 'p'},
725 {"si", no_argument, 0, SI_OPTION},
726 {"dereference-command-line", no_argument, 0, 'H'},
727 {"dereference-command-line-symlink-to-dir", no_argument, 0,
728 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
729 {"ignore", required_argument, 0, 'I'},
730 {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
731 {"dereference", no_argument, 0, 'L'},
732 {"literal", no_argument, 0, 'N'},
733 {"quote-name", no_argument, 0, 'Q'},
734 {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
735 {"recursive", no_argument, 0, 'R'},
736 {"format", required_argument, 0, FORMAT_OPTION},
737 {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
738 {"sort", required_argument, 0, SORT_OPTION},
739 {"tabsize", required_argument, 0, 'T'},
740 {"time", required_argument, 0, TIME_OPTION},
741 {"time-style", required_argument, 0, TIME_STYLE_OPTION},
742 {"color", optional_argument, 0, COLOR_OPTION},
743 {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
744 {"author", no_argument, 0, AUTHOR_OPTION},
745 {GETOPT_HELP_OPTION_DECL},
746 {GETOPT_VERSION_OPTION_DECL},
750 static char const *const format_args[] =
752 "verbose", "long", "commas", "horizontal", "across",
753 "vertical", "single-column", 0
756 static enum format const format_types[] =
758 long_format, long_format, with_commas, horizontal, horizontal,
759 many_per_line, one_per_line
762 static char const *const sort_args[] =
764 "none", "time", "size", "extension", "version", 0
767 static enum sort_type const sort_types[] =
769 sort_none, sort_time, sort_size, sort_extension, sort_version
772 static char const *const time_args[] =
774 "atime", "access", "use", "ctime", "status", 0
777 static enum time_type const time_types[] =
779 time_atime, time_atime, time_atime, time_ctime, time_ctime
782 static char const *const color_args[] =
784 /* force and none are for compatibility with another color-ls version */
785 "always", "yes", "force",
786 "never", "no", "none",
787 "auto", "tty", "if-tty", 0
790 static enum color_type const color_types[] =
792 color_always, color_always, color_always,
793 color_never, color_never, color_never,
794 color_if_tty, color_if_tty, color_if_tty
797 /* Information about filling a column. */
805 /* Array with information about column filledness. */
806 static struct column_info *column_info;
808 /* Maximum number of columns ever possible for this display. */
811 /* The minimum width of a colum is 3: 1 character for the name and 2
812 for the separating white space. */
813 #define MIN_COLUMN_WIDTH 3
816 /* This zero-based index is used solely with the --dired option.
817 When that option is in effect, this counter is incremented for each
818 character of output generated by this program so that the beginning
819 and ending indices (in that output) of every file name can be recorded
820 and later output themselves. */
821 static size_t dired_pos;
823 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
825 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
826 #define DIRED_FPUTS(s, stream, s_len) \
827 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
829 /* Like DIRED_FPUTS, but for use when S is a literal string. */
830 #define DIRED_FPUTS_LITERAL(s, stream) \
831 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
833 #define DIRED_INDENT() \
837 DIRED_FPUTS_LITERAL (" ", stdout); \
841 /* With --dired, store pairs of beginning and ending indices of filenames. */
842 static struct obstack dired_obstack;
844 /* With --dired, store pairs of beginning and ending indices of any
845 directory names that appear as headers (just before `total' line)
846 for lists of directory entries. Such directory names are seen when
847 listing hierarchies using -R and when a directory is listed with at
848 least one other command line argument. */
849 static struct obstack subdired_obstack;
851 /* Save the current index on the specified obstack, OBS. */
852 #define PUSH_CURRENT_DIRED_POS(obs) \
856 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
860 /* With -R, this stack is used to help detect directory cycles.
861 The device/inode pairs on this stack mirror the pairs in the
862 active_dir_set hash table. */
863 static struct obstack dev_ino_obstack;
865 /* Push a pair onto the device/inode stack. */
866 #define DEV_INO_PUSH(Dev, Ino) \
869 struct dev_ino *di; \
870 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
871 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
872 di->st_dev = (Dev); \
873 di->st_ino = (Ino); \
877 /* Pop a dev/ino struct off the global dev_ino_obstack
878 and return that struct. */
879 static struct dev_ino
882 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
883 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
884 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
887 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
892 assert (0 <= stat (Name, &sb)); \
893 assert (sb.st_dev == Di.st_dev); \
894 assert (sb.st_ino == Di.st_ino); \
899 /* Write to standard output PREFIX, followed by the quoting style and
900 a space-separated list of the integers stored in OS all on one line. */
903 dired_dump_obstack (const char *prefix, struct obstack *os)
907 n_pos = obstack_object_size (os) / sizeof (dired_pos);
913 pos = (size_t *) obstack_finish (os);
914 fputs (prefix, stdout);
915 for (i = 0; i < n_pos; i++)
916 printf (" %lu", (unsigned long) pos[i]);
922 dev_ino_hash (void const *x, unsigned int table_size)
924 struct dev_ino const *p = x;
925 return (uintmax_t) p->st_ino % table_size;
929 dev_ino_compare (void const *x, void const *y)
931 struct dev_ino const *a = x;
932 struct dev_ino const *b = y;
933 return SAME_INODE (*a, *b) ? true : false;
937 dev_ino_free (void *x)
942 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
943 active directories. Return nonzero if there is already a matching
944 entry in the table. Otherwise, return zero. */
947 visit_dir (dev_t dev, ino_t ino)
950 struct dev_ino *ent_from_table;
953 ent = XMALLOC (struct dev_ino, 1);
957 /* Attempt to insert this entry into the table. */
958 ent_from_table = hash_insert (active_dir_set, ent);
960 if (ent_from_table == NULL)
962 /* Insertion failed due to lack of memory. */
966 found_match = (ent_from_table != ent);
970 /* ent was not inserted, so free it. */
978 free_pending_ent (struct pending *p)
988 restore_default_color (void)
990 if (put_indicator_direct (&color_indicator[C_LEFT]) == 0)
991 put_indicator_direct (&color_indicator[C_RIGHT]);
994 /* Upon interrupt, suspend, hangup, etc. ensure that the
995 terminal text color is restored to the default. */
1000 signal (sig, SIG_IGN);
1003 restore_default_color ();
1005 /* SIGTSTP is special, since the application can receive that signal more
1006 than once. In this case, don't set the signal handler to the default.
1007 Instead, just raise the uncatchable SIGSTOP. */
1015 struct sigaction sigact;
1017 sigact.sa_handler = SIG_DFL;
1018 sigemptyset (&sigact.sa_mask);
1019 sigact.sa_flags = 0;
1020 sigaction (sig, &sigact, NULL);
1022 signal (sig, SIG_DFL);
1030 main (int argc, char **argv)
1033 register struct pending *thispend;
1034 unsigned int n_files;
1036 initialize_main (&argc, &argv);
1037 program_name = argv[0];
1038 setlocale (LC_ALL, "");
1039 bindtextdomain (PACKAGE, LOCALEDIR);
1040 textdomain (PACKAGE);
1042 atexit (close_stdout);
1044 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1045 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1052 i = decode_switches (argc, argv);
1054 if (print_with_color)
1057 /* Test print_with_color again, because the call to parse_ls_color
1058 may have just reset it -- e.g., if LS_COLORS is invalid. */
1059 if (print_with_color)
1061 prep_non_filename_text ();
1062 /* Avoid following symbolic links when possible. */
1063 if (color_indicator[C_ORPHAN].string != NULL
1064 || (color_indicator[C_MISSING].string != NULL
1065 && format == long_format))
1066 check_symlink_color = 1;
1070 static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE,
1071 SIGQUIT, SIGTERM, SIGTSTP };
1072 unsigned nsigs = sizeof sigs / sizeof *sigs;
1074 struct sigaction oldact, newact;
1075 sigset_t caught_signals;
1077 sigemptyset (&caught_signals);
1078 for (j = 0; j < nsigs; j++)
1079 sigaddset (&caught_signals, sigs[j]);
1080 newact.sa_handler = sighandler;
1081 newact.sa_mask = caught_signals;
1082 newact.sa_flags = 0;
1085 for (j = 0; j < nsigs; j++)
1089 sigaction (sig, NULL, &oldact);
1090 if (oldact.sa_handler != SIG_IGN)
1091 sigaction (sig, &newact, NULL);
1093 if (signal (sig, SIG_IGN) != SIG_IGN)
1094 signal (sig, sighandler);
1100 if (dereference == DEREF_UNDEFINED)
1101 dereference = ((immediate_dirs
1102 || indicator_style == classify
1103 || format == long_format)
1105 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1107 /* When using -R, initialize a data structure we'll use to
1108 detect any directory cycles. */
1111 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1115 if (active_dir_set == NULL)
1118 obstack_init (&dev_ino_obstack);
1121 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1122 || format == long_format
1123 || dereference == DEREF_ALWAYS
1124 || print_block_size || print_inode;
1125 format_needs_type = (format_needs_stat == 0
1126 && (recursive || print_with_color
1127 || indicator_style != none));
1131 obstack_init (&dired_obstack);
1132 obstack_init (&subdired_obstack);
1136 files = XMALLOC (struct fileinfo, nfiles);
1145 for (; i < argc; i++)
1147 gobble_file (argv[i], unknown, 1, "");
1153 gobble_file (".", directory, 1, "");
1155 queue_directory (".", 0);
1161 if (!immediate_dirs)
1162 extract_dirs_from_files ("", 0);
1163 /* `files_index' might be zero now. */
1166 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1167 (and not pending_dirs->name) because there may be no markers in the queue
1168 at this point. A marker may be enqueued when extract_dirs_from_files is
1169 called with a non-empty string or via print_dir. */
1172 print_current_files ();
1174 DIRED_PUTCHAR ('\n');
1176 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1179 while (pending_dirs)
1181 thispend = pending_dirs;
1182 pending_dirs = pending_dirs->next;
1186 if (thispend->name == NULL)
1188 /* thispend->name == NULL means this is a marker entry
1189 indicating we've finished processing the directory.
1190 Use its dev/ino numbers to remove the corresponding
1191 entry from the active_dir_set hash table. */
1192 struct dev_ino di = dev_ino_pop ();
1193 struct dev_ino *found = hash_delete (active_dir_set, &di);
1194 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1196 dev_ino_free (found);
1197 free_pending_ent (thispend);
1202 print_dir (thispend->name, thispend->realname);
1204 free_pending_ent (thispend);
1210 /* No need to free these since we're about to exit. */
1211 dired_dump_obstack ("//DIRED//", &dired_obstack);
1212 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1213 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1214 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1217 /* Restore default color before exiting */
1218 if (print_with_color)
1220 put_indicator (&color_indicator[C_LEFT]);
1221 put_indicator (&color_indicator[C_RIGHT]);
1226 assert (hash_get_n_entries (active_dir_set) == 0);
1227 hash_free (active_dir_set);
1233 /* Set all the option flags according to the switches specified.
1234 Return the index of the first non-option argument. */
1237 decode_switches (int argc, char **argv)
1240 char *time_style_option = 0;
1242 /* Record whether there is an option specifying sort type. */
1243 int sort_type_specified = 0;
1245 qmark_funny_chars = 0;
1247 /* initialize all switches to default settings */
1252 /* This is for the `dir' program. */
1253 format = many_per_line;
1254 set_quoting_style (NULL, escape_quoting_style);
1257 case LS_LONG_FORMAT:
1258 /* This is for the `vdir' program. */
1259 format = long_format;
1260 set_quoting_style (NULL, escape_quoting_style);
1264 /* This is for the `ls' program. */
1265 if (isatty (STDOUT_FILENO))
1267 format = many_per_line;
1268 /* See description of qmark_funny_chars, above. */
1269 qmark_funny_chars = 1;
1273 format = one_per_line;
1274 qmark_funny_chars = 0;
1282 time_type = time_mtime;
1283 sort_type = sort_name;
1286 print_block_size = 0;
1287 indicator_style = none;
1289 dereference = DEREF_UNDEFINED;
1293 really_all_files = 0;
1294 ignore_patterns = 0;
1296 /* FIXME: put this in a function. */
1298 char const *q_style = getenv ("QUOTING_STYLE");
1301 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1303 set_quoting_style (NULL, quoting_style_vals[i]);
1306 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1307 quotearg (q_style));
1312 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1313 human_output_opts = human_options (ls_block_size, false,
1314 &output_block_size);
1315 if (ls_block_size || getenv ("BLOCK_SIZE"))
1316 file_output_block_size = output_block_size;
1321 char const *p = getenv ("COLUMNS");
1325 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1326 && 0 < tmp_long && tmp_long <= INT_MAX)
1328 line_length = (int) tmp_long;
1333 _("ignoring invalid width in environment variable COLUMNS: %s"),
1343 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
1344 line_length = ws.ws_col;
1348 /* Using the TABSIZE environment variable is not POSIX-approved.
1349 Ignore it when POSIXLY_CORRECT is set. */
1353 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1356 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1357 && 0 <= tmp_long && tmp_long <= INT_MAX)
1359 tabsize = (int) tmp_long;
1364 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1370 while ((c = getopt_long (argc, argv,
1371 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1372 long_options, NULL)) != -1)
1381 really_all_files = 1;
1385 set_quoting_style (NULL, escape_quoting_style);
1389 time_type = time_ctime;
1397 /* Same as enabling -a -U and disabling -l -s. */
1399 really_all_files = 1;
1400 sort_type = sort_none;
1401 sort_type_specified = 1;
1403 if (format == long_format)
1404 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1405 print_block_size = 0; /* disable -s */
1406 print_with_color = 0; /* disable --color */
1410 format = long_format;
1415 human_output_opts = human_autoscale | human_SI | human_base_1024;
1416 file_output_block_size = output_block_size = 1;
1424 human_output_opts = 0;
1425 file_output_block_size = output_block_size = 1024;
1429 format = long_format;
1433 format = with_commas;
1438 format = long_format;
1441 case 'o': /* Just like -l, but don't display group info. */
1442 format = long_format;
1447 indicator_style = file_type;
1451 qmark_funny_chars = 1;
1459 print_block_size = 1;
1463 sort_type = sort_time;
1464 sort_type_specified = 1;
1468 time_type = time_atime;
1472 sort_type = sort_version;
1473 sort_type_specified = 1;
1479 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1480 || tmp_long <= 0 || tmp_long > INT_MAX)
1481 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1483 line_length = (int) tmp_long;
1488 format = horizontal;
1492 really_all_files = 0;
1497 add_ignore_pattern ("*~");
1498 add_ignore_pattern (".*~");
1502 format = many_per_line;
1510 indicator_style = classify;
1513 case 'G': /* inhibit display of group info */
1518 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1521 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1522 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1526 add_ignore_pattern (optarg);
1530 dereference = DEREF_ALWAYS;
1534 set_quoting_style (NULL, literal_quoting_style);
1538 set_quoting_style (NULL, c_quoting_style);
1546 sort_type = sort_size;
1547 sort_type_specified = 1;
1553 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1554 || tmp_long < 0 || tmp_long > INT_MAX)
1555 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1557 tabsize = (int) tmp_long;
1562 sort_type = sort_none;
1563 sort_type_specified = 1;
1567 sort_type = sort_extension;
1568 sort_type_specified = 1;
1572 /* -1 has no effect after -l. */
1573 if (format != long_format)
1574 format = one_per_line;
1578 print_author = true;
1582 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1583 sort_type_specified = 1;
1587 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1591 format = XARGMATCH ("--format", optarg, format_args, format_types);
1594 case FULL_TIME_OPTION:
1595 format = long_format;
1596 time_style_option = "full-iso";
1603 i = XARGMATCH ("--color", optarg, color_args, color_types);
1605 /* Using --color with no argument is equivalent to using
1609 print_with_color = (i == color_always
1610 || (i == color_if_tty
1611 && isatty (STDOUT_FILENO)));
1613 if (print_with_color)
1615 /* Don't use TAB characters in output. Some terminal
1616 emulators can't handle the combination of tabs and
1617 color codes on the same line. */
1623 case INDICATOR_STYLE_OPTION:
1624 indicator_style = XARGMATCH ("--indicator-style", optarg,
1625 indicator_style_args,
1626 indicator_style_types);
1629 case QUOTING_STYLE_OPTION:
1630 set_quoting_style (NULL,
1631 XARGMATCH ("--quoting-style", optarg,
1633 quoting_style_vals));
1636 case TIME_STYLE_OPTION:
1637 time_style_option = optarg;
1640 case SHOW_CONTROL_CHARS_OPTION:
1641 qmark_funny_chars = 0;
1644 case BLOCK_SIZE_OPTION:
1645 human_output_opts = human_options (optarg, true, &output_block_size);
1646 file_output_block_size = output_block_size;
1650 human_output_opts = human_autoscale | human_SI;
1651 file_output_block_size = output_block_size = 1;
1654 case_GETOPT_HELP_CHAR;
1656 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1659 usage (EXIT_FAILURE);
1663 filename_quoting_options = clone_quoting_options (NULL);
1664 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1665 set_char_quoting (filename_quoting_options, ' ', 1);
1666 if (indicator_style != none)
1669 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1670 set_char_quoting (filename_quoting_options, *p, 1);
1673 dirname_quoting_options = clone_quoting_options (NULL);
1674 set_char_quoting (dirname_quoting_options, ':', 1);
1676 /* --dired is meaningful only with --format=long (-l).
1677 Otherwise, ignore it. FIXME: warn about this?
1678 Alternatively, make --dired imply --format=long? */
1679 if (dired && format != long_format)
1682 /* If -c or -u is specified and not -l (or any other option that implies -l),
1683 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1684 The behavior of ls when using either -c or -u but with neither -l nor -t
1685 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1686 sort by atime (this is the one that's not specified by the POSIX spec),
1687 -lu means show atime and sort by name, -lut means show atime and sort
1690 if ((time_type == time_ctime || time_type == time_atime)
1691 && !sort_type_specified && format != long_format)
1693 sort_type = sort_time;
1696 if (format == long_format)
1698 char *style = time_style_option;
1699 static char const posix_prefix[] = "posix-";
1702 if (! (style = getenv ("TIME_STYLE")))
1703 style = "posix-long-iso";
1705 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1707 if (! hard_locale (LC_TIME))
1709 style += sizeof posix_prefix - 1;
1714 char *p0 = style + 1;
1715 char *p1 = strchr (p0, '\n');
1720 if (strchr (p1 + 1, '\n'))
1721 error (EXIT_FAILURE, 0, _("invalid time style format %s"),
1725 long_time_format[0] = p0;
1726 long_time_format[1] = p1;
1729 switch (XARGMATCH ("time style", style,
1733 case full_iso_time_style:
1734 long_time_format[0] = long_time_format[1] =
1735 "%Y-%m-%d %H:%M:%S.%N %z";
1738 case long_iso_time_style:
1739 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1742 case iso_time_style:
1743 long_time_format[0] = "%Y-%m-%d ";
1744 long_time_format[1] = "%m-%d %H:%M";
1747 case locale_time_style:
1748 if (hard_locale (LC_TIME))
1751 for (i = 0; i < 2; i++)
1752 long_time_format[i] =
1753 dcgettext (NULL, long_time_format[i], LC_TIME);
1761 /* Parse a string as part of the LS_COLORS variable; this may involve
1762 decoding all kinds of escape characters. If equals_end is set an
1763 unescaped equal sign ends the string, otherwise only a : or \0
1764 does. Returns the number of characters output, or -1 on failure.
1766 The resulting string is *not* null-terminated, but may contain
1769 Note that both dest and src are char **; on return they point to
1770 the first free byte after the array and the character that ended
1771 the input string, respectively. */
1774 get_funky_string (char **dest, const char **src, int equals_end)
1776 int num; /* For numerical codes */
1777 int count; /* Something to count with */
1779 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1784 p = *src; /* We don't want to double-indirect */
1785 q = *dest; /* the whole darn time. */
1787 count = 0; /* No characters counted in yet. */
1790 state = ST_GND; /* Start in ground state. */
1791 while (state < ST_END)
1795 case ST_GND: /* Ground state (no escapes) */
1800 state = ST_END; /* End of string */
1803 state = ST_BACKSLASH; /* Backslash scape sequence */
1807 state = ST_CARET; /* Caret escape */
1813 state = ST_END; /* End */
1816 /* else fall through */
1824 case ST_BACKSLASH: /* Backslash escaped character */
1835 state = ST_OCTAL; /* Octal sequence */
1840 state = ST_HEX; /* Hex sequence */
1843 case 'a': /* Bell */
1844 num = 7; /* Not all C compilers know what \a means */
1846 case 'b': /* Backspace */
1849 case 'e': /* Escape */
1852 case 'f': /* Form feed */
1855 case 'n': /* Newline */
1858 case 'r': /* Carriage return */
1864 case 'v': /* Vtab */
1867 case '?': /* Delete */
1870 case '_': /* Space */
1873 case '\0': /* End of string */
1874 state = ST_ERROR; /* Error! */
1876 default: /* Escaped character like \ ^ : = */
1880 if (state == ST_BACKSLASH)
1889 case ST_OCTAL: /* Octal sequence */
1890 if (*p < '0' || *p > '7')
1897 num = (num << 3) + (*(p++) - '0');
1900 case ST_HEX: /* Hex sequence */
1913 num = (num << 4) + (*(p++) - '0');
1921 num = (num << 4) + (*(p++) - 'a') + 10;
1929 num = (num << 4) + (*(p++) - 'A') + 10;
1939 case ST_CARET: /* Caret escape */
1940 state = ST_GND; /* Should be the next state... */
1941 if (*p >= '@' && *p <= '~')
1943 *(q++) = *(p++) & 037;
1963 return state == ST_ERROR ? -1 : count;
1967 parse_ls_color (void)
1969 const char *p; /* Pointer to character being parsed */
1970 char *buf; /* color_buf buffer pointer */
1971 int state; /* State of parser */
1972 int ind_no; /* Indicator number */
1973 char label[3]; /* Indicator label */
1974 struct color_ext_type *ext; /* Extension we are working on */
1976 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1980 strcpy (label, "??");
1982 /* This is an overly conservative estimate, but any possible
1983 LS_COLORS string will *not* generate a color_buf longer than
1984 itself, so it is a safe way of allocating a buffer in
1986 buf = color_buf = xstrdup (p);
1993 case 1: /* First label character */
2001 /* Allocate new extension block and add to head of
2002 linked list (this way a later definition will
2003 override an earlier one, which can be useful for
2004 having terminal-specific defs override global). */
2006 ext = XMALLOC (struct color_ext_type, 1);
2007 ext->next = color_ext_list;
2008 color_ext_list = ext;
2011 ext->ext.string = buf;
2013 state = (ext->ext.len =
2014 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
2018 state = 0; /* Done! */
2021 default: /* Assume it is file type label */
2028 case 2: /* Second label character */
2035 state = -1; /* Error */
2038 case 3: /* Equal sign after indicator label */
2039 state = -1; /* Assume failure... */
2040 if (*(p++) == '=')/* It *should* be... */
2042 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2044 if (STREQ (label, indicator_name[ind_no]))
2046 color_indicator[ind_no].string = buf;
2047 state = ((color_indicator[ind_no].len =
2048 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
2053 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2057 case 4: /* Equal sign after *.ext */
2060 ext->seq.string = buf;
2061 state = (ext->seq.len =
2062 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
2072 struct color_ext_type *e;
2073 struct color_ext_type *e2;
2076 _("unparsable value for LS_COLORS environment variable"));
2078 for (e = color_ext_list; e != NULL; /* empty */)
2084 print_with_color = 0;
2087 if (color_indicator[C_LINK].len == 6
2088 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2089 color_symlink_as_referent = 1;
2092 /* Request that the directory named NAME have its contents listed later.
2093 If REALNAME is nonzero, it will be used instead of NAME when the
2094 directory name is printed. This allows symbolic links to directories
2095 to be treated as regular directories but still be listed under their
2096 real names. NAME == NULL is used to insert a marker entry for the
2097 directory named in REALNAME.
2098 If F is non-NULL, we use its dev/ino information to save
2099 a call to stat -- when doing a recursive (-R) traversal. */
2102 queue_directory (const char *name, const char *realname)
2104 struct pending *new;
2106 new = XMALLOC (struct pending, 1);
2107 new->realname = realname ? xstrdup (realname) : NULL;
2108 new->name = name ? xstrdup (name) : NULL;
2109 new->next = pending_dirs;
2113 /* Read directory `name', and list the files in it.
2114 If `realname' is nonzero, print its name instead of `name';
2115 this is used for symbolic links to directories. */
2118 print_dir (const char *name, const char *realname)
2121 register struct dirent *next;
2122 register uintmax_t total_blocks = 0;
2123 static int first = 1;
2126 dirp = opendir (name);
2129 error (0, errno, "%s", quotearg_colon (name));
2136 struct stat dir_stat;
2137 int fd = dirfd (dirp);
2139 /* If dirfd failed, endure the overhead of using stat. */
2141 ? fstat (fd, &dir_stat)
2142 : stat (name, &dir_stat)) < 0)
2144 error (0, errno, _("cannot determine device and inode of %s"),
2145 quotearg_colon (name));
2150 /* If we've already visited this dev/inode pair, warn that
2151 we've found a loop, and do not process this directory. */
2152 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2154 error (0, 0, _("not listing already-listed directory: %s"),
2155 quotearg_colon (name));
2159 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2162 /* Read the directory entries, and insert the subfiles into the `files'
2169 /* Set errno to zero so we can distinguish between a readdir failure
2170 and when readdir simply finds that there are no more entries. */
2172 if ((next = readdir (dirp)) == NULL)
2176 /* Save/restore errno across closedir call. */
2181 /* Arrange to give a diagnostic after exiting this loop. */
2187 if (file_interesting (next))
2189 enum filetype type = unknown;
2191 #if HAVE_STRUCT_DIRENT_D_TYPE
2192 if (next->d_type == DT_BLK
2193 || next->d_type == DT_CHR
2194 || next->d_type == DT_DIR
2195 || next->d_type == DT_FIFO
2196 || next->d_type == DT_LNK
2197 || next->d_type == DT_REG
2198 || next->d_type == DT_SOCK)
2199 type = next->d_type;
2201 total_blocks += gobble_file (next->d_name, type, 0, name);
2205 if (dirp == NULL || CLOSEDIR (dirp))
2207 error (0, errno, _("reading directory %s"), quotearg_colon (name));
2209 /* Don't return; print whatever we got. */
2212 /* Sort the directory contents. */
2215 /* If any member files are subdirectories, perhaps they should have their
2216 contents listed rather than being mentioned here as files. */
2219 extract_dirs_from_files (name, 1);
2221 if (recursive || print_dir_name)
2224 DIRED_PUTCHAR ('\n');
2227 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2228 dired_pos += quote_name (stdout, realname ? realname : name,
2229 dirname_quoting_options, NULL);
2230 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2231 DIRED_FPUTS_LITERAL (":\n", stdout);
2234 if (format == long_format || print_block_size)
2237 char buf[LONGEST_HUMAN_READABLE + 1];
2241 DIRED_FPUTS (p, stdout, strlen (p));
2242 DIRED_PUTCHAR (' ');
2243 p = human_readable (total_blocks, buf, human_output_opts,
2244 ST_NBLOCKSIZE, output_block_size);
2245 DIRED_FPUTS (p, stdout, strlen (p));
2246 DIRED_PUTCHAR ('\n');
2250 print_current_files ();
2253 /* Add `pattern' to the list of patterns for which files that match are
2257 add_ignore_pattern (const char *pattern)
2259 register struct ignore_pattern *ignore;
2261 ignore = XMALLOC (struct ignore_pattern, 1);
2262 ignore->pattern = pattern;
2263 /* Add it to the head of the linked list. */
2264 ignore->next = ignore_patterns;
2265 ignore_patterns = ignore;
2268 /* Return nonzero if the file in `next' should be listed. */
2271 file_interesting (const struct dirent *next)
2273 register struct ignore_pattern *ignore;
2275 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2276 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2279 if (really_all_files
2280 || next->d_name[0] != '.'
2282 && next->d_name[1] != '\0'
2283 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2289 /* Enter and remove entries in the table `files'. */
2291 /* Empty the table of files. */
2298 for (i = 0; i < files_index; i++)
2300 free (files[i].name);
2301 if (files[i].linkname)
2302 free (files[i].linkname);
2306 block_size_size = 4;
2309 /* Add a file to the current table of files.
2310 Verify that the file exists, and print an error message if it does not.
2311 Return the number of blocks that the file occupies. */
2314 gobble_file (const char *name, enum filetype type, int explicit_arg,
2315 const char *dirname)
2317 register uintmax_t blocks;
2318 register char *path;
2320 if (files_index == nfiles)
2323 files = XREALLOC (files, struct fileinfo, nfiles);
2326 files[files_index].linkname = 0;
2327 files[files_index].linkmode = 0;
2328 files[files_index].linkok = 0;
2331 || format_needs_stat
2332 || (format_needs_type
2335 /* FIXME: remove this disjunct.
2336 I don't think we care about symlinks here, but for now
2337 this won't make a big performance difference. */
2338 || type == symbolic_link
2340 /* --indicator-style=classify (aka -F)
2341 requires that we stat each regular file
2342 to see if it's executable. */
2343 || (type == normal && (indicator_style == classify
2344 /* This is so that --color ends up
2345 highlighting files with the executable
2346 bit set even when options like -F are
2348 || print_with_color)))))
2351 /* `path' is the absolute pathname of this file. */
2354 if (name[0] == '/' || dirname[0] == 0)
2355 path = (char *) name;
2358 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
2359 attach (path, dirname, name);
2362 switch (dereference)
2365 err = stat (path, &files[files_index].stat);
2368 case DEREF_COMMAND_LINE_ARGUMENTS:
2369 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2373 err = stat (path, &files[files_index].stat);
2375 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2378 need_lstat = (err < 0
2380 : ! S_ISDIR (files[files_index].stat.st_mode));
2384 /* stat failed because of ENOENT, maybe indicating a dangling
2385 symlink. Or stat succeeded, PATH does not refer to a
2386 directory, and --dereference-command-line-symlink-to-dir is
2387 in effect. Fall through so that we call lstat instead. */
2390 default: /* DEREF_NEVER */
2391 err = lstat (path, &files[files_index].stat);
2397 error (0, errno, "%s", quotearg_colon (path));
2403 if (format == long_format)
2405 int n = file_has_acl (path, &files[files_index].stat);
2406 files[files_index].have_acl = (0 < n);
2408 error (0, errno, "%s", quotearg_colon (path));
2412 if (S_ISLNK (files[files_index].stat.st_mode)
2413 && (format == long_format || check_symlink_color))
2416 struct stat linkstats;
2418 get_link_name (path, &files[files_index]);
2419 linkpath = make_link_path (path, files[files_index].linkname);
2421 /* Avoid following symbolic links when possible, ie, when
2422 they won't be traced and when no indicator is needed. */
2424 && (indicator_style != none || check_symlink_color)
2425 && stat (linkpath, &linkstats) == 0)
2427 files[files_index].linkok = 1;
2429 /* Symbolic links to directories that are mentioned on the
2430 command line are automatically traced if not being
2432 if (!explicit_arg || format == long_format
2433 || !S_ISDIR (linkstats.st_mode))
2435 /* Get the linked-to file's mode for the filetype indicator
2436 in long listings. */
2437 files[files_index].linkmode = linkstats.st_mode;
2438 files[files_index].linkok = 1;
2445 if (S_ISLNK (files[files_index].stat.st_mode))
2446 files[files_index].filetype = symbolic_link;
2447 else if (S_ISDIR (files[files_index].stat.st_mode))
2449 if (explicit_arg && !immediate_dirs)
2450 files[files_index].filetype = arg_directory;
2452 files[files_index].filetype = directory;
2455 files[files_index].filetype = normal;
2457 blocks = ST_NBLOCKS (files[files_index].stat);
2459 char buf[LONGEST_HUMAN_READABLE + 1];
2460 int len = strlen (human_readable (blocks, buf, human_output_opts,
2461 ST_NBLOCKSIZE, output_block_size));
2462 if (block_size_size < len)
2463 block_size_size = len < 7 ? len : 7;
2468 files[files_index].filetype = type;
2469 #if HAVE_STRUCT_DIRENT_D_TYPE
2470 files[files_index].stat.st_mode = DTTOIF (type);
2475 files[files_index].name = xstrdup (name);
2483 /* Put the name of the file that `filename' is a symbolic link to
2484 into the `linkname' field of `f'. */
2487 get_link_name (const char *filename, struct fileinfo *f)
2489 f->linkname = xreadlink (filename);
2490 if (f->linkname == NULL)
2492 error (0, errno, _("cannot read symbolic link %s"),
2493 quotearg_colon (filename));
2498 /* If `linkname' is a relative path and `path' contains one or more
2499 leading directories, return `linkname' with those directories
2500 prepended; otherwise, return a copy of `linkname'.
2501 If `linkname' is zero, return zero. */
2504 make_link_path (const char *path, const char *linkname)
2512 if (*linkname == '/')
2513 return xstrdup (linkname);
2515 /* The link is to a relative path. Prepend any leading path
2516 in `path' to the link name. */
2517 linkbuf = strrchr (path, '/');
2519 return xstrdup (linkname);
2521 bufsiz = linkbuf - path + 1;
2522 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2523 strncpy (linkbuf, path, bufsiz);
2524 strcpy (linkbuf + bufsiz, linkname);
2529 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2530 This is so we don't try to recurse on `././././. ...' */
2533 basename_is_dot_or_dotdot (const char *name)
2535 char const *base = base_name (name);
2536 return DOT_OR_DOTDOT (base);
2539 /* Remove any entries from `files' that are for directories,
2540 and queue them to be listed as directories instead.
2541 `dirname' is the prefix to prepend to each dirname
2542 to make it correct relative to ls's working dir.
2543 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2544 This is desirable when processing directories recursively. */
2547 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2551 if (*dirname && LOOP_DETECT)
2553 /* Insert a marker entry first. When we dequeue this marker entry,
2554 we'll know that DIRNAME has been processed and may be removed
2555 from the set of active directories. */
2556 queue_directory (NULL, dirname);
2559 /* Queue the directories last one first, because queueing reverses the
2561 for (i = files_index - 1; i >= 0; i--)
2562 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2563 && (!ignore_dot_and_dot_dot
2564 || !basename_is_dot_or_dotdot (files[i].name)))
2566 if (files[i].name[0] == '/' || dirname[0] == 0)
2568 queue_directory (files[i].name, files[i].linkname);
2572 char *path = path_concat (dirname, files[i].name, NULL);
2573 queue_directory (path, files[i].linkname);
2576 if (files[i].filetype == arg_directory)
2577 free (files[i].name);
2580 /* Now delete the directories from the table, compacting all the remaining
2583 for (i = 0, j = 0; i < files_index; i++)
2584 if (files[i].filetype != arg_directory)
2585 files[j++] = files[i];
2589 /* Use strcoll to compare strings in this locale. If an error occurs,
2590 report an error and longjmp to failed_strcoll. */
2592 static jmp_buf failed_strcoll;
2595 xstrcoll (char const *a, char const *b)
2599 diff = strcoll (a, b);
2602 error (0, errno, _("cannot compare file names %s and %s"),
2603 quote_n (0, a), quote_n (1, b));
2605 longjmp (failed_strcoll, 1);
2610 /* Comparison routines for sorting the files. */
2612 typedef void const *V;
2615 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2616 int (*cmp) (char const *, char const *))
2618 int diff = CTIME_CMP (b->stat, a->stat);
2619 return diff ? diff : cmp (a->name, b->name);
2621 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2622 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2623 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2624 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2627 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2628 int (*cmp) (char const *, char const *))
2630 int diff = MTIME_CMP (b->stat, a->stat);
2631 return diff ? diff : cmp (a->name, b->name);
2633 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2634 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2635 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2636 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2639 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2640 int (*cmp) (char const *, char const *))
2642 int diff = ATIME_CMP (b->stat, a->stat);
2643 return diff ? diff : cmp (a->name, b->name);
2645 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2646 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2647 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2648 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2651 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2652 int (*cmp) (char const *, char const *))
2654 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2655 return diff ? diff : cmp (a->name, b->name);
2657 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2658 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2659 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2660 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2663 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2665 return strverscmp (a->name, b->name);
2667 static int compare_version (V a, V b) { return cmp_version (a, b); }
2668 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2671 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2672 int (*cmp) (char const *, char const *))
2674 return cmp (a->name, b->name);
2676 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2677 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2678 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2679 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2681 /* Compare file extensions. Files with no extension are `smallest'.
2682 If extensions are the same, compare by filenames instead. */
2685 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2686 int (*cmp) (char const *, char const *))
2688 char const *base1 = strrchr (a->name, '.');
2689 char const *base2 = strrchr (b->name, '.');
2690 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2691 return diff ? diff : cmp (a->name, b->name);
2693 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2694 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2695 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2696 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2698 /* Sort the files now in the table. */
2713 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2716 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2719 func = sort_reverse ? rev_cmp_atime : compare_atime;
2726 func = sort_reverse ? rev_cmp_name : compare_name;
2728 case sort_extension:
2729 func = sort_reverse ? rev_cmp_extension : compare_extension;
2732 func = sort_reverse ? rev_cmp_size : compare_size;
2735 func = sort_reverse ? rev_cmp_version : compare_version;
2741 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2742 ignore strcoll failures, as a failing strcoll might be a
2743 comparison function that is not a total order, and if we ignored
2744 the failure this might cause qsort to dump core. */
2746 if (setjmp (failed_strcoll))
2754 func = sort_reverse ? rev_str_ctime : compstr_ctime;
2757 func = sort_reverse ? rev_str_mtime : compstr_mtime;
2760 func = sort_reverse ? rev_str_atime : compstr_atime;
2767 func = sort_reverse ? rev_str_name : compstr_name;
2769 case sort_extension:
2770 func = sort_reverse ? rev_str_extension : compstr_extension;
2773 func = sort_reverse ? rev_str_size : compstr_size;
2780 qsort (files, files_index, sizeof (struct fileinfo), func);
2783 /* List all the files now in the table. */
2786 print_current_files (void)
2793 for (i = 0; i < files_index; i++)
2795 print_file_name_and_frills (files + i);
2801 init_column_info ();
2802 print_many_per_line ();
2806 init_column_info ();
2807 print_horizontal ();
2811 print_with_commas ();
2815 for (i = 0; i < files_index; i++)
2817 print_long_format (files + i);
2818 DIRED_PUTCHAR ('\n');
2824 /* Return the expected number of columns in a long-format time stamp,
2825 or zero if it cannot be calculated. */
2828 long_time_expected_width (void)
2830 static int width = -1;
2835 struct tm const *tm = localtime (&epoch);
2836 char const *fmt = long_time_format[0];
2838 char *buf = initbuf;
2839 size_t bufsize = sizeof initbuf;
2845 len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2848 buf = alloca (bufsize *= 2);
2851 width = mbsnwidth (buf, len, 0);
2859 /* Get the current time. */
2862 get_current_time (void)
2864 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2866 struct timespec timespec;
2867 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
2869 current_time = timespec.tv_sec;
2870 current_time_ns = timespec.tv_nsec;
2876 /* The clock does not have nanosecond resolution, so get the maximum
2877 possible value for the current time that is consistent with the
2878 reported clock. That way, files are not considered to be in the
2879 future merely because their time stamps have higher resolution
2880 than the clock resolution. */
2882 #if HAVE_GETTIMEOFDAY
2884 struct timeval timeval;
2885 if (gettimeofday (&timeval, NULL) == 0)
2887 current_time = timeval.tv_sec;
2888 current_time_ns = timeval.tv_usec * 1000 + 999;
2894 current_time = time (NULL);
2895 current_time_ns = 999999999;
2898 /* Format into BUFFER the name or id of the user with id U. Return
2899 the length of the formatted buffer, not counting the terminating
2903 format_user (char *buffer, uid_t u)
2905 char const *name = (numeric_ids ? NULL : getuser (u));
2907 sprintf (buffer, "%-8s ", name);
2909 sprintf (buffer, "%-8lu ", (unsigned long) u);
2910 return strlen (buffer);
2913 /* Print information about F in long format. */
2916 print_long_format (const struct fileinfo *f)
2920 [LONGEST_HUMAN_READABLE + 1 /* inode */
2921 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
2922 + sizeof (modebuf) - 1 + 1 /* mode string */
2923 + LONGEST_HUMAN_READABLE + 1 /* st_nlink */
2924 + ID_LENGTH_MAX + 1 /* owner name */
2925 + ID_LENGTH_MAX + 1 /* group name */
2926 + ID_LENGTH_MAX + 1 /* author name */
2927 + LONGEST_HUMAN_READABLE + 1 /* major device number */
2928 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
2929 + 35 + 1 /* usual length of time/date -- may be longer; see below */
2931 char *buf = init_bigbuf;
2932 size_t bufsize = sizeof (init_bigbuf);
2936 int when_ns IF_LINT (= 0);
2937 struct tm *when_local;
2939 /* Compute mode string. On most systems, it's based on st_mode.
2940 On systems with migration (via the stat.st_dm_mode field), use
2941 the file's migrated status. */
2942 mode_string (ST_DM_MODE (f->stat), modebuf);
2944 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2950 when = f->stat.st_ctime;
2951 when_ns = TIMESPEC_NS (f->stat.st_ctim);
2954 when = f->stat.st_mtime;
2955 when_ns = TIMESPEC_NS (f->stat.st_mtim);
2958 when = f->stat.st_atime;
2959 when_ns = TIMESPEC_NS (f->stat.st_atim);
2967 char hbuf[LONGEST_HUMAN_READABLE + 1];
2968 sprintf (p, "%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, hbuf));
2972 if (print_block_size)
2974 char hbuf[LONGEST_HUMAN_READABLE + 1];
2975 sprintf (p, "%*s ", block_size_size,
2976 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
2977 ST_NBLOCKSIZE, output_block_size));
2981 /* The last byte of the mode string is the POSIX
2982 "optional alternate access method flag". */
2983 sprintf (p, "%s %3lu ", modebuf, (unsigned long) f->stat.st_nlink);
2987 p += format_user (p, f->stat.st_uid);
2991 char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2993 sprintf (p, "%-8s ", group_name);
2995 sprintf (p, "%-8lu ", (unsigned long) f->stat.st_gid);
3000 p += format_user (p, f->stat.st_author);
3002 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3003 sprintf (p, "%3lu, %3lu ",
3004 (unsigned long) major (f->stat.st_rdev),
3005 (unsigned long) minor (f->stat.st_rdev));
3008 char hbuf[LONGEST_HUMAN_READABLE + 1];
3009 uintmax_t size = f->stat.st_size;
3011 /* POSIX requires that the size be printed without a sign, even
3012 when negative. Assume the typical case where negative sizes
3013 are actually positive values that have wrapped around. */
3014 size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3017 human_readable (size, hbuf, human_output_opts,
3018 1, file_output_block_size));
3023 if ((when_local = localtime (&when)))
3025 time_t six_months_ago;
3029 /* If the file appears to be in the future, update the current
3030 time, in case the file happens to have been modified since
3031 the last time we checked the clock. */
3032 if (current_time < when
3033 || (current_time == when && current_time_ns < when_ns))
3035 /* Note that get_current_time calls gettimeofday which, on some non-
3036 compliant systems, clobbers the buffer used for localtime's result.
3037 But it's ok here, because we use a gettimeofday wrapper that
3038 saves and restores the buffer around the gettimeofday call. */
3039 get_current_time ();
3042 /* Consider a time to be recent if it is within the past six
3043 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3044 31556952 seconds on the average. Write this value as an
3045 integer constant to avoid floating point hassles. */
3046 six_months_ago = current_time - 31556952 / 2;
3047 recent = (six_months_ago <= when
3048 && (when < current_time
3049 || (when == current_time && when_ns <= current_time_ns)));
3050 fmt = long_time_format[recent];
3056 s = nstrftime (p, buf + bufsize - p - 1, fmt,
3057 when_local, 0, when_ns);
3060 newbuf = alloca (bufsize *= 2);
3061 memcpy (newbuf, buf, p - buf);
3062 p = newbuf + (p - buf);
3069 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3074 /* The time cannot be represented as a local time;
3075 print it as a huge integer number of seconds. */
3076 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3077 sprintf (p, "%*s ", long_time_expected_width (),
3078 (TYPE_SIGNED (time_t)
3079 ? imaxtostr (when, hbuf)
3080 : umaxtostr (when, hbuf)));
3085 DIRED_FPUTS (buf, stdout, p - buf);
3086 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3089 if (f->filetype == symbolic_link)
3093 DIRED_FPUTS_LITERAL (" -> ", stdout);
3094 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3096 if (indicator_style != none)
3097 print_type_indicator (f->linkmode);
3100 else if (indicator_style != none)
3101 print_type_indicator (f->stat.st_mode);
3104 /* Output to OUT a quoted representation of the file name NAME,
3105 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3106 Store the number of screen columns occupied by NAME's quoted
3107 representation into WIDTH, if non-NULL. Return the number of bytes
3111 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3114 char smallbuf[BUFSIZ];
3115 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3117 size_t displayed_width IF_LINT (= 0);
3119 if (len < sizeof smallbuf)
3123 buf = (char *) alloca (len + 1);
3124 quotearg_buffer (buf, len + 1, name, -1, options);
3127 if (qmark_funny_chars)
3132 char const *p = buf;
3133 char const *plimit = buf + len;
3135 displayed_width = 0;
3140 case ' ': case '!': case '"': case '#': case '%':
3141 case '&': case '\'': case '(': case ')': case '*':
3142 case '+': case ',': case '-': case '.': case '/':
3143 case '0': case '1': case '2': case '3': case '4':
3144 case '5': case '6': case '7': case '8': case '9':
3145 case ':': case ';': case '<': case '=': case '>':
3147 case 'A': case 'B': case 'C': case 'D': case 'E':
3148 case 'F': case 'G': case 'H': case 'I': case 'J':
3149 case 'K': case 'L': case 'M': case 'N': case 'O':
3150 case 'P': case 'Q': case 'R': case 'S': case 'T':
3151 case 'U': case 'V': case 'W': case 'X': case 'Y':
3153 case '[': case '\\': case ']': case '^': case '_':
3154 case 'a': case 'b': case 'c': case 'd': case 'e':
3155 case 'f': case 'g': case 'h': case 'i': case 'j':
3156 case 'k': case 'l': case 'm': case 'n': case 'o':
3157 case 'p': case 'q': case 'r': case 's': case 't':
3158 case 'u': case 'v': case 'w': case 'x': case 'y':
3159 case 'z': case '{': case '|': case '}': case '~':
3160 /* These characters are printable ASCII characters. */
3162 displayed_width += 1;
3165 /* If we have a multibyte sequence, copy it until we
3166 reach its end, replacing each non-printable multibyte
3167 character with a single question mark. */
3170 memset (&mbstate, 0, sizeof mbstate);
3177 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3179 if (bytes == (size_t) -1)
3181 /* An invalid multibyte sequence was
3182 encountered. Skip one input byte, and
3183 put a question mark. */
3186 displayed_width += 1;
3190 if (bytes == (size_t) -2)
3192 /* An incomplete multibyte character
3193 at the end. Replace it entirely with
3197 displayed_width += 1;
3202 /* A null wide character was encountered. */
3208 /* A printable multibyte character.
3210 for (; bytes > 0; --bytes)
3212 displayed_width += w;
3216 /* An unprintable multibyte character.
3217 Replace it entirely with a question
3221 displayed_width += 1;
3224 while (! mbsinit (&mbstate));
3229 /* The buffer may have shrunk. */
3236 char const *plimit = buf + len;
3240 if (! ISPRINT ((unsigned char) *p))
3244 displayed_width = len;
3247 else if (width != NULL)
3251 displayed_width = mbsnwidth (buf, len, 0);
3255 char const *p = buf;
3256 char const *plimit = buf + len;
3258 displayed_width = 0;
3261 if (ISPRINT ((unsigned char) *p))
3269 fwrite (buf, 1, len, out);
3271 *width = displayed_width;
3276 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3277 struct obstack *stack)
3279 if (print_with_color)
3280 print_color_indicator (p, mode, linkok);
3283 PUSH_CURRENT_DIRED_POS (stack);
3285 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3288 PUSH_CURRENT_DIRED_POS (stack);
3290 if (print_with_color)
3291 prep_non_filename_text ();
3295 prep_non_filename_text (void)
3297 if (color_indicator[C_END].string != NULL)
3298 put_indicator (&color_indicator[C_END]);
3301 put_indicator (&color_indicator[C_LEFT]);
3302 put_indicator (&color_indicator[C_NORM]);
3303 put_indicator (&color_indicator[C_RIGHT]);
3307 /* Print the file name of `f' with appropriate quoting.
3308 Also print file size, inode number, and filetype indicator character,
3309 as requested by switches. */
3312 print_file_name_and_frills (const struct fileinfo *f)
3314 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3317 printf ("%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, buf));
3319 if (print_block_size)
3320 printf ("%*s ", block_size_size,
3321 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3322 ST_NBLOCKSIZE, output_block_size));
3324 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3326 if (indicator_style != none)
3327 print_type_indicator (f->stat.st_mode);
3331 print_type_indicator (mode_t mode)
3337 if (indicator_style == classify && (mode & S_IXUGO))
3346 else if (S_ISLNK (mode))
3348 else if (S_ISFIFO (mode))
3350 else if (S_ISSOCK (mode))
3352 else if (S_ISDOOR (mode))
3363 print_color_indicator (const char *name, mode_t mode, int linkok)
3366 struct color_ext_type *ext; /* Color extension */
3367 size_t len; /* Length of name */
3369 /* Is this a nonexistent file? If so, linkok == -1. */
3371 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3380 else if (S_ISLNK (mode))
3381 type = ((!linkok && color_indicator[C_ORPHAN].string)
3382 ? C_ORPHAN : C_LINK);
3383 else if (S_ISFIFO (mode))
3385 else if (S_ISSOCK (mode))
3387 else if (S_ISBLK (mode))
3389 else if (S_ISCHR (mode))
3391 else if (S_ISDOOR (mode))
3394 if (type == C_FILE && (mode & S_IXUGO) != 0)
3397 /* Check the file's suffix only if still classified as C_FILE. */
3401 /* Test if NAME has a recognized suffix. */
3403 len = strlen (name);
3404 name += len; /* Pointer to final \0. */
3405 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3407 if ((size_t) ext->ext.len <= len
3408 && strncmp (name - ext->ext.len, ext->ext.string,
3415 put_indicator (&color_indicator[C_LEFT]);
3416 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3417 put_indicator (&color_indicator[C_RIGHT]);
3420 /* Output a color indicator (which may contain nulls). */
3422 put_indicator (const struct bin_str *ind)
3425 register const char *p;
3429 for (i = ind->len; i > 0; --i)
3433 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3434 Return zero if the write is successful or if the string length is zero.
3435 Return nonzero if the write fails. */
3437 put_indicator_direct (const struct bin_str *ind)
3444 return (full_write (STDOUT_FILENO, ind->string, len) != len);
3448 length_of_file_name_and_frills (const struct fileinfo *f)
3450 register int len = 0;
3454 len += INODE_DIGITS + 1;
3456 if (print_block_size)
3457 len += 1 + block_size_size;
3459 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3462 if (indicator_style != none)
3464 mode_t filetype = f->stat.st_mode;
3466 if (S_ISREG (filetype))
3468 if (indicator_style == classify
3469 && (f->stat.st_mode & S_IXUGO))
3472 else if (S_ISDIR (filetype)
3473 || S_ISLNK (filetype)
3474 || S_ISFIFO (filetype)
3475 || S_ISSOCK (filetype)
3476 || S_ISDOOR (filetype)
3485 print_many_per_line (void)
3487 struct column_info *line_fmt;
3488 int filesno; /* Index into files. */
3489 int row; /* Current row. */
3490 int max_name_length; /* Length of longest file name + frills. */
3491 int name_length; /* Length of each file name + frills. */
3492 int pos; /* Current character column. */
3493 int cols; /* Number of files across. */
3494 int rows; /* Maximum number of files down. */
3497 /* Normally the maximum number of columns is determined by the
3498 screen width. But if few files are available this might limit it
3500 max_cols = max_idx > files_index ? files_index : max_idx;
3502 /* Compute the maximum number of possible columns. */
3503 for (filesno = 0; filesno < files_index; ++filesno)
3507 name_length = length_of_file_name_and_frills (files + filesno);
3509 for (i = 0; i < max_cols; ++i)
3511 if (column_info[i].valid_len)
3513 int idx = filesno / ((files_index + i) / (i + 1));
3514 int real_length = name_length + (idx == i ? 0 : 2);
3516 if (real_length > column_info[i].col_arr[idx])
3518 column_info[i].line_len += (real_length
3519 - column_info[i].col_arr[idx]);
3520 column_info[i].col_arr[idx] = real_length;
3521 column_info[i].valid_len = column_info[i].line_len < line_length;
3527 /* Find maximum allowed columns. */
3528 for (cols = max_cols; cols > 1; --cols)
3530 if (column_info[cols - 1].valid_len)
3534 line_fmt = &column_info[cols - 1];
3536 /* Calculate the number of rows that will be in each column except possibly
3537 for a short column on the right. */
3538 rows = files_index / cols + (files_index % cols != 0);
3540 for (row = 0; row < rows; row++)
3545 /* Print the next row. */
3548 print_file_name_and_frills (files + filesno);
3549 name_length = length_of_file_name_and_frills (files + filesno);
3550 max_name_length = line_fmt->col_arr[col++];
3553 if (filesno >= files_index)
3556 indent (pos + name_length, pos + max_name_length);
3557 pos += max_name_length;
3564 print_horizontal (void)
3566 struct column_info *line_fmt;
3568 int max_name_length;
3574 /* Normally the maximum number of columns is determined by the
3575 screen width. But if few files are available this might limit it
3577 max_cols = max_idx > files_index ? files_index : max_idx;
3579 /* Compute the maximum file name length. */
3580 max_name_length = 0;
3581 for (filesno = 0; filesno < files_index; ++filesno)
3585 name_length = length_of_file_name_and_frills (files + filesno);
3587 for (i = 0; i < max_cols; ++i)
3589 if (column_info[i].valid_len)
3591 int idx = filesno % (i + 1);
3592 int real_length = name_length + (idx == i ? 0 : 2);
3594 if (real_length > column_info[i].col_arr[idx])
3596 column_info[i].line_len += (real_length
3597 - column_info[i].col_arr[idx]);
3598 column_info[i].col_arr[idx] = real_length;
3599 column_info[i].valid_len = column_info[i].line_len < line_length;
3605 /* Find maximum allowed columns. */
3606 for (cols = max_cols; cols > 1; --cols)
3608 if (column_info[cols - 1].valid_len)
3612 line_fmt = &column_info[cols - 1];
3616 /* Print first entry. */
3617 print_file_name_and_frills (files);
3618 name_length = length_of_file_name_and_frills (files);
3619 max_name_length = line_fmt->col_arr[0];
3622 for (filesno = 1; filesno < files_index; ++filesno)
3624 int col = filesno % cols;
3633 indent (pos + name_length, pos + max_name_length);
3634 pos += max_name_length;
3637 print_file_name_and_frills (files + filesno);
3639 name_length = length_of_file_name_and_frills (files + filesno);
3640 max_name_length = line_fmt->col_arr[col];
3646 print_with_commas (void)
3653 for (filesno = 0; filesno < files_index; filesno++)
3657 pos += length_of_file_name_and_frills (files + filesno);
3658 if (filesno + 1 < files_index)
3659 pos += 2; /* For the comma and space */
3661 if (old_pos != 0 && pos >= line_length)
3667 print_file_name_and_frills (files + filesno);
3668 if (filesno + 1 < files_index)
3677 /* Assuming cursor is at position FROM, indent up to position TO.
3678 Use a TAB character instead of two or more spaces whenever possible. */
3681 indent (int from, int to)
3685 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
3688 from += tabsize - from % tabsize;
3698 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3699 /* FIXME: maybe remove this function someday. See about using a
3700 non-malloc'ing version of path_concat. */
3703 attach (char *dest, const char *dirname, const char *name)
3705 const char *dirnamep = dirname;
3707 /* Copy dirname if it is not ".". */
3708 if (dirname[0] != '.' || dirname[1] != 0)
3711 *dest++ = *dirnamep++;
3712 /* Add '/' if `dirname' doesn't already end with it. */
3713 if (dirnamep > dirname && dirnamep[-1] != '/')
3722 init_column_info (void)
3727 max_idx = line_length / MIN_COLUMN_WIDTH;
3731 if (column_info == NULL)
3733 column_info = XMALLOC (struct column_info, max_idx);
3737 for (i = 0; i < max_idx; ++i)
3741 column_info[i].valid_len = 1;
3742 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3745 column_info[i].col_arr = XMALLOC (int, i + 1);
3747 for (j = 0; j <= i; ++j)
3748 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3756 fprintf (stderr, _("Try `%s --help' for more information.\n"),
3760 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3762 List information about the FILEs (the current directory by default).\n\
3763 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3767 Mandatory arguments to long options are mandatory for short options too.\n\
3770 -a, --all do not hide entries starting with .\n\
3771 -A, --almost-all do not list implied . and ..\n\
3772 --author print the author of each file\n\
3773 -b, --escape print octal escapes for nongraphic characters\n\
3776 --block-size=SIZE use SIZE-byte blocks\n\
3777 -B, --ignore-backups do not list implied entries ending with ~\n\
3778 -c with -lt: sort by, and show, ctime (time of last\n\
3779 modification of file status information)\n\
3780 with -l: show ctime and sort by name\n\
3781 otherwise: sort by ctime\n\
3784 -C list entries by columns\n\
3785 --color[=WHEN] control whether color is used to distinguish file\n\
3786 types. WHEN may be `never', `always', or `auto'\n\
3787 -d, --directory list directory entries instead of contents,\n\
3788 and do not dereference symbolic links\n\
3789 -D, --dired generate output designed for Emacs' dired mode\n\
3792 -f do not sort, enable -aU, disable -lst\n\
3793 -F, --classify append indicator (one of */=@|) to entries\n\
3794 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3795 single-column -1, verbose -l, vertical -C\n\
3796 --full-time like -l --time-style=full-iso\n\
3799 -g like -l, but do not list owner\n\
3800 -G, --no-group inhibit display of group information\n\
3801 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3802 --si likewise, but use powers of 1000 not 1024\n\
3803 -H, --dereference-command-line\n\
3804 follow symbolic links listed on the command line\n\
3805 --dereference-command-line-symlink-to-dir\n\
3806 follow each command line symbolic link\n\
3807 that points to a directory\n\
3810 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3811 none (default), classify (-F), file-type (-p)\n\
3812 -i, --inode print index number of each file\n\
3813 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3814 -k like --block-size=1K\n\
3817 -l use a long listing format\n\
3818 -L, --dereference when showing file information for a symbolic\n\
3819 link, show information for the file the link\n\
3820 references rather than for the link itself\n\
3821 -m fill width with a comma separated list of entries\n\
3824 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3825 -N, --literal print raw entry names (don't treat e.g. control\n\
3826 characters specially)\n\
3827 -o like -l, but do not list group information\n\
3828 -p, --file-type append indicator (one of /=@|) to entries\n\
3831 -q, --hide-control-chars print ? instead of non graphic characters\n\
3832 --show-control-chars show non graphic characters as-is (default\n\
3833 unless program is `ls' and output is a terminal)\n\
3834 -Q, --quote-name enclose entry names in double quotes\n\
3835 --quoting-style=WORD use quoting style WORD for entry names:\n\
3836 literal, locale, shell, shell-always, c, escape\n\
3839 -r, --reverse reverse order while sorting\n\
3840 -R, --recursive list subdirectories recursively\n\
3841 -s, --size print size of each file, in blocks\n\
3844 -S sort by file size\n\
3845 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3847 status -c, time -t, atime -u, access -u, use -u\n\
3848 --time=WORD show time as WORD instead of modification time:\n\
3849 atime, access, use, ctime or status; use\n\
3850 specified time as sort key if --sort=time\n\
3853 --time-style=STYLE show times using style STYLE:\n\
3854 full-iso, long-iso, iso, locale, +FORMAT\n\
3855 FORMAT is interpreted like `date'; if FORMAT is\n\
3856 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
3857 non-recent files and FORMAT2 to recent files;\n\
3858 if STYLE is prefixed with `posix-', STYLE\n\
3859 takes effect only outside the POSIX locale\n\
3860 -t sort by modification time\n\
3861 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
3864 -u with -lt: sort by, and show, access time\n\
3865 with -l: show access time and sort by name\n\
3866 otherwise: sort by access time\n\
3867 -U do not sort; list entries in directory order\n\
3868 -v sort by version\n\
3871 -w, --width=COLS assume screen width instead of current value\n\
3872 -x list entries by lines instead of by columns\n\
3873 -X sort alphabetically by entry extension\n\
3874 -1 list one file per line\n\
3876 fputs (HELP_OPTION_DESCRIPTION, stdout);
3877 fputs (VERSION_OPTION_DESCRIPTION, stdout);
3879 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3880 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
3884 By default, color is not used to distinguish types of files. That is\n\
3885 equivalent to using --color=none. Using the --color option without the\n\
3886 optional WHEN argument is equivalent to using --color=always. With\n\
3887 --color=auto, color codes are output only if standard output is connected\n\
3888 to a terminal (tty).\n\
3890 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);