1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2002 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>
47 # include <inttypes.h>
54 #ifdef GWINSZ_IN_SYS_IOCTL
55 # include <sys/ioctl.h>
58 #ifdef WINSIZE_IN_PTEM
59 # include <sys/stream.h>
60 # include <sys/ptem.h>
79 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
88 #if !defined iswprint && !HAVE_ISWPRINT
89 # define iswprint(wc) 1
92 #ifndef HAVE_DECL_WCWIDTH
93 "this configure-time declaration test was not run"
95 #if !HAVE_DECL_WCWIDTH
99 /* If wcwidth() doesn't exist, assume all printable characters have
103 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
110 #include "argmatch.h"
114 #include "hard-locale.h"
117 #include "filemode.h"
119 #include "mbswidth.h"
121 #include "path-concat.h"
123 #include "quotearg.h"
125 #include "strverscmp.h"
128 #include "xreadlink.h"
130 /* Use access control lists only under all the following conditions.
131 Some systems (OSF4, Irix5, Irix6) have the acl function, but not
132 sys/acl.h or don't define the GETACLCNT macro. */
133 #if HAVE_SYS_ACL_H && HAVE_ACL && defined GETACLCNT
137 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
138 : (ls_mode == LS_MULTI_COL \
141 #define AUTHORS N_ ("Richard Stallman and David MacKenzie")
143 #define obstack_chunk_alloc malloc
144 #define obstack_chunk_free free
146 /* Return an int indicating the result of comparing two integers.
147 Subtracting doesn't always work, due to overflow. */
148 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
150 /* The field width for inode numbers. On some hosts inode numbers are
151 64 bits, so columns won't line up exactly when a huge inode number
152 is encountered, but in practice 7 digits is usually enough. */
154 # define INODE_DIGITS 7
158 # define HAVE_SYMLINKS 1
160 # define HAVE_SYMLINKS 0
163 /* If any of the S_* macros are undefined, define them here so each
164 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
166 # define S_ISLNK(Mode) 0
170 # define S_ISFIFO(Mode) 0
174 # define S_ISSOCK(Mode) 0
178 # define S_ISCHR(Mode) 0
182 # define S_ISBLK(Mode) 0
186 # define S_ISDOOR(Mode) 0
189 /* Arrange to make lstat calls go through the wrapper function
190 on systems with an lstat function that does not dereference symlinks
191 that are specified with a trailing slash. */
192 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
193 int rpl_lstat PARAMS((const char *, struct stat *));
195 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
198 #if D_TYPE_IN_DIRENT && defined DTTOIF
199 # define HAVE_STRUCT_DIRENT_D_TYPE 1
200 # define DT_INIT(Val) = Val
202 # define HAVE_STRUCT_DIRENT_D_TYPE 0
203 # define DT_INIT(Val) /* empty */
207 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
209 # define TIMESPEC_NS(timespec) 0
214 unknown DT_INIT (DT_UNKNOWN),
215 fifo DT_INIT (DT_FIFO),
216 chardev DT_INIT (DT_CHR),
217 directory DT_INIT (DT_DIR),
218 blockdev DT_INIT (DT_BLK),
219 normal DT_INIT (DT_REG),
220 symbolic_link DT_INIT (DT_LNK),
221 sock DT_INIT (DT_SOCK),
222 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
223 | DT_REG | DT_LNK | DT_SOCK))
233 /* For symbolic link, name of the file linked to, otherwise zero. */
236 /* For symbolic link and long listing, st_mode of file linked to, otherwise
240 /* For symbolic link and color printing, 1 if linked-to file
241 exists, otherwise 0. */
244 enum filetype filetype;
247 /* For long listings, nonzero if the file has an access control list,
254 # define FILE_HAS_ACL(F) ((F)->have_acl)
256 # define FILE_HAS_ACL(F) 0
259 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
261 /* Null is a valid character in a color indicator (think about Epson
262 printers, for example) so we have to use a length/buffer string
267 int len; /* Number of bytes */
268 const char *string; /* Pointer to the same */
275 size_t nstrftime PARAMS ((char *, size_t, char const *,
276 struct tm const *, int, int));
280 static size_t quote_name PARAMS ((FILE *out, const char *name,
281 struct quoting_options const *options));
282 static char *make_link_path PARAMS ((const char *path, const char *linkname));
283 static int decode_switches PARAMS ((int argc, char **argv));
284 static int file_interesting PARAMS ((const struct dirent *next));
285 static uintmax_t gobble_file PARAMS ((const char *name, enum filetype type,
286 int explicit_arg, const char *dirname));
287 static void print_color_indicator PARAMS ((const char *name, mode_t mode,
289 static void put_indicator PARAMS ((const struct bin_str *ind));
290 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
291 static void add_ignore_pattern PARAMS ((const char *pattern));
292 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
293 static void clear_files PARAMS ((void));
294 static void extract_dirs_from_files PARAMS ((const char *dirname,
295 int ignore_dot_and_dot_dot));
296 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
297 static void indent PARAMS ((int from, int to));
298 static void init_column_info PARAMS ((void));
299 static void print_current_files PARAMS ((void));
300 static void print_dir PARAMS ((const char *name, const char *realname));
301 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
302 static void print_horizontal PARAMS ((void));
303 static void print_long_format PARAMS ((const struct fileinfo *f));
304 static void print_many_per_line PARAMS ((void));
305 static void print_name_with_quoting PARAMS ((const char *p, mode_t mode,
307 struct obstack *stack));
308 static void prep_non_filename_text PARAMS ((void));
309 static void print_type_indicator PARAMS ((mode_t mode));
310 static void print_with_commas PARAMS ((void));
311 static void queue_directory PARAMS ((const char *name, const char *realname));
312 static void sort_files PARAMS ((void));
313 static void parse_ls_color PARAMS ((void));
314 void usage PARAMS ((int status));
316 /* The name the program was run with, stripped of any leading path. */
319 /* Initial size of hash table.
320 Most hierarchies are likely to be shallower than this. */
321 #define INITIAL_TABLE_SIZE 30
323 /* The set of `active' directories, from the current command-line argument
324 to the level in the hierarchy at which files are being listed.
325 A directory is represented by its device and inode numbers.
326 A directory is added to this set when ls begins listing it or its
327 entries, and it is removed from the set just after ls has finished
328 processing it. This set is used solely to detect loops, e.g., with
329 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
330 static Hash_table *active_dir_set;
332 #define LOOP_DETECT (!!active_dir_set)
334 /* An entry in the active_dir_set. */
341 /* The table of files in the current directory:
343 `files' points to a vector of `struct fileinfo', one per file.
344 `nfiles' is the number of elements space has been allocated for.
345 `files_index' is the number actually in use. */
347 /* Address of block containing the files that are described. */
348 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
350 /* Length of block that `files' points to, measured in files. */
351 static int nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
353 /* Index of first unused in `files'. */
354 static int files_index; /* FIXME: rename this to e.g. cwd_n_used */
356 /* When nonzero, in a color listing, color each symlink name according to the
357 type of file it points to. Otherwise, color them according to the `ln'
358 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
359 regardless. This is set when `ln=target' appears in LS_COLORS. */
361 static int color_symlink_as_referent;
363 /* mode of appropriate file for colorization */
364 #define FILE_OR_LINK_MODE(File) \
365 ((color_symlink_as_referent && (File)->linkok) \
366 ? (File)->linkmode : (File)->stat.st_mode)
369 /* Record of one pending directory waiting to be listed. */
374 /* If the directory is actually the file pointed to by a symbolic link we
375 were told to list, `realname' will contain the name of the symbolic
376 link, otherwise zero. */
378 struct pending *next;
381 static struct pending *pending_dirs;
383 /* Current time in seconds and nanoseconds since 1970, updated as
384 needed when deciding whether a file is recent. */
386 static time_t current_time = TYPE_MINIMUM (time_t);
387 static int current_time_ns = -1;
389 /* The number of digits to use for block sizes.
390 4, or more if needed for bigger numbers. */
392 static int block_size_size;
396 /* long_format for lots of info, one per line.
397 one_per_line for just names, one per line.
398 many_per_line for just names, many per line, sorted vertically.
399 horizontal for just names, many per line, sorted horizontally.
400 with_commas for just names, many per line, separated by commas.
402 -l (and other options that imply -l), -1, -C, -x and -m control
407 long_format, /* -l and other options that imply -l */
408 one_per_line, /* -1 */
409 many_per_line, /* -C */
414 static enum format format;
416 /* `full-iso' uses full ISO-style dates and times. `iso' uses shorter
417 ISO-style time stamps. `locale' uses locale-dependent time stamps.
418 `posix-iso' uses traditional POSIX-locale-style dates where
419 POSIX requires it, ISO-style dates otherwise. */
422 full_iso_time_style, /* --time-style=full-iso */
423 iso_time_style, /* --time-style=iso */
424 locale_time_style, /* --time-style=locale */
425 posix_iso_time_style /* --time-style=posix-iso (default) */
428 static char const *const time_style_args[] =
430 "full-iso", "iso", "locale", "posix-iso", 0
433 static enum time_style const time_style_types[] =
435 full_iso_time_style, iso_time_style,
436 locale_time_style, posix_iso_time_style, 0
439 /* Type of time to print or sort by. Controlled by -c and -u. */
443 time_mtime, /* default */
448 static enum time_type time_type;
450 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
455 sort_name, /* default */
456 sort_extension, /* -X */
459 sort_version /* -v */
462 static enum sort_type sort_type;
464 /* Direction of sort.
465 0 means highest first if numeric,
466 lowest first if alphabetic;
467 these are the defaults.
468 1 means the opposite order in each case. -r */
470 static int sort_reverse;
472 /* Nonzero means to display owner information. -g turns this off. */
474 static int print_owner = 1;
476 /* Nonzero means to display group information. -G and -o turn this off. */
478 static int print_group = 1;
480 /* Nonzero means print the user and group id's as numbers rather
483 static int numeric_ids;
485 /* Nonzero means mention the size in blocks of each file. -s */
487 static int print_block_size;
489 /* If positive, the units to use when printing sizes;
490 if negative, the human-readable base. */
491 static int output_block_size;
493 /* Precede each line of long output (per file) with a string like `m,n:'
494 where M is the number of characters after the `:' and before the
495 filename and N is the length of the filename. Using this format,
496 Emacs' dired mode starts up twice as fast, and can handle all
497 strange characters in file names. */
500 /* `none' means don't mention the type of files.
501 `classify' means mention file types and mark executables.
502 `file_type' means mention only file types.
504 Controlled by -F, -p, and --indicator-style. */
508 none, /* --indicator-style=none */
509 classify, /* -F, --indicator-style=classify */
510 file_type /* -p, --indicator-style=file-type */
513 static enum indicator_style indicator_style;
515 /* Names of indicator styles. */
516 static char const *const indicator_style_args[] =
518 "none", "classify", "file-type", 0
521 static enum indicator_style const indicator_style_types[]=
523 none, classify, file_type
526 /* Nonzero means use colors to mark types. Also define the different
527 colors as well as the stuff for the LS_COLORS environment variable.
528 The LS_COLORS variable is now in a termcap-like format. */
530 static int print_with_color;
534 color_never, /* 0: default or --color=never */
535 color_always, /* 1: --color=always */
536 color_if_tty /* 2: --color=tty */
539 enum Dereference_symlink
543 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
544 DEREF_ALWAYS /* -L */
549 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
550 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
553 static const char *const indicator_name[]=
555 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
556 "bd", "cd", "mi", "or", "ex", "do", NULL
559 struct color_ext_type
561 struct bin_str ext; /* The extension we're looking for */
562 struct bin_str seq; /* The sequence to output when we do */
563 struct color_ext_type *next; /* Next in list */
566 static struct bin_str color_indicator[] =
568 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
569 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
570 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
571 { LEN_STR_PAIR ("0") }, /* no: Normal */
572 { LEN_STR_PAIR ("0") }, /* fi: File: default */
573 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
574 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
575 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
576 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
577 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
578 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
579 { 0, NULL }, /* mi: Missing file: undefined */
580 { 0, NULL }, /* or: Orphanned symlink: undefined */
581 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
582 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
586 static struct color_ext_type *color_ext_list = NULL;
588 /* Buffer for color sequences */
589 static char *color_buf;
591 /* Nonzero means to check for orphaned symbolic link, for displaying
594 static int check_symlink_color;
596 /* Nonzero means mention the inode number of each file. -i */
598 static int print_inode;
600 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
601 other options that imply -l), and -L. */
603 static enum Dereference_symlink dereference;
605 /* Nonzero means when a directory is found, display info on its
608 static int recursive;
610 /* Nonzero means when an argument is a directory name, display info
613 static int immediate_dirs;
615 /* Nonzero means don't omit files whose names start with `.'. -A */
617 static int all_files;
619 /* Nonzero means don't omit files `.' and `..'
620 This flag implies `all_files'. -a */
622 static int really_all_files;
624 /* A linked list of shell-style globbing patterns. If a non-argument
625 file name matches any of these patterns, it is omitted.
626 Controlled by -I. Multiple -I options accumulate.
627 The -B option adds `*~' and `.*~' to this list. */
629 struct ignore_pattern
632 struct ignore_pattern *next;
635 static struct ignore_pattern *ignore_patterns;
637 /* Nonzero means output nongraphic chars in file names as `?'.
638 (-q, --hide-control-chars)
639 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
640 independent. The algorithm is: first, obey the quoting style to get a
641 string representing the file name; then, if qmark_funny_chars is set,
642 replace all nonprintable chars in that string with `?'. It's necessary
643 to replace nonprintable chars even in quoted strings, because we don't
644 want to mess up the terminal if control chars get sent to it, and some
645 quoting methods pass through control chars as-is. */
646 static int qmark_funny_chars;
648 /* Quoting options for file and dir name output. */
650 static struct quoting_options *filename_quoting_options;
651 static struct quoting_options *dirname_quoting_options;
653 /* The number of chars per hardware tab stop. Setting this to zero
654 inhibits the use of TAB characters for separating columns. -T */
657 /* Nonzero means we are listing the working directory because no
658 non-option arguments were given. */
660 static int dir_defaulted;
662 /* Nonzero means print each directory name before listing it. */
664 static int print_dir_name;
666 /* The line length to use for breaking lines in many-per-line format.
667 Can be set with -w. */
669 static int line_length;
671 /* If nonzero, the file listing format requires that stat be called on
674 static int format_needs_stat;
676 /* Similar to `format_needs_stat', but set if only the file type is
679 static int format_needs_type;
681 /* strftime formats for non-recent and recent files, respectively, in
684 static char const *long_time_format[2] =
686 /* strftime format for non-recent files (older than 6 months), in
687 -l output when --time-style=locale is specified. This should
688 contain the year, month and day (at least), in an order that is
689 understood by people in your locale's territory.
690 Please try to keep the number of used screen columns small,
691 because many people work in windows with only 80 columns. But
692 make this as wide as the other string below, for recent files. */
694 /* strftime format for recent files (younger than 6 months), in
695 -l output when --time-style=locale is specified. This should
696 contain the month, day and time (at least), in an order that is
697 understood by people in your locale's territory.
698 Please try to keep the number of used screen columns small,
699 because many people work in windows with only 80 columns. But
700 make this as wide as the other string above, for non-recent files. */
704 /* The exit status to use if we don't get any fatal errors. */
706 static int exit_status;
708 /* For long options that have no equivalent short option, use a
709 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
712 BLOCK_SIZE_OPTION = CHAR_MAX + 1,
716 INDICATOR_STYLE_OPTION,
717 QUOTING_STYLE_OPTION,
718 SHOW_CONTROL_CHARS_OPTION,
725 static struct option const long_options[] =
727 {"all", no_argument, 0, 'a'},
728 {"escape", no_argument, 0, 'b'},
729 {"directory", no_argument, 0, 'd'},
730 {"dired", no_argument, 0, 'D'},
731 {"full-time", no_argument, 0, FULL_TIME_OPTION},
732 {"human-readable", no_argument, 0, 'h'},
733 {"inode", no_argument, 0, 'i'},
734 {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
735 {"numeric-uid-gid", no_argument, 0, 'n'},
736 {"no-group", no_argument, 0, 'G'},
737 {"hide-control-chars", no_argument, 0, 'q'},
738 {"reverse", no_argument, 0, 'r'},
739 {"size", no_argument, 0, 's'},
740 {"width", required_argument, 0, 'w'},
741 {"almost-all", no_argument, 0, 'A'},
742 {"ignore-backups", no_argument, 0, 'B'},
743 {"classify", no_argument, 0, 'F'},
744 {"file-type", no_argument, 0, 'p'},
745 {"si", no_argument, 0, SI_OPTION},
746 {"dereference-command-line", no_argument, 0, 'H'},
747 {"ignore", required_argument, 0, 'I'},
748 {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
749 {"dereference", no_argument, 0, 'L'},
750 {"literal", no_argument, 0, 'N'},
751 {"quote-name", no_argument, 0, 'Q'},
752 {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
753 {"recursive", no_argument, 0, 'R'},
754 {"format", required_argument, 0, FORMAT_OPTION},
755 {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
756 {"sort", required_argument, 0, SORT_OPTION},
757 {"tabsize", required_argument, 0, 'T'},
758 {"time", required_argument, 0, TIME_OPTION},
759 {"time-style", required_argument, 0, TIME_STYLE_OPTION},
760 {"color", optional_argument, 0, COLOR_OPTION},
761 {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
762 {GETOPT_HELP_OPTION_DECL},
763 {GETOPT_VERSION_OPTION_DECL},
767 static char const *const format_args[] =
769 "verbose", "long", "commas", "horizontal", "across",
770 "vertical", "single-column", 0
773 static enum format const format_types[] =
775 long_format, long_format, with_commas, horizontal, horizontal,
776 many_per_line, one_per_line
779 static char const *const sort_args[] =
781 "none", "time", "size", "extension", "version", 0
784 static enum sort_type const sort_types[] =
786 sort_none, sort_time, sort_size, sort_extension, sort_version
789 static char const *const time_args[] =
791 "atime", "access", "use", "ctime", "status", 0
794 static enum time_type const time_types[] =
796 time_atime, time_atime, time_atime, time_ctime, time_ctime
799 static char const *const color_args[] =
801 /* force and none are for compatibility with another color-ls version */
802 "always", "yes", "force",
803 "never", "no", "none",
804 "auto", "tty", "if-tty", 0
807 static enum color_type const color_types[] =
809 color_always, color_always, color_always,
810 color_never, color_never, color_never,
811 color_if_tty, color_if_tty, color_if_tty
814 /* Information about filling a column. */
822 /* Array with information about column filledness. */
823 static struct column_info *column_info;
825 /* Maximum number of columns ever possible for this display. */
828 /* The minimum width of a colum is 3: 1 character for the name and 2
829 for the separating white space. */
830 #define MIN_COLUMN_WIDTH 3
833 /* This zero-based index is used solely with the --dired option.
834 When that option is in effect, this counter is incremented for each
835 character of output generated by this program so that the beginning
836 and ending indices (in that output) of every file name can be recorded
837 and later output themselves. */
838 static size_t dired_pos;
840 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
842 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
843 #define DIRED_FPUTS(s, stream, s_len) \
844 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
846 /* Like DIRED_FPUTS, but for use when S is a literal string. */
847 #define DIRED_FPUTS_LITERAL(s, stream) \
848 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
850 #define DIRED_INDENT() \
853 /* FIXME: remove the `&& format == long_format' clause. */ \
854 if (dired && format == long_format) \
855 DIRED_FPUTS_LITERAL (" ", stdout); \
859 /* With --dired, store pairs of beginning and ending indices of filenames. */
860 static struct obstack dired_obstack;
862 /* With --dired, store pairs of beginning and ending indices of any
863 directory names that appear as headers (just before `total' line)
864 for lists of directory entries. Such directory names are seen when
865 listing hierarchies using -R and when a directory is listed with at
866 least one other command line argument. */
867 static struct obstack subdired_obstack;
869 /* Save the current index on the specified obstack, OBS. */
870 #define PUSH_CURRENT_DIRED_POS(obs) \
873 /* FIXME: remove the `&& format == long_format' clause. */ \
874 if (dired && format == long_format) \
875 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
879 /* With -R, this stack is used to help detect directory cycles.
880 The device/inode pairs on this stack mirror the pairs in the
881 active_dir_set hash table. */
882 static struct obstack dev_ino_obstack;
884 /* Push a pair onto the device/inode stack. */
885 #define DEV_INO_PUSH(Dev, Ino) \
888 struct dev_ino *di; \
889 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
890 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
891 di->st_dev = (Dev); \
892 di->st_ino = (Ino); \
896 /* Pop a dev/ino struct off the global dev_ino_obstack
897 and return that struct. */
898 static struct dev_ino
901 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
902 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
903 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
906 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
911 assert (0 <= stat (Name, &sb)); \
912 assert (sb.st_dev == Di.st_dev); \
913 assert (sb.st_ino == Di.st_ino); \
918 /* Write to standard output PREFIX, followed by the quoting style and
919 a space-separated list of the integers stored in OS all on one line. */
922 dired_dump_obstack (const char *prefix, struct obstack *os)
926 n_pos = obstack_object_size (os) / sizeof (dired_pos);
932 pos = (size_t *) obstack_finish (os);
933 fputs (prefix, stdout);
934 for (i = 0; i < n_pos; i++)
935 printf (" %lu", (unsigned long) pos[i]);
936 fputs ("\n", stdout);
941 dev_ino_hash (void const *x, unsigned int table_size)
943 struct dev_ino const *p = x;
944 return (uintmax_t) p->st_ino % table_size;
948 dev_ino_compare (void const *x, void const *y)
950 struct dev_ino const *a = x;
951 struct dev_ino const *b = y;
952 return SAME_INODE (*a, *b) ? true : false;
956 dev_ino_free (void *x)
961 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
962 active directories. Return nonzero if there is already a matching
963 entry in the table. Otherwise, return zero. */
966 visit_dir (dev_t dev, ino_t ino)
969 struct dev_ino *ent_from_table;
972 ent = XMALLOC (struct dev_ino, 1);
976 /* Attempt to insert this entry into the table. */
977 ent_from_table = hash_insert (active_dir_set, ent);
979 if (ent_from_table == NULL)
981 /* Insertion failed due to lack of memory. */
985 found_match = (ent_from_table != ent);
989 /* ent was not inserted, so free it. */
997 free_pending_ent (struct pending *p)
1007 main (int argc, char **argv)
1010 register struct pending *thispend;
1011 unsigned int n_files;
1013 program_name = argv[0];
1014 setlocale (LC_ALL, "");
1015 bindtextdomain (PACKAGE, LOCALEDIR);
1016 textdomain (PACKAGE);
1018 atexit (close_stdout);
1020 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1021 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1028 i = decode_switches (argc, argv);
1030 if (print_with_color)
1033 /* Test print_with_color again, because the call to parse_ls_color
1034 may have just reset it -- e.g., if LS_COLORS is invalid. */
1035 if (print_with_color)
1037 prep_non_filename_text ();
1038 /* Avoid following symbolic links when possible. */
1039 if (color_indicator[C_ORPHAN].string != NULL
1040 || (color_indicator[C_MISSING].string != NULL
1041 && format == long_format))
1042 check_symlink_color = 1;
1045 if (dereference == DEREF_UNDEFINED)
1046 dereference = ((immediate_dirs
1047 || indicator_style == classify
1048 || format == long_format)
1050 : DEREF_COMMAND_LINE_ARGUMENTS);
1052 /* When using -R, initialize a data structure we'll use to
1053 detect any directory cycles. */
1056 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1060 if (active_dir_set == NULL)
1063 obstack_init (&dev_ino_obstack);
1066 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1067 || format == long_format
1068 || dereference == DEREF_ALWAYS
1069 || recursive || print_block_size || print_inode;
1070 format_needs_type = (format_needs_stat == 0
1071 && (print_with_color || indicator_style != none));
1073 if (dired && format == long_format)
1075 obstack_init (&dired_obstack);
1076 obstack_init (&subdired_obstack);
1080 files = XMALLOC (struct fileinfo, nfiles);
1089 for (; i < argc; i++)
1091 gobble_file (argv[i], unknown, 1, "");
1097 gobble_file (".", directory, 1, "");
1099 queue_directory (".", 0);
1105 if (!immediate_dirs)
1106 extract_dirs_from_files ("", 0);
1107 /* `files_index' might be zero now. */
1110 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1111 (and not pending_dirs->name) because there may be no markers in the queue
1112 at this point. A marker may be enqueued when extract_dirs_from_files is
1113 called with a non-empty string or via print_dir. */
1116 print_current_files ();
1118 DIRED_PUTCHAR ('\n');
1120 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1123 while (pending_dirs)
1125 thispend = pending_dirs;
1126 pending_dirs = pending_dirs->next;
1130 if (thispend->name == NULL)
1132 /* thispend->name == NULL means this is a marker entry
1133 indicating we've finished processing the directory.
1134 Use its dev/ino numbers to remove the corresponding
1135 entry from the active_dir_set hash table. */
1136 struct dev_ino di = dev_ino_pop ();
1137 struct dev_ino *found = hash_delete (active_dir_set, &di);
1138 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1140 dev_ino_free (found);
1141 free_pending_ent (thispend);
1146 print_dir (thispend->name, thispend->realname);
1148 free_pending_ent (thispend);
1152 if (dired && format == long_format)
1154 /* No need to free these since we're about to exit. */
1155 dired_dump_obstack ("//DIRED//", &dired_obstack);
1156 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1157 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1158 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1161 /* Restore default color before exiting */
1162 if (print_with_color)
1164 put_indicator (&color_indicator[C_LEFT]);
1165 put_indicator (&color_indicator[C_RIGHT]);
1170 assert (hash_get_n_entries (active_dir_set) == 0);
1171 hash_free (active_dir_set);
1177 /* Set all the option flags according to the switches specified.
1178 Return the index of the first non-option argument. */
1181 decode_switches (int argc, char **argv)
1184 char const *time_style_option = 0;
1186 /* Record whether there is an option specifying sort type. */
1187 int sort_type_specified = 0;
1189 qmark_funny_chars = 0;
1191 /* initialize all switches to default settings */
1196 /* This is for the `dir' program. */
1197 format = many_per_line;
1198 set_quoting_style (NULL, escape_quoting_style);
1201 case LS_LONG_FORMAT:
1202 /* This is for the `vdir' program. */
1203 format = long_format;
1204 set_quoting_style (NULL, escape_quoting_style);
1208 /* This is for the `ls' program. */
1209 if (isatty (STDOUT_FILENO))
1211 format = many_per_line;
1212 /* See description of qmark_funny_chars, above. */
1213 qmark_funny_chars = 1;
1217 format = one_per_line;
1218 qmark_funny_chars = 0;
1226 time_type = time_mtime;
1227 sort_type = sort_name;
1230 print_block_size = 0;
1231 indicator_style = none;
1233 dereference = DEREF_UNDEFINED;
1237 really_all_files = 0;
1238 ignore_patterns = 0;
1240 /* FIXME: put this in a function. */
1242 char const *q_style = getenv ("QUOTING_STYLE");
1245 int i = ARGCASEMATCH (q_style, quoting_style_args, quoting_style_vals);
1247 set_quoting_style (NULL, quoting_style_vals[i]);
1250 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1251 quotearg (q_style));
1255 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
1259 char const *p = getenv ("COLUMNS");
1263 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1264 && 0 < tmp_long && tmp_long <= INT_MAX)
1266 line_length = (int) tmp_long;
1271 _("ignoring invalid width in environment variable COLUMNS: %s"),
1281 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
1282 line_length = ws.ws_col;
1286 /* Using the TABSIZE environment variable is not POSIX-approved.
1287 Ignore it when POSIXLY_CORRECT is set. */
1291 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1294 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1295 && 0 <= tmp_long && tmp_long <= INT_MAX)
1297 tabsize = (int) tmp_long;
1302 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1308 while ((c = getopt_long (argc, argv,
1309 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1310 long_options, NULL)) != -1)
1319 really_all_files = 1;
1323 set_quoting_style (NULL, escape_quoting_style);
1327 time_type = time_ctime;
1335 /* Same as enabling -a -U and disabling -l -s. */
1337 really_all_files = 1;
1338 sort_type = sort_none;
1339 sort_type_specified = 1;
1341 if (format == long_format)
1342 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1343 print_block_size = 0; /* disable -s */
1344 print_with_color = 0; /* disable --color */
1348 format = long_format;
1353 output_block_size = -1024;
1361 output_block_size = 1024;
1365 format = long_format;
1369 format = with_commas;
1374 format = long_format;
1377 case 'o': /* Just like -l, but don't display group info. */
1378 format = long_format;
1383 indicator_style = file_type;
1387 qmark_funny_chars = 1;
1395 print_block_size = 1;
1399 sort_type = sort_time;
1400 sort_type_specified = 1;
1404 time_type = time_atime;
1408 sort_type = sort_version;
1409 sort_type_specified = 1;
1415 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1416 || tmp_long <= 0 || tmp_long > INT_MAX)
1417 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1419 line_length = (int) tmp_long;
1424 format = horizontal;
1428 really_all_files = 0;
1433 add_ignore_pattern ("*~");
1434 add_ignore_pattern (".*~");
1438 format = many_per_line;
1446 indicator_style = classify;
1449 case 'G': /* inhibit display of group info */
1454 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1458 add_ignore_pattern (optarg);
1462 dereference = DEREF_ALWAYS;
1466 set_quoting_style (NULL, literal_quoting_style);
1470 set_quoting_style (NULL, c_quoting_style);
1478 sort_type = sort_size;
1479 sort_type_specified = 1;
1485 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1486 || tmp_long < 0 || tmp_long > INT_MAX)
1487 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1489 tabsize = (int) tmp_long;
1494 sort_type = sort_none;
1495 sort_type_specified = 1;
1499 sort_type = sort_extension;
1500 sort_type_specified = 1;
1504 /* -1 has no effect after -l. */
1505 if (format != long_format)
1506 format = one_per_line;
1510 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1511 sort_type_specified = 1;
1515 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1519 format = XARGMATCH ("--format", optarg, format_args, format_types);
1522 case FULL_TIME_OPTION:
1523 format = long_format;
1524 time_style_option = "full-iso";
1531 i = XARGMATCH ("--color", optarg, color_args, color_types);
1533 /* Using --color with no argument is equivalent to using
1537 print_with_color = (i == color_always
1538 || (i == color_if_tty
1539 && isatty (STDOUT_FILENO)));
1541 if (print_with_color)
1543 /* Don't use TAB characters in output. Some terminal
1544 emulators can't handle the combination of tabs and
1545 color codes on the same line. */
1551 case INDICATOR_STYLE_OPTION:
1552 indicator_style = XARGMATCH ("--indicator-style", optarg,
1553 indicator_style_args,
1554 indicator_style_types);
1557 case QUOTING_STYLE_OPTION:
1558 set_quoting_style (NULL,
1559 XARGMATCH ("--quoting-style", optarg,
1561 quoting_style_vals));
1564 case TIME_STYLE_OPTION:
1565 time_style_option = optarg;
1568 case SHOW_CONTROL_CHARS_OPTION:
1569 qmark_funny_chars = 0;
1572 case BLOCK_SIZE_OPTION:
1573 human_block_size (optarg, 1, &output_block_size);
1577 output_block_size = -1000;
1580 case_GETOPT_HELP_CHAR;
1582 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1585 usage (EXIT_FAILURE);
1589 filename_quoting_options = clone_quoting_options (NULL);
1590 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1591 set_char_quoting (filename_quoting_options, ' ', 1);
1592 if (indicator_style != none)
1595 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1596 set_char_quoting (filename_quoting_options, *p, 1);
1599 dirname_quoting_options = clone_quoting_options (NULL);
1600 set_char_quoting (dirname_quoting_options, ':', 1);
1602 /* If -c or -u is specified and not -l (or any other option that implies -l),
1603 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1604 The behavior of ls when using either -c or -u but with neither -l nor -t
1605 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1606 sort by atime (this is the one that's not specified by the POSIX spec),
1607 -lu means show atime and sort by name, -lut means show atime and sort
1610 if ((time_type == time_ctime || time_type == time_atime)
1611 && !sort_type_specified && format != long_format)
1613 sort_type = sort_time;
1616 if (format == long_format)
1618 if (! time_style_option)
1619 time_style_option = getenv ("TIME_STYLE");
1621 switch (time_style_option
1622 ? XARGMATCH ("time style", time_style_option,
1625 : posix_iso_time_style)
1627 case full_iso_time_style:
1628 long_time_format[0] = long_time_format[1] =
1629 "%Y-%m-%d %H:%M:%S.%N %z";
1632 case posix_iso_time_style:
1633 if (! hard_locale (LC_TIME))
1636 case iso_time_style:
1637 long_time_format[0] = "%Y-%m-%d ";
1638 long_time_format[1] = "%m-%d %H:%M";
1641 case locale_time_style:
1642 if (hard_locale (LC_TIME))
1645 for (i = 0; i < 2; i++)
1646 long_time_format[i] =
1647 dcgettext (NULL, long_time_format[i], LC_TIME);
1655 /* Parse a string as part of the LS_COLORS variable; this may involve
1656 decoding all kinds of escape characters. If equals_end is set an
1657 unescaped equal sign ends the string, otherwise only a : or \0
1658 does. Returns the number of characters output, or -1 on failure.
1660 The resulting string is *not* null-terminated, but may contain
1663 Note that both dest and src are char **; on return they point to
1664 the first free byte after the array and the character that ended
1665 the input string, respectively. */
1668 get_funky_string (char **dest, const char **src, int equals_end)
1670 int num; /* For numerical codes */
1671 int count; /* Something to count with */
1673 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1678 p = *src; /* We don't want to double-indirect */
1679 q = *dest; /* the whole darn time. */
1681 count = 0; /* No characters counted in yet. */
1684 state = ST_GND; /* Start in ground state. */
1685 while (state < ST_END)
1689 case ST_GND: /* Ground state (no escapes) */
1694 state = ST_END; /* End of string */
1697 state = ST_BACKSLASH; /* Backslash scape sequence */
1701 state = ST_CARET; /* Caret escape */
1707 state = ST_END; /* End */
1710 /* else fall through */
1718 case ST_BACKSLASH: /* Backslash escaped character */
1729 state = ST_OCTAL; /* Octal sequence */
1734 state = ST_HEX; /* Hex sequence */
1737 case 'a': /* Bell */
1738 num = 7; /* Not all C compilers know what \a means */
1740 case 'b': /* Backspace */
1743 case 'e': /* Escape */
1746 case 'f': /* Form feed */
1749 case 'n': /* Newline */
1752 case 'r': /* Carriage return */
1758 case 'v': /* Vtab */
1761 case '?': /* Delete */
1764 case '_': /* Space */
1767 case '\0': /* End of string */
1768 state = ST_ERROR; /* Error! */
1770 default: /* Escaped character like \ ^ : = */
1774 if (state == ST_BACKSLASH)
1783 case ST_OCTAL: /* Octal sequence */
1784 if (*p < '0' || *p > '7')
1791 num = (num << 3) + (*(p++) - '0');
1794 case ST_HEX: /* Hex sequence */
1807 num = (num << 4) + (*(p++) - '0');
1815 num = (num << 4) + (*(p++) - 'a') + 10;
1823 num = (num << 4) + (*(p++) - 'A') + 10;
1833 case ST_CARET: /* Caret escape */
1834 state = ST_GND; /* Should be the next state... */
1835 if (*p >= '@' && *p <= '~')
1837 *(q++) = *(p++) & 037;
1857 return state == ST_ERROR ? -1 : count;
1861 parse_ls_color (void)
1863 const char *p; /* Pointer to character being parsed */
1864 char *buf; /* color_buf buffer pointer */
1865 int state; /* State of parser */
1866 int ind_no; /* Indicator number */
1867 char label[3]; /* Indicator label */
1868 struct color_ext_type *ext; /* Extension we are working on */
1870 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1874 strcpy (label, "??");
1876 /* This is an overly conservative estimate, but any possible
1877 LS_COLORS string will *not* generate a color_buf longer than
1878 itself, so it is a safe way of allocating a buffer in
1880 buf = color_buf = xstrdup (p);
1887 case 1: /* First label character */
1895 /* Allocate new extension block and add to head of
1896 linked list (this way a later definition will
1897 override an earlier one, which can be useful for
1898 having terminal-specific defs override global). */
1900 ext = XMALLOC (struct color_ext_type, 1);
1901 ext->next = color_ext_list;
1902 color_ext_list = ext;
1905 ext->ext.string = buf;
1907 state = (ext->ext.len =
1908 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1912 state = 0; /* Done! */
1915 default: /* Assume it is file type label */
1922 case 2: /* Second label character */
1929 state = -1; /* Error */
1932 case 3: /* Equal sign after indicator label */
1933 state = -1; /* Assume failure... */
1934 if (*(p++) == '=')/* It *should* be... */
1936 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1938 if (STREQ (label, indicator_name[ind_no]))
1940 color_indicator[ind_no].string = buf;
1941 state = ((color_indicator[ind_no].len =
1942 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1947 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1951 case 4: /* Equal sign after *.ext */
1954 ext->seq.string = buf;
1955 state = (ext->seq.len =
1956 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1966 struct color_ext_type *e;
1967 struct color_ext_type *e2;
1970 _("unparsable value for LS_COLORS environment variable"));
1972 for (e = color_ext_list; e != NULL; /* empty */)
1978 print_with_color = 0;
1981 if (color_indicator[C_LINK].len == 6
1982 && !strncmp (color_indicator[C_LINK].string, "target", 6))
1983 color_symlink_as_referent = 1;
1986 /* Request that the directory named NAME have its contents listed later.
1987 If REALNAME is nonzero, it will be used instead of NAME when the
1988 directory name is printed. This allows symbolic links to directories
1989 to be treated as regular directories but still be listed under their
1990 real names. NAME == NULL is used to insert a marker entry for the
1991 directory named in REALNAME.
1992 If F is non-NULL, we use its dev/ino information to save
1993 a call to stat -- when doing a recursive (-R) traversal. */
1996 queue_directory (const char *name, const char *realname)
1998 struct pending *new;
2000 new = XMALLOC (struct pending, 1);
2001 new->realname = realname ? xstrdup (realname) : NULL;
2002 new->name = name ? xstrdup (name) : NULL;
2003 new->next = pending_dirs;
2007 /* Read directory `name', and list the files in it.
2008 If `realname' is nonzero, print its name instead of `name';
2009 this is used for symbolic links to directories. */
2012 print_dir (const char *name, const char *realname)
2014 register DIR *reading;
2015 register struct dirent *next;
2016 register uintmax_t total_blocks = 0;
2017 static int first = 1;
2020 reading = opendir (name);
2023 error (0, errno, "%s", quotearg_colon (name));
2030 struct stat dir_stat;
2031 int fd = dirfd (reading);
2033 /* If dirfd failed, endure the overhead of using stat. */
2035 ? fstat (fd, &dir_stat)
2036 : stat (name, &dir_stat)) < 0)
2038 error (0, errno, _("cannot determine device and inode of %s"),
2039 quotearg_colon (name));
2044 /* If we've already visited this dev/inode pair, warn that
2045 we've found a loop, and do not process this directory. */
2046 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2048 error (0, 0, _("not listing already-listed directory: %s"),
2049 quotearg_colon (name));
2053 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2056 /* Read the directory entries, and insert the subfiles into the `files'
2061 while ((next = readdir (reading)) != NULL)
2062 if (file_interesting (next))
2064 enum filetype type = unknown;
2066 #if HAVE_STRUCT_DIRENT_D_TYPE
2067 if (next->d_type == DT_DIR || next->d_type == DT_CHR
2068 || next->d_type == DT_BLK || next->d_type == DT_SOCK
2069 || next->d_type == DT_FIFO)
2070 type = next->d_type;
2072 total_blocks += gobble_file (next->d_name, type, 0, name);
2075 if (CLOSEDIR (reading))
2077 error (0, errno, "%s", quotearg_colon (name));
2079 /* Don't return; print whatever we got. */
2082 /* Sort the directory contents. */
2085 /* If any member files are subdirectories, perhaps they should have their
2086 contents listed rather than being mentioned here as files. */
2089 extract_dirs_from_files (name, 1);
2091 if (recursive || print_dir_name)
2094 DIRED_PUTCHAR ('\n');
2097 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2098 dired_pos += quote_name (stdout, realname ? realname : name,
2099 dirname_quoting_options);
2100 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2101 DIRED_FPUTS_LITERAL (":\n", stdout);
2104 if (format == long_format || print_block_size)
2107 char buf[LONGEST_HUMAN_READABLE + 1];
2111 DIRED_FPUTS (p, stdout, strlen (p));
2112 DIRED_PUTCHAR (' ');
2113 p = human_readable_inexact (total_blocks, buf, ST_NBLOCKSIZE,
2114 output_block_size, human_ceiling);
2115 DIRED_FPUTS (p, stdout, strlen (p));
2116 DIRED_PUTCHAR ('\n');
2120 print_current_files ();
2123 /* Add `pattern' to the list of patterns for which files that match are
2127 add_ignore_pattern (const char *pattern)
2129 register struct ignore_pattern *ignore;
2131 ignore = XMALLOC (struct ignore_pattern, 1);
2132 ignore->pattern = pattern;
2133 /* Add it to the head of the linked list. */
2134 ignore->next = ignore_patterns;
2135 ignore_patterns = ignore;
2138 /* Return nonzero if the file in `next' should be listed. */
2141 file_interesting (const struct dirent *next)
2143 register struct ignore_pattern *ignore;
2145 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2146 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2149 if (really_all_files
2150 || next->d_name[0] != '.'
2152 && next->d_name[1] != '\0'
2153 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2159 /* Enter and remove entries in the table `files'. */
2161 /* Empty the table of files. */
2168 for (i = 0; i < files_index; i++)
2170 free (files[i].name);
2171 if (files[i].linkname)
2172 free (files[i].linkname);
2176 block_size_size = 4;
2179 /* Add a file to the current table of files.
2180 Verify that the file exists, and print an error message if it does not.
2181 Return the number of blocks that the file occupies. */
2184 gobble_file (const char *name, enum filetype type, int explicit_arg,
2185 const char *dirname)
2187 register uintmax_t blocks;
2188 register char *path;
2190 if (files_index == nfiles)
2193 files = XREALLOC (files, struct fileinfo, nfiles);
2196 files[files_index].linkname = 0;
2197 files[files_index].linkmode = 0;
2198 files[files_index].linkok = 0;
2200 /* FIXME: this use of ls: `mkdir a; touch a/{b,c,d}; ls -R a'
2201 shouldn't require that ls stat b, c, and d -- at least
2202 not on systems with usable d_type. The problem is that
2203 format_needs_stat is set, because of the -R. */
2204 if (explicit_arg || format_needs_stat
2205 || (format_needs_type && type == unknown))
2207 /* `path' is the absolute pathname of this file. */
2210 if (name[0] == '/' || dirname[0] == 0)
2211 path = (char *) name;
2214 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
2215 attach (path, dirname, name);
2218 val = (DEREF_ALWAYS <= dereference + explicit_arg
2219 ? stat (path, &files[files_index].stat)
2220 : lstat (path, &files[files_index].stat));
2224 error (0, errno, "%s", quotearg_colon (path));
2230 if (format == long_format)
2231 files[files_index].have_acl =
2232 (! S_ISLNK (files[files_index].stat.st_mode)
2233 && 4 < acl (path, GETACLCNT, 0, NULL));
2236 if (S_ISLNK (files[files_index].stat.st_mode)
2237 && (format == long_format || check_symlink_color))
2240 struct stat linkstats;
2242 get_link_name (path, &files[files_index]);
2243 linkpath = make_link_path (path, files[files_index].linkname);
2245 /* Avoid following symbolic links when possible, ie, when
2246 they won't be traced and when no indicator is needed. */
2248 && (indicator_style != none || check_symlink_color)
2249 && stat (linkpath, &linkstats) == 0)
2251 files[files_index].linkok = 1;
2253 /* Symbolic links to directories that are mentioned on the
2254 command line are automatically traced if not being
2256 if (explicit_arg && format != long_format
2257 && S_ISDIR (linkstats.st_mode))
2259 /* Substitute the linked-to directory's name, but
2260 save the real name in `linkname' for printing. */
2261 if (!immediate_dirs)
2263 const char *tempname = name;
2265 linkpath = files[files_index].linkname;
2266 files[files_index].linkname = (char *) tempname;
2268 files[files_index].stat = linkstats;
2272 /* Get the linked-to file's mode for the filetype indicator
2273 in long listings. */
2274 files[files_index].linkmode = linkstats.st_mode;
2275 files[files_index].linkok = 1;
2282 if (S_ISLNK (files[files_index].stat.st_mode))
2283 files[files_index].filetype = symbolic_link;
2284 else if (S_ISDIR (files[files_index].stat.st_mode))
2286 if (explicit_arg && !immediate_dirs)
2287 files[files_index].filetype = arg_directory;
2289 files[files_index].filetype = directory;
2292 files[files_index].filetype = normal;
2294 blocks = ST_NBLOCKS (files[files_index].stat);
2296 char buf[LONGEST_HUMAN_READABLE + 1];
2297 int len = strlen (human_readable_inexact (blocks, buf, ST_NBLOCKSIZE,
2300 if (block_size_size < len)
2301 block_size_size = len < 7 ? len : 7;
2306 files[files_index].filetype = type;
2307 #if HAVE_STRUCT_DIRENT_D_TYPE
2308 files[files_index].stat.st_mode = DTTOIF (type);
2313 files[files_index].name = xstrdup (name);
2321 /* Put the name of the file that `filename' is a symbolic link to
2322 into the `linkname' field of `f'. */
2325 get_link_name (const char *filename, struct fileinfo *f)
2327 f->linkname = xreadlink (filename);
2328 if (f->linkname == NULL)
2330 error (0, errno, _("cannot read symbolic link %s"),
2331 quotearg_colon (filename));
2336 /* If `linkname' is a relative path and `path' contains one or more
2337 leading directories, return `linkname' with those directories
2338 prepended; otherwise, return a copy of `linkname'.
2339 If `linkname' is zero, return zero. */
2342 make_link_path (const char *path, const char *linkname)
2350 if (*linkname == '/')
2351 return xstrdup (linkname);
2353 /* The link is to a relative path. Prepend any leading path
2354 in `path' to the link name. */
2355 linkbuf = strrchr (path, '/');
2357 return xstrdup (linkname);
2359 bufsiz = linkbuf - path + 1;
2360 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2361 strncpy (linkbuf, path, bufsiz);
2362 strcpy (linkbuf + bufsiz, linkname);
2367 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2368 This is so we don't try to recurse on `././././. ...' */
2371 basename_is_dot_or_dotdot (const char *name)
2373 char const *base = base_name (name);
2374 return DOT_OR_DOTDOT (base);
2377 /* Remove any entries from `files' that are for directories,
2378 and queue them to be listed as directories instead.
2379 `dirname' is the prefix to prepend to each dirname
2380 to make it correct relative to ls's working dir.
2381 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2382 This is desirable when processing directories recursively. */
2385 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2389 if (*dirname && LOOP_DETECT)
2391 /* Insert a marker entry first. When we dequeue this marker entry,
2392 we'll know that DIRNAME has been processed and may be removed
2393 from the set of active directories. */
2394 queue_directory (NULL, dirname);
2397 /* Queue the directories last one first, because queueing reverses the
2399 for (i = files_index - 1; i >= 0; i--)
2400 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2401 && (!ignore_dot_and_dot_dot
2402 || !basename_is_dot_or_dotdot (files[i].name)))
2404 if (files[i].name[0] == '/' || dirname[0] == 0)
2406 queue_directory (files[i].name, files[i].linkname);
2410 char *path = path_concat (dirname, files[i].name, NULL);
2411 queue_directory (path, files[i].linkname);
2414 if (files[i].filetype == arg_directory)
2415 free (files[i].name);
2418 /* Now delete the directories from the table, compacting all the remaining
2421 for (i = 0, j = 0; i < files_index; i++)
2422 if (files[i].filetype != arg_directory)
2423 files[j++] = files[i];
2427 /* Use strcoll to compare strings in this locale. If an error occurs,
2428 report an error and longjmp to failed_strcoll. */
2430 static jmp_buf failed_strcoll;
2433 xstrcoll (char const *a, char const *b)
2437 diff = strcoll (a, b);
2440 error (0, errno, _("cannot compare file names %s and %s"),
2441 quote_n (0, a), quote_n (1, b));
2443 longjmp (failed_strcoll, 1);
2448 /* Comparison routines for sorting the files. */
2450 typedef void const *V;
2453 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2454 int (*cmp) PARAMS ((char const *, char const *)))
2456 int diff = CTIME_CMP (b->stat, a->stat);
2457 return diff ? diff : cmp (a->name, b->name);
2459 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2460 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2461 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2462 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2465 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2466 int (*cmp) PARAMS((char const *, char const *)))
2468 int diff = MTIME_CMP (b->stat, a->stat);
2469 return diff ? diff : cmp (a->name, b->name);
2471 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2472 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2473 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2474 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2477 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2478 int (*cmp) PARAMS ((char const *, char const *)))
2480 int diff = ATIME_CMP (b->stat, a->stat);
2481 return diff ? diff : cmp (a->name, b->name);
2483 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2484 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2485 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2486 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2489 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2490 int (*cmp) PARAMS ((char const *, char const *)))
2492 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2493 return diff ? diff : cmp (a->name, b->name);
2495 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2496 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2497 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2498 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2501 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2503 return strverscmp (a->name, b->name);
2505 static int compare_version (V a, V b) { return cmp_version (a, b); }
2506 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2509 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2510 int (*cmp) PARAMS ((char const *, char const *)))
2512 return cmp (a->name, b->name);
2514 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2515 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2516 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2517 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2519 /* Compare file extensions. Files with no extension are `smallest'.
2520 If extensions are the same, compare by filenames instead. */
2523 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2524 int (*cmp) PARAMS ((char const *, char const *)))
2526 char const *base1 = strrchr (a->name, '.');
2527 char const *base2 = strrchr (b->name, '.');
2528 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2529 return diff ? diff : cmp (a->name, b->name);
2531 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2532 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2533 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2534 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2536 /* Sort the files now in the table. */
2541 int (*func) PARAMS ((V, V));
2551 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2554 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2557 func = sort_reverse ? rev_cmp_atime : compare_atime;
2564 func = sort_reverse ? rev_cmp_name : compare_name;
2566 case sort_extension:
2567 func = sort_reverse ? rev_cmp_extension : compare_extension;
2570 func = sort_reverse ? rev_cmp_size : compare_size;
2573 func = sort_reverse ? rev_cmp_version : compare_version;
2579 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2580 ignore strcoll failures, as a failing strcoll might be a
2581 comparison function that is not a total order, and if we ignored
2582 the failure this might cause qsort to dump core. */
2584 if (setjmp (failed_strcoll))
2592 func = sort_reverse ? rev_str_ctime : compstr_ctime;
2595 func = sort_reverse ? rev_str_mtime : compstr_mtime;
2598 func = sort_reverse ? rev_str_atime : compstr_atime;
2605 func = sort_reverse ? rev_str_name : compstr_name;
2607 case sort_extension:
2608 func = sort_reverse ? rev_str_extension : compstr_extension;
2611 func = sort_reverse ? rev_str_size : compstr_size;
2618 qsort (files, files_index, sizeof (struct fileinfo), func);
2621 /* List all the files now in the table. */
2624 print_current_files (void)
2631 for (i = 0; i < files_index; i++)
2633 print_file_name_and_frills (files + i);
2639 init_column_info ();
2640 print_many_per_line ();
2644 init_column_info ();
2645 print_horizontal ();
2649 print_with_commas ();
2653 for (i = 0; i < files_index; i++)
2655 print_long_format (files + i);
2656 DIRED_PUTCHAR ('\n');
2662 /* Return the expected number of columns in a long-format time stamp,
2663 or zero if it cannot be calculated. */
2666 long_time_expected_width (void)
2668 static int width = -1;
2673 struct tm const *tm = localtime (&epoch);
2674 char const *fmt = long_time_format[0];
2676 char *buf = initbuf;
2677 size_t bufsize = sizeof initbuf;
2683 len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2686 buf = alloca (bufsize *= 2);
2689 width = mbsnwidth (buf, len, 0);
2697 /* Get the current time. */
2700 get_current_time (void)
2702 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2704 struct timespec timespec;
2705 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
2707 current_time = timespec.tv_sec;
2708 current_time_ns = timespec.tv_nsec;
2714 /* The clock does not have nanosecond resolution, so get the maximum
2715 possible value for the current time that is consistent with the
2716 reported clock. That way, files are not considered to be in the
2717 future merely because their time stamps have higher resolution
2718 than the clock resolution. */
2720 #if HAVE_GETTIMEOFDAY
2722 struct timeval timeval;
2723 if (gettimeofday (&timeval, NULL) == 0)
2725 current_time = timeval.tv_sec;
2726 current_time_ns = timeval.tv_usec * 1000 + 999;
2732 current_time = time (NULL);
2733 current_time_ns = 999999999;
2737 print_long_format (const struct fileinfo *f)
2741 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2742 1 10-byte mode string,
2743 1 35-byte time string (may be longer in some locales -- see below)
2744 or LONGEST_HUMAN_READABLE integer,
2745 9 spaces, one following each of these fields, and
2746 1 trailing NUL byte. */
2747 char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2748 + MAX (35, LONGEST_HUMAN_READABLE)
2750 char *buf = init_bigbuf;
2751 size_t bufsize = sizeof (init_bigbuf);
2755 int when_ns IF_LINT (= 0);
2756 struct tm *when_local;
2759 /* Cray DMF: look at the file's migrated, not real, status */
2760 mode_string (f->stat.st_dm_mode, modebuf);
2762 mode_string (f->stat.st_mode, modebuf);
2765 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2771 when = f->stat.st_ctime;
2772 when_ns = TIMESPEC_NS (f->stat.st_ctim);
2775 when = f->stat.st_mtime;
2776 when_ns = TIMESPEC_NS (f->stat.st_mtim);
2779 when = f->stat.st_atime;
2780 when_ns = TIMESPEC_NS (f->stat.st_atim);
2788 char hbuf[LONGEST_HUMAN_READABLE + 1];
2789 sprintf (p, "%*s ", INODE_DIGITS,
2790 human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2794 if (print_block_size)
2796 char hbuf[LONGEST_HUMAN_READABLE + 1];
2797 sprintf (p, "%*s ", block_size_size,
2798 human_readable_inexact ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2799 ST_NBLOCKSIZE, output_block_size,
2804 /* The last byte of the mode string is the POSIX
2805 "optional alternate access method flag". */
2806 sprintf (p, "%s %3lu ", modebuf, (unsigned long) f->stat.st_nlink);
2811 char const *user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2813 sprintf (p, "%-8s ", user_name);
2815 sprintf (p, "%-8lu ", (unsigned long) f->stat.st_uid);
2821 char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2823 sprintf (p, "%-8s ", group_name);
2825 sprintf (p, "%-8lu ", (unsigned long) f->stat.st_gid);
2829 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2830 sprintf (p, "%3lu, %3lu ",
2831 (unsigned long) major (f->stat.st_rdev),
2832 (unsigned long) minor (f->stat.st_rdev));
2835 char hbuf[LONGEST_HUMAN_READABLE + 1];
2836 uintmax_t size = f->stat.st_size;
2838 /* POSIX requires that the size be printed without a sign, even
2839 when negative. Assume the typical case where negative sizes
2840 are actually positive values that have wrapped around. */
2841 size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2844 human_readable (size, hbuf, 1,
2845 output_block_size < 0 ? output_block_size : 1));
2850 if ((when_local = localtime (&when)))
2852 time_t six_months_ago;
2856 /* If the file appears to be in the future, update the current
2857 time, in case the file happens to have been modified since
2858 the last time we checked the clock. */
2859 if (current_time < when
2860 || (current_time == when && current_time_ns < when_ns))
2862 /* Note that get_current_time calls gettimeofday which, on some non-
2863 compliant systems, clobbers the buffer used for localtime's result.
2864 But it's ok here, because we use a gettimeofday wrapper that
2865 saves and restores the buffer around the gettimeofday call. */
2866 get_current_time ();
2869 /* Consider a time to be recent if it is within the past six
2870 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
2871 31556952 seconds on the average. Write this value as an
2872 integer constant to avoid floating point hassles. */
2873 six_months_ago = current_time - 31556952 / 2;
2874 recent = (six_months_ago <= when
2875 && (when < current_time
2876 || (when == current_time && when_ns <= current_time_ns)));
2877 fmt = long_time_format[recent];
2883 s = nstrftime (p, buf + bufsize - p - 1, fmt,
2884 when_local, 0, when_ns);
2887 newbuf = alloca (bufsize *= 2);
2888 memcpy (newbuf, buf, p - buf);
2889 p = newbuf + (p - buf);
2896 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2901 /* The time cannot be represented as a local time;
2902 print it as a huge integer number of seconds. */
2903 char hbuf[LONGEST_HUMAN_READABLE + 1];
2904 int width = long_time_expected_width ();
2908 const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2909 int sign_width = width - strlen (num);
2910 sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2913 sprintf (p, "%*s ", width,
2914 human_readable ((uintmax_t) when, hbuf, 1, 1));
2920 DIRED_FPUTS (buf, stdout, p - buf);
2921 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
2924 if (f->filetype == symbolic_link)
2928 DIRED_FPUTS_LITERAL (" -> ", stdout);
2929 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2931 if (indicator_style != none)
2932 print_type_indicator (f->linkmode);
2935 else if (indicator_style != none)
2936 print_type_indicator (f->stat.st_mode);
2939 /* Output to OUT a quoted representation of the file name NAME,
2940 using OPTIONS to control quoting. Produce no output if OUT is NULL.
2941 Return the number of screen columns occupied by NAME's quoted
2945 quote_name (FILE *out, const char *name, struct quoting_options const *options)
2947 char smallbuf[BUFSIZ];
2948 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
2950 int displayed_width;
2952 if (len < sizeof smallbuf)
2956 buf = (char *) alloca (len + 1);
2957 quotearg_buffer (buf, len + 1, name, -1, options);
2960 if (qmark_funny_chars)
2965 char const *p = buf;
2966 char const *plimit = buf + len;
2968 displayed_width = 0;
2973 case ' ': case '!': case '"': case '#': case '%':
2974 case '&': case '\'': case '(': case ')': case '*':
2975 case '+': case ',': case '-': case '.': case '/':
2976 case '0': case '1': case '2': case '3': case '4':
2977 case '5': case '6': case '7': case '8': case '9':
2978 case ':': case ';': case '<': case '=': case '>':
2980 case 'A': case 'B': case 'C': case 'D': case 'E':
2981 case 'F': case 'G': case 'H': case 'I': case 'J':
2982 case 'K': case 'L': case 'M': case 'N': case 'O':
2983 case 'P': case 'Q': case 'R': case 'S': case 'T':
2984 case 'U': case 'V': case 'W': case 'X': case 'Y':
2986 case '[': case '\\': case ']': case '^': case '_':
2987 case 'a': case 'b': case 'c': case 'd': case 'e':
2988 case 'f': case 'g': case 'h': case 'i': case 'j':
2989 case 'k': case 'l': case 'm': case 'n': case 'o':
2990 case 'p': case 'q': case 'r': case 's': case 't':
2991 case 'u': case 'v': case 'w': case 'x': case 'y':
2992 case 'z': case '{': case '|': case '}': case '~':
2993 /* These characters are printable ASCII characters. */
2995 displayed_width += 1;
2998 /* If we have a multibyte sequence, copy it until we
2999 reach its end, replacing each non-printable multibyte
3000 character with a single question mark. */
3003 memset (&mbstate, 0, sizeof mbstate);
3010 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3012 if (bytes == (size_t) -1)
3014 /* An invalid multibyte sequence was
3015 encountered. Skip one input byte, and
3016 put a question mark. */
3019 displayed_width += 1;
3023 if (bytes == (size_t) -2)
3025 /* An incomplete multibyte character
3026 at the end. Replace it entirely with
3030 displayed_width += 1;
3035 /* A null wide character was encountered. */
3041 /* A printable multibyte character.
3043 for (; bytes > 0; --bytes)
3045 displayed_width += w;
3049 /* An unprintable multibyte character.
3050 Replace it entirely with a question
3054 displayed_width += 1;
3057 while (! mbsinit (&mbstate));
3062 /* The buffer may have shrunk. */
3069 char const *plimit = buf + len;
3073 if (! ISPRINT ((unsigned char) *p))
3077 displayed_width = len;
3082 /* Assume unprintable characters have a displayed_width of 1. */
3085 displayed_width = mbsnwidth (buf, len, 0);
3088 displayed_width = len;
3092 fwrite (buf, 1, len, out);
3093 return displayed_width;
3097 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3098 struct obstack *stack)
3100 if (print_with_color)
3101 print_color_indicator (p, mode, linkok);
3104 PUSH_CURRENT_DIRED_POS (stack);
3106 dired_pos += quote_name (stdout, p, filename_quoting_options);
3109 PUSH_CURRENT_DIRED_POS (stack);
3111 if (print_with_color)
3112 prep_non_filename_text ();
3116 prep_non_filename_text (void)
3118 if (color_indicator[C_END].string != NULL)
3119 put_indicator (&color_indicator[C_END]);
3122 put_indicator (&color_indicator[C_LEFT]);
3123 put_indicator (&color_indicator[C_NORM]);
3124 put_indicator (&color_indicator[C_RIGHT]);
3128 /* Print the file name of `f' with appropriate quoting.
3129 Also print file size, inode number, and filetype indicator character,
3130 as requested by switches. */
3133 print_file_name_and_frills (const struct fileinfo *f)
3135 char buf[LONGEST_HUMAN_READABLE + 1];
3138 printf ("%*s ", INODE_DIGITS,
3139 human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
3141 if (print_block_size)
3142 printf ("%*s ", block_size_size,
3143 human_readable_inexact ((uintmax_t) ST_NBLOCKS (f->stat), buf,
3144 ST_NBLOCKSIZE, output_block_size,
3147 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3149 if (indicator_style != none)
3150 print_type_indicator (f->stat.st_mode);
3154 print_type_indicator (mode_t mode)
3160 if (indicator_style == classify && (mode & S_IXUGO))
3169 else if (S_ISLNK (mode))
3171 else if (S_ISFIFO (mode))
3173 else if (S_ISSOCK (mode))
3175 else if (S_ISDOOR (mode))
3186 print_color_indicator (const char *name, mode_t mode, int linkok)
3189 struct color_ext_type *ext; /* Color extension */
3190 size_t len; /* Length of name */
3192 /* Is this a nonexistent file? If so, linkok == -1. */
3194 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3203 else if (S_ISLNK (mode))
3204 type = ((!linkok && color_indicator[C_ORPHAN].string)
3205 ? C_ORPHAN : C_LINK);
3206 else if (S_ISFIFO (mode))
3208 else if (S_ISSOCK (mode))
3210 else if (S_ISBLK (mode))
3212 else if (S_ISCHR (mode))
3214 else if (S_ISDOOR (mode))
3217 if (type == C_FILE && (mode & S_IXUGO) != 0)
3220 /* Check the file's suffix only if still classified as C_FILE. */
3224 /* Test if NAME has a recognized suffix. */
3226 len = strlen (name);
3227 name += len; /* Pointer to final \0. */
3228 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3230 if ((size_t) ext->ext.len <= len
3231 && strncmp (name - ext->ext.len, ext->ext.string,
3238 put_indicator (&color_indicator[C_LEFT]);
3239 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3240 put_indicator (&color_indicator[C_RIGHT]);
3243 /* Output a color indicator (which may contain nulls). */
3245 put_indicator (const struct bin_str *ind)
3248 register const char *p;
3252 for (i = ind->len; i > 0; --i)
3257 length_of_file_name_and_frills (const struct fileinfo *f)
3259 register int len = 0;
3262 len += INODE_DIGITS + 1;
3264 if (print_block_size)
3265 len += 1 + block_size_size;
3267 len += quote_name (NULL, f->name, filename_quoting_options);
3269 if (indicator_style != none)
3271 mode_t filetype = f->stat.st_mode;
3273 if (S_ISREG (filetype))
3275 if (indicator_style == classify
3276 && (f->stat.st_mode & S_IXUGO))
3279 else if (S_ISDIR (filetype)
3280 || S_ISLNK (filetype)
3281 || S_ISFIFO (filetype)
3282 || S_ISSOCK (filetype)
3283 || S_ISDOOR (filetype)
3292 print_many_per_line (void)
3294 struct column_info *line_fmt;
3295 int filesno; /* Index into files. */
3296 int row; /* Current row. */
3297 int max_name_length; /* Length of longest file name + frills. */
3298 int name_length; /* Length of each file name + frills. */
3299 int pos; /* Current character column. */
3300 int cols; /* Number of files across. */
3301 int rows; /* Maximum number of files down. */
3304 /* Normally the maximum number of columns is determined by the
3305 screen width. But if few files are available this might limit it
3307 max_cols = max_idx > files_index ? files_index : max_idx;
3309 /* Compute the maximum number of possible columns. */
3310 for (filesno = 0; filesno < files_index; ++filesno)
3314 name_length = length_of_file_name_and_frills (files + filesno);
3316 for (i = 0; i < max_cols; ++i)
3318 if (column_info[i].valid_len)
3320 int idx = filesno / ((files_index + i) / (i + 1));
3321 int real_length = name_length + (idx == i ? 0 : 2);
3323 if (real_length > column_info[i].col_arr[idx])
3325 column_info[i].line_len += (real_length
3326 - column_info[i].col_arr[idx]);
3327 column_info[i].col_arr[idx] = real_length;
3328 column_info[i].valid_len = column_info[i].line_len < line_length;
3334 /* Find maximum allowed columns. */
3335 for (cols = max_cols; cols > 1; --cols)
3337 if (column_info[cols - 1].valid_len)
3341 line_fmt = &column_info[cols - 1];
3343 /* Calculate the number of rows that will be in each column except possibly
3344 for a short column on the right. */
3345 rows = files_index / cols + (files_index % cols != 0);
3347 for (row = 0; row < rows; row++)
3352 /* Print the next row. */
3355 print_file_name_and_frills (files + filesno);
3356 name_length = length_of_file_name_and_frills (files + filesno);
3357 max_name_length = line_fmt->col_arr[col++];
3360 if (filesno >= files_index)
3363 indent (pos + name_length, pos + max_name_length);
3364 pos += max_name_length;
3371 print_horizontal (void)
3373 struct column_info *line_fmt;
3375 int max_name_length;
3381 /* Normally the maximum number of columns is determined by the
3382 screen width. But if few files are available this might limit it
3384 max_cols = max_idx > files_index ? files_index : max_idx;
3386 /* Compute the maximum file name length. */
3387 max_name_length = 0;
3388 for (filesno = 0; filesno < files_index; ++filesno)
3392 name_length = length_of_file_name_and_frills (files + filesno);
3394 for (i = 0; i < max_cols; ++i)
3396 if (column_info[i].valid_len)
3398 int idx = filesno % (i + 1);
3399 int real_length = name_length + (idx == i ? 0 : 2);
3401 if (real_length > column_info[i].col_arr[idx])
3403 column_info[i].line_len += (real_length
3404 - column_info[i].col_arr[idx]);
3405 column_info[i].col_arr[idx] = real_length;
3406 column_info[i].valid_len = column_info[i].line_len < line_length;
3412 /* Find maximum allowed columns. */
3413 for (cols = max_cols; cols > 1; --cols)
3415 if (column_info[cols - 1].valid_len)
3419 line_fmt = &column_info[cols - 1];
3423 /* Print first entry. */
3424 print_file_name_and_frills (files);
3425 name_length = length_of_file_name_and_frills (files);
3426 max_name_length = line_fmt->col_arr[0];
3429 for (filesno = 1; filesno < files_index; ++filesno)
3431 int col = filesno % cols;
3440 indent (pos + name_length, pos + max_name_length);
3441 pos += max_name_length;
3444 print_file_name_and_frills (files + filesno);
3446 name_length = length_of_file_name_and_frills (files + filesno);
3447 max_name_length = line_fmt->col_arr[col];
3453 print_with_commas (void)
3460 for (filesno = 0; filesno < files_index; filesno++)
3464 pos += length_of_file_name_and_frills (files + filesno);
3465 if (filesno + 1 < files_index)
3466 pos += 2; /* For the comma and space */
3468 if (old_pos != 0 && pos >= line_length)
3474 print_file_name_and_frills (files + filesno);
3475 if (filesno + 1 < files_index)
3484 /* Assuming cursor is at position FROM, indent up to position TO.
3485 Use a TAB character instead of two or more spaces whenever possible. */
3488 indent (int from, int to)
3492 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
3495 from += tabsize - from % tabsize;
3505 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3506 /* FIXME: maybe remove this function someday. See about using a
3507 non-malloc'ing version of path_concat. */
3510 attach (char *dest, const char *dirname, const char *name)
3512 const char *dirnamep = dirname;
3514 /* Copy dirname if it is not ".". */
3515 if (dirname[0] != '.' || dirname[1] != 0)
3518 *dest++ = *dirnamep++;
3519 /* Add '/' if `dirname' doesn't already end with it. */
3520 if (dirnamep > dirname && dirnamep[-1] != '/')
3529 init_column_info (void)
3534 max_idx = line_length / MIN_COLUMN_WIDTH;
3538 if (column_info == NULL)
3540 column_info = XMALLOC (struct column_info, max_idx);
3544 for (i = 0; i < max_idx; ++i)
3548 column_info[i].valid_len = 1;
3549 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3552 column_info[i].col_arr = XMALLOC (int, i + 1);
3554 for (j = 0; j <= i; ++j)
3555 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3563 fprintf (stderr, _("Try `%s --help' for more information.\n"),
3567 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3569 List information about the FILEs (the current directory by default).\n\
3570 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3574 Mandatory arguments to long options are mandatory for short options too.\n\
3577 -a, --all do not hide entries starting with .\n\
3578 -A, --almost-all do not list implied . and ..\n\
3579 -b, --escape print octal escapes for nongraphic characters\n\
3582 --block-size=SIZE use SIZE-byte blocks\n\
3583 -B, --ignore-backups do not list implied entries ending with ~\n\
3584 -c with -lt: sort by, and show, ctime (time of last\n\
3585 modification of file status information)\n\
3586 with -l: show ctime and sort by name\n\
3587 otherwise: sort by ctime\n\
3590 -C list entries by columns\n\
3591 --color[=WHEN] control whether color is used to distinguish file\n\
3592 types. WHEN may be `never', `always', or `auto'\n\
3593 -d, --directory list directory entries instead of contents\n\
3594 -D, --dired generate output designed for Emacs' dired mode\n\
3597 -f do not sort, enable -aU, disable -lst\n\
3598 -F, --classify append indicator (one of */=@|) to entries\n\
3599 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3600 single-column -1, verbose -l, vertical -C\n\
3601 --full-time like -l --time-style=full-iso\n\
3604 -g like -l, but do not list owner\n\
3605 -G, --no-group inhibit display of group information\n\
3606 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3607 --si likewise, but use powers of 1000 not 1024\n\
3608 -H, --dereference-command-line follow symbolic links on the command line\n\
3611 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3612 none (default), classify (-F), file-type (-p)\n\
3613 -i, --inode print index number of each file\n\
3614 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3615 -k like --block-size=1K\n\
3618 -l use a long listing format\n\
3619 -L, --dereference when showing file information for a symbolic\n\
3620 link, show information for the file the link\n\
3621 references rather than for the link itself\n\
3622 -m fill width with a comma separated list of entries\n\
3625 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3626 -N, --literal print raw entry names (don't treat e.g. control\n\
3627 characters specially)\n\
3628 -o like -l, but do not list group information\n\
3629 -p, --file-type append indicator (one of /=@|) to entries\n\
3632 -q, --hide-control-chars print ? instead of non graphic characters\n\
3633 --show-control-chars show non graphic characters as-is (default\n\
3634 unless program is `ls' and output is a terminal)\n\
3635 -Q, --quote-name enclose entry names in double quotes\n\
3636 --quoting-style=WORD use quoting style WORD for entry names:\n\
3637 literal, locale, shell, shell-always, c, escape\n\
3640 -r, --reverse reverse order while sorting\n\
3641 -R, --recursive list subdirectories recursively\n\
3642 -s, --size print size of each file, in blocks\n\
3645 -S sort by file size\n\
3646 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3648 status -c, time -t, atime -u, access -u, use -u\n\
3649 --time=WORD show time as WORD instead of modification time:\n\
3650 atime, access, use, ctime or status; use\n\
3651 specified time as sort key if --sort=time\n\
3654 --time-style=WORD show times using style WORD:\n\
3655 full-iso, iso, locale, posix-iso\n\
3656 -t sort by modification time\n\
3657 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
3660 -u with -lt: sort by, and show, access time\n\
3661 with -l: show access time and sort by name\n\
3662 otherwise: sort by access time\n\
3663 -U do not sort; list entries in directory order\n\
3664 -v sort by version\n\
3667 -w, --width=COLS assume screen width instead of current value\n\
3668 -x list entries by lines instead of by columns\n\
3669 -X sort alphabetically by entry extension\n\
3670 -1 list one file per line\n\
3672 fputs (HELP_OPTION_DESCRIPTION, stdout);
3673 fputs (VERSION_OPTION_DESCRIPTION, stdout);
3675 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3676 kB 1000, K 1024, MB 1,000,000, M 1,048,576, and so on for G, T, P, E, Z, Y.\n\
3680 By default, color is not used to distinguish types of files. That is\n\
3681 equivalent to using --color=none. Using the --color option without the\n\
3682 optional WHEN argument is equivalent to using --color=always. With\n\
3683 --color=auto, color codes are output only if standard output is connected\n\
3684 to a terminal (tty).\n\
3686 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));