.
[coreutils.git] / src / ls.c
blobfb97314d6095b06a3028fad92bd8b73aac527075
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)
7 any later version.
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.
28 If ls_mode is LS_LS,
29 the output format depends on whether the output
30 device is a terminal.
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>. */
39 #ifdef _AIX
40 #pragma alloca
41 #endif
43 #include <config.h>
44 #include <sys/types.h>
46 #if HAVE_TERMIOS_H
47 # include <termios.h>
48 #endif
50 #ifdef GWINSZ_IN_SYS_IOCTL
51 # include <sys/ioctl.h>
52 #endif
54 #ifdef WINSIZE_IN_PTEM
55 # include <sys/stream.h>
56 # include <sys/ptem.h>
57 #endif
59 #include <stdio.h>
60 #include <assert.h>
61 #include <setjmp.h>
62 #include <grp.h>
63 #include <pwd.h>
64 #include <getopt.h>
65 #include <signal.h>
67 /* Get MB_CUR_MAX. */
68 #if HAVE_STDLIB_H
69 # include <stdlib.h>
70 #endif
72 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
73 #if HAVE_WCHAR_H
74 # include <wchar.h>
75 #endif
77 /* Get iswprint(). */
78 #if HAVE_WCTYPE_H
79 # include <wctype.h>
80 #endif
81 #if !defined iswprint && !HAVE_ISWPRINT
82 # define iswprint(wc) 1
83 #endif
85 #ifndef HAVE_DECL_WCWIDTH
86 "this configure-time declaration test was not run"
87 #endif
88 #if !HAVE_DECL_WCWIDTH
89 int wcwidth ();
90 #endif
92 /* If wcwidth() doesn't exist, assume all printable characters have
93 width 1. */
94 #ifndef wcwidth
95 # if !HAVE_WCWIDTH
96 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
97 # endif
98 #endif
100 #include "system.h"
101 #include <fnmatch.h>
103 #include "acl.h"
104 #include "argmatch.h"
105 #include "dev-ino.h"
106 #include "dirname.h"
107 #include "dirfd.h"
108 #include "error.h"
109 #include "full-write.h"
110 #include "hard-locale.h"
111 #include "hash.h"
112 #include "human.h"
113 #include "filemode.h"
114 #include "inttostr.h"
115 #include "ls.h"
116 #include "mbswidth.h"
117 #include "obstack.h"
118 #include "path-concat.h"
119 #include "quote.h"
120 #include "quotearg.h"
121 #include "same.h"
122 #include "strftime.h"
123 #include "strverscmp.h"
124 #include "xstrtol.h"
125 #include "xreadlink.h"
127 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
128 : (ls_mode == LS_MULTI_COL \
129 ? "dir" : "vdir"))
131 #define AUTHORS N_ ("Richard Stallman and David MacKenzie")
133 #define obstack_chunk_alloc malloc
134 #define obstack_chunk_free free
136 /* Return an int indicating the result of comparing two integers.
137 Subtracting doesn't always work, due to overflow. */
138 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
140 /* The field width for inode numbers. On some hosts inode numbers are
141 64 bits, so columns won't line up exactly when a huge inode number
142 is encountered, but in practice 7 digits is usually enough. */
143 #ifndef INODE_DIGITS
144 # define INODE_DIGITS 7
145 #endif
147 /* Arrange to make lstat calls go through the wrapper function
148 on systems with an lstat function that does not dereference symlinks
149 that are specified with a trailing slash. */
150 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
151 int rpl_lstat (const char *, struct stat *);
152 # undef lstat
153 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
154 #endif
156 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
157 # define DT_INIT(Val) = Val
158 #else
159 # define DT_INIT(Val) /* empty */
160 #endif
162 #ifdef ST_MTIM_NSEC
163 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
164 #else
165 # define TIMESPEC_NS(timespec) 0
166 #endif
168 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
169 # define st_author st_uid
170 #endif
172 /* Cray/Unicos DMF: use the file's migrated, not real, status */
173 #if HAVE_ST_DM_MODE
174 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
175 #else
176 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
177 #endif
179 #ifndef LOGIN_NAME_MAX
180 # if _POSIX_LOGIN_NAME_MAX
181 # define LOGIN_NAME_MAX _POSIX_LOGIN_NAME_MAX
182 # else
183 # define LOGIN_NAME_MAX 17
184 # endif
185 #endif
187 /* The maximum length of a string representation of a user or group ID,
188 not counting any terminating NUL byte. */
189 #define ID_LENGTH_MAX \
190 MAX (LOGIN_NAME_MAX - 1, LONGEST_HUMAN_READABLE)
192 enum filetype
194 unknown DT_INIT (DT_UNKNOWN),
195 fifo DT_INIT (DT_FIFO),
196 chardev DT_INIT (DT_CHR),
197 directory DT_INIT (DT_DIR),
198 blockdev DT_INIT (DT_BLK),
199 normal DT_INIT (DT_REG),
200 symbolic_link DT_INIT (DT_LNK),
201 sock DT_INIT (DT_SOCK),
202 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
203 | DT_REG | DT_LNK | DT_SOCK))
206 struct fileinfo
208 /* The file name. */
209 char *name;
211 struct stat stat;
213 /* For symbolic link, name of the file linked to, otherwise zero. */
214 char *linkname;
216 /* For symbolic link and long listing, st_mode of file linked to, otherwise
217 zero. */
218 mode_t linkmode;
220 /* For symbolic link and color printing, 1 if linked-to file
221 exists, otherwise 0. */
222 int linkok;
224 enum filetype filetype;
226 #if HAVE_ACL
227 /* For long listings, true if the file has an access control list. */
228 bool have_acl;
229 #endif
232 #if HAVE_ACL
233 # define FILE_HAS_ACL(F) ((F)->have_acl)
234 #else
235 # define FILE_HAS_ACL(F) 0
236 #endif
238 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
240 /* Null is a valid character in a color indicator (think about Epson
241 printers, for example) so we have to use a length/buffer string
242 type. */
244 struct bin_str
246 int len; /* Number of bytes */
247 const char *string; /* Pointer to the same */
250 #ifndef STDC_HEADERS
251 time_t time ();
252 #endif
254 char *getgroup ();
255 char *getuser ();
257 static size_t quote_name (FILE *out, const char *name,
258 struct quoting_options const *options,
259 size_t *width);
260 static char *make_link_path (const char *path, const char *linkname);
261 static int decode_switches (int argc, char **argv);
262 static int file_interesting (const struct dirent *next);
263 static uintmax_t gobble_file (const char *name, enum filetype type,
264 int explicit_arg, const char *dirname);
265 static void print_color_indicator (const char *name, mode_t mode, int linkok);
266 static void put_indicator (const struct bin_str *ind);
267 static int put_indicator_direct (const struct bin_str *ind);
268 static int length_of_file_name_and_frills (const struct fileinfo *f);
269 static void add_ignore_pattern (const char *pattern);
270 static void attach (char *dest, const char *dirname, const char *name);
271 static void clear_files (void);
272 static void extract_dirs_from_files (const char *dirname,
273 int ignore_dot_and_dot_dot);
274 static void get_link_name (const char *filename, struct fileinfo *f);
275 static void indent (int from, int to);
276 static void init_column_info (void);
277 static void print_current_files (void);
278 static void print_dir (const char *name, const char *realname);
279 static void print_file_name_and_frills (const struct fileinfo *f);
280 static void print_horizontal (void);
281 static void print_long_format (const struct fileinfo *f);
282 static void print_many_per_line (void);
283 static void print_name_with_quoting (const char *p, mode_t mode,
284 int linkok,
285 struct obstack *stack);
286 static void prep_non_filename_text (void);
287 static void print_type_indicator (mode_t mode);
288 static void print_with_commas (void);
289 static void queue_directory (const char *name, const char *realname);
290 static void sort_files (void);
291 static void parse_ls_color (void);
292 void usage (int status);
294 /* The name the program was run with, stripped of any leading path. */
295 char *program_name;
297 /* Initial size of hash table.
298 Most hierarchies are likely to be shallower than this. */
299 #define INITIAL_TABLE_SIZE 30
301 /* The set of `active' directories, from the current command-line argument
302 to the level in the hierarchy at which files are being listed.
303 A directory is represented by its device and inode numbers (struct dev_ino).
304 A directory is added to this set when ls begins listing it or its
305 entries, and it is removed from the set just after ls has finished
306 processing it. This set is used solely to detect loops, e.g., with
307 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
308 static Hash_table *active_dir_set;
310 #define LOOP_DETECT (!!active_dir_set)
312 /* The table of files in the current directory:
314 `files' points to a vector of `struct fileinfo', one per file.
315 `nfiles' is the number of elements space has been allocated for.
316 `files_index' is the number actually in use. */
318 /* Address of block containing the files that are described. */
319 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
321 /* Length of block that `files' points to, measured in files. */
322 static int nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
324 /* Index of first unused in `files'. */
325 static int files_index; /* FIXME: rename this to e.g. cwd_n_used */
327 /* When nonzero, in a color listing, color each symlink name according to the
328 type of file it points to. Otherwise, color them according to the `ln'
329 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
330 regardless. This is set when `ln=target' appears in LS_COLORS. */
332 static int color_symlink_as_referent;
334 /* mode of appropriate file for colorization */
335 #define FILE_OR_LINK_MODE(File) \
336 ((color_symlink_as_referent && (File)->linkok) \
337 ? (File)->linkmode : (File)->stat.st_mode)
340 /* Record of one pending directory waiting to be listed. */
342 struct pending
344 char *name;
345 /* If the directory is actually the file pointed to by a symbolic link we
346 were told to list, `realname' will contain the name of the symbolic
347 link, otherwise zero. */
348 char *realname;
349 struct pending *next;
352 static struct pending *pending_dirs;
354 /* Current time in seconds and nanoseconds since 1970, updated as
355 needed when deciding whether a file is recent. */
357 static time_t current_time = TYPE_MINIMUM (time_t);
358 static int current_time_ns = -1;
360 /* The number of digits to use for block sizes.
361 4, or more if needed for bigger numbers. */
363 static int block_size_size;
365 /* Option flags */
367 /* long_format for lots of info, one per line.
368 one_per_line for just names, one per line.
369 many_per_line for just names, many per line, sorted vertically.
370 horizontal for just names, many per line, sorted horizontally.
371 with_commas for just names, many per line, separated by commas.
373 -l (and other options that imply -l), -1, -C, -x and -m control
374 this parameter. */
376 enum format
378 long_format, /* -l and other options that imply -l */
379 one_per_line, /* -1 */
380 many_per_line, /* -C */
381 horizontal, /* -x */
382 with_commas /* -m */
385 static enum format format;
387 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
388 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
389 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
390 enum time_style
392 full_iso_time_style, /* --time-style=full-iso */
393 long_iso_time_style, /* --time-style=long-iso */
394 iso_time_style, /* --time-style=iso */
395 locale_time_style /* --time-style=locale */
398 static char const *const time_style_args[] =
400 "full-iso", "long-iso", "iso", "locale", 0
403 static enum time_style const time_style_types[] =
405 full_iso_time_style, long_iso_time_style, iso_time_style,
406 locale_time_style, 0
409 /* Type of time to print or sort by. Controlled by -c and -u. */
411 enum time_type
413 time_mtime, /* default */
414 time_ctime, /* -c */
415 time_atime /* -u */
418 static enum time_type time_type;
420 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
422 enum sort_type
424 sort_none, /* -U */
425 sort_name, /* default */
426 sort_extension, /* -X */
427 sort_time, /* -t */
428 sort_size, /* -S */
429 sort_version /* -v */
432 static enum sort_type sort_type;
434 /* Direction of sort.
435 0 means highest first if numeric,
436 lowest first if alphabetic;
437 these are the defaults.
438 1 means the opposite order in each case. -r */
440 static int sort_reverse;
442 /* Nonzero means to display owner information. -g turns this off. */
444 static int print_owner = 1;
446 /* Nonzero means to display author information. */
448 static bool print_author;
450 /* Nonzero means to display group information. -G and -o turn this off. */
452 static int print_group = 1;
454 /* Nonzero means print the user and group id's as numbers rather
455 than as names. -n */
457 static int numeric_ids;
459 /* Nonzero means mention the size in blocks of each file. -s */
461 static int print_block_size;
463 /* Human-readable options for output. */
464 static int human_output_opts;
466 /* The units to use when printing sizes other than file sizes. */
467 static uintmax_t output_block_size;
469 /* Likewise, but for file sizes. */
470 static uintmax_t file_output_block_size = 1;
472 /* Precede each line of long output (per file) with a string like `m,n:'
473 where M is the number of characters after the `:' and before the
474 filename and N is the length of the filename. Using this format,
475 Emacs' dired mode starts up twice as fast, and can handle all
476 strange characters in file names. */
477 static int dired;
479 /* `none' means don't mention the type of files.
480 `classify' means mention file types and mark executables.
481 `file_type' means mention only file types.
483 Controlled by -F, -p, and --indicator-style. */
485 enum indicator_style
487 none, /* --indicator-style=none */
488 classify, /* -F, --indicator-style=classify */
489 file_type /* -p, --indicator-style=file-type */
492 static enum indicator_style indicator_style;
494 /* Names of indicator styles. */
495 static char const *const indicator_style_args[] =
497 "none", "classify", "file-type", 0
500 static enum indicator_style const indicator_style_types[]=
502 none, classify, file_type
505 /* Nonzero means use colors to mark types. Also define the different
506 colors as well as the stuff for the LS_COLORS environment variable.
507 The LS_COLORS variable is now in a termcap-like format. */
509 static int print_with_color;
511 enum color_type
513 color_never, /* 0: default or --color=never */
514 color_always, /* 1: --color=always */
515 color_if_tty /* 2: --color=tty */
518 enum Dereference_symlink
520 DEREF_UNDEFINED = 1,
521 DEREF_NEVER,
522 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
523 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
524 DEREF_ALWAYS /* -L */
527 enum indicator_no
529 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
530 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
533 static const char *const indicator_name[]=
535 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
536 "bd", "cd", "mi", "or", "ex", "do", NULL
539 struct color_ext_type
541 struct bin_str ext; /* The extension we're looking for */
542 struct bin_str seq; /* The sequence to output when we do */
543 struct color_ext_type *next; /* Next in list */
546 static struct bin_str color_indicator[] =
548 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
549 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
550 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
551 { LEN_STR_PAIR ("0") }, /* no: Normal */
552 { LEN_STR_PAIR ("0") }, /* fi: File: default */
553 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
554 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
555 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
556 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
557 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
558 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
559 { 0, NULL }, /* mi: Missing file: undefined */
560 { 0, NULL }, /* or: Orphanned symlink: undefined */
561 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
562 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
565 /* FIXME: comment */
566 static struct color_ext_type *color_ext_list = NULL;
568 /* Buffer for color sequences */
569 static char *color_buf;
571 /* Nonzero means to check for orphaned symbolic link, for displaying
572 colors. */
574 static int check_symlink_color;
576 /* Nonzero means mention the inode number of each file. -i */
578 static int print_inode;
580 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
581 other options that imply -l), and -L. */
583 static enum Dereference_symlink dereference;
585 /* Nonzero means when a directory is found, display info on its
586 contents. -R */
588 static int recursive;
590 /* Nonzero means when an argument is a directory name, display info
591 on it itself. -d */
593 static int immediate_dirs;
595 /* Nonzero means don't omit files whose names start with `.'. -A */
597 static int all_files;
599 /* Nonzero means don't omit files `.' and `..'
600 This flag implies `all_files'. -a */
602 static int really_all_files;
604 /* A linked list of shell-style globbing patterns. If a non-argument
605 file name matches any of these patterns, it is omitted.
606 Controlled by -I. Multiple -I options accumulate.
607 The -B option adds `*~' and `.*~' to this list. */
609 struct ignore_pattern
611 const char *pattern;
612 struct ignore_pattern *next;
615 static struct ignore_pattern *ignore_patterns;
617 /* Nonzero means output nongraphic chars in file names as `?'.
618 (-q, --hide-control-chars)
619 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
620 independent. The algorithm is: first, obey the quoting style to get a
621 string representing the file name; then, if qmark_funny_chars is set,
622 replace all nonprintable chars in that string with `?'. It's necessary
623 to replace nonprintable chars even in quoted strings, because we don't
624 want to mess up the terminal if control chars get sent to it, and some
625 quoting methods pass through control chars as-is. */
626 static int qmark_funny_chars;
628 /* Quoting options for file and dir name output. */
630 static struct quoting_options *filename_quoting_options;
631 static struct quoting_options *dirname_quoting_options;
633 /* The number of chars per hardware tab stop. Setting this to zero
634 inhibits the use of TAB characters for separating columns. -T */
635 static int tabsize;
637 /* Nonzero means we are listing the working directory because no
638 non-option arguments were given. */
640 static int dir_defaulted;
642 /* Nonzero means print each directory name before listing it. */
644 static int print_dir_name;
646 /* The line length to use for breaking lines in many-per-line format.
647 Can be set with -w. */
649 static int line_length;
651 /* If nonzero, the file listing format requires that stat be called on
652 each file. */
654 static int format_needs_stat;
656 /* Similar to `format_needs_stat', but set if only the file type is
657 needed. */
659 static int format_needs_type;
661 /* strftime formats for non-recent and recent files, respectively, in
662 -l output. */
664 static char const *long_time_format[2] =
666 /* strftime format for non-recent files (older than 6 months), in
667 -l output when --time-style=locale is specified. This should
668 contain the year, month and day (at least), in an order that is
669 understood by people in your locale's territory.
670 Please try to keep the number of used screen columns small,
671 because many people work in windows with only 80 columns. But
672 make this as wide as the other string below, for recent files. */
673 N_("%b %e %Y"),
674 /* strftime format for recent files (younger than 6 months), in
675 -l output when --time-style=locale is specified. This should
676 contain the month, day and time (at least), in an order that is
677 understood by people in your locale's territory.
678 Please try to keep the number of used screen columns small,
679 because many people work in windows with only 80 columns. But
680 make this as wide as the other string above, for non-recent files. */
681 N_("%b %e %H:%M")
684 /* The exit status to use if we don't get any fatal errors. */
686 static int exit_status;
688 /* For long options that have no equivalent short option, use a
689 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
690 enum
692 AUTHOR_OPTION = CHAR_MAX + 1,
693 BLOCK_SIZE_OPTION,
694 COLOR_OPTION,
695 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
696 FORMAT_OPTION,
697 FULL_TIME_OPTION,
698 INDICATOR_STYLE_OPTION,
699 QUOTING_STYLE_OPTION,
700 SHOW_CONTROL_CHARS_OPTION,
701 SI_OPTION,
702 SORT_OPTION,
703 TIME_OPTION,
704 TIME_STYLE_OPTION
707 static struct option const long_options[] =
709 {"all", no_argument, 0, 'a'},
710 {"escape", no_argument, 0, 'b'},
711 {"directory", no_argument, 0, 'd'},
712 {"dired", no_argument, 0, 'D'},
713 {"full-time", no_argument, 0, FULL_TIME_OPTION},
714 {"human-readable", no_argument, 0, 'h'},
715 {"inode", no_argument, 0, 'i'},
716 {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
717 {"numeric-uid-gid", no_argument, 0, 'n'},
718 {"no-group", no_argument, 0, 'G'},
719 {"hide-control-chars", no_argument, 0, 'q'},
720 {"reverse", no_argument, 0, 'r'},
721 {"size", no_argument, 0, 's'},
722 {"width", required_argument, 0, 'w'},
723 {"almost-all", no_argument, 0, 'A'},
724 {"ignore-backups", no_argument, 0, 'B'},
725 {"classify", no_argument, 0, 'F'},
726 {"file-type", no_argument, 0, 'p'},
727 {"si", no_argument, 0, SI_OPTION},
728 {"dereference-command-line", no_argument, 0, 'H'},
729 {"dereference-command-line-symlink-to-dir", no_argument, 0,
730 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
731 {"ignore", required_argument, 0, 'I'},
732 {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
733 {"dereference", no_argument, 0, 'L'},
734 {"literal", no_argument, 0, 'N'},
735 {"quote-name", no_argument, 0, 'Q'},
736 {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
737 {"recursive", no_argument, 0, 'R'},
738 {"format", required_argument, 0, FORMAT_OPTION},
739 {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
740 {"sort", required_argument, 0, SORT_OPTION},
741 {"tabsize", required_argument, 0, 'T'},
742 {"time", required_argument, 0, TIME_OPTION},
743 {"time-style", required_argument, 0, TIME_STYLE_OPTION},
744 {"color", optional_argument, 0, COLOR_OPTION},
745 {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
746 {"author", no_argument, 0, AUTHOR_OPTION},
747 {GETOPT_HELP_OPTION_DECL},
748 {GETOPT_VERSION_OPTION_DECL},
749 {NULL, 0, NULL, 0}
752 static char const *const format_args[] =
754 "verbose", "long", "commas", "horizontal", "across",
755 "vertical", "single-column", 0
758 static enum format const format_types[] =
760 long_format, long_format, with_commas, horizontal, horizontal,
761 many_per_line, one_per_line
764 static char const *const sort_args[] =
766 "none", "time", "size", "extension", "version", 0
769 static enum sort_type const sort_types[] =
771 sort_none, sort_time, sort_size, sort_extension, sort_version
774 static char const *const time_args[] =
776 "atime", "access", "use", "ctime", "status", 0
779 static enum time_type const time_types[] =
781 time_atime, time_atime, time_atime, time_ctime, time_ctime
784 static char const *const color_args[] =
786 /* force and none are for compatibility with another color-ls version */
787 "always", "yes", "force",
788 "never", "no", "none",
789 "auto", "tty", "if-tty", 0
792 static enum color_type const color_types[] =
794 color_always, color_always, color_always,
795 color_never, color_never, color_never,
796 color_if_tty, color_if_tty, color_if_tty
799 /* Information about filling a column. */
800 struct column_info
802 int valid_len;
803 int line_len;
804 int *col_arr;
807 /* Array with information about column filledness. */
808 static struct column_info *column_info;
810 /* Maximum number of columns ever possible for this display. */
811 static int max_idx;
813 /* The minimum width of a colum is 3: 1 character for the name and 2
814 for the separating white space. */
815 #define MIN_COLUMN_WIDTH 3
818 /* This zero-based index is used solely with the --dired option.
819 When that option is in effect, this counter is incremented for each
820 character of output generated by this program so that the beginning
821 and ending indices (in that output) of every file name can be recorded
822 and later output themselves. */
823 static size_t dired_pos;
825 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
827 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
828 #define DIRED_FPUTS(s, stream, s_len) \
829 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
831 /* Like DIRED_FPUTS, but for use when S is a literal string. */
832 #define DIRED_FPUTS_LITERAL(s, stream) \
833 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
835 #define DIRED_INDENT() \
836 do \
838 if (dired) \
839 DIRED_FPUTS_LITERAL (" ", stdout); \
841 while (0)
843 /* With --dired, store pairs of beginning and ending indices of filenames. */
844 static struct obstack dired_obstack;
846 /* With --dired, store pairs of beginning and ending indices of any
847 directory names that appear as headers (just before `total' line)
848 for lists of directory entries. Such directory names are seen when
849 listing hierarchies using -R and when a directory is listed with at
850 least one other command line argument. */
851 static struct obstack subdired_obstack;
853 /* Save the current index on the specified obstack, OBS. */
854 #define PUSH_CURRENT_DIRED_POS(obs) \
855 do \
857 if (dired) \
858 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
860 while (0)
862 /* With -R, this stack is used to help detect directory cycles.
863 The device/inode pairs on this stack mirror the pairs in the
864 active_dir_set hash table. */
865 static struct obstack dev_ino_obstack;
867 /* Push a pair onto the device/inode stack. */
868 #define DEV_INO_PUSH(Dev, Ino) \
869 do \
871 struct dev_ino *di; \
872 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
873 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
874 di->st_dev = (Dev); \
875 di->st_ino = (Ino); \
877 while (0)
879 /* Pop a dev/ino struct off the global dev_ino_obstack
880 and return that struct. */
881 static struct dev_ino
882 dev_ino_pop (void)
884 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
885 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
886 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
889 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
890 do \
892 struct stat sb; \
893 assert (Name); \
894 assert (0 <= stat (Name, &sb)); \
895 assert (sb.st_dev == Di.st_dev); \
896 assert (sb.st_ino == Di.st_ino); \
898 while (0)
901 /* Write to standard output PREFIX, followed by the quoting style and
902 a space-separated list of the integers stored in OS all on one line. */
904 static void
905 dired_dump_obstack (const char *prefix, struct obstack *os)
907 int n_pos;
909 n_pos = obstack_object_size (os) / sizeof (dired_pos);
910 if (n_pos > 0)
912 int i;
913 size_t *pos;
915 pos = (size_t *) obstack_finish (os);
916 fputs (prefix, stdout);
917 for (i = 0; i < n_pos; i++)
918 printf (" %lu", (unsigned long) pos[i]);
919 putchar ('\n');
923 static unsigned int
924 dev_ino_hash (void const *x, unsigned int table_size)
926 struct dev_ino const *p = x;
927 return (uintmax_t) p->st_ino % table_size;
930 static bool
931 dev_ino_compare (void const *x, void const *y)
933 struct dev_ino const *a = x;
934 struct dev_ino const *b = y;
935 return SAME_INODE (*a, *b) ? true : false;
938 static void
939 dev_ino_free (void *x)
941 free (x);
944 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
945 active directories. Return nonzero if there is already a matching
946 entry in the table. Otherwise, return zero. */
948 static int
949 visit_dir (dev_t dev, ino_t ino)
951 struct dev_ino *ent;
952 struct dev_ino *ent_from_table;
953 int found_match;
955 ent = XMALLOC (struct dev_ino, 1);
956 ent->st_ino = ino;
957 ent->st_dev = dev;
959 /* Attempt to insert this entry into the table. */
960 ent_from_table = hash_insert (active_dir_set, ent);
962 if (ent_from_table == NULL)
964 /* Insertion failed due to lack of memory. */
965 xalloc_die ();
968 found_match = (ent_from_table != ent);
970 if (found_match)
972 /* ent was not inserted, so free it. */
973 free (ent);
976 return found_match;
979 static void
980 free_pending_ent (struct pending *p)
982 if (p->name)
983 free (p->name);
984 if (p->realname)
985 free (p->realname);
986 free (p);
989 static void
990 restore_default_color (void)
992 if (put_indicator_direct (&color_indicator[C_LEFT]) == 0)
993 put_indicator_direct (&color_indicator[C_RIGHT]);
996 /* Upon interrupt, suspend, hangup, etc. ensure that the
997 terminal text color is restored to the default. */
998 static void
999 sighandler (int sig)
1001 #ifndef SA_NOCLDSTOP
1002 signal (sig, SIG_IGN);
1003 #endif
1005 restore_default_color ();
1007 /* SIGTSTP is special, since the application can receive that signal more
1008 than once. In this case, don't set the signal handler to the default.
1009 Instead, just raise the uncatchable SIGSTOP. */
1010 if (sig == SIGTSTP)
1012 sig = SIGSTOP;
1014 else
1016 #ifdef SA_NOCLDSTOP
1017 struct sigaction sigact;
1019 sigact.sa_handler = SIG_DFL;
1020 sigemptyset (&sigact.sa_mask);
1021 sigact.sa_flags = 0;
1022 sigaction (sig, &sigact, NULL);
1023 #else
1024 signal (sig, SIG_DFL);
1025 #endif
1028 raise (sig);
1032 main (int argc, char **argv)
1034 register int i;
1035 register struct pending *thispend;
1036 unsigned int n_files;
1038 program_name = argv[0];
1039 setlocale (LC_ALL, "");
1040 bindtextdomain (PACKAGE, LOCALEDIR);
1041 textdomain (PACKAGE);
1043 atexit (close_stdout);
1045 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1046 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1048 exit_status = 0;
1049 dir_defaulted = 1;
1050 print_dir_name = 1;
1051 pending_dirs = 0;
1053 i = decode_switches (argc, argv);
1055 if (print_with_color)
1056 parse_ls_color ();
1058 /* Test print_with_color again, because the call to parse_ls_color
1059 may have just reset it -- e.g., if LS_COLORS is invalid. */
1060 if (print_with_color)
1062 prep_non_filename_text ();
1063 /* Avoid following symbolic links when possible. */
1064 if (color_indicator[C_ORPHAN].string != NULL
1065 || (color_indicator[C_MISSING].string != NULL
1066 && format == long_format))
1067 check_symlink_color = 1;
1070 unsigned j;
1071 static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE,
1072 SIGQUIT, SIGTERM, SIGTSTP };
1073 unsigned nsigs = sizeof sigs / sizeof *sigs;
1074 #ifdef SA_NOCLDSTOP
1075 struct sigaction oldact, newact;
1076 sigset_t caught_signals;
1078 sigemptyset (&caught_signals);
1079 for (j = 0; j < nsigs; j++)
1080 sigaddset (&caught_signals, sigs[j]);
1081 newact.sa_handler = sighandler;
1082 newact.sa_mask = caught_signals;
1083 newact.sa_flags = 0;
1084 #endif
1086 for (j = 0; j < nsigs; j++)
1088 int sig = sigs[j];
1089 #ifdef SA_NOCLDSTOP
1090 sigaction (sig, NULL, &oldact);
1091 if (oldact.sa_handler != SIG_IGN)
1092 sigaction (sig, &newact, NULL);
1093 #else
1094 if (signal (sig, SIG_IGN) != SIG_IGN)
1095 signal (sig, sighandler);
1096 #endif
1101 if (dereference == DEREF_UNDEFINED)
1102 dereference = ((immediate_dirs
1103 || indicator_style == classify
1104 || format == long_format)
1105 ? DEREF_NEVER
1106 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1108 /* When using -R, initialize a data structure we'll use to
1109 detect any directory cycles. */
1110 if (recursive)
1112 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1113 dev_ino_hash,
1114 dev_ino_compare,
1115 dev_ino_free);
1116 if (active_dir_set == NULL)
1117 xalloc_die ();
1119 obstack_init (&dev_ino_obstack);
1122 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1123 || format == long_format
1124 || dereference == DEREF_ALWAYS
1125 || print_block_size || print_inode;
1126 format_needs_type = (format_needs_stat == 0
1127 && (recursive || print_with_color
1128 || indicator_style != none));
1130 if (dired)
1132 obstack_init (&dired_obstack);
1133 obstack_init (&subdired_obstack);
1136 nfiles = 100;
1137 files = XMALLOC (struct fileinfo, nfiles);
1138 files_index = 0;
1140 clear_files ();
1142 n_files = argc - i;
1143 if (0 < n_files)
1144 dir_defaulted = 0;
1146 for (; i < argc; i++)
1148 gobble_file (argv[i], unknown, 1, "");
1151 if (dir_defaulted)
1153 if (immediate_dirs)
1154 gobble_file (".", directory, 1, "");
1155 else
1156 queue_directory (".", 0);
1159 if (files_index)
1161 sort_files ();
1162 if (!immediate_dirs)
1163 extract_dirs_from_files ("", 0);
1164 /* `files_index' might be zero now. */
1167 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1168 (and not pending_dirs->name) because there may be no markers in the queue
1169 at this point. A marker may be enqueued when extract_dirs_from_files is
1170 called with a non-empty string or via print_dir. */
1171 if (files_index)
1173 print_current_files ();
1174 if (pending_dirs)
1175 DIRED_PUTCHAR ('\n');
1177 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1178 print_dir_name = 0;
1180 while (pending_dirs)
1182 thispend = pending_dirs;
1183 pending_dirs = pending_dirs->next;
1185 if (LOOP_DETECT)
1187 if (thispend->name == NULL)
1189 /* thispend->name == NULL means this is a marker entry
1190 indicating we've finished processing the directory.
1191 Use its dev/ino numbers to remove the corresponding
1192 entry from the active_dir_set hash table. */
1193 struct dev_ino di = dev_ino_pop ();
1194 struct dev_ino *found = hash_delete (active_dir_set, &di);
1195 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1196 assert (found);
1197 dev_ino_free (found);
1198 free_pending_ent (thispend);
1199 continue;
1203 print_dir (thispend->name, thispend->realname);
1205 free_pending_ent (thispend);
1206 print_dir_name = 1;
1209 if (dired)
1211 /* No need to free these since we're about to exit. */
1212 dired_dump_obstack ("//DIRED//", &dired_obstack);
1213 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1214 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1215 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1218 /* Restore default color before exiting */
1219 if (print_with_color)
1221 put_indicator (&color_indicator[C_LEFT]);
1222 put_indicator (&color_indicator[C_RIGHT]);
1225 if (LOOP_DETECT)
1227 assert (hash_get_n_entries (active_dir_set) == 0);
1228 hash_free (active_dir_set);
1231 exit (exit_status);
1234 /* Set all the option flags according to the switches specified.
1235 Return the index of the first non-option argument. */
1237 static int
1238 decode_switches (int argc, char **argv)
1240 int c;
1241 char *time_style_option = 0;
1243 /* Record whether there is an option specifying sort type. */
1244 int sort_type_specified = 0;
1246 qmark_funny_chars = 0;
1248 /* initialize all switches to default settings */
1250 switch (ls_mode)
1252 case LS_MULTI_COL:
1253 /* This is for the `dir' program. */
1254 format = many_per_line;
1255 set_quoting_style (NULL, escape_quoting_style);
1256 break;
1258 case LS_LONG_FORMAT:
1259 /* This is for the `vdir' program. */
1260 format = long_format;
1261 set_quoting_style (NULL, escape_quoting_style);
1262 break;
1264 case LS_LS:
1265 /* This is for the `ls' program. */
1266 if (isatty (STDOUT_FILENO))
1268 format = many_per_line;
1269 /* See description of qmark_funny_chars, above. */
1270 qmark_funny_chars = 1;
1272 else
1274 format = one_per_line;
1275 qmark_funny_chars = 0;
1277 break;
1279 default:
1280 abort ();
1283 time_type = time_mtime;
1284 sort_type = sort_name;
1285 sort_reverse = 0;
1286 numeric_ids = 0;
1287 print_block_size = 0;
1288 indicator_style = none;
1289 print_inode = 0;
1290 dereference = DEREF_UNDEFINED;
1291 recursive = 0;
1292 immediate_dirs = 0;
1293 all_files = 0;
1294 really_all_files = 0;
1295 ignore_patterns = 0;
1297 /* FIXME: put this in a function. */
1299 char const *q_style = getenv ("QUOTING_STYLE");
1300 if (q_style)
1302 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1303 if (0 <= i)
1304 set_quoting_style (NULL, quoting_style_vals[i]);
1305 else
1306 error (0, 0,
1307 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1308 quotearg (q_style));
1313 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1314 human_output_opts = human_options (ls_block_size, false,
1315 &output_block_size);
1316 if (ls_block_size || getenv ("BLOCK_SIZE"))
1317 file_output_block_size = output_block_size;
1320 line_length = 80;
1322 char const *p = getenv ("COLUMNS");
1323 if (p && *p)
1325 long int tmp_long;
1326 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1327 && 0 < tmp_long && tmp_long <= INT_MAX)
1329 line_length = (int) tmp_long;
1331 else
1333 error (0, 0,
1334 _("ignoring invalid width in environment variable COLUMNS: %s"),
1335 quotearg (p));
1340 #ifdef TIOCGWINSZ
1342 struct winsize ws;
1344 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
1345 line_length = ws.ws_col;
1347 #endif
1349 /* Using the TABSIZE environment variable is not POSIX-approved.
1350 Ignore it when POSIXLY_CORRECT is set. */
1352 char const *p;
1353 tabsize = 8;
1354 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1356 long int tmp_long;
1357 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1358 && 0 <= tmp_long && tmp_long <= INT_MAX)
1360 tabsize = (int) tmp_long;
1362 else
1364 error (0, 0,
1365 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1366 quotearg (p));
1371 while ((c = getopt_long (argc, argv,
1372 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1373 long_options, NULL)) != -1)
1375 switch (c)
1377 case 0:
1378 break;
1380 case 'a':
1381 all_files = 1;
1382 really_all_files = 1;
1383 break;
1385 case 'b':
1386 set_quoting_style (NULL, escape_quoting_style);
1387 break;
1389 case 'c':
1390 time_type = time_ctime;
1391 break;
1393 case 'd':
1394 immediate_dirs = 1;
1395 break;
1397 case 'f':
1398 /* Same as enabling -a -U and disabling -l -s. */
1399 all_files = 1;
1400 really_all_files = 1;
1401 sort_type = sort_none;
1402 sort_type_specified = 1;
1403 /* disable -l */
1404 if (format == long_format)
1405 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1406 print_block_size = 0; /* disable -s */
1407 print_with_color = 0; /* disable --color */
1408 break;
1410 case 'g':
1411 format = long_format;
1412 print_owner = 0;
1413 break;
1415 case 'h':
1416 human_output_opts = human_autoscale | human_SI | human_base_1024;
1417 file_output_block_size = output_block_size = 1;
1418 break;
1420 case 'i':
1421 print_inode = 1;
1422 break;
1424 case 'k':
1425 human_output_opts = 0;
1426 file_output_block_size = output_block_size = 1024;
1427 break;
1429 case 'l':
1430 format = long_format;
1431 break;
1433 case 'm':
1434 format = with_commas;
1435 break;
1437 case 'n':
1438 numeric_ids = 1;
1439 format = long_format;
1440 break;
1442 case 'o': /* Just like -l, but don't display group info. */
1443 format = long_format;
1444 print_group = 0;
1445 break;
1447 case 'p':
1448 indicator_style = file_type;
1449 break;
1451 case 'q':
1452 qmark_funny_chars = 1;
1453 break;
1455 case 'r':
1456 sort_reverse = 1;
1457 break;
1459 case 's':
1460 print_block_size = 1;
1461 break;
1463 case 't':
1464 sort_type = sort_time;
1465 sort_type_specified = 1;
1466 break;
1468 case 'u':
1469 time_type = time_atime;
1470 break;
1472 case 'v':
1473 sort_type = sort_version;
1474 sort_type_specified = 1;
1475 break;
1477 case 'w':
1479 long int tmp_long;
1480 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1481 || tmp_long <= 0 || tmp_long > INT_MAX)
1482 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1483 quotearg (optarg));
1484 line_length = (int) tmp_long;
1485 break;
1488 case 'x':
1489 format = horizontal;
1490 break;
1492 case 'A':
1493 really_all_files = 0;
1494 all_files = 1;
1495 break;
1497 case 'B':
1498 add_ignore_pattern ("*~");
1499 add_ignore_pattern (".*~");
1500 break;
1502 case 'C':
1503 format = many_per_line;
1504 break;
1506 case 'D':
1507 dired = 1;
1508 break;
1510 case 'F':
1511 indicator_style = classify;
1512 break;
1514 case 'G': /* inhibit display of group info */
1515 print_group = 0;
1516 break;
1518 case 'H':
1519 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1520 break;
1522 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1523 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1524 break;
1526 case 'I':
1527 add_ignore_pattern (optarg);
1528 break;
1530 case 'L':
1531 dereference = DEREF_ALWAYS;
1532 break;
1534 case 'N':
1535 set_quoting_style (NULL, literal_quoting_style);
1536 break;
1538 case 'Q':
1539 set_quoting_style (NULL, c_quoting_style);
1540 break;
1542 case 'R':
1543 recursive = 1;
1544 break;
1546 case 'S':
1547 sort_type = sort_size;
1548 sort_type_specified = 1;
1549 break;
1551 case 'T':
1553 long int tmp_long;
1554 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1555 || tmp_long < 0 || tmp_long > INT_MAX)
1556 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1557 quotearg (optarg));
1558 tabsize = (int) tmp_long;
1559 break;
1562 case 'U':
1563 sort_type = sort_none;
1564 sort_type_specified = 1;
1565 break;
1567 case 'X':
1568 sort_type = sort_extension;
1569 sort_type_specified = 1;
1570 break;
1572 case '1':
1573 /* -1 has no effect after -l. */
1574 if (format != long_format)
1575 format = one_per_line;
1576 break;
1578 case AUTHOR_OPTION:
1579 print_author = true;
1580 break;
1582 case SORT_OPTION:
1583 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1584 sort_type_specified = 1;
1585 break;
1587 case TIME_OPTION:
1588 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1589 break;
1591 case FORMAT_OPTION:
1592 format = XARGMATCH ("--format", optarg, format_args, format_types);
1593 break;
1595 case FULL_TIME_OPTION:
1596 format = long_format;
1597 time_style_option = "full-iso";
1598 break;
1600 case COLOR_OPTION:
1602 int i;
1603 if (optarg)
1604 i = XARGMATCH ("--color", optarg, color_args, color_types);
1605 else
1606 /* Using --color with no argument is equivalent to using
1607 --color=always. */
1608 i = color_always;
1610 print_with_color = (i == color_always
1611 || (i == color_if_tty
1612 && isatty (STDOUT_FILENO)));
1614 if (print_with_color)
1616 /* Don't use TAB characters in output. Some terminal
1617 emulators can't handle the combination of tabs and
1618 color codes on the same line. */
1619 tabsize = 0;
1621 break;
1624 case INDICATOR_STYLE_OPTION:
1625 indicator_style = XARGMATCH ("--indicator-style", optarg,
1626 indicator_style_args,
1627 indicator_style_types);
1628 break;
1630 case QUOTING_STYLE_OPTION:
1631 set_quoting_style (NULL,
1632 XARGMATCH ("--quoting-style", optarg,
1633 quoting_style_args,
1634 quoting_style_vals));
1635 break;
1637 case TIME_STYLE_OPTION:
1638 time_style_option = optarg;
1639 break;
1641 case SHOW_CONTROL_CHARS_OPTION:
1642 qmark_funny_chars = 0;
1643 break;
1645 case BLOCK_SIZE_OPTION:
1646 human_output_opts = human_options (optarg, true, &output_block_size);
1647 file_output_block_size = output_block_size;
1648 break;
1650 case SI_OPTION:
1651 human_output_opts = human_autoscale | human_SI;
1652 file_output_block_size = output_block_size = 1;
1653 break;
1655 case_GETOPT_HELP_CHAR;
1657 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1659 default:
1660 usage (EXIT_FAILURE);
1664 filename_quoting_options = clone_quoting_options (NULL);
1665 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1666 set_char_quoting (filename_quoting_options, ' ', 1);
1667 if (indicator_style != none)
1669 char const *p;
1670 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1671 set_char_quoting (filename_quoting_options, *p, 1);
1674 dirname_quoting_options = clone_quoting_options (NULL);
1675 set_char_quoting (dirname_quoting_options, ':', 1);
1677 /* --dired is meaningful only with --format=long (-l).
1678 Otherwise, ignore it. FIXME: warn about this?
1679 Alternatively, make --dired imply --format=long? */
1680 if (dired && format != long_format)
1681 dired = 0;
1683 /* If -c or -u is specified and not -l (or any other option that implies -l),
1684 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1685 The behavior of ls when using either -c or -u but with neither -l nor -t
1686 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1687 sort by atime (this is the one that's not specified by the POSIX spec),
1688 -lu means show atime and sort by name, -lut means show atime and sort
1689 by atime. */
1691 if ((time_type == time_ctime || time_type == time_atime)
1692 && !sort_type_specified && format != long_format)
1694 sort_type = sort_time;
1697 if (format == long_format)
1699 char *style = time_style_option;
1700 static char const posix_prefix[] = "posix-";
1702 if (! style)
1703 if (! (style = getenv ("TIME_STYLE")))
1704 style = "posix-long-iso";
1706 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1708 if (! hard_locale (LC_TIME))
1709 return optind;
1710 style += sizeof posix_prefix - 1;
1713 if (*style == '+')
1715 char *p0 = style + 1;
1716 char *p1 = strchr (p0, '\n');
1717 if (! p1)
1718 p1 = p0;
1719 else
1721 if (strchr (p1 + 1, '\n'))
1722 error (EXIT_FAILURE, 0, _("invalid time style format %s"),
1723 quote (p0));
1724 *p1++ = '\0';
1726 long_time_format[0] = p0;
1727 long_time_format[1] = p1;
1729 else
1730 switch (XARGMATCH ("time style", style,
1731 time_style_args,
1732 time_style_types))
1734 case full_iso_time_style:
1735 long_time_format[0] = long_time_format[1] =
1736 "%Y-%m-%d %H:%M:%S.%N %z";
1737 break;
1739 case long_iso_time_style:
1740 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1741 break;
1743 case iso_time_style:
1744 long_time_format[0] = "%Y-%m-%d ";
1745 long_time_format[1] = "%m-%d %H:%M";
1746 break;
1748 case locale_time_style:
1749 if (hard_locale (LC_TIME))
1751 unsigned int i;
1752 for (i = 0; i < 2; i++)
1753 long_time_format[i] =
1754 dcgettext (NULL, long_time_format[i], LC_TIME);
1759 return optind;
1762 /* Parse a string as part of the LS_COLORS variable; this may involve
1763 decoding all kinds of escape characters. If equals_end is set an
1764 unescaped equal sign ends the string, otherwise only a : or \0
1765 does. Returns the number of characters output, or -1 on failure.
1767 The resulting string is *not* null-terminated, but may contain
1768 embedded nulls.
1770 Note that both dest and src are char **; on return they point to
1771 the first free byte after the array and the character that ended
1772 the input string, respectively. */
1774 static int
1775 get_funky_string (char **dest, const char **src, int equals_end)
1777 int num; /* For numerical codes */
1778 int count; /* Something to count with */
1779 enum {
1780 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1781 } state;
1782 const char *p;
1783 char *q;
1785 p = *src; /* We don't want to double-indirect */
1786 q = *dest; /* the whole darn time. */
1788 count = 0; /* No characters counted in yet. */
1789 num = 0;
1791 state = ST_GND; /* Start in ground state. */
1792 while (state < ST_END)
1794 switch (state)
1796 case ST_GND: /* Ground state (no escapes) */
1797 switch (*p)
1799 case ':':
1800 case '\0':
1801 state = ST_END; /* End of string */
1802 break;
1803 case '\\':
1804 state = ST_BACKSLASH; /* Backslash scape sequence */
1805 ++p;
1806 break;
1807 case '^':
1808 state = ST_CARET; /* Caret escape */
1809 ++p;
1810 break;
1811 case '=':
1812 if (equals_end)
1814 state = ST_END; /* End */
1815 break;
1817 /* else fall through */
1818 default:
1819 *(q++) = *(p++);
1820 ++count;
1821 break;
1823 break;
1825 case ST_BACKSLASH: /* Backslash escaped character */
1826 switch (*p)
1828 case '0':
1829 case '1':
1830 case '2':
1831 case '3':
1832 case '4':
1833 case '5':
1834 case '6':
1835 case '7':
1836 state = ST_OCTAL; /* Octal sequence */
1837 num = *p - '0';
1838 break;
1839 case 'x':
1840 case 'X':
1841 state = ST_HEX; /* Hex sequence */
1842 num = 0;
1843 break;
1844 case 'a': /* Bell */
1845 num = 7; /* Not all C compilers know what \a means */
1846 break;
1847 case 'b': /* Backspace */
1848 num = '\b';
1849 break;
1850 case 'e': /* Escape */
1851 num = 27;
1852 break;
1853 case 'f': /* Form feed */
1854 num = '\f';
1855 break;
1856 case 'n': /* Newline */
1857 num = '\n';
1858 break;
1859 case 'r': /* Carriage return */
1860 num = '\r';
1861 break;
1862 case 't': /* Tab */
1863 num = '\t';
1864 break;
1865 case 'v': /* Vtab */
1866 num = '\v';
1867 break;
1868 case '?': /* Delete */
1869 num = 127;
1870 break;
1871 case '_': /* Space */
1872 num = ' ';
1873 break;
1874 case '\0': /* End of string */
1875 state = ST_ERROR; /* Error! */
1876 break;
1877 default: /* Escaped character like \ ^ : = */
1878 num = *p;
1879 break;
1881 if (state == ST_BACKSLASH)
1883 *(q++) = num;
1884 ++count;
1885 state = ST_GND;
1887 ++p;
1888 break;
1890 case ST_OCTAL: /* Octal sequence */
1891 if (*p < '0' || *p > '7')
1893 *(q++) = num;
1894 ++count;
1895 state = ST_GND;
1897 else
1898 num = (num << 3) + (*(p++) - '0');
1899 break;
1901 case ST_HEX: /* Hex sequence */
1902 switch (*p)
1904 case '0':
1905 case '1':
1906 case '2':
1907 case '3':
1908 case '4':
1909 case '5':
1910 case '6':
1911 case '7':
1912 case '8':
1913 case '9':
1914 num = (num << 4) + (*(p++) - '0');
1915 break;
1916 case 'a':
1917 case 'b':
1918 case 'c':
1919 case 'd':
1920 case 'e':
1921 case 'f':
1922 num = (num << 4) + (*(p++) - 'a') + 10;
1923 break;
1924 case 'A':
1925 case 'B':
1926 case 'C':
1927 case 'D':
1928 case 'E':
1929 case 'F':
1930 num = (num << 4) + (*(p++) - 'A') + 10;
1931 break;
1932 default:
1933 *(q++) = num;
1934 ++count;
1935 state = ST_GND;
1936 break;
1938 break;
1940 case ST_CARET: /* Caret escape */
1941 state = ST_GND; /* Should be the next state... */
1942 if (*p >= '@' && *p <= '~')
1944 *(q++) = *(p++) & 037;
1945 ++count;
1947 else if (*p == '?')
1949 *(q++) = 127;
1950 ++count;
1952 else
1953 state = ST_ERROR;
1954 break;
1956 default:
1957 abort ();
1961 *dest = q;
1962 *src = p;
1964 return state == ST_ERROR ? -1 : count;
1967 static void
1968 parse_ls_color (void)
1970 const char *p; /* Pointer to character being parsed */
1971 char *buf; /* color_buf buffer pointer */
1972 int state; /* State of parser */
1973 int ind_no; /* Indicator number */
1974 char label[3]; /* Indicator label */
1975 struct color_ext_type *ext; /* Extension we are working on */
1977 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1978 return;
1980 ext = NULL;
1981 strcpy (label, "??");
1983 /* This is an overly conservative estimate, but any possible
1984 LS_COLORS string will *not* generate a color_buf longer than
1985 itself, so it is a safe way of allocating a buffer in
1986 advance. */
1987 buf = color_buf = xstrdup (p);
1989 state = 1;
1990 while (state > 0)
1992 switch (state)
1994 case 1: /* First label character */
1995 switch (*p)
1997 case ':':
1998 ++p;
1999 break;
2001 case '*':
2002 /* Allocate new extension block and add to head of
2003 linked list (this way a later definition will
2004 override an earlier one, which can be useful for
2005 having terminal-specific defs override global). */
2007 ext = XMALLOC (struct color_ext_type, 1);
2008 ext->next = color_ext_list;
2009 color_ext_list = ext;
2011 ++p;
2012 ext->ext.string = buf;
2014 state = (ext->ext.len =
2015 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
2016 break;
2018 case '\0':
2019 state = 0; /* Done! */
2020 break;
2022 default: /* Assume it is file type label */
2023 label[0] = *(p++);
2024 state = 2;
2025 break;
2027 break;
2029 case 2: /* Second label character */
2030 if (*p)
2032 label[1] = *(p++);
2033 state = 3;
2035 else
2036 state = -1; /* Error */
2037 break;
2039 case 3: /* Equal sign after indicator label */
2040 state = -1; /* Assume failure... */
2041 if (*(p++) == '=')/* It *should* be... */
2043 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2045 if (STREQ (label, indicator_name[ind_no]))
2047 color_indicator[ind_no].string = buf;
2048 state = ((color_indicator[ind_no].len =
2049 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
2050 break;
2053 if (state == -1)
2054 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2056 break;
2058 case 4: /* Equal sign after *.ext */
2059 if (*(p++) == '=')
2061 ext->seq.string = buf;
2062 state = (ext->seq.len =
2063 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
2065 else
2066 state = -1;
2067 break;
2071 if (state < 0)
2073 struct color_ext_type *e;
2074 struct color_ext_type *e2;
2076 error (0, 0,
2077 _("unparsable value for LS_COLORS environment variable"));
2078 free (color_buf);
2079 for (e = color_ext_list; e != NULL; /* empty */)
2081 e2 = e;
2082 e = e->next;
2083 free (e2);
2085 print_with_color = 0;
2088 if (color_indicator[C_LINK].len == 6
2089 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2090 color_symlink_as_referent = 1;
2093 /* Request that the directory named NAME have its contents listed later.
2094 If REALNAME is nonzero, it will be used instead of NAME when the
2095 directory name is printed. This allows symbolic links to directories
2096 to be treated as regular directories but still be listed under their
2097 real names. NAME == NULL is used to insert a marker entry for the
2098 directory named in REALNAME.
2099 If F is non-NULL, we use its dev/ino information to save
2100 a call to stat -- when doing a recursive (-R) traversal. */
2102 static void
2103 queue_directory (const char *name, const char *realname)
2105 struct pending *new;
2107 new = XMALLOC (struct pending, 1);
2108 new->realname = realname ? xstrdup (realname) : NULL;
2109 new->name = name ? xstrdup (name) : NULL;
2110 new->next = pending_dirs;
2111 pending_dirs = new;
2114 /* Read directory `name', and list the files in it.
2115 If `realname' is nonzero, print its name instead of `name';
2116 this is used for symbolic links to directories. */
2118 static void
2119 print_dir (const char *name, const char *realname)
2121 register DIR *dirp;
2122 register struct dirent *next;
2123 register uintmax_t total_blocks = 0;
2124 static int first = 1;
2126 errno = 0;
2127 dirp = opendir (name);
2128 if (!dirp)
2130 error (0, errno, "%s", quotearg_colon (name));
2131 exit_status = 1;
2132 return;
2135 if (LOOP_DETECT)
2137 struct stat dir_stat;
2138 int fd = dirfd (dirp);
2140 /* If dirfd failed, endure the overhead of using stat. */
2141 if ((0 <= fd
2142 ? fstat (fd, &dir_stat)
2143 : stat (name, &dir_stat)) < 0)
2145 error (0, errno, _("cannot determine device and inode of %s"),
2146 quotearg_colon (name));
2147 exit_status = 1;
2148 return;
2151 /* If we've already visited this dev/inode pair, warn that
2152 we've found a loop, and do not process this directory. */
2153 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2155 error (0, 0, _("not listing already-listed directory: %s"),
2156 quotearg_colon (name));
2157 return;
2160 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2163 /* Read the directory entries, and insert the subfiles into the `files'
2164 table. */
2166 clear_files ();
2168 while (1)
2170 /* Set errno to zero so we can distinguish between a readdir failure
2171 and when readdir simply finds that there are no more entries. */
2172 errno = 0;
2173 if ((next = readdir (dirp)) == NULL)
2175 if (errno)
2177 /* Save/restore errno across closedir call. */
2178 int e = errno;
2179 closedir (dirp);
2180 errno = e;
2182 /* Arrange to give a diagnostic after exiting this loop. */
2183 dirp = NULL;
2185 break;
2188 if (file_interesting (next))
2190 enum filetype type = unknown;
2192 #if HAVE_STRUCT_DIRENT_D_TYPE
2193 if (next->d_type == DT_BLK
2194 || next->d_type == DT_CHR
2195 || next->d_type == DT_DIR
2196 || next->d_type == DT_FIFO
2197 || next->d_type == DT_LNK
2198 || next->d_type == DT_REG
2199 || next->d_type == DT_SOCK)
2200 type = next->d_type;
2201 #endif
2202 total_blocks += gobble_file (next->d_name, type, 0, name);
2206 if (dirp == NULL || CLOSEDIR (dirp))
2208 error (0, errno, _("reading directory %s"), quotearg_colon (name));
2209 exit_status = 1;
2210 /* Don't return; print whatever we got. */
2213 /* Sort the directory contents. */
2214 sort_files ();
2216 /* If any member files are subdirectories, perhaps they should have their
2217 contents listed rather than being mentioned here as files. */
2219 if (recursive)
2220 extract_dirs_from_files (name, 1);
2222 if (recursive || print_dir_name)
2224 if (!first)
2225 DIRED_PUTCHAR ('\n');
2226 first = 0;
2227 DIRED_INDENT ();
2228 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2229 dired_pos += quote_name (stdout, realname ? realname : name,
2230 dirname_quoting_options, NULL);
2231 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2232 DIRED_FPUTS_LITERAL (":\n", stdout);
2235 if (format == long_format || print_block_size)
2237 const char *p;
2238 char buf[LONGEST_HUMAN_READABLE + 1];
2240 DIRED_INDENT ();
2241 p = _("total");
2242 DIRED_FPUTS (p, stdout, strlen (p));
2243 DIRED_PUTCHAR (' ');
2244 p = human_readable (total_blocks, buf, human_output_opts,
2245 ST_NBLOCKSIZE, output_block_size);
2246 DIRED_FPUTS (p, stdout, strlen (p));
2247 DIRED_PUTCHAR ('\n');
2250 if (files_index)
2251 print_current_files ();
2254 /* Add `pattern' to the list of patterns for which files that match are
2255 not listed. */
2257 static void
2258 add_ignore_pattern (const char *pattern)
2260 register struct ignore_pattern *ignore;
2262 ignore = XMALLOC (struct ignore_pattern, 1);
2263 ignore->pattern = pattern;
2264 /* Add it to the head of the linked list. */
2265 ignore->next = ignore_patterns;
2266 ignore_patterns = ignore;
2269 /* Return nonzero if the file in `next' should be listed. */
2271 static int
2272 file_interesting (const struct dirent *next)
2274 register struct ignore_pattern *ignore;
2276 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2277 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2278 return 0;
2280 if (really_all_files
2281 || next->d_name[0] != '.'
2282 || (all_files
2283 && next->d_name[1] != '\0'
2284 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2285 return 1;
2287 return 0;
2290 /* Enter and remove entries in the table `files'. */
2292 /* Empty the table of files. */
2294 static void
2295 clear_files (void)
2297 register int i;
2299 for (i = 0; i < files_index; i++)
2301 free (files[i].name);
2302 if (files[i].linkname)
2303 free (files[i].linkname);
2306 files_index = 0;
2307 block_size_size = 4;
2310 /* Add a file to the current table of files.
2311 Verify that the file exists, and print an error message if it does not.
2312 Return the number of blocks that the file occupies. */
2314 static uintmax_t
2315 gobble_file (const char *name, enum filetype type, int explicit_arg,
2316 const char *dirname)
2318 register uintmax_t blocks;
2319 register char *path;
2321 if (files_index == nfiles)
2323 nfiles *= 2;
2324 files = XREALLOC (files, struct fileinfo, nfiles);
2327 files[files_index].linkname = 0;
2328 files[files_index].linkmode = 0;
2329 files[files_index].linkok = 0;
2331 if (explicit_arg
2332 || format_needs_stat
2333 || (format_needs_type
2334 && (type == unknown
2336 /* FIXME: remove this disjunct.
2337 I don't think we care about symlinks here, but for now
2338 this won't make a big performance difference. */
2339 || type == symbolic_link
2341 /* --indicator-style=classify (aka -F)
2342 requires that we stat each regular file
2343 to see if it's executable. */
2344 || (type == normal && (indicator_style == classify
2345 /* This is so that --color ends up
2346 highlighting files with the executable
2347 bit set even when options like -F are
2348 not specified. */
2349 || print_with_color)))))
2352 /* `path' is the absolute pathname of this file. */
2353 int err;
2355 if (name[0] == '/' || dirname[0] == 0)
2356 path = (char *) name;
2357 else
2359 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
2360 attach (path, dirname, name);
2363 switch (dereference)
2365 case DEREF_ALWAYS:
2366 err = stat (path, &files[files_index].stat);
2367 break;
2369 case DEREF_COMMAND_LINE_ARGUMENTS:
2370 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2371 if (explicit_arg)
2373 int need_lstat;
2374 err = stat (path, &files[files_index].stat);
2376 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2377 break;
2379 need_lstat = (err < 0
2380 ? errno == ENOENT
2381 : ! S_ISDIR (files[files_index].stat.st_mode));
2382 if (!need_lstat)
2383 break;
2385 /* stat failed because of ENOENT, maybe indicating a dangling
2386 symlink. Or stat succeeded, PATH does not refer to a
2387 directory, and --dereference-command-line-symlink-to-dir is
2388 in effect. Fall through so that we call lstat instead. */
2391 default: /* DEREF_NEVER */
2392 err = lstat (path, &files[files_index].stat);
2393 break;
2396 if (err < 0)
2398 error (0, errno, "%s", quotearg_colon (path));
2399 exit_status = 1;
2400 return 0;
2403 #if HAVE_ACL
2404 if (format == long_format)
2406 int n = file_has_acl (path, &files[files_index].stat);
2407 files[files_index].have_acl = (0 < n);
2408 if (n < 0)
2409 error (0, errno, "%s", quotearg_colon (path));
2411 #endif
2413 if (S_ISLNK (files[files_index].stat.st_mode)
2414 && (format == long_format || check_symlink_color))
2416 char *linkpath;
2417 struct stat linkstats;
2419 get_link_name (path, &files[files_index]);
2420 linkpath = make_link_path (path, files[files_index].linkname);
2422 /* Avoid following symbolic links when possible, ie, when
2423 they won't be traced and when no indicator is needed. */
2424 if (linkpath
2425 && (indicator_style != none || check_symlink_color)
2426 && stat (linkpath, &linkstats) == 0)
2428 files[files_index].linkok = 1;
2430 /* Symbolic links to directories that are mentioned on the
2431 command line are automatically traced if not being
2432 listed as files. */
2433 if (!explicit_arg || format == long_format
2434 || !S_ISDIR (linkstats.st_mode))
2436 /* Get the linked-to file's mode for the filetype indicator
2437 in long listings. */
2438 files[files_index].linkmode = linkstats.st_mode;
2439 files[files_index].linkok = 1;
2442 if (linkpath)
2443 free (linkpath);
2446 if (S_ISLNK (files[files_index].stat.st_mode))
2447 files[files_index].filetype = symbolic_link;
2448 else if (S_ISDIR (files[files_index].stat.st_mode))
2450 if (explicit_arg && !immediate_dirs)
2451 files[files_index].filetype = arg_directory;
2452 else
2453 files[files_index].filetype = directory;
2455 else
2456 files[files_index].filetype = normal;
2458 blocks = ST_NBLOCKS (files[files_index].stat);
2460 char buf[LONGEST_HUMAN_READABLE + 1];
2461 int len = strlen (human_readable (blocks, buf, human_output_opts,
2462 ST_NBLOCKSIZE, output_block_size));
2463 if (block_size_size < len)
2464 block_size_size = len < 7 ? len : 7;
2467 else
2469 files[files_index].filetype = type;
2470 #if HAVE_STRUCT_DIRENT_D_TYPE
2471 files[files_index].stat.st_mode = DTTOIF (type);
2472 #endif
2473 blocks = 0;
2476 files[files_index].name = xstrdup (name);
2477 files_index++;
2479 return blocks;
2482 #ifdef S_ISLNK
2484 /* Put the name of the file that `filename' is a symbolic link to
2485 into the `linkname' field of `f'. */
2487 static void
2488 get_link_name (const char *filename, struct fileinfo *f)
2490 f->linkname = xreadlink (filename);
2491 if (f->linkname == NULL)
2493 error (0, errno, _("cannot read symbolic link %s"),
2494 quotearg_colon (filename));
2495 exit_status = 1;
2499 /* If `linkname' is a relative path and `path' contains one or more
2500 leading directories, return `linkname' with those directories
2501 prepended; otherwise, return a copy of `linkname'.
2502 If `linkname' is zero, return zero. */
2504 static char *
2505 make_link_path (const char *path, const char *linkname)
2507 char *linkbuf;
2508 size_t bufsiz;
2510 if (linkname == 0)
2511 return 0;
2513 if (*linkname == '/')
2514 return xstrdup (linkname);
2516 /* The link is to a relative path. Prepend any leading path
2517 in `path' to the link name. */
2518 linkbuf = strrchr (path, '/');
2519 if (linkbuf == 0)
2520 return xstrdup (linkname);
2522 bufsiz = linkbuf - path + 1;
2523 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2524 strncpy (linkbuf, path, bufsiz);
2525 strcpy (linkbuf + bufsiz, linkname);
2526 return linkbuf;
2528 #endif
2530 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2531 This is so we don't try to recurse on `././././. ...' */
2533 static int
2534 basename_is_dot_or_dotdot (const char *name)
2536 char const *base = base_name (name);
2537 return DOT_OR_DOTDOT (base);
2540 /* Remove any entries from `files' that are for directories,
2541 and queue them to be listed as directories instead.
2542 `dirname' is the prefix to prepend to each dirname
2543 to make it correct relative to ls's working dir.
2544 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2545 This is desirable when processing directories recursively. */
2547 static void
2548 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2550 register int i, j;
2552 if (*dirname && LOOP_DETECT)
2554 /* Insert a marker entry first. When we dequeue this marker entry,
2555 we'll know that DIRNAME has been processed and may be removed
2556 from the set of active directories. */
2557 queue_directory (NULL, dirname);
2560 /* Queue the directories last one first, because queueing reverses the
2561 order. */
2562 for (i = files_index - 1; i >= 0; i--)
2563 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2564 && (!ignore_dot_and_dot_dot
2565 || !basename_is_dot_or_dotdot (files[i].name)))
2567 if (files[i].name[0] == '/' || dirname[0] == 0)
2569 queue_directory (files[i].name, files[i].linkname);
2571 else
2573 char *path = path_concat (dirname, files[i].name, NULL);
2574 queue_directory (path, files[i].linkname);
2575 free (path);
2577 if (files[i].filetype == arg_directory)
2578 free (files[i].name);
2581 /* Now delete the directories from the table, compacting all the remaining
2582 entries. */
2584 for (i = 0, j = 0; i < files_index; i++)
2585 if (files[i].filetype != arg_directory)
2586 files[j++] = files[i];
2587 files_index = j;
2590 /* Use strcoll to compare strings in this locale. If an error occurs,
2591 report an error and longjmp to failed_strcoll. */
2593 static jmp_buf failed_strcoll;
2595 static int
2596 xstrcoll (char const *a, char const *b)
2598 int diff;
2599 errno = 0;
2600 diff = strcoll (a, b);
2601 if (errno)
2603 error (0, errno, _("cannot compare file names %s and %s"),
2604 quote_n (0, a), quote_n (1, b));
2605 exit_status = 1;
2606 longjmp (failed_strcoll, 1);
2608 return diff;
2611 /* Comparison routines for sorting the files. */
2613 typedef void const *V;
2615 static inline int
2616 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2617 int (*cmp) (char const *, char const *))
2619 int diff = CTIME_CMP (b->stat, a->stat);
2620 return diff ? diff : cmp (a->name, b->name);
2622 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2623 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2624 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2625 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2627 static inline int
2628 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2629 int (*cmp) (char const *, char const *))
2631 int diff = MTIME_CMP (b->stat, a->stat);
2632 return diff ? diff : cmp (a->name, b->name);
2634 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2635 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2636 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2637 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2639 static inline int
2640 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2641 int (*cmp) (char const *, char const *))
2643 int diff = ATIME_CMP (b->stat, a->stat);
2644 return diff ? diff : cmp (a->name, b->name);
2646 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2647 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2648 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2649 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2651 static inline int
2652 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2653 int (*cmp) (char const *, char const *))
2655 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2656 return diff ? diff : cmp (a->name, b->name);
2658 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2659 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2660 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2661 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2663 static inline int
2664 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2666 return strverscmp (a->name, b->name);
2668 static int compare_version (V a, V b) { return cmp_version (a, b); }
2669 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2671 static inline int
2672 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2673 int (*cmp) (char const *, char const *))
2675 return cmp (a->name, b->name);
2677 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2678 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2679 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2680 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2682 /* Compare file extensions. Files with no extension are `smallest'.
2683 If extensions are the same, compare by filenames instead. */
2685 static inline int
2686 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2687 int (*cmp) (char const *, char const *))
2689 char const *base1 = strrchr (a->name, '.');
2690 char const *base2 = strrchr (b->name, '.');
2691 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2692 return diff ? diff : cmp (a->name, b->name);
2694 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2695 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2696 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2697 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2699 /* Sort the files now in the table. */
2701 static void
2702 sort_files (void)
2704 int (*func) (V, V);
2706 switch (sort_type)
2708 case sort_none:
2709 return;
2710 case sort_time:
2711 switch (time_type)
2713 case time_ctime:
2714 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2715 break;
2716 case time_mtime:
2717 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2718 break;
2719 case time_atime:
2720 func = sort_reverse ? rev_cmp_atime : compare_atime;
2721 break;
2722 default:
2723 abort ();
2725 break;
2726 case sort_name:
2727 func = sort_reverse ? rev_cmp_name : compare_name;
2728 break;
2729 case sort_extension:
2730 func = sort_reverse ? rev_cmp_extension : compare_extension;
2731 break;
2732 case sort_size:
2733 func = sort_reverse ? rev_cmp_size : compare_size;
2734 break;
2735 case sort_version:
2736 func = sort_reverse ? rev_cmp_version : compare_version;
2737 break;
2738 default:
2739 abort ();
2742 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2743 ignore strcoll failures, as a failing strcoll might be a
2744 comparison function that is not a total order, and if we ignored
2745 the failure this might cause qsort to dump core. */
2747 if (setjmp (failed_strcoll))
2749 switch (sort_type)
2751 case sort_time:
2752 switch (time_type)
2754 case time_ctime:
2755 func = sort_reverse ? rev_str_ctime : compstr_ctime;
2756 break;
2757 case time_mtime:
2758 func = sort_reverse ? rev_str_mtime : compstr_mtime;
2759 break;
2760 case time_atime:
2761 func = sort_reverse ? rev_str_atime : compstr_atime;
2762 break;
2763 default:
2764 abort ();
2766 break;
2767 case sort_name:
2768 func = sort_reverse ? rev_str_name : compstr_name;
2769 break;
2770 case sort_extension:
2771 func = sort_reverse ? rev_str_extension : compstr_extension;
2772 break;
2773 case sort_size:
2774 func = sort_reverse ? rev_str_size : compstr_size;
2775 break;
2776 default:
2777 abort ();
2781 qsort (files, files_index, sizeof (struct fileinfo), func);
2784 /* List all the files now in the table. */
2786 static void
2787 print_current_files (void)
2789 register int i;
2791 switch (format)
2793 case one_per_line:
2794 for (i = 0; i < files_index; i++)
2796 print_file_name_and_frills (files + i);
2797 putchar ('\n');
2799 break;
2801 case many_per_line:
2802 init_column_info ();
2803 print_many_per_line ();
2804 break;
2806 case horizontal:
2807 init_column_info ();
2808 print_horizontal ();
2809 break;
2811 case with_commas:
2812 print_with_commas ();
2813 break;
2815 case long_format:
2816 for (i = 0; i < files_index; i++)
2818 print_long_format (files + i);
2819 DIRED_PUTCHAR ('\n');
2821 break;
2825 /* Return the expected number of columns in a long-format time stamp,
2826 or zero if it cannot be calculated. */
2828 static int
2829 long_time_expected_width (void)
2831 static int width = -1;
2833 if (width < 0)
2835 time_t epoch = 0;
2836 struct tm const *tm = localtime (&epoch);
2837 char const *fmt = long_time_format[0];
2838 char initbuf[100];
2839 char *buf = initbuf;
2840 size_t bufsize = sizeof initbuf;
2841 size_t len;
2843 for (;;)
2845 *buf = '\1';
2846 len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2847 if (len || ! *buf)
2848 break;
2849 buf = alloca (bufsize *= 2);
2852 width = mbsnwidth (buf, len, 0);
2853 if (width < 0)
2854 width = 0;
2857 return width;
2860 /* Get the current time. */
2862 static void
2863 get_current_time (void)
2865 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2867 struct timespec timespec;
2868 if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
2870 current_time = timespec.tv_sec;
2871 current_time_ns = timespec.tv_nsec;
2872 return;
2875 #endif
2877 /* The clock does not have nanosecond resolution, so get the maximum
2878 possible value for the current time that is consistent with the
2879 reported clock. That way, files are not considered to be in the
2880 future merely because their time stamps have higher resolution
2881 than the clock resolution. */
2883 #if HAVE_GETTIMEOFDAY
2885 struct timeval timeval;
2886 if (gettimeofday (&timeval, NULL) == 0)
2888 current_time = timeval.tv_sec;
2889 current_time_ns = timeval.tv_usec * 1000 + 999;
2890 return;
2893 #endif
2895 current_time = time (NULL);
2896 current_time_ns = 999999999;
2899 /* Format into BUFFER the name or id of the user with id U. Return
2900 the length of the formatted buffer, not counting the terminating
2901 null. */
2903 static size_t
2904 format_user (char *buffer, uid_t u)
2906 char const *name = (numeric_ids ? NULL : getuser (u));
2907 if (name)
2908 sprintf (buffer, "%-8s ", name);
2909 else
2910 sprintf (buffer, "%-8lu ", (unsigned long) u);
2911 return strlen (buffer);
2914 /* Print information about F in long format. */
2916 static void
2917 print_long_format (const struct fileinfo *f)
2919 char modebuf[12];
2920 char init_bigbuf
2921 [LONGEST_HUMAN_READABLE + 1 /* inode */
2922 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
2923 + sizeof (modebuf) - 1 + 1 /* mode string */
2924 + LONGEST_HUMAN_READABLE + 1 /* st_nlink */
2925 + ID_LENGTH_MAX + 1 /* owner name */
2926 + ID_LENGTH_MAX + 1 /* group name */
2927 + ID_LENGTH_MAX + 1 /* author name */
2928 + LONGEST_HUMAN_READABLE + 1 /* major device number */
2929 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
2930 + 35 + 1 /* usual length of time/date -- may be longer; see below */
2932 char *buf = init_bigbuf;
2933 size_t bufsize = sizeof (init_bigbuf);
2934 size_t s;
2935 char *p;
2936 time_t when;
2937 int when_ns IF_LINT (= 0);
2938 struct tm *when_local;
2940 /* Compute mode string. On most systems, it's based on st_mode.
2941 On systems with migration (via the stat.st_dm_mode field), use
2942 the file's migrated status. */
2943 mode_string (ST_DM_MODE (f->stat), modebuf);
2945 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2946 modebuf[11] = '\0';
2948 switch (time_type)
2950 case time_ctime:
2951 when = f->stat.st_ctime;
2952 when_ns = TIMESPEC_NS (f->stat.st_ctim);
2953 break;
2954 case time_mtime:
2955 when = f->stat.st_mtime;
2956 when_ns = TIMESPEC_NS (f->stat.st_mtim);
2957 break;
2958 case time_atime:
2959 when = f->stat.st_atime;
2960 when_ns = TIMESPEC_NS (f->stat.st_atim);
2961 break;
2964 p = buf;
2966 if (print_inode)
2968 char hbuf[LONGEST_HUMAN_READABLE + 1];
2969 sprintf (p, "%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, hbuf));
2970 p += strlen (p);
2973 if (print_block_size)
2975 char hbuf[LONGEST_HUMAN_READABLE + 1];
2976 sprintf (p, "%*s ", block_size_size,
2977 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
2978 ST_NBLOCKSIZE, output_block_size));
2979 p += strlen (p);
2982 /* The last byte of the mode string is the POSIX
2983 "optional alternate access method flag". */
2984 sprintf (p, "%s %3lu ", modebuf, (unsigned long) f->stat.st_nlink);
2985 p += strlen (p);
2987 if (print_owner)
2988 p += format_user (p, f->stat.st_uid);
2990 if (print_group)
2992 char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2993 if (group_name)
2994 sprintf (p, "%-8s ", group_name);
2995 else
2996 sprintf (p, "%-8lu ", (unsigned long) f->stat.st_gid);
2997 p += strlen (p);
3000 if (print_author)
3001 p += format_user (p, f->stat.st_author);
3003 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3004 sprintf (p, "%3lu, %3lu ",
3005 (unsigned long) major (f->stat.st_rdev),
3006 (unsigned long) minor (f->stat.st_rdev));
3007 else
3009 char hbuf[LONGEST_HUMAN_READABLE + 1];
3010 uintmax_t size = f->stat.st_size;
3012 /* POSIX requires that the size be printed without a sign, even
3013 when negative. Assume the typical case where negative sizes
3014 are actually positive values that have wrapped around. */
3015 size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3017 sprintf (p, "%8s ",
3018 human_readable (size, hbuf, human_output_opts,
3019 1, file_output_block_size));
3022 p += strlen (p);
3024 if ((when_local = localtime (&when)))
3026 time_t six_months_ago;
3027 int recent;
3028 char const *fmt;
3030 /* If the file appears to be in the future, update the current
3031 time, in case the file happens to have been modified since
3032 the last time we checked the clock. */
3033 if (current_time < when
3034 || (current_time == when && current_time_ns < when_ns))
3036 /* Note that get_current_time calls gettimeofday which, on some non-
3037 compliant systems, clobbers the buffer used for localtime's result.
3038 But it's ok here, because we use a gettimeofday wrapper that
3039 saves and restores the buffer around the gettimeofday call. */
3040 get_current_time ();
3043 /* Consider a time to be recent if it is within the past six
3044 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3045 31556952 seconds on the average. Write this value as an
3046 integer constant to avoid floating point hassles. */
3047 six_months_ago = current_time - 31556952 / 2;
3048 recent = (six_months_ago <= when
3049 && (when < current_time
3050 || (when == current_time && when_ns <= current_time_ns)));
3051 fmt = long_time_format[recent];
3053 for (;;)
3055 char *newbuf;
3056 *p = '\1';
3057 s = nstrftime (p, buf + bufsize - p - 1, fmt,
3058 when_local, 0, when_ns);
3059 if (s || ! *p)
3060 break;
3061 newbuf = alloca (bufsize *= 2);
3062 memcpy (newbuf, buf, p - buf);
3063 p = newbuf + (p - buf);
3064 buf = newbuf;
3067 p += s;
3068 *p++ = ' ';
3070 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3071 *p = '\0';
3073 else
3075 /* The time cannot be represented as a local time;
3076 print it as a huge integer number of seconds. */
3077 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3078 sprintf (p, "%*s ", long_time_expected_width (),
3079 (TYPE_SIGNED (time_t)
3080 ? imaxtostr (when, hbuf)
3081 : umaxtostr (when, hbuf)));
3082 p += strlen (p);
3085 DIRED_INDENT ();
3086 DIRED_FPUTS (buf, stdout, p - buf);
3087 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3088 &dired_obstack);
3090 if (f->filetype == symbolic_link)
3092 if (f->linkname)
3094 DIRED_FPUTS_LITERAL (" -> ", stdout);
3095 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3096 NULL);
3097 if (indicator_style != none)
3098 print_type_indicator (f->linkmode);
3101 else if (indicator_style != none)
3102 print_type_indicator (f->stat.st_mode);
3105 /* Output to OUT a quoted representation of the file name NAME,
3106 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3107 Store the number of screen columns occupied by NAME's quoted
3108 representation into WIDTH, if non-NULL. Return the number of bytes
3109 produced. */
3111 static size_t
3112 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3113 size_t *width)
3115 char smallbuf[BUFSIZ];
3116 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3117 char *buf;
3118 size_t displayed_width IF_LINT (= 0);
3120 if (len < sizeof smallbuf)
3121 buf = smallbuf;
3122 else
3124 buf = (char *) alloca (len + 1);
3125 quotearg_buffer (buf, len + 1, name, -1, options);
3128 if (qmark_funny_chars)
3130 #if HAVE_MBRTOWC
3131 if (MB_CUR_MAX > 1)
3133 char const *p = buf;
3134 char const *plimit = buf + len;
3135 char *q = buf;
3136 displayed_width = 0;
3138 while (p < plimit)
3139 switch (*p)
3141 case ' ': case '!': case '"': case '#': case '%':
3142 case '&': case '\'': case '(': case ')': case '*':
3143 case '+': case ',': case '-': case '.': case '/':
3144 case '0': case '1': case '2': case '3': case '4':
3145 case '5': case '6': case '7': case '8': case '9':
3146 case ':': case ';': case '<': case '=': case '>':
3147 case '?':
3148 case 'A': case 'B': case 'C': case 'D': case 'E':
3149 case 'F': case 'G': case 'H': case 'I': case 'J':
3150 case 'K': case 'L': case 'M': case 'N': case 'O':
3151 case 'P': case 'Q': case 'R': case 'S': case 'T':
3152 case 'U': case 'V': case 'W': case 'X': case 'Y':
3153 case 'Z':
3154 case '[': case '\\': case ']': case '^': case '_':
3155 case 'a': case 'b': case 'c': case 'd': case 'e':
3156 case 'f': case 'g': case 'h': case 'i': case 'j':
3157 case 'k': case 'l': case 'm': case 'n': case 'o':
3158 case 'p': case 'q': case 'r': case 's': case 't':
3159 case 'u': case 'v': case 'w': case 'x': case 'y':
3160 case 'z': case '{': case '|': case '}': case '~':
3161 /* These characters are printable ASCII characters. */
3162 *q++ = *p++;
3163 displayed_width += 1;
3164 break;
3165 default:
3166 /* If we have a multibyte sequence, copy it until we
3167 reach its end, replacing each non-printable multibyte
3168 character with a single question mark. */
3170 mbstate_t mbstate;
3171 memset (&mbstate, 0, sizeof mbstate);
3174 wchar_t wc;
3175 size_t bytes;
3176 int w;
3178 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3180 if (bytes == (size_t) -1)
3182 /* An invalid multibyte sequence was
3183 encountered. Skip one input byte, and
3184 put a question mark. */
3185 p++;
3186 *q++ = '?';
3187 displayed_width += 1;
3188 break;
3191 if (bytes == (size_t) -2)
3193 /* An incomplete multibyte character
3194 at the end. Replace it entirely with
3195 a question mark. */
3196 p = plimit;
3197 *q++ = '?';
3198 displayed_width += 1;
3199 break;
3202 if (bytes == 0)
3203 /* A null wide character was encountered. */
3204 bytes = 1;
3206 w = wcwidth (wc);
3207 if (w >= 0)
3209 /* A printable multibyte character.
3210 Keep it. */
3211 for (; bytes > 0; --bytes)
3212 *q++ = *p++;
3213 displayed_width += w;
3215 else
3217 /* An unprintable multibyte character.
3218 Replace it entirely with a question
3219 mark. */
3220 p += bytes;
3221 *q++ = '?';
3222 displayed_width += 1;
3225 while (! mbsinit (&mbstate));
3227 break;
3230 /* The buffer may have shrunk. */
3231 len = q - buf;
3233 else
3234 #endif
3236 char *p = buf;
3237 char const *plimit = buf + len;
3239 while (p < plimit)
3241 if (! ISPRINT ((unsigned char) *p))
3242 *p = '?';
3243 p++;
3245 displayed_width = len;
3248 else if (width != NULL)
3250 #if HAVE_MBRTOWC
3251 if (MB_CUR_MAX > 1)
3252 displayed_width = mbsnwidth (buf, len, 0);
3253 else
3254 #endif
3256 char const *p = buf;
3257 char const *plimit = buf + len;
3259 displayed_width = 0;
3260 while (p < plimit)
3262 if (ISPRINT ((unsigned char) *p))
3263 displayed_width++;
3264 p++;
3269 if (out != NULL)
3270 fwrite (buf, 1, len, out);
3271 if (width != NULL)
3272 *width = displayed_width;
3273 return len;
3276 static void
3277 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3278 struct obstack *stack)
3280 if (print_with_color)
3281 print_color_indicator (p, mode, linkok);
3283 if (stack)
3284 PUSH_CURRENT_DIRED_POS (stack);
3286 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3288 if (stack)
3289 PUSH_CURRENT_DIRED_POS (stack);
3291 if (print_with_color)
3292 prep_non_filename_text ();
3295 static void
3296 prep_non_filename_text (void)
3298 if (color_indicator[C_END].string != NULL)
3299 put_indicator (&color_indicator[C_END]);
3300 else
3302 put_indicator (&color_indicator[C_LEFT]);
3303 put_indicator (&color_indicator[C_NORM]);
3304 put_indicator (&color_indicator[C_RIGHT]);
3308 /* Print the file name of `f' with appropriate quoting.
3309 Also print file size, inode number, and filetype indicator character,
3310 as requested by switches. */
3312 static void
3313 print_file_name_and_frills (const struct fileinfo *f)
3315 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3317 if (print_inode)
3318 printf ("%*s ", INODE_DIGITS, umaxtostr (f->stat.st_ino, buf));
3320 if (print_block_size)
3321 printf ("%*s ", block_size_size,
3322 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3323 ST_NBLOCKSIZE, output_block_size));
3325 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3327 if (indicator_style != none)
3328 print_type_indicator (f->stat.st_mode);
3331 static void
3332 print_type_indicator (mode_t mode)
3334 int c;
3336 if (S_ISREG (mode))
3338 if (indicator_style == classify && (mode & S_IXUGO))
3339 c ='*';
3340 else
3341 c = 0;
3343 else
3345 if (S_ISDIR (mode))
3346 c = '/';
3347 else if (S_ISLNK (mode))
3348 c = '@';
3349 else if (S_ISFIFO (mode))
3350 c = '|';
3351 else if (S_ISSOCK (mode))
3352 c = '=';
3353 else if (S_ISDOOR (mode))
3354 c = '>';
3355 else
3356 c = 0;
3359 if (c)
3360 DIRED_PUTCHAR (c);
3363 static void
3364 print_color_indicator (const char *name, mode_t mode, int linkok)
3366 int type = C_FILE;
3367 struct color_ext_type *ext; /* Color extension */
3368 size_t len; /* Length of name */
3370 /* Is this a nonexistent file? If so, linkok == -1. */
3372 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3374 ext = NULL;
3375 type = C_MISSING;
3377 else
3379 if (S_ISDIR (mode))
3380 type = C_DIR;
3381 else if (S_ISLNK (mode))
3382 type = ((!linkok && color_indicator[C_ORPHAN].string)
3383 ? C_ORPHAN : C_LINK);
3384 else if (S_ISFIFO (mode))
3385 type = C_FIFO;
3386 else if (S_ISSOCK (mode))
3387 type = C_SOCK;
3388 else if (S_ISBLK (mode))
3389 type = C_BLK;
3390 else if (S_ISCHR (mode))
3391 type = C_CHR;
3392 else if (S_ISDOOR (mode))
3393 type = C_DOOR;
3395 if (type == C_FILE && (mode & S_IXUGO) != 0)
3396 type = C_EXEC;
3398 /* Check the file's suffix only if still classified as C_FILE. */
3399 ext = NULL;
3400 if (type == C_FILE)
3402 /* Test if NAME has a recognized suffix. */
3404 len = strlen (name);
3405 name += len; /* Pointer to final \0. */
3406 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3408 if ((size_t) ext->ext.len <= len
3409 && strncmp (name - ext->ext.len, ext->ext.string,
3410 ext->ext.len) == 0)
3411 break;
3416 put_indicator (&color_indicator[C_LEFT]);
3417 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3418 put_indicator (&color_indicator[C_RIGHT]);
3421 /* Output a color indicator (which may contain nulls). */
3422 static void
3423 put_indicator (const struct bin_str *ind)
3425 register int i;
3426 register const char *p;
3428 p = ind->string;
3430 for (i = ind->len; i > 0; --i)
3431 putchar (*(p++));
3434 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3435 Return zero if the write is successful or if the string length is zero.
3436 Return nonzero if the write fails. */
3437 static int
3438 put_indicator_direct (const struct bin_str *ind)
3440 size_t len;
3441 if (ind->len <= 0)
3442 return 0;
3444 len = ind->len;
3445 return (full_write (STDOUT_FILENO, ind->string, len) != len);
3448 static int
3449 length_of_file_name_and_frills (const struct fileinfo *f)
3451 register int len = 0;
3452 size_t name_width;
3454 if (print_inode)
3455 len += INODE_DIGITS + 1;
3457 if (print_block_size)
3458 len += 1 + block_size_size;
3460 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3461 len += name_width;
3463 if (indicator_style != none)
3465 mode_t filetype = f->stat.st_mode;
3467 if (S_ISREG (filetype))
3469 if (indicator_style == classify
3470 && (f->stat.st_mode & S_IXUGO))
3471 len += 1;
3473 else if (S_ISDIR (filetype)
3474 || S_ISLNK (filetype)
3475 || S_ISFIFO (filetype)
3476 || S_ISSOCK (filetype)
3477 || S_ISDOOR (filetype)
3479 len += 1;
3482 return len;
3485 static void
3486 print_many_per_line (void)
3488 struct column_info *line_fmt;
3489 int filesno; /* Index into files. */
3490 int row; /* Current row. */
3491 int max_name_length; /* Length of longest file name + frills. */
3492 int name_length; /* Length of each file name + frills. */
3493 int pos; /* Current character column. */
3494 int cols; /* Number of files across. */
3495 int rows; /* Maximum number of files down. */
3496 int max_cols;
3498 /* Normally the maximum number of columns is determined by the
3499 screen width. But if few files are available this might limit it
3500 as well. */
3501 max_cols = max_idx > files_index ? files_index : max_idx;
3503 /* Compute the maximum number of possible columns. */
3504 for (filesno = 0; filesno < files_index; ++filesno)
3506 int i;
3508 name_length = length_of_file_name_and_frills (files + filesno);
3510 for (i = 0; i < max_cols; ++i)
3512 if (column_info[i].valid_len)
3514 int idx = filesno / ((files_index + i) / (i + 1));
3515 int real_length = name_length + (idx == i ? 0 : 2);
3517 if (real_length > column_info[i].col_arr[idx])
3519 column_info[i].line_len += (real_length
3520 - column_info[i].col_arr[idx]);
3521 column_info[i].col_arr[idx] = real_length;
3522 column_info[i].valid_len = column_info[i].line_len < line_length;
3528 /* Find maximum allowed columns. */
3529 for (cols = max_cols; cols > 1; --cols)
3531 if (column_info[cols - 1].valid_len)
3532 break;
3535 line_fmt = &column_info[cols - 1];
3537 /* Calculate the number of rows that will be in each column except possibly
3538 for a short column on the right. */
3539 rows = files_index / cols + (files_index % cols != 0);
3541 for (row = 0; row < rows; row++)
3543 int col = 0;
3544 filesno = row;
3545 pos = 0;
3546 /* Print the next row. */
3547 while (1)
3549 print_file_name_and_frills (files + filesno);
3550 name_length = length_of_file_name_and_frills (files + filesno);
3551 max_name_length = line_fmt->col_arr[col++];
3553 filesno += rows;
3554 if (filesno >= files_index)
3555 break;
3557 indent (pos + name_length, pos + max_name_length);
3558 pos += max_name_length;
3560 putchar ('\n');
3564 static void
3565 print_horizontal (void)
3567 struct column_info *line_fmt;
3568 int filesno;
3569 int max_name_length;
3570 int name_length;
3571 int cols;
3572 int pos;
3573 int max_cols;
3575 /* Normally the maximum number of columns is determined by the
3576 screen width. But if few files are available this might limit it
3577 as well. */
3578 max_cols = max_idx > files_index ? files_index : max_idx;
3580 /* Compute the maximum file name length. */
3581 max_name_length = 0;
3582 for (filesno = 0; filesno < files_index; ++filesno)
3584 int i;
3586 name_length = length_of_file_name_and_frills (files + filesno);
3588 for (i = 0; i < max_cols; ++i)
3590 if (column_info[i].valid_len)
3592 int idx = filesno % (i + 1);
3593 int real_length = name_length + (idx == i ? 0 : 2);
3595 if (real_length > column_info[i].col_arr[idx])
3597 column_info[i].line_len += (real_length
3598 - column_info[i].col_arr[idx]);
3599 column_info[i].col_arr[idx] = real_length;
3600 column_info[i].valid_len = column_info[i].line_len < line_length;
3606 /* Find maximum allowed columns. */
3607 for (cols = max_cols; cols > 1; --cols)
3609 if (column_info[cols - 1].valid_len)
3610 break;
3613 line_fmt = &column_info[cols - 1];
3615 pos = 0;
3617 /* Print first entry. */
3618 print_file_name_and_frills (files);
3619 name_length = length_of_file_name_and_frills (files);
3620 max_name_length = line_fmt->col_arr[0];
3622 /* Now the rest. */
3623 for (filesno = 1; filesno < files_index; ++filesno)
3625 int col = filesno % cols;
3627 if (col == 0)
3629 putchar ('\n');
3630 pos = 0;
3632 else
3634 indent (pos + name_length, pos + max_name_length);
3635 pos += max_name_length;
3638 print_file_name_and_frills (files + filesno);
3640 name_length = length_of_file_name_and_frills (files + filesno);
3641 max_name_length = line_fmt->col_arr[col];
3643 putchar ('\n');
3646 static void
3647 print_with_commas (void)
3649 int filesno;
3650 int pos, old_pos;
3652 pos = 0;
3654 for (filesno = 0; filesno < files_index; filesno++)
3656 old_pos = pos;
3658 pos += length_of_file_name_and_frills (files + filesno);
3659 if (filesno + 1 < files_index)
3660 pos += 2; /* For the comma and space */
3662 if (old_pos != 0 && pos >= line_length)
3664 putchar ('\n');
3665 pos -= old_pos;
3668 print_file_name_and_frills (files + filesno);
3669 if (filesno + 1 < files_index)
3671 putchar (',');
3672 putchar (' ');
3675 putchar ('\n');
3678 /* Assuming cursor is at position FROM, indent up to position TO.
3679 Use a TAB character instead of two or more spaces whenever possible. */
3681 static void
3682 indent (int from, int to)
3684 while (from < to)
3686 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
3688 putchar ('\t');
3689 from += tabsize - from % tabsize;
3691 else
3693 putchar (' ');
3694 from++;
3699 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3700 /* FIXME: maybe remove this function someday. See about using a
3701 non-malloc'ing version of path_concat. */
3703 static void
3704 attach (char *dest, const char *dirname, const char *name)
3706 const char *dirnamep = dirname;
3708 /* Copy dirname if it is not ".". */
3709 if (dirname[0] != '.' || dirname[1] != 0)
3711 while (*dirnamep)
3712 *dest++ = *dirnamep++;
3713 /* Add '/' if `dirname' doesn't already end with it. */
3714 if (dirnamep > dirname && dirnamep[-1] != '/')
3715 *dest++ = '/';
3717 while (*name)
3718 *dest++ = *name++;
3719 *dest = 0;
3722 static void
3723 init_column_info (void)
3725 int i;
3726 int allocate = 0;
3728 max_idx = line_length / MIN_COLUMN_WIDTH;
3729 if (max_idx == 0)
3730 max_idx = 1;
3732 if (column_info == NULL)
3734 column_info = XMALLOC (struct column_info, max_idx);
3735 allocate = 1;
3738 for (i = 0; i < max_idx; ++i)
3740 int j;
3742 column_info[i].valid_len = 1;
3743 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3745 if (allocate)
3746 column_info[i].col_arr = XMALLOC (int, i + 1);
3748 for (j = 0; j <= i; ++j)
3749 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3753 void
3754 usage (int status)
3756 if (status != 0)
3757 fprintf (stderr, _("Try `%s --help' for more information.\n"),
3758 program_name);
3759 else
3761 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3762 fputs (_("\
3763 List information about the FILEs (the current directory by default).\n\
3764 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3766 "), stdout);
3767 fputs (_("\
3768 Mandatory arguments to long options are mandatory for short options too.\n\
3769 "), stdout);
3770 fputs (_("\
3771 -a, --all do not hide entries starting with .\n\
3772 -A, --almost-all do not list implied . and ..\n\
3773 --author print the author of each file\n\
3774 -b, --escape print octal escapes for nongraphic characters\n\
3775 "), stdout);
3776 fputs (_("\
3777 --block-size=SIZE use SIZE-byte blocks\n\
3778 -B, --ignore-backups do not list implied entries ending with ~\n\
3779 -c with -lt: sort by, and show, ctime (time of last\n\
3780 modification of file status information)\n\
3781 with -l: show ctime and sort by name\n\
3782 otherwise: sort by ctime\n\
3783 "), stdout);
3784 fputs (_("\
3785 -C list entries by columns\n\
3786 --color[=WHEN] control whether color is used to distinguish file\n\
3787 types. WHEN may be `never', `always', or `auto'\n\
3788 -d, --directory list directory entries instead of contents,\n\
3789 and do not dereference symbolic links\n\
3790 -D, --dired generate output designed for Emacs' dired mode\n\
3791 "), stdout);
3792 fputs (_("\
3793 -f do not sort, enable -aU, disable -lst\n\
3794 -F, --classify append indicator (one of */=@|) to entries\n\
3795 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3796 single-column -1, verbose -l, vertical -C\n\
3797 --full-time like -l --time-style=full-iso\n\
3798 "), stdout);
3799 fputs (_("\
3800 -g like -l, but do not list owner\n\
3801 -G, --no-group inhibit display of group information\n\
3802 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3803 --si likewise, but use powers of 1000 not 1024\n\
3804 -H, --dereference-command-line\n\
3805 follow symbolic links listed on the command line\n\
3806 --dereference-command-line-symlink-to-dir\n\
3807 follow each command line symbolic link\n\
3808 that points to a directory\n\
3809 "), stdout);
3810 fputs (_("\
3811 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3812 none (default), classify (-F), file-type (-p)\n\
3813 -i, --inode print index number of each file\n\
3814 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3815 -k like --block-size=1K\n\
3816 "), stdout);
3817 fputs (_("\
3818 -l use a long listing format\n\
3819 -L, --dereference when showing file information for a symbolic\n\
3820 link, show information for the file the link\n\
3821 references rather than for the link itself\n\
3822 -m fill width with a comma separated list of entries\n\
3823 "), stdout);
3824 fputs (_("\
3825 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3826 -N, --literal print raw entry names (don't treat e.g. control\n\
3827 characters specially)\n\
3828 -o like -l, but do not list group information\n\
3829 -p, --file-type append indicator (one of /=@|) to entries\n\
3830 "), stdout);
3831 fputs (_("\
3832 -q, --hide-control-chars print ? instead of non graphic characters\n\
3833 --show-control-chars show non graphic characters as-is (default\n\
3834 unless program is `ls' and output is a terminal)\n\
3835 -Q, --quote-name enclose entry names in double quotes\n\
3836 --quoting-style=WORD use quoting style WORD for entry names:\n\
3837 literal, locale, shell, shell-always, c, escape\n\
3838 "), stdout);
3839 fputs (_("\
3840 -r, --reverse reverse order while sorting\n\
3841 -R, --recursive list subdirectories recursively\n\
3842 -s, --size print size of each file, in blocks\n\
3843 "), stdout);
3844 fputs (_("\
3845 -S sort by file size\n\
3846 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3847 version -v\n\
3848 status -c, time -t, atime -u, access -u, use -u\n\
3849 --time=WORD show time as WORD instead of modification time:\n\
3850 atime, access, use, ctime or status; use\n\
3851 specified time as sort key if --sort=time\n\
3852 "), stdout);
3853 fputs (_("\
3854 --time-style=STYLE show times using style STYLE:\n\
3855 full-iso, long-iso, iso, locale, +FORMAT\n\
3856 FORMAT is interpreted like `date'; if FORMAT is\n\
3857 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
3858 non-recent files and FORMAT2 to recent files;\n\
3859 if STYLE is prefixed with `posix-', STYLE\n\
3860 takes effect only outside the POSIX locale\n\
3861 -t sort by modification time\n\
3862 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
3863 "), stdout);
3864 fputs (_("\
3865 -u with -lt: sort by, and show, access time\n\
3866 with -l: show access time and sort by name\n\
3867 otherwise: sort by access time\n\
3868 -U do not sort; list entries in directory order\n\
3869 -v sort by version\n\
3870 "), stdout);
3871 fputs (_("\
3872 -w, --width=COLS assume screen width instead of current value\n\
3873 -x list entries by lines instead of by columns\n\
3874 -X sort alphabetically by entry extension\n\
3875 -1 list one file per line\n\
3876 "), stdout);
3877 fputs (HELP_OPTION_DESCRIPTION, stdout);
3878 fputs (VERSION_OPTION_DESCRIPTION, stdout);
3879 fputs (_("\n\
3880 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3881 kB 1000, K 1024, MB 1,000,000, M 1,048,576, and so on for G, T, P, E, Z, Y.\n\
3882 "), stdout);
3883 fputs (_("\
3885 By default, color is not used to distinguish types of files. That is\n\
3886 equivalent to using --color=none. Using the --color option without the\n\
3887 optional WHEN argument is equivalent to using --color=always. With\n\
3888 --color=auto, color codes are output only if standard output is connected\n\
3889 to a terminal (tty).\n\
3890 "), stdout);
3891 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
3893 exit (status);