1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2003 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* If ls_mode is LS_MULTI_COL,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
29 the output format depends on whether the output
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
40 #include <sys/types.h>
46 #ifdef GWINSZ_IN_SYS_IOCTL
47 # include <sys/ioctl.h>
50 #ifdef WINSIZE_IN_PTEM
51 # include <sys/stream.h>
52 # include <sys/ptem.h>
63 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
72 #if !defined iswprint && !HAVE_ISWPRINT
73 # define iswprint(wc) 1
76 #ifndef HAVE_DECL_WCWIDTH
77 "this configure-time declaration test was not run"
79 #if !HAVE_DECL_WCWIDTH
83 /* If wcwidth() doesn't exist, assume all printable characters have
87 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
100 #include "full-write.h"
101 #include "hard-locale.h"
104 #include "filemode.h"
105 #include "inttostr.h"
107 #include "mbswidth.h"
109 #include "path-concat.h"
111 #include "quotearg.h"
113 #include "strftime.h"
114 #include "strverscmp.h"
116 #include "xreadlink.h"
118 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
119 : (ls_mode == LS_MULTI_COL \
122 #define AUTHORS "Richard Stallman", "David MacKenzie"
124 #define obstack_chunk_alloc malloc
125 #define obstack_chunk_free free
127 /* Return an int indicating the result of comparing two integers.
128 Subtracting doesn't always work, due to overflow. */
129 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
131 /* Arrange to make lstat calls go through the wrapper function
132 on systems with an lstat function that does not dereference symlinks
133 that are specified with a trailing slash. */
134 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
135 int rpl_lstat (const char *, struct stat
*);
137 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
140 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
141 # define DT_INIT(Val) = Val
143 # define DT_INIT(Val) /* empty */
147 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
149 # define TIMESPEC_NS(timespec) 0
152 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
153 # define st_author st_uid
156 /* Cray/Unicos DMF: use the file's migrated, not real, status */
158 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
160 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
165 unknown
DT_INIT (DT_UNKNOWN
),
166 fifo
DT_INIT (DT_FIFO
),
167 chardev
DT_INIT (DT_CHR
),
168 directory
DT_INIT (DT_DIR
),
169 blockdev
DT_INIT (DT_BLK
),
170 normal
DT_INIT (DT_REG
),
171 symbolic_link
DT_INIT (DT_LNK
),
172 sock
DT_INIT (DT_SOCK
),
173 arg_directory
DT_INIT (2 * (DT_UNKNOWN
| DT_FIFO
| DT_CHR
| DT_DIR
| DT_BLK
174 | DT_REG
| DT_LNK
| DT_SOCK
))
184 /* For symbolic link, name of the file linked to, otherwise zero. */
187 /* For symbolic link and long listing, st_mode of file linked to, otherwise
191 /* For symbolic link and color printing, 1 if linked-to file
192 exists, otherwise 0. */
195 enum filetype filetype
;
198 /* For long listings, true if the file has an access control list. */
204 # define FILE_HAS_ACL(F) ((F)->have_acl)
206 # define FILE_HAS_ACL(F) 0
209 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
211 /* Null is a valid character in a color indicator (think about Epson
212 printers, for example) so we have to use a length/buffer string
217 size_t len
; /* Number of bytes */
218 const char *string
; /* Pointer to the same */
228 static size_t quote_name (FILE *out
, const char *name
,
229 struct quoting_options
const *options
,
231 static char *make_link_path (const char *path
, const char *linkname
);
232 static int decode_switches (int argc
, char **argv
);
233 static int file_interesting (const struct dirent
*next
);
234 static uintmax_t gobble_file (const char *name
, enum filetype type
,
235 int explicit_arg
, const char *dirname
);
236 static void print_color_indicator (const char *name
, mode_t mode
, int linkok
);
237 static void put_indicator (const struct bin_str
*ind
);
238 static int put_indicator_direct (const struct bin_str
*ind
);
239 static void add_ignore_pattern (const char *pattern
);
240 static void attach (char *dest
, const char *dirname
, const char *name
);
241 static void clear_files (void);
242 static void extract_dirs_from_files (const char *dirname
,
243 int ignore_dot_and_dot_dot
);
244 static void get_link_name (const char *filename
, struct fileinfo
*f
);
245 static void indent (size_t from
, size_t to
);
246 static size_t calculate_columns (bool by_columns
);
247 static void print_current_files (void);
248 static void print_dir (const char *name
, const char *realname
);
249 static void print_file_name_and_frills (const struct fileinfo
*f
);
250 static void print_horizontal (void);
251 static int format_user_width (uid_t u
);
252 static int format_group_width (gid_t g
);
253 static void print_long_format (const struct fileinfo
*f
);
254 static void print_many_per_line (void);
255 static void print_name_with_quoting (const char *p
, mode_t mode
,
257 struct obstack
*stack
);
258 static void prep_non_filename_text (void);
259 static void print_type_indicator (mode_t mode
);
260 static void print_with_commas (void);
261 static void queue_directory (const char *name
, const char *realname
);
262 static void sort_files (void);
263 static void parse_ls_color (void);
264 void usage (int status
);
266 /* The name the program was run with, stripped of any leading path. */
269 /* Initial size of hash table.
270 Most hierarchies are likely to be shallower than this. */
271 #define INITIAL_TABLE_SIZE 30
273 /* The set of `active' directories, from the current command-line argument
274 to the level in the hierarchy at which files are being listed.
275 A directory is represented by its device and inode numbers (struct dev_ino).
276 A directory is added to this set when ls begins listing it or its
277 entries, and it is removed from the set just after ls has finished
278 processing it. This set is used solely to detect loops, e.g., with
279 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
280 static Hash_table
*active_dir_set
;
282 #define LOOP_DETECT (!!active_dir_set)
284 /* The table of files in the current directory:
286 `files' points to a vector of `struct fileinfo', one per file.
287 `nfiles' is the number of elements space has been allocated for.
288 `files_index' is the number actually in use. */
290 /* Address of block containing the files that are described. */
291 static struct fileinfo
*files
; /* FIXME: rename this to e.g. cwd_file */
293 /* Length of block that `files' points to, measured in files. */
294 static size_t nfiles
; /* FIXME: rename this to e.g. cwd_n_alloc */
296 /* Index of first unused in `files'. */
297 static size_t files_index
; /* FIXME: rename this to e.g. cwd_n_used */
299 /* When nonzero, in a color listing, color each symlink name according to the
300 type of file it points to. Otherwise, color them according to the `ln'
301 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
302 regardless. This is set when `ln=target' appears in LS_COLORS. */
304 static int color_symlink_as_referent
;
306 /* mode of appropriate file for colorization */
307 #define FILE_OR_LINK_MODE(File) \
308 ((color_symlink_as_referent && (File)->linkok) \
309 ? (File)->linkmode : (File)->stat.st_mode)
312 /* Record of one pending directory waiting to be listed. */
317 /* If the directory is actually the file pointed to by a symbolic link we
318 were told to list, `realname' will contain the name of the symbolic
319 link, otherwise zero. */
321 struct pending
*next
;
324 static struct pending
*pending_dirs
;
326 /* Current time in seconds and nanoseconds since 1970, updated as
327 needed when deciding whether a file is recent. */
329 static time_t current_time
= TYPE_MINIMUM (time_t);
330 static int current_time_ns
= -1;
332 /* The number of bytes to use for columns containing inode numbers,
333 block sizes, link counts, owners, groups, authors, major device
334 numbers, minor device numbers, and file sizes, respectively. */
336 static int inode_number_width
;
337 static int block_size_width
;
338 static int nlink_width
;
339 static int owner_width
;
340 static int group_width
;
341 static int author_width
;
342 static int major_device_number_width
;
343 static int minor_device_number_width
;
344 static int file_size_width
;
348 /* long_format for lots of info, one per line.
349 one_per_line for just names, one per line.
350 many_per_line for just names, many per line, sorted vertically.
351 horizontal for just names, many per line, sorted horizontally.
352 with_commas for just names, many per line, separated by commas.
354 -l (and other options that imply -l), -1, -C, -x and -m control
359 long_format
, /* -l and other options that imply -l */
360 one_per_line
, /* -1 */
361 many_per_line
, /* -C */
366 static enum format format
;
368 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
369 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
370 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
373 full_iso_time_style
, /* --time-style=full-iso */
374 long_iso_time_style
, /* --time-style=long-iso */
375 iso_time_style
, /* --time-style=iso */
376 locale_time_style
/* --time-style=locale */
379 static char const *const time_style_args
[] =
381 "full-iso", "long-iso", "iso", "locale", 0
384 static enum time_style
const time_style_types
[] =
386 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
390 /* Type of time to print or sort by. Controlled by -c and -u. */
394 time_mtime
, /* default */
399 static enum time_type time_type
;
401 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
406 sort_name
, /* default */
407 sort_extension
, /* -X */
410 sort_version
/* -v */
413 static enum sort_type sort_type
;
415 /* Direction of sort.
416 0 means highest first if numeric,
417 lowest first if alphabetic;
418 these are the defaults.
419 1 means the opposite order in each case. -r */
421 static int sort_reverse
;
423 /* Nonzero means to display owner information. -g turns this off. */
425 static int print_owner
= 1;
427 /* Nonzero means to display author information. */
429 static bool print_author
;
431 /* Nonzero means to display group information. -G and -o turn this off. */
433 static int print_group
= 1;
435 /* Nonzero means print the user and group id's as numbers rather
438 static int numeric_ids
;
440 /* Nonzero means mention the size in blocks of each file. -s */
442 static int print_block_size
;
444 /* Human-readable options for output. */
445 static int human_output_opts
;
447 /* The units to use when printing sizes other than file sizes. */
448 static uintmax_t output_block_size
;
450 /* Likewise, but for file sizes. */
451 static uintmax_t file_output_block_size
= 1;
453 /* Precede each line of long output (per file) with a string like `m,n:'
454 where M is the number of characters after the `:' and before the
455 filename and N is the length of the filename. Using this format,
456 Emacs' dired mode starts up twice as fast, and can handle all
457 strange characters in file names. */
460 /* `none' means don't mention the type of files.
461 `classify' means mention file types and mark executables.
462 `file_type' means mention only file types.
464 Controlled by -F, -p, and --indicator-style. */
468 none
, /* --indicator-style=none */
469 classify
, /* -F, --indicator-style=classify */
470 file_type
/* -p, --indicator-style=file-type */
473 static enum indicator_style indicator_style
;
475 /* Names of indicator styles. */
476 static char const *const indicator_style_args
[] =
478 "none", "classify", "file-type", 0
481 static enum indicator_style
const indicator_style_types
[]=
483 none
, classify
, file_type
486 /* Nonzero means use colors to mark types. Also define the different
487 colors as well as the stuff for the LS_COLORS environment variable.
488 The LS_COLORS variable is now in a termcap-like format. */
490 static int print_with_color
;
494 color_never
, /* 0: default or --color=never */
495 color_always
, /* 1: --color=always */
496 color_if_tty
/* 2: --color=tty */
499 enum Dereference_symlink
503 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
504 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
505 DEREF_ALWAYS
/* -L */
510 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
511 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
514 static const char *const indicator_name
[]=
516 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
517 "bd", "cd", "mi", "or", "ex", "do", NULL
520 struct color_ext_type
522 struct bin_str ext
; /* The extension we're looking for */
523 struct bin_str seq
; /* The sequence to output when we do */
524 struct color_ext_type
*next
; /* Next in list */
527 static struct bin_str color_indicator
[] =
529 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
530 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
531 { 0, NULL
}, /* ec: End color (replaces lc+no+rc) */
532 { LEN_STR_PAIR ("0") }, /* no: Normal */
533 { LEN_STR_PAIR ("0") }, /* fi: File: default */
534 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
535 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
536 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
537 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
538 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
539 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
540 { 0, NULL
}, /* mi: Missing file: undefined */
541 { 0, NULL
}, /* or: Orphanned symlink: undefined */
542 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
543 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
547 static struct color_ext_type
*color_ext_list
= NULL
;
549 /* Buffer for color sequences */
550 static char *color_buf
;
552 /* Nonzero means to check for orphaned symbolic link, for displaying
555 static int check_symlink_color
;
557 /* Nonzero means mention the inode number of each file. -i */
559 static int print_inode
;
561 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
562 other options that imply -l), and -L. */
564 static enum Dereference_symlink dereference
;
566 /* Nonzero means when a directory is found, display info on its
569 static int recursive
;
571 /* Nonzero means when an argument is a directory name, display info
574 static int immediate_dirs
;
576 /* Nonzero means don't omit files whose names start with `.'. -A */
578 static int all_files
;
580 /* Nonzero means don't omit files `.' and `..'
581 This flag implies `all_files'. -a */
583 static int really_all_files
;
585 /* A linked list of shell-style globbing patterns. If a non-argument
586 file name matches any of these patterns, it is omitted.
587 Controlled by -I. Multiple -I options accumulate.
588 The -B option adds `*~' and `.*~' to this list. */
590 struct ignore_pattern
593 struct ignore_pattern
*next
;
596 static struct ignore_pattern
*ignore_patterns
;
598 /* Nonzero means output nongraphic chars in file names as `?'.
599 (-q, --hide-control-chars)
600 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
601 independent. The algorithm is: first, obey the quoting style to get a
602 string representing the file name; then, if qmark_funny_chars is set,
603 replace all nonprintable chars in that string with `?'. It's necessary
604 to replace nonprintable chars even in quoted strings, because we don't
605 want to mess up the terminal if control chars get sent to it, and some
606 quoting methods pass through control chars as-is. */
607 static int qmark_funny_chars
;
609 /* Quoting options for file and dir name output. */
611 static struct quoting_options
*filename_quoting_options
;
612 static struct quoting_options
*dirname_quoting_options
;
614 /* The number of chars per hardware tab stop. Setting this to zero
615 inhibits the use of TAB characters for separating columns. -T */
616 static size_t tabsize
;
618 /* Nonzero means we are listing the working directory because no
619 non-option arguments were given. */
621 static int dir_defaulted
;
623 /* Nonzero means print each directory name before listing it. */
625 static int print_dir_name
;
627 /* The line length to use for breaking lines in many-per-line format.
628 Can be set with -w. */
630 static size_t line_length
;
632 /* If nonzero, the file listing format requires that stat be called on
635 static int format_needs_stat
;
637 /* Similar to `format_needs_stat', but set if only the file type is
640 static int format_needs_type
;
642 /* strftime formats for non-recent and recent files, respectively, in
645 static char const *long_time_format
[2] =
647 /* strftime format for non-recent files (older than 6 months), in
648 -l output when --time-style=locale is specified. This should
649 contain the year, month and day (at least), in an order that is
650 understood by people in your locale's territory.
651 Please try to keep the number of used screen columns small,
652 because many people work in windows with only 80 columns. But
653 make this as wide as the other string below, for recent files. */
655 /* strftime format for recent files (younger than 6 months), in
656 -l output when --time-style=locale is specified. This should
657 contain the month, day and time (at least), in an order that is
658 understood by people in your locale's territory.
659 Please try to keep the number of used screen columns small,
660 because many people work in windows with only 80 columns. But
661 make this as wide as the other string above, for non-recent files. */
665 /* The exit status to use if we don't get any fatal errors. */
667 static int exit_status
;
669 /* For long options that have no equivalent short option, use a
670 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
673 AUTHOR_OPTION
= CHAR_MAX
+ 1,
676 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
679 INDICATOR_STYLE_OPTION
,
680 QUOTING_STYLE_OPTION
,
681 SHOW_CONTROL_CHARS_OPTION
,
688 static struct option
const long_options
[] =
690 {"all", no_argument
, 0, 'a'},
691 {"escape", no_argument
, 0, 'b'},
692 {"directory", no_argument
, 0, 'd'},
693 {"dired", no_argument
, 0, 'D'},
694 {"full-time", no_argument
, 0, FULL_TIME_OPTION
},
695 {"human-readable", no_argument
, 0, 'h'},
696 {"inode", no_argument
, 0, 'i'},
697 {"kilobytes", no_argument
, 0, 'k'}, /* long form is obsolescent */
698 {"numeric-uid-gid", no_argument
, 0, 'n'},
699 {"no-group", no_argument
, 0, 'G'},
700 {"hide-control-chars", no_argument
, 0, 'q'},
701 {"reverse", no_argument
, 0, 'r'},
702 {"size", no_argument
, 0, 's'},
703 {"width", required_argument
, 0, 'w'},
704 {"almost-all", no_argument
, 0, 'A'},
705 {"ignore-backups", no_argument
, 0, 'B'},
706 {"classify", no_argument
, 0, 'F'},
707 {"file-type", no_argument
, 0, 'p'},
708 {"si", no_argument
, 0, SI_OPTION
},
709 {"dereference-command-line", no_argument
, 0, 'H'},
710 {"dereference-command-line-symlink-to-dir", no_argument
, 0,
711 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
712 {"ignore", required_argument
, 0, 'I'},
713 {"indicator-style", required_argument
, 0, INDICATOR_STYLE_OPTION
},
714 {"dereference", no_argument
, 0, 'L'},
715 {"literal", no_argument
, 0, 'N'},
716 {"quote-name", no_argument
, 0, 'Q'},
717 {"quoting-style", required_argument
, 0, QUOTING_STYLE_OPTION
},
718 {"recursive", no_argument
, 0, 'R'},
719 {"format", required_argument
, 0, FORMAT_OPTION
},
720 {"show-control-chars", no_argument
, 0, SHOW_CONTROL_CHARS_OPTION
},
721 {"sort", required_argument
, 0, SORT_OPTION
},
722 {"tabsize", required_argument
, 0, 'T'},
723 {"time", required_argument
, 0, TIME_OPTION
},
724 {"time-style", required_argument
, 0, TIME_STYLE_OPTION
},
725 {"color", optional_argument
, 0, COLOR_OPTION
},
726 {"block-size", required_argument
, 0, BLOCK_SIZE_OPTION
},
727 {"author", no_argument
, 0, AUTHOR_OPTION
},
728 {GETOPT_HELP_OPTION_DECL
},
729 {GETOPT_VERSION_OPTION_DECL
},
733 static char const *const format_args
[] =
735 "verbose", "long", "commas", "horizontal", "across",
736 "vertical", "single-column", 0
739 static enum format
const format_types
[] =
741 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
742 many_per_line
, one_per_line
745 static char const *const sort_args
[] =
747 "none", "time", "size", "extension", "version", 0
750 static enum sort_type
const sort_types
[] =
752 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
755 static char const *const time_args
[] =
757 "atime", "access", "use", "ctime", "status", 0
760 static enum time_type
const time_types
[] =
762 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
765 static char const *const color_args
[] =
767 /* force and none are for compatibility with another color-ls version */
768 "always", "yes", "force",
769 "never", "no", "none",
770 "auto", "tty", "if-tty", 0
773 static enum color_type
const color_types
[] =
775 color_always
, color_always
, color_always
,
776 color_never
, color_never
, color_never
,
777 color_if_tty
, color_if_tty
, color_if_tty
780 /* Information about filling a column. */
788 /* Array with information about column filledness. */
789 static struct column_info
*column_info
;
791 /* Maximum number of columns ever possible for this display. */
792 static size_t max_idx
;
794 /* The minimum width of a colum is 3: 1 character for the name and 2
795 for the separating white space. */
796 #define MIN_COLUMN_WIDTH 3
799 /* This zero-based index is used solely with the --dired option.
800 When that option is in effect, this counter is incremented for each
801 character of output generated by this program so that the beginning
802 and ending indices (in that output) of every file name can be recorded
803 and later output themselves. */
804 static size_t dired_pos
;
806 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
808 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
809 #define DIRED_FPUTS(s, stream, s_len) \
810 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
812 /* Like DIRED_FPUTS, but for use when S is a literal string. */
813 #define DIRED_FPUTS_LITERAL(s, stream) \
814 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
816 #define DIRED_INDENT() \
820 DIRED_FPUTS_LITERAL (" ", stdout); \
824 /* With --dired, store pairs of beginning and ending indices of filenames. */
825 static struct obstack dired_obstack
;
827 /* With --dired, store pairs of beginning and ending indices of any
828 directory names that appear as headers (just before `total' line)
829 for lists of directory entries. Such directory names are seen when
830 listing hierarchies using -R and when a directory is listed with at
831 least one other command line argument. */
832 static struct obstack subdired_obstack
;
834 /* Save the current index on the specified obstack, OBS. */
835 #define PUSH_CURRENT_DIRED_POS(obs) \
839 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
843 /* With -R, this stack is used to help detect directory cycles.
844 The device/inode pairs on this stack mirror the pairs in the
845 active_dir_set hash table. */
846 static struct obstack dev_ino_obstack
;
848 /* Push a pair onto the device/inode stack. */
849 #define DEV_INO_PUSH(Dev, Ino) \
852 struct dev_ino *di; \
853 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
854 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
855 di->st_dev = (Dev); \
856 di->st_ino = (Ino); \
860 /* Pop a dev/ino struct off the global dev_ino_obstack
861 and return that struct. */
862 static struct dev_ino
865 assert (sizeof (struct dev_ino
) <= obstack_object_size (&dev_ino_obstack
));
866 obstack_blank (&dev_ino_obstack
, -(int) (sizeof (struct dev_ino
)));
867 return *(struct dev_ino
*) obstack_next_free (&dev_ino_obstack
);
870 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
875 assert (0 <= stat (Name, &sb)); \
876 assert (sb.st_dev == Di.st_dev); \
877 assert (sb.st_ino == Di.st_ino); \
882 /* Write to standard output PREFIX, followed by the quoting style and
883 a space-separated list of the integers stored in OS all on one line. */
886 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
890 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
896 pos
= (size_t *) obstack_finish (os
);
897 fputs (prefix
, stdout
);
898 for (i
= 0; i
< n_pos
; i
++)
899 printf (" %lu", (unsigned long int) pos
[i
]);
905 dev_ino_hash (void const *x
, size_t table_size
)
907 struct dev_ino
const *p
= x
;
908 return (uintmax_t) p
->st_ino
% table_size
;
912 dev_ino_compare (void const *x
, void const *y
)
914 struct dev_ino
const *a
= x
;
915 struct dev_ino
const *b
= y
;
916 return SAME_INODE (*a
, *b
) ? true : false;
920 dev_ino_free (void *x
)
925 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
926 active directories. Return nonzero if there is already a matching
927 entry in the table. Otherwise, return zero. */
930 visit_dir (dev_t dev
, ino_t ino
)
933 struct dev_ino
*ent_from_table
;
936 ent
= xmalloc (sizeof *ent
);
940 /* Attempt to insert this entry into the table. */
941 ent_from_table
= hash_insert (active_dir_set
, ent
);
943 if (ent_from_table
== NULL
)
945 /* Insertion failed due to lack of memory. */
949 found_match
= (ent_from_table
!= ent
);
953 /* ent was not inserted, so free it. */
961 free_pending_ent (struct pending
*p
)
971 restore_default_color (void)
973 if (put_indicator_direct (&color_indicator
[C_LEFT
]) == 0)
974 put_indicator_direct (&color_indicator
[C_RIGHT
]);
977 /* Upon interrupt, suspend, hangup, etc. ensure that the
978 terminal text color is restored to the default. */
983 signal (sig
, SIG_IGN
);
986 restore_default_color ();
988 /* SIGTSTP is special, since the application can receive that signal more
989 than once. In this case, don't set the signal handler to the default.
990 Instead, just raise the uncatchable SIGSTOP. */
998 struct sigaction sigact
;
1000 sigact
.sa_handler
= SIG_DFL
;
1001 sigemptyset (&sigact
.sa_mask
);
1002 sigact
.sa_flags
= 0;
1003 sigaction (sig
, &sigact
, NULL
);
1005 signal (sig
, SIG_DFL
);
1013 main (int argc
, char **argv
)
1016 register struct pending
*thispend
;
1017 unsigned int n_files
;
1019 initialize_main (&argc
, &argv
);
1020 program_name
= argv
[0];
1021 setlocale (LC_ALL
, "");
1022 bindtextdomain (PACKAGE
, LOCALEDIR
);
1023 textdomain (PACKAGE
);
1025 atexit (close_stdout
);
1027 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1028 assert (N_ENTRIES (color_indicator
) + 1 == N_ENTRIES (indicator_name
));
1035 i
= decode_switches (argc
, argv
);
1037 if (print_with_color
)
1040 /* Test print_with_color again, because the call to parse_ls_color
1041 may have just reset it -- e.g., if LS_COLORS is invalid. */
1042 if (print_with_color
)
1044 prep_non_filename_text ();
1045 /* Avoid following symbolic links when possible. */
1046 if (color_indicator
[C_ORPHAN
].string
!= NULL
1047 || (color_indicator
[C_MISSING
].string
!= NULL
1048 && format
== long_format
))
1049 check_symlink_color
= 1;
1053 static int const sigs
[] = { SIGHUP
, SIGINT
, SIGPIPE
,
1054 SIGQUIT
, SIGTERM
, SIGTSTP
};
1055 unsigned int nsigs
= sizeof sigs
/ sizeof *sigs
;
1057 struct sigaction oldact
, newact
;
1058 sigset_t caught_signals
;
1060 sigemptyset (&caught_signals
);
1061 for (j
= 0; j
< nsigs
; j
++)
1062 sigaddset (&caught_signals
, sigs
[j
]);
1063 newact
.sa_handler
= sighandler
;
1064 newact
.sa_mask
= caught_signals
;
1065 newact
.sa_flags
= 0;
1068 for (j
= 0; j
< nsigs
; j
++)
1072 sigaction (sig
, NULL
, &oldact
);
1073 if (oldact
.sa_handler
!= SIG_IGN
)
1074 sigaction (sig
, &newact
, NULL
);
1076 if (signal (sig
, SIG_IGN
) != SIG_IGN
)
1077 signal (sig
, sighandler
);
1083 if (dereference
== DEREF_UNDEFINED
)
1084 dereference
= ((immediate_dirs
1085 || indicator_style
== classify
1086 || format
== long_format
)
1088 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1090 /* When using -R, initialize a data structure we'll use to
1091 detect any directory cycles. */
1094 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, NULL
,
1098 if (active_dir_set
== NULL
)
1101 obstack_init (&dev_ino_obstack
);
1104 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
1105 || format
== long_format
1106 || dereference
== DEREF_ALWAYS
1107 || print_block_size
|| print_inode
;
1108 format_needs_type
= (format_needs_stat
== 0
1109 && (recursive
|| print_with_color
1110 || indicator_style
!= none
));
1114 obstack_init (&dired_obstack
);
1115 obstack_init (&subdired_obstack
);
1119 files
= xnmalloc (nfiles
, sizeof *files
);
1128 for (; i
< argc
; i
++)
1130 gobble_file (argv
[i
], unknown
, 1, "");
1136 gobble_file (".", directory
, 1, "");
1138 queue_directory (".", 0);
1144 if (!immediate_dirs
)
1145 extract_dirs_from_files ("", 0);
1146 /* `files_index' might be zero now. */
1149 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1150 (and not pending_dirs->name) because there may be no markers in the queue
1151 at this point. A marker may be enqueued when extract_dirs_from_files is
1152 called with a non-empty string or via print_dir. */
1155 print_current_files ();
1157 DIRED_PUTCHAR ('\n');
1159 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1162 while (pending_dirs
)
1164 thispend
= pending_dirs
;
1165 pending_dirs
= pending_dirs
->next
;
1169 if (thispend
->name
== NULL
)
1171 /* thispend->name == NULL means this is a marker entry
1172 indicating we've finished processing the directory.
1173 Use its dev/ino numbers to remove the corresponding
1174 entry from the active_dir_set hash table. */
1175 struct dev_ino di
= dev_ino_pop ();
1176 struct dev_ino
*found
= hash_delete (active_dir_set
, &di
);
1177 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1179 dev_ino_free (found
);
1180 free_pending_ent (thispend
);
1185 print_dir (thispend
->name
, thispend
->realname
);
1187 free_pending_ent (thispend
);
1193 /* No need to free these since we're about to exit. */
1194 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1195 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1196 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1197 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1200 /* Restore default color before exiting */
1201 if (print_with_color
)
1203 put_indicator (&color_indicator
[C_LEFT
]);
1204 put_indicator (&color_indicator
[C_RIGHT
]);
1209 assert (hash_get_n_entries (active_dir_set
) == 0);
1210 hash_free (active_dir_set
);
1216 /* Set all the option flags according to the switches specified.
1217 Return the index of the first non-option argument. */
1220 decode_switches (int argc
, char **argv
)
1223 char *time_style_option
= 0;
1225 /* Record whether there is an option specifying sort type. */
1226 int sort_type_specified
= 0;
1228 qmark_funny_chars
= 0;
1230 /* initialize all switches to default settings */
1235 /* This is for the `dir' program. */
1236 format
= many_per_line
;
1237 set_quoting_style (NULL
, escape_quoting_style
);
1240 case LS_LONG_FORMAT
:
1241 /* This is for the `vdir' program. */
1242 format
= long_format
;
1243 set_quoting_style (NULL
, escape_quoting_style
);
1247 /* This is for the `ls' program. */
1248 if (isatty (STDOUT_FILENO
))
1250 format
= many_per_line
;
1251 /* See description of qmark_funny_chars, above. */
1252 qmark_funny_chars
= 1;
1256 format
= one_per_line
;
1257 qmark_funny_chars
= 0;
1265 time_type
= time_mtime
;
1266 sort_type
= sort_name
;
1269 print_block_size
= 0;
1270 indicator_style
= none
;
1272 dereference
= DEREF_UNDEFINED
;
1276 really_all_files
= 0;
1277 ignore_patterns
= 0;
1279 /* FIXME: put this in a function. */
1281 char const *q_style
= getenv ("QUOTING_STYLE");
1284 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
1286 set_quoting_style (NULL
, quoting_style_vals
[i
]);
1289 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1290 quotearg (q_style
));
1295 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
1296 human_output_opts
= human_options (ls_block_size
, false,
1297 &output_block_size
);
1298 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
1299 file_output_block_size
= output_block_size
;
1304 char const *p
= getenv ("COLUMNS");
1307 unsigned long int tmp_ulong
;
1308 if (xstrtoul (p
, NULL
, 0, &tmp_ulong
, NULL
) == LONGINT_OK
1309 && 0 < tmp_ulong
&& tmp_ulong
<= SIZE_MAX
)
1311 line_length
= tmp_ulong
;
1316 _("ignoring invalid width in environment variable COLUMNS: %s"),
1326 if (ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
) != -1
1327 && 0 < ws
.ws_col
/* && ws.ws_col <= SIZE_MAX */ )
1328 line_length
= ws
.ws_col
;
1332 /* Using the TABSIZE environment variable is not POSIX-approved.
1333 Ignore it when POSIXLY_CORRECT is set. */
1337 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
1339 unsigned long int tmp_ulong
;
1340 if (xstrtoul (p
, NULL
, 0, &tmp_ulong
, NULL
) == LONGINT_OK
1341 && tmp_ulong
<= SIZE_MAX
)
1343 tabsize
= tmp_ulong
;
1348 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1354 while ((c
= getopt_long (argc
, argv
,
1355 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1356 long_options
, NULL
)) != -1)
1365 really_all_files
= 1;
1369 set_quoting_style (NULL
, escape_quoting_style
);
1373 time_type
= time_ctime
;
1381 /* Same as enabling -a -U and disabling -l -s. */
1383 really_all_files
= 1;
1384 sort_type
= sort_none
;
1385 sort_type_specified
= 1;
1387 if (format
== long_format
)
1388 format
= (isatty (STDOUT_FILENO
) ? many_per_line
: one_per_line
);
1389 print_block_size
= 0; /* disable -s */
1390 print_with_color
= 0; /* disable --color */
1394 format
= long_format
;
1399 human_output_opts
= human_autoscale
| human_SI
| human_base_1024
;
1400 file_output_block_size
= output_block_size
= 1;
1408 human_output_opts
= 0;
1409 file_output_block_size
= output_block_size
= 1024;
1413 format
= long_format
;
1417 format
= with_commas
;
1422 format
= long_format
;
1425 case 'o': /* Just like -l, but don't display group info. */
1426 format
= long_format
;
1431 indicator_style
= file_type
;
1435 qmark_funny_chars
= 1;
1443 print_block_size
= 1;
1447 sort_type
= sort_time
;
1448 sort_type_specified
= 1;
1452 time_type
= time_atime
;
1456 sort_type
= sort_version
;
1457 sort_type_specified
= 1;
1462 unsigned long int tmp_ulong
;
1463 if (xstrtoul (optarg
, NULL
, 0, &tmp_ulong
, NULL
) != LONGINT_OK
1464 || ! (0 < tmp_ulong
&& tmp_ulong
<= SIZE_MAX
))
1465 error (EXIT_FAILURE
, 0, _("invalid line width: %s"),
1467 line_length
= tmp_ulong
;
1472 format
= horizontal
;
1476 really_all_files
= 0;
1481 add_ignore_pattern ("*~");
1482 add_ignore_pattern (".*~");
1486 format
= many_per_line
;
1494 indicator_style
= classify
;
1497 case 'G': /* inhibit display of group info */
1502 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
1505 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
1506 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
1510 add_ignore_pattern (optarg
);
1514 dereference
= DEREF_ALWAYS
;
1518 set_quoting_style (NULL
, literal_quoting_style
);
1522 set_quoting_style (NULL
, c_quoting_style
);
1530 sort_type
= sort_size
;
1531 sort_type_specified
= 1;
1536 unsigned long int tmp_ulong
;
1537 if (xstrtoul (optarg
, NULL
, 0, &tmp_ulong
, NULL
) != LONGINT_OK
1538 || SIZE_MAX
< tmp_ulong
)
1539 error (EXIT_FAILURE
, 0, _("invalid tab size: %s"),
1541 tabsize
= tmp_ulong
;
1546 sort_type
= sort_none
;
1547 sort_type_specified
= 1;
1551 sort_type
= sort_extension
;
1552 sort_type_specified
= 1;
1556 /* -1 has no effect after -l. */
1557 if (format
!= long_format
)
1558 format
= one_per_line
;
1562 print_author
= true;
1566 sort_type
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
1567 sort_type_specified
= 1;
1571 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
1575 format
= XARGMATCH ("--format", optarg
, format_args
, format_types
);
1578 case FULL_TIME_OPTION
:
1579 format
= long_format
;
1580 time_style_option
= "full-iso";
1587 i
= XARGMATCH ("--color", optarg
, color_args
, color_types
);
1589 /* Using --color with no argument is equivalent to using
1593 print_with_color
= (i
== color_always
1594 || (i
== color_if_tty
1595 && isatty (STDOUT_FILENO
)));
1597 if (print_with_color
)
1599 /* Don't use TAB characters in output. Some terminal
1600 emulators can't handle the combination of tabs and
1601 color codes on the same line. */
1607 case INDICATOR_STYLE_OPTION
:
1608 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
1609 indicator_style_args
,
1610 indicator_style_types
);
1613 case QUOTING_STYLE_OPTION
:
1614 set_quoting_style (NULL
,
1615 XARGMATCH ("--quoting-style", optarg
,
1617 quoting_style_vals
));
1620 case TIME_STYLE_OPTION
:
1621 time_style_option
= optarg
;
1624 case SHOW_CONTROL_CHARS_OPTION
:
1625 qmark_funny_chars
= 0;
1628 case BLOCK_SIZE_OPTION
:
1629 human_output_opts
= human_options (optarg
, true, &output_block_size
);
1630 file_output_block_size
= output_block_size
;
1634 human_output_opts
= human_autoscale
| human_SI
;
1635 file_output_block_size
= output_block_size
= 1;
1638 case_GETOPT_HELP_CHAR
;
1640 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1643 usage (EXIT_FAILURE
);
1647 max_idx
= MAX (1, line_length
/ MIN_COLUMN_WIDTH
);
1649 filename_quoting_options
= clone_quoting_options (NULL
);
1650 if (get_quoting_style (filename_quoting_options
) == escape_quoting_style
)
1651 set_char_quoting (filename_quoting_options
, ' ', 1);
1652 if (indicator_style
!= none
)
1655 for (p
= "*=@|" + (int) indicator_style
- 1; *p
; p
++)
1656 set_char_quoting (filename_quoting_options
, *p
, 1);
1659 dirname_quoting_options
= clone_quoting_options (NULL
);
1660 set_char_quoting (dirname_quoting_options
, ':', 1);
1662 /* --dired is meaningful only with --format=long (-l).
1663 Otherwise, ignore it. FIXME: warn about this?
1664 Alternatively, make --dired imply --format=long? */
1665 if (dired
&& format
!= long_format
)
1668 /* If -c or -u is specified and not -l (or any other option that implies -l),
1669 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1670 The behavior of ls when using either -c or -u but with neither -l nor -t
1671 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1672 sort by atime (this is the one that's not specified by the POSIX spec),
1673 -lu means show atime and sort by name, -lut means show atime and sort
1676 if ((time_type
== time_ctime
|| time_type
== time_atime
)
1677 && !sort_type_specified
&& format
!= long_format
)
1679 sort_type
= sort_time
;
1682 if (format
== long_format
)
1684 char *style
= time_style_option
;
1685 static char const posix_prefix
[] = "posix-";
1688 if (! (style
= getenv ("TIME_STYLE")))
1689 style
= "posix-long-iso";
1691 while (strncmp (style
, posix_prefix
, sizeof posix_prefix
- 1) == 0)
1693 if (! hard_locale (LC_TIME
))
1695 style
+= sizeof posix_prefix
- 1;
1700 char *p0
= style
+ 1;
1701 char *p1
= strchr (p0
, '\n');
1706 if (strchr (p1
+ 1, '\n'))
1707 error (EXIT_FAILURE
, 0, _("invalid time style format %s"),
1711 long_time_format
[0] = p0
;
1712 long_time_format
[1] = p1
;
1715 switch (XARGMATCH ("time style", style
,
1719 case full_iso_time_style
:
1720 long_time_format
[0] = long_time_format
[1] =
1721 "%Y-%m-%d %H:%M:%S.%N %z";
1724 case long_iso_time_style
:
1725 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
1728 case iso_time_style
:
1729 long_time_format
[0] = "%Y-%m-%d ";
1730 long_time_format
[1] = "%m-%d %H:%M";
1733 case locale_time_style
:
1734 if (hard_locale (LC_TIME
))
1737 for (i
= 0; i
< 2; i
++)
1738 long_time_format
[i
] =
1739 dcgettext (NULL
, long_time_format
[i
], LC_TIME
);
1747 /* Parse a string as part of the LS_COLORS variable; this may involve
1748 decoding all kinds of escape characters. If equals_end is set an
1749 unescaped equal sign ends the string, otherwise only a : or \0
1750 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1753 The resulting string is *not* null-terminated, but may contain
1756 Note that both dest and src are char **; on return they point to
1757 the first free byte after the array and the character that ended
1758 the input string, respectively. */
1761 get_funky_string (char **dest
, const char **src
, bool equals_end
,
1762 size_t *output_count
)
1764 int num
; /* For numerical codes */
1765 size_t count
; /* Something to count with */
1767 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1772 p
= *src
; /* We don't want to double-indirect */
1773 q
= *dest
; /* the whole darn time. */
1775 count
= 0; /* No characters counted in yet. */
1778 state
= ST_GND
; /* Start in ground state. */
1779 while (state
< ST_END
)
1783 case ST_GND
: /* Ground state (no escapes) */
1788 state
= ST_END
; /* End of string */
1791 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1795 state
= ST_CARET
; /* Caret escape */
1801 state
= ST_END
; /* End */
1804 /* else fall through */
1812 case ST_BACKSLASH
: /* Backslash escaped character */
1823 state
= ST_OCTAL
; /* Octal sequence */
1828 state
= ST_HEX
; /* Hex sequence */
1831 case 'a': /* Bell */
1832 num
= 7; /* Not all C compilers know what \a means */
1834 case 'b': /* Backspace */
1837 case 'e': /* Escape */
1840 case 'f': /* Form feed */
1843 case 'n': /* Newline */
1846 case 'r': /* Carriage return */
1852 case 'v': /* Vtab */
1855 case '?': /* Delete */
1858 case '_': /* Space */
1861 case '\0': /* End of string */
1862 state
= ST_ERROR
; /* Error! */
1864 default: /* Escaped character like \ ^ : = */
1868 if (state
== ST_BACKSLASH
)
1877 case ST_OCTAL
: /* Octal sequence */
1878 if (*p
< '0' || *p
> '7')
1885 num
= (num
<< 3) + (*(p
++) - '0');
1888 case ST_HEX
: /* Hex sequence */
1901 num
= (num
<< 4) + (*(p
++) - '0');
1909 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1917 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1927 case ST_CARET
: /* Caret escape */
1928 state
= ST_GND
; /* Should be the next state... */
1929 if (*p
>= '@' && *p
<= '~')
1931 *(q
++) = *(p
++) & 037;
1950 *output_count
= count
;
1952 return state
!= ST_ERROR
;
1956 parse_ls_color (void)
1958 const char *p
; /* Pointer to character being parsed */
1959 char *buf
; /* color_buf buffer pointer */
1960 int state
; /* State of parser */
1961 int ind_no
; /* Indicator number */
1962 char label
[3]; /* Indicator label */
1963 struct color_ext_type
*ext
; /* Extension we are working on */
1965 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1969 strcpy (label
, "??");
1971 /* This is an overly conservative estimate, but any possible
1972 LS_COLORS string will *not* generate a color_buf longer than
1973 itself, so it is a safe way of allocating a buffer in
1975 buf
= color_buf
= xstrdup (p
);
1982 case 1: /* First label character */
1990 /* Allocate new extension block and add to head of
1991 linked list (this way a later definition will
1992 override an earlier one, which can be useful for
1993 having terminal-specific defs override global). */
1995 ext
= xmalloc (sizeof *ext
);
1996 ext
->next
= color_ext_list
;
1997 color_ext_list
= ext
;
2000 ext
->ext
.string
= buf
;
2002 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2007 state
= 0; /* Done! */
2010 default: /* Assume it is file type label */
2017 case 2: /* Second label character */
2024 state
= -1; /* Error */
2027 case 3: /* Equal sign after indicator label */
2028 state
= -1; /* Assume failure... */
2029 if (*(p
++) == '=')/* It *should* be... */
2031 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
2033 if (STREQ (label
, indicator_name
[ind_no
]))
2035 color_indicator
[ind_no
].string
= buf
;
2036 state
= (get_funky_string (&buf
, &p
, false,
2037 &color_indicator
[ind_no
].len
)
2043 error (0, 0, _("unrecognized prefix: %s"), quotearg (label
));
2047 case 4: /* Equal sign after *.ext */
2050 ext
->seq
.string
= buf
;
2051 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2062 struct color_ext_type
*e
;
2063 struct color_ext_type
*e2
;
2066 _("unparsable value for LS_COLORS environment variable"));
2068 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
2074 print_with_color
= 0;
2077 if (color_indicator
[C_LINK
].len
== 6
2078 && !strncmp (color_indicator
[C_LINK
].string
, "target", 6))
2079 color_symlink_as_referent
= 1;
2082 /* Request that the directory named NAME have its contents listed later.
2083 If REALNAME is nonzero, it will be used instead of NAME when the
2084 directory name is printed. This allows symbolic links to directories
2085 to be treated as regular directories but still be listed under their
2086 real names. NAME == NULL is used to insert a marker entry for the
2087 directory named in REALNAME.
2088 If F is non-NULL, we use its dev/ino information to save
2089 a call to stat -- when doing a recursive (-R) traversal. */
2092 queue_directory (const char *name
, const char *realname
)
2094 struct pending
*new;
2096 new = xmalloc (sizeof *new);
2097 new->realname
= realname
? xstrdup (realname
) : NULL
;
2098 new->name
= name
? xstrdup (name
) : NULL
;
2099 new->next
= pending_dirs
;
2103 /* Read directory `name', and list the files in it.
2104 If `realname' is nonzero, print its name instead of `name';
2105 this is used for symbolic links to directories. */
2108 print_dir (const char *name
, const char *realname
)
2111 register struct dirent
*next
;
2112 register uintmax_t total_blocks
= 0;
2113 static int first
= 1;
2116 dirp
= opendir (name
);
2119 error (0, errno
, "%s", quotearg_colon (name
));
2126 struct stat dir_stat
;
2127 int fd
= dirfd (dirp
);
2129 /* If dirfd failed, endure the overhead of using stat. */
2131 ? fstat (fd
, &dir_stat
)
2132 : stat (name
, &dir_stat
)) < 0)
2134 error (0, errno
, _("cannot determine device and inode of %s"),
2135 quotearg_colon (name
));
2140 /* If we've already visited this dev/inode pair, warn that
2141 we've found a loop, and do not process this directory. */
2142 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
2144 error (0, 0, _("not listing already-listed directory: %s"),
2145 quotearg_colon (name
));
2149 DEV_INO_PUSH (dir_stat
.st_dev
, dir_stat
.st_ino
);
2152 /* Read the directory entries, and insert the subfiles into the `files'
2159 /* Set errno to zero so we can distinguish between a readdir failure
2160 and when readdir simply finds that there are no more entries. */
2162 if ((next
= readdir (dirp
)) == NULL
)
2166 /* Save/restore errno across closedir call. */
2171 /* Arrange to give a diagnostic after exiting this loop. */
2177 if (file_interesting (next
))
2179 enum filetype type
= unknown
;
2181 #if HAVE_STRUCT_DIRENT_D_TYPE
2182 if (next
->d_type
== DT_BLK
2183 || next
->d_type
== DT_CHR
2184 || next
->d_type
== DT_DIR
2185 || next
->d_type
== DT_FIFO
2186 || next
->d_type
== DT_LNK
2187 || next
->d_type
== DT_REG
2188 || next
->d_type
== DT_SOCK
)
2189 type
= next
->d_type
;
2191 total_blocks
+= gobble_file (next
->d_name
, type
, 0, name
);
2195 if (dirp
== NULL
|| CLOSEDIR (dirp
))
2197 error (0, errno
, _("reading directory %s"), quotearg_colon (name
));
2199 /* Don't return; print whatever we got. */
2202 /* Sort the directory contents. */
2205 /* If any member files are subdirectories, perhaps they should have their
2206 contents listed rather than being mentioned here as files. */
2209 extract_dirs_from_files (name
, 1);
2211 if (recursive
|| print_dir_name
)
2214 DIRED_PUTCHAR ('\n');
2217 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
2218 dired_pos
+= quote_name (stdout
, realname
? realname
: name
,
2219 dirname_quoting_options
, NULL
);
2220 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
2221 DIRED_FPUTS_LITERAL (":\n", stdout
);
2224 if (format
== long_format
|| print_block_size
)
2227 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2231 DIRED_FPUTS (p
, stdout
, strlen (p
));
2232 DIRED_PUTCHAR (' ');
2233 p
= human_readable (total_blocks
, buf
, human_output_opts
,
2234 ST_NBLOCKSIZE
, output_block_size
);
2235 DIRED_FPUTS (p
, stdout
, strlen (p
));
2236 DIRED_PUTCHAR ('\n');
2240 print_current_files ();
2243 /* Add `pattern' to the list of patterns for which files that match are
2247 add_ignore_pattern (const char *pattern
)
2249 register struct ignore_pattern
*ignore
;
2251 ignore
= xmalloc (sizeof *ignore
);
2252 ignore
->pattern
= pattern
;
2253 /* Add it to the head of the linked list. */
2254 ignore
->next
= ignore_patterns
;
2255 ignore_patterns
= ignore
;
2258 /* Return nonzero if the file in `next' should be listed. */
2261 file_interesting (const struct dirent
*next
)
2263 register struct ignore_pattern
*ignore
;
2265 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
2266 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
2269 if (really_all_files
2270 || next
->d_name
[0] != '.'
2272 && next
->d_name
[1] != '\0'
2273 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
2279 /* POSIX requires that a file size be printed without a sign, even
2280 when negative. Assume the typical case where negative sizes are
2281 actually positive values that have wrapped around. */
2284 unsigned_file_size (off_t size
)
2286 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
2289 /* Enter and remove entries in the table `files'. */
2291 /* Empty the table of files. */
2298 for (i
= 0; i
< files_index
; i
++)
2300 free (files
[i
].name
);
2301 if (files
[i
].linkname
)
2302 free (files
[i
].linkname
);
2306 inode_number_width
= 0;
2307 block_size_width
= 0;
2312 major_device_number_width
= 0;
2313 minor_device_number_width
= 0;
2314 file_size_width
= 0;
2317 /* Add a file to the current table of files.
2318 Verify that the file exists, and print an error message if it does not.
2319 Return the number of blocks that the file occupies. */
2322 gobble_file (const char *name
, enum filetype type
, int explicit_arg
,
2323 const char *dirname
)
2325 register uintmax_t blocks
;
2326 register char *path
;
2327 register struct fileinfo
*f
;
2329 if (files_index
== nfiles
)
2331 files
= xnrealloc (files
, nfiles
, 2 * sizeof *files
);
2335 f
= &files
[files_index
];
2341 || format_needs_stat
2342 || (format_needs_type
2345 /* FIXME: remove this disjunct.
2346 I don't think we care about symlinks here, but for now
2347 this won't make a big performance difference. */
2348 || type
== symbolic_link
2350 /* --indicator-style=classify (aka -F)
2351 requires that we stat each regular file
2352 to see if it's executable. */
2353 || (type
== normal
&& (indicator_style
== classify
2354 /* This is so that --color ends up
2355 highlighting files with the executable
2356 bit set even when options like -F are
2358 || print_with_color
)))))
2361 /* `path' is the absolute pathname of this file. */
2364 if (name
[0] == '/' || dirname
[0] == 0)
2365 path
= (char *) name
;
2368 path
= alloca (strlen (name
) + strlen (dirname
) + 2);
2369 attach (path
, dirname
, name
);
2372 switch (dereference
)
2375 err
= stat (path
, &f
->stat
);
2378 case DEREF_COMMAND_LINE_ARGUMENTS
:
2379 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
2383 err
= stat (path
, &f
->stat
);
2385 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2388 need_lstat
= (err
< 0
2390 : ! S_ISDIR (f
->stat
.st_mode
));
2394 /* stat failed because of ENOENT, maybe indicating a dangling
2395 symlink. Or stat succeeded, PATH does not refer to a
2396 directory, and --dereference-command-line-symlink-to-dir is
2397 in effect. Fall through so that we call lstat instead. */
2400 default: /* DEREF_NEVER */
2401 err
= lstat (path
, &f
->stat
);
2407 error (0, errno
, "%s", quotearg_colon (path
));
2413 if (format
== long_format
)
2415 int n
= file_has_acl (path
, &f
->stat
);
2416 f
->have_acl
= (0 < n
);
2418 error (0, errno
, "%s", quotearg_colon (path
));
2422 if (S_ISLNK (f
->stat
.st_mode
)
2423 && (format
== long_format
|| check_symlink_color
))
2426 struct stat linkstats
;
2428 get_link_name (path
, f
);
2429 linkpath
= make_link_path (path
, f
->linkname
);
2431 /* Avoid following symbolic links when possible, ie, when
2432 they won't be traced and when no indicator is needed. */
2434 && (indicator_style
!= none
|| check_symlink_color
)
2435 && stat (linkpath
, &linkstats
) == 0)
2439 /* Symbolic links to directories that are mentioned on the
2440 command line are automatically traced if not being
2442 if (!explicit_arg
|| format
== long_format
2443 || !S_ISDIR (linkstats
.st_mode
))
2445 /* Get the linked-to file's mode for the filetype indicator
2446 in long listings. */
2447 f
->linkmode
= linkstats
.st_mode
;
2455 if (S_ISLNK (f
->stat
.st_mode
))
2456 f
->filetype
= symbolic_link
;
2457 else if (S_ISDIR (f
->stat
.st_mode
))
2459 if (explicit_arg
&& !immediate_dirs
)
2460 f
->filetype
= arg_directory
;
2462 f
->filetype
= directory
;
2465 f
->filetype
= normal
;
2468 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
2469 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
2470 if (inode_number_width
< len
)
2471 inode_number_width
= len
;
2474 blocks
= ST_NBLOCKS (f
->stat
);
2476 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2477 int len
= strlen (human_readable (blocks
, buf
, human_output_opts
,
2478 ST_NBLOCKSIZE
, output_block_size
));
2479 if (block_size_width
< len
)
2480 block_size_width
= len
;
2485 int len
= format_user_width (f
->stat
.st_uid
);
2486 if (owner_width
< len
)
2492 int len
= format_group_width (f
->stat
.st_gid
);
2493 if (group_width
< len
)
2499 int len
= format_user_width (f
->stat
.st_uid
);
2500 if (author_width
< len
)
2505 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
2506 int len
= strlen (umaxtostr (f
->stat
.st_nlink
, buf
));
2507 if (nlink_width
< len
)
2511 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2513 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
2514 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
2515 if (major_device_number_width
< len
)
2516 major_device_number_width
= len
;
2517 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
2518 if (minor_device_number_width
< len
)
2519 minor_device_number_width
= len
;
2520 len
= major_device_number_width
+ 2 + minor_device_number_width
;
2521 if (file_size_width
< len
)
2522 file_size_width
= len
;
2526 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2527 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
2528 int len
= strlen (human_readable (size
, buf
, human_output_opts
,
2529 1, file_output_block_size
));
2530 if (file_size_width
< len
)
2531 file_size_width
= len
;
2537 #if HAVE_STRUCT_DIRENT_D_TYPE
2538 f
->stat
.st_mode
= DTTOIF (type
);
2543 f
->name
= xstrdup (name
);
2551 /* Put the name of the file that `filename' is a symbolic link to
2552 into the `linkname' field of `f'. */
2555 get_link_name (const char *filename
, struct fileinfo
*f
)
2557 f
->linkname
= xreadlink (filename
);
2558 if (f
->linkname
== NULL
)
2560 error (0, errno
, _("cannot read symbolic link %s"),
2561 quotearg_colon (filename
));
2566 /* If `linkname' is a relative path and `path' contains one or more
2567 leading directories, return `linkname' with those directories
2568 prepended; otherwise, return a copy of `linkname'.
2569 If `linkname' is zero, return zero. */
2572 make_link_path (const char *path
, const char *linkname
)
2580 if (*linkname
== '/')
2581 return xstrdup (linkname
);
2583 /* The link is to a relative path. Prepend any leading path
2584 in `path' to the link name. */
2585 linkbuf
= strrchr (path
, '/');
2587 return xstrdup (linkname
);
2589 bufsiz
= linkbuf
- path
+ 1;
2590 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
2591 strncpy (linkbuf
, path
, bufsiz
);
2592 strcpy (linkbuf
+ bufsiz
, linkname
);
2597 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2598 This is so we don't try to recurse on `././././. ...' */
2601 basename_is_dot_or_dotdot (const char *name
)
2603 char const *base
= base_name (name
);
2604 return DOT_OR_DOTDOT (base
);
2607 /* Remove any entries from `files' that are for directories,
2608 and queue them to be listed as directories instead.
2609 `dirname' is the prefix to prepend to each dirname
2610 to make it correct relative to ls's working dir.
2611 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2612 This is desirable when processing directories recursively. */
2615 extract_dirs_from_files (const char *dirname
, int ignore_dot_and_dot_dot
)
2620 if (*dirname
&& LOOP_DETECT
)
2622 /* Insert a marker entry first. When we dequeue this marker entry,
2623 we'll know that DIRNAME has been processed and may be removed
2624 from the set of active directories. */
2625 queue_directory (NULL
, dirname
);
2628 /* Queue the directories last one first, because queueing reverses the
2630 for (i
= files_index
; i
-- != 0; )
2631 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
2632 && (!ignore_dot_and_dot_dot
2633 || !basename_is_dot_or_dotdot (files
[i
].name
)))
2635 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
2637 queue_directory (files
[i
].name
, files
[i
].linkname
);
2641 char *path
= path_concat (dirname
, files
[i
].name
, NULL
);
2642 queue_directory (path
, files
[i
].linkname
);
2645 if (files
[i
].filetype
== arg_directory
)
2646 free (files
[i
].name
);
2649 /* Now delete the directories from the table, compacting all the remaining
2652 for (i
= 0, j
= 0; i
< files_index
; i
++)
2654 if (files
[i
].filetype
!= arg_directory
)
2657 files
[j
] = files
[i
];
2664 /* Use strcoll to compare strings in this locale. If an error occurs,
2665 report an error and longjmp to failed_strcoll. */
2667 static jmp_buf failed_strcoll
;
2670 xstrcoll (char const *a
, char const *b
)
2674 diff
= strcoll (a
, b
);
2677 error (0, errno
, _("cannot compare file names %s and %s"),
2678 quote_n (0, a
), quote_n (1, b
));
2680 longjmp (failed_strcoll
, 1);
2685 /* Comparison routines for sorting the files. */
2687 typedef void const *V
;
2690 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
2691 int (*cmp
) (char const *, char const *))
2693 int diff
= CTIME_CMP (b
->stat
, a
->stat
);
2694 return diff
? diff
: cmp (a
->name
, b
->name
);
2696 static int compare_ctime (V a
, V b
) { return cmp_ctime (a
, b
, xstrcoll
); }
2697 static int compstr_ctime (V a
, V b
) { return cmp_ctime (a
, b
, strcmp
); }
2698 static int rev_cmp_ctime (V a
, V b
) { return compare_ctime (b
, a
); }
2699 static int rev_str_ctime (V a
, V b
) { return compstr_ctime (b
, a
); }
2702 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
2703 int (*cmp
) (char const *, char const *))
2705 int diff
= MTIME_CMP (b
->stat
, a
->stat
);
2706 return diff
? diff
: cmp (a
->name
, b
->name
);
2708 static int compare_mtime (V a
, V b
) { return cmp_mtime (a
, b
, xstrcoll
); }
2709 static int compstr_mtime (V a
, V b
) { return cmp_mtime (a
, b
, strcmp
); }
2710 static int rev_cmp_mtime (V a
, V b
) { return compare_mtime (b
, a
); }
2711 static int rev_str_mtime (V a
, V b
) { return compstr_mtime (b
, a
); }
2714 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
2715 int (*cmp
) (char const *, char const *))
2717 int diff
= ATIME_CMP (b
->stat
, a
->stat
);
2718 return diff
? diff
: cmp (a
->name
, b
->name
);
2720 static int compare_atime (V a
, V b
) { return cmp_atime (a
, b
, xstrcoll
); }
2721 static int compstr_atime (V a
, V b
) { return cmp_atime (a
, b
, strcmp
); }
2722 static int rev_cmp_atime (V a
, V b
) { return compare_atime (b
, a
); }
2723 static int rev_str_atime (V a
, V b
) { return compstr_atime (b
, a
); }
2726 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
2727 int (*cmp
) (char const *, char const *))
2729 int diff
= longdiff (b
->stat
.st_size
, a
->stat
.st_size
);
2730 return diff
? diff
: cmp (a
->name
, b
->name
);
2732 static int compare_size (V a
, V b
) { return cmp_size (a
, b
, xstrcoll
); }
2733 static int compstr_size (V a
, V b
) { return cmp_size (a
, b
, strcmp
); }
2734 static int rev_cmp_size (V a
, V b
) { return compare_size (b
, a
); }
2735 static int rev_str_size (V a
, V b
) { return compstr_size (b
, a
); }
2738 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
2740 return strverscmp (a
->name
, b
->name
);
2742 static int compare_version (V a
, V b
) { return cmp_version (a
, b
); }
2743 static int rev_cmp_version (V a
, V b
) { return compare_version (b
, a
); }
2746 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
2747 int (*cmp
) (char const *, char const *))
2749 return cmp (a
->name
, b
->name
);
2751 static int compare_name (V a
, V b
) { return cmp_name (a
, b
, xstrcoll
); }
2752 static int compstr_name (V a
, V b
) { return cmp_name (a
, b
, strcmp
); }
2753 static int rev_cmp_name (V a
, V b
) { return compare_name (b
, a
); }
2754 static int rev_str_name (V a
, V b
) { return compstr_name (b
, a
); }
2756 /* Compare file extensions. Files with no extension are `smallest'.
2757 If extensions are the same, compare by filenames instead. */
2760 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
2761 int (*cmp
) (char const *, char const *))
2763 char const *base1
= strrchr (a
->name
, '.');
2764 char const *base2
= strrchr (b
->name
, '.');
2765 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
2766 return diff
? diff
: cmp (a
->name
, b
->name
);
2768 static int compare_extension (V a
, V b
) { return cmp_extension (a
, b
, xstrcoll
); }
2769 static int compstr_extension (V a
, V b
) { return cmp_extension (a
, b
, strcmp
); }
2770 static int rev_cmp_extension (V a
, V b
) { return compare_extension (b
, a
); }
2771 static int rev_str_extension (V a
, V b
) { return compstr_extension (b
, a
); }
2773 /* Sort the files now in the table. */
2778 /* `func' must be `volatile', so it can't be
2779 clobbered by a `longjmp' into this function. */
2780 int (* volatile func
) (V
, V
);
2790 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
2793 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
2796 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
2803 func
= sort_reverse
? rev_cmp_name
: compare_name
;
2805 case sort_extension
:
2806 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
2809 func
= sort_reverse
? rev_cmp_size
: compare_size
;
2812 func
= sort_reverse
? rev_cmp_version
: compare_version
;
2818 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2819 ignore strcoll failures, as a failing strcoll might be a
2820 comparison function that is not a total order, and if we ignored
2821 the failure this might cause qsort to dump core. */
2823 if (setjmp (failed_strcoll
))
2831 func
= sort_reverse
? rev_str_ctime
: compstr_ctime
;
2834 func
= sort_reverse
? rev_str_mtime
: compstr_mtime
;
2837 func
= sort_reverse
? rev_str_atime
: compstr_atime
;
2844 func
= sort_reverse
? rev_str_name
: compstr_name
;
2846 case sort_extension
:
2847 func
= sort_reverse
? rev_str_extension
: compstr_extension
;
2850 func
= sort_reverse
? rev_str_size
: compstr_size
;
2857 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
2860 /* List all the files now in the table. */
2863 print_current_files (void)
2870 for (i
= 0; i
< files_index
; i
++)
2872 print_file_name_and_frills (files
+ i
);
2878 print_many_per_line ();
2882 print_horizontal ();
2886 print_with_commas ();
2890 for (i
= 0; i
< files_index
; i
++)
2892 print_long_format (files
+ i
);
2893 DIRED_PUTCHAR ('\n');
2899 /* Return the expected number of columns in a long-format time stamp,
2900 or zero if it cannot be calculated. */
2903 long_time_expected_width (void)
2905 static int width
= -1;
2910 struct tm
const *tm
= localtime (&epoch
);
2911 char const *fmt
= long_time_format
[0];
2913 char *buf
= initbuf
;
2914 size_t bufsize
= sizeof initbuf
;
2920 len
= nstrftime (buf
, bufsize
, fmt
, tm
, 0, 0);
2923 buf
= alloca (bufsize
*= 2);
2926 width
= mbsnwidth (buf
, len
, 0);
2934 /* Get the current time. */
2937 get_current_time (void)
2939 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2941 struct timespec timespec
;
2942 if (clock_gettime (CLOCK_REALTIME
, ×pec
) == 0)
2944 current_time
= timespec
.tv_sec
;
2945 current_time_ns
= timespec
.tv_nsec
;
2951 /* The clock does not have nanosecond resolution, so get the maximum
2952 possible value for the current time that is consistent with the
2953 reported clock. That way, files are not considered to be in the
2954 future merely because their time stamps have higher resolution
2955 than the clock resolution. */
2957 #if HAVE_GETTIMEOFDAY
2959 struct timeval timeval
;
2960 if (gettimeofday (&timeval
, NULL
) == 0)
2962 current_time
= timeval
.tv_sec
;
2963 current_time_ns
= timeval
.tv_usec
* 1000 + 999;
2969 current_time
= time (NULL
);
2970 current_time_ns
= 999999999;
2973 /* Print the name or id of the user with id U, using a print width of
2977 format_user (uid_t u
, int width
)
2979 char const *name
= (numeric_ids
? NULL
: getuser (u
));
2981 printf ("%-*s ", width
, name
);
2983 printf ("%*lu ", width
, (unsigned long int) u
);
2988 /* Likewise, for groups. */
2991 format_group (gid_t g
, int width
)
2993 char const *name
= (numeric_ids
? NULL
: getgroup (g
));
2995 printf ("%-*s ", width
, name
);
2997 printf ("%*lu ", width
, (unsigned long int) g
);
3002 /* Return the number of bytes that format_user will print. */
3005 format_user_width (uid_t u
)
3007 char const *name
= (numeric_ids
? NULL
: getuser (u
));
3008 char buf
[INT_BUFSIZE_BOUND (unsigned long int)];
3013 sprintf (buf
, "%lu", (unsigned long int) u
);
3017 len
= strlen (name
);
3019 error (EXIT_FAILURE
, 0, _("User name too long"));
3023 /* Likewise, for groups. */
3026 format_group_width (gid_t g
)
3028 char const *name
= (numeric_ids
? NULL
: getgroup (g
));
3029 char buf
[INT_BUFSIZE_BOUND (unsigned long int)];
3034 sprintf (buf
, "%lu", (unsigned long int) g
);
3038 len
= strlen (name
);
3040 error (EXIT_FAILURE
, 0, _("Group name too long"));
3045 /* Print information about F in long format. */
3048 print_long_format (const struct fileinfo
*f
)
3052 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
3053 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
3054 + sizeof (modebuf
) - 1 + 1 /* mode string */
3055 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3056 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
3057 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
3058 + 35 + 1 /* usual length of time/date -- may be longer; see below */
3060 char *buf
= init_bigbuf
;
3061 size_t bufsize
= sizeof (init_bigbuf
);
3065 int when_ns
IF_LINT (= 0);
3066 struct tm
*when_local
;
3068 /* Compute mode string. On most systems, it's based on st_mode.
3069 On systems with migration (via the stat.st_dm_mode field), use
3070 the file's migrated status. */
3071 mode_string (ST_DM_MODE (f
->stat
), modebuf
);
3073 modebuf
[10] = (FILE_HAS_ACL (f
) ? '+' : ' ');
3079 when
= f
->stat
.st_ctime
;
3080 when_ns
= TIMESPEC_NS (f
->stat
.st_ctim
);
3083 when
= f
->stat
.st_mtime
;
3084 when_ns
= TIMESPEC_NS (f
->stat
.st_mtim
);
3087 when
= f
->stat
.st_atime
;
3088 when_ns
= TIMESPEC_NS (f
->stat
.st_atim
);
3096 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
3097 sprintf (p
, "%*s ", inode_number_width
,
3098 umaxtostr (f
->stat
.st_ino
, hbuf
));
3099 p
+= inode_number_width
+ 1;
3102 if (print_block_size
)
3104 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
3105 sprintf (p
, "%*s ", block_size_width
,
3106 human_readable (ST_NBLOCKS (f
->stat
), hbuf
, human_output_opts
,
3107 ST_NBLOCKSIZE
, output_block_size
));
3108 p
+= block_size_width
+ 1;
3111 /* The last byte of the mode string is the POSIX
3112 "optional alternate access method flag". */
3114 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
3115 sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
3116 umaxtostr (f
->stat
.st_nlink
, hbuf
));
3118 p
+= sizeof modebuf
+ nlink_width
+ 1;
3122 if (print_owner
| print_group
| print_author
)
3124 DIRED_FPUTS (buf
, stdout
, p
- buf
);
3127 format_user (f
->stat
.st_uid
, owner_width
);
3130 format_group (f
->stat
.st_gid
, group_width
);
3133 format_user (f
->stat
.st_author
, author_width
);
3138 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
3140 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
3141 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
3142 int blanks_width
= (file_size_width
3143 - (major_device_number_width
+ 2
3144 + minor_device_number_width
));
3145 sprintf (p
, "%*s, %*s ",
3146 major_device_number_width
+ MAX (0, blanks_width
),
3147 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
3148 minor_device_number_width
,
3149 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
3153 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
3154 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3155 sprintf (p
, "%*s ", file_size_width
,
3156 human_readable (size
, hbuf
, human_output_opts
,
3157 1, file_output_block_size
));
3160 p
+= file_size_width
+ 1;
3162 if ((when_local
= localtime (&when
)))
3164 time_t six_months_ago
;
3168 /* If the file appears to be in the future, update the current
3169 time, in case the file happens to have been modified since
3170 the last time we checked the clock. */
3171 if (current_time
< when
3172 || (current_time
== when
&& current_time_ns
< when_ns
))
3174 /* Note that get_current_time calls gettimeofday which, on some non-
3175 compliant systems, clobbers the buffer used for localtime's result.
3176 But it's ok here, because we use a gettimeofday wrapper that
3177 saves and restores the buffer around the gettimeofday call. */
3178 get_current_time ();
3181 /* Consider a time to be recent if it is within the past six
3182 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3183 31556952 seconds on the average. Write this value as an
3184 integer constant to avoid floating point hassles. */
3185 six_months_ago
= current_time
- 31556952 / 2;
3186 recent
= (six_months_ago
<= when
3187 && (when
< current_time
3188 || (when
== current_time
&& when_ns
<= current_time_ns
)));
3189 fmt
= long_time_format
[recent
];
3195 s
= nstrftime (p
, buf
+ bufsize
- p
- 1, fmt
,
3196 when_local
, 0, when_ns
);
3199 newbuf
= alloca (bufsize
*= 2);
3200 memcpy (newbuf
, buf
, p
- buf
);
3201 p
= newbuf
+ (p
- buf
);
3208 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3213 /* The time cannot be represented as a local time;
3214 print it as a huge integer number of seconds. */
3215 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
3216 sprintf (p
, "%*s ", long_time_expected_width (),
3217 (TYPE_SIGNED (time_t)
3218 ? imaxtostr (when
, hbuf
)
3219 : umaxtostr (when
, hbuf
)));
3223 DIRED_FPUTS (buf
, stdout
, p
- buf
);
3224 print_name_with_quoting (f
->name
, FILE_OR_LINK_MODE (f
), f
->linkok
,
3227 if (f
->filetype
== symbolic_link
)
3231 DIRED_FPUTS_LITERAL (" -> ", stdout
);
3232 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
- 1,
3234 if (indicator_style
!= none
)
3235 print_type_indicator (f
->linkmode
);
3238 else if (indicator_style
!= none
)
3239 print_type_indicator (f
->stat
.st_mode
);
3242 /* Output to OUT a quoted representation of the file name NAME,
3243 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3244 Store the number of screen columns occupied by NAME's quoted
3245 representation into WIDTH, if non-NULL. Return the number of bytes
3249 quote_name (FILE *out
, const char *name
, struct quoting_options
const *options
,
3252 char smallbuf
[BUFSIZ
];
3253 size_t len
= quotearg_buffer (smallbuf
, sizeof smallbuf
, name
, -1, options
);
3255 size_t displayed_width
IF_LINT (= 0);
3257 if (len
< sizeof smallbuf
)
3261 buf
= alloca (len
+ 1);
3262 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
3265 if (qmark_funny_chars
)
3270 char const *p
= buf
;
3271 char const *plimit
= buf
+ len
;
3273 displayed_width
= 0;
3278 case ' ': case '!': case '"': case '#': case '%':
3279 case '&': case '\'': case '(': case ')': case '*':
3280 case '+': case ',': case '-': case '.': case '/':
3281 case '0': case '1': case '2': case '3': case '4':
3282 case '5': case '6': case '7': case '8': case '9':
3283 case ':': case ';': case '<': case '=': case '>':
3285 case 'A': case 'B': case 'C': case 'D': case 'E':
3286 case 'F': case 'G': case 'H': case 'I': case 'J':
3287 case 'K': case 'L': case 'M': case 'N': case 'O':
3288 case 'P': case 'Q': case 'R': case 'S': case 'T':
3289 case 'U': case 'V': case 'W': case 'X': case 'Y':
3291 case '[': case '\\': case ']': case '^': case '_':
3292 case 'a': case 'b': case 'c': case 'd': case 'e':
3293 case 'f': case 'g': case 'h': case 'i': case 'j':
3294 case 'k': case 'l': case 'm': case 'n': case 'o':
3295 case 'p': case 'q': case 'r': case 's': case 't':
3296 case 'u': case 'v': case 'w': case 'x': case 'y':
3297 case 'z': case '{': case '|': case '}': case '~':
3298 /* These characters are printable ASCII characters. */
3300 displayed_width
+= 1;
3303 /* If we have a multibyte sequence, copy it until we
3304 reach its end, replacing each non-printable multibyte
3305 character with a single question mark. */
3308 memset (&mbstate
, 0, sizeof mbstate
);
3315 bytes
= mbrtowc (&wc
, p
, plimit
- p
, &mbstate
);
3317 if (bytes
== (size_t) -1)
3319 /* An invalid multibyte sequence was
3320 encountered. Skip one input byte, and
3321 put a question mark. */
3324 displayed_width
+= 1;
3328 if (bytes
== (size_t) -2)
3330 /* An incomplete multibyte character
3331 at the end. Replace it entirely with
3335 displayed_width
+= 1;
3340 /* A null wide character was encountered. */
3346 /* A printable multibyte character.
3348 for (; bytes
> 0; --bytes
)
3350 displayed_width
+= w
;
3354 /* An unprintable multibyte character.
3355 Replace it entirely with a question
3359 displayed_width
+= 1;
3362 while (! mbsinit (&mbstate
));
3367 /* The buffer may have shrunk. */
3374 char const *plimit
= buf
+ len
;
3378 if (! ISPRINT ((unsigned char) *p
))
3382 displayed_width
= len
;
3385 else if (width
!= NULL
)
3389 displayed_width
= mbsnwidth (buf
, len
, 0);
3393 char const *p
= buf
;
3394 char const *plimit
= buf
+ len
;
3396 displayed_width
= 0;
3399 if (ISPRINT ((unsigned char) *p
))
3407 fwrite (buf
, 1, len
, out
);
3409 *width
= displayed_width
;
3414 print_name_with_quoting (const char *p
, mode_t mode
, int linkok
,
3415 struct obstack
*stack
)
3417 if (print_with_color
)
3418 print_color_indicator (p
, mode
, linkok
);
3421 PUSH_CURRENT_DIRED_POS (stack
);
3423 dired_pos
+= quote_name (stdout
, p
, filename_quoting_options
, NULL
);
3426 PUSH_CURRENT_DIRED_POS (stack
);
3428 if (print_with_color
)
3429 prep_non_filename_text ();
3433 prep_non_filename_text (void)
3435 if (color_indicator
[C_END
].string
!= NULL
)
3436 put_indicator (&color_indicator
[C_END
]);
3439 put_indicator (&color_indicator
[C_LEFT
]);
3440 put_indicator (&color_indicator
[C_NORM
]);
3441 put_indicator (&color_indicator
[C_RIGHT
]);
3445 /* Print the file name of `f' with appropriate quoting.
3446 Also print file size, inode number, and filetype indicator character,
3447 as requested by switches. */
3450 print_file_name_and_frills (const struct fileinfo
*f
)
3452 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
3455 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
3456 umaxtostr (f
->stat
.st_ino
, buf
));
3458 if (print_block_size
)
3459 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
3460 human_readable (ST_NBLOCKS (f
->stat
), buf
, human_output_opts
,
3461 ST_NBLOCKSIZE
, output_block_size
));
3463 print_name_with_quoting (f
->name
, FILE_OR_LINK_MODE (f
), f
->linkok
, NULL
);
3465 if (indicator_style
!= none
)
3466 print_type_indicator (f
->stat
.st_mode
);
3470 print_type_indicator (mode_t mode
)
3476 if (indicator_style
== classify
&& (mode
& S_IXUGO
))
3485 else if (S_ISLNK (mode
))
3487 else if (S_ISFIFO (mode
))
3489 else if (S_ISSOCK (mode
))
3491 else if (S_ISDOOR (mode
))
3502 print_color_indicator (const char *name
, mode_t mode
, int linkok
)
3505 struct color_ext_type
*ext
; /* Color extension */
3506 size_t len
; /* Length of name */
3508 /* Is this a nonexistent file? If so, linkok == -1. */
3510 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
3519 else if (S_ISLNK (mode
))
3520 type
= ((!linkok
&& color_indicator
[C_ORPHAN
].string
)
3521 ? C_ORPHAN
: C_LINK
);
3522 else if (S_ISFIFO (mode
))
3524 else if (S_ISSOCK (mode
))
3526 else if (S_ISBLK (mode
))
3528 else if (S_ISCHR (mode
))
3530 else if (S_ISDOOR (mode
))
3533 if (type
== C_FILE
&& (mode
& S_IXUGO
) != 0)
3536 /* Check the file's suffix only if still classified as C_FILE. */
3540 /* Test if NAME has a recognized suffix. */
3542 len
= strlen (name
);
3543 name
+= len
; /* Pointer to final \0. */
3544 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
3546 if (ext
->ext
.len
<= len
3547 && strncmp (name
- ext
->ext
.len
, ext
->ext
.string
,
3554 put_indicator (&color_indicator
[C_LEFT
]);
3555 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
3556 put_indicator (&color_indicator
[C_RIGHT
]);
3559 /* Output a color indicator (which may contain nulls). */
3561 put_indicator (const struct bin_str
*ind
)
3564 register const char *p
;
3568 for (i
= ind
->len
; i
!= 0; --i
)
3572 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3573 Return zero if the write is successful or if the string length is zero.
3574 Return nonzero if the write fails. */
3576 put_indicator_direct (const struct bin_str
*ind
)
3583 return (full_write (STDOUT_FILENO
, ind
->string
, len
) != len
);
3587 length_of_file_name_and_frills (const struct fileinfo
*f
)
3589 register size_t len
= 0;
3591 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
3594 len
+= 1 + (format
== with_commas
3595 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
3596 : inode_number_width
);
3598 if (print_block_size
)
3599 len
+= 1 + (format
== with_commas
3600 ? strlen (human_readable (ST_NBLOCKS (f
->stat
), buf
,
3601 human_output_opts
, ST_NBLOCKSIZE
,
3603 : block_size_width
);
3605 quote_name (NULL
, f
->name
, filename_quoting_options
, &name_width
);
3608 if (indicator_style
!= none
)
3610 mode_t filetype
= f
->stat
.st_mode
;
3612 if (S_ISREG (filetype
))
3614 if (indicator_style
== classify
3615 && (f
->stat
.st_mode
& S_IXUGO
))
3618 else if (S_ISDIR (filetype
)
3619 || S_ISLNK (filetype
)
3620 || S_ISFIFO (filetype
)
3621 || S_ISSOCK (filetype
)
3622 || S_ISDOOR (filetype
)
3631 print_many_per_line (void)
3633 size_t row
; /* Current row. */
3634 size_t cols
= calculate_columns (true);
3635 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
3637 /* Calculate the number of rows that will be in each column except possibly
3638 for a short column on the right. */
3639 size_t rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
3641 for (row
= 0; row
< rows
; row
++)
3644 size_t filesno
= row
;
3647 /* Print the next row. */
3650 size_t name_length
= length_of_file_name_and_frills (files
+ filesno
);
3651 size_t max_name_length
= line_fmt
->col_arr
[col
++];
3652 print_file_name_and_frills (files
+ filesno
);
3655 if (filesno
>= files_index
)
3658 indent (pos
+ name_length
, pos
+ max_name_length
);
3659 pos
+= max_name_length
;
3666 print_horizontal (void)
3670 size_t cols
= calculate_columns (false);
3671 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
3672 size_t name_length
= length_of_file_name_and_frills (files
);
3673 size_t max_name_length
= line_fmt
->col_arr
[0];
3675 /* Print first entry. */
3676 print_file_name_and_frills (files
);
3679 for (filesno
= 1; filesno
< files_index
; ++filesno
)
3681 size_t col
= filesno
% cols
;
3690 indent (pos
+ name_length
, pos
+ max_name_length
);
3691 pos
+= max_name_length
;
3694 print_file_name_and_frills (files
+ filesno
);
3696 name_length
= length_of_file_name_and_frills (files
+ filesno
);
3697 max_name_length
= line_fmt
->col_arr
[col
];
3703 print_with_commas (void)
3708 for (filesno
= 0; filesno
< files_index
; filesno
++)
3710 size_t len
= length_of_file_name_and_frills (files
+ filesno
);
3716 if (pos
+ len
+ 2 < line_length
)
3728 putchar (separator
);
3731 print_file_name_and_frills (files
+ filesno
);
3737 /* Assuming cursor is at position FROM, indent up to position TO.
3738 Use a TAB character instead of two or more spaces whenever possible. */
3741 indent (size_t from
, size_t to
)
3745 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
3748 from
+= tabsize
- from
% tabsize
;
3758 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3759 /* FIXME: maybe remove this function someday. See about using a
3760 non-malloc'ing version of path_concat. */
3763 attach (char *dest
, const char *dirname
, const char *name
)
3765 const char *dirnamep
= dirname
;
3767 /* Copy dirname if it is not ".". */
3768 if (dirname
[0] != '.' || dirname
[1] != 0)
3771 *dest
++ = *dirnamep
++;
3772 /* Add '/' if `dirname' doesn't already end with it. */
3773 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
3781 /* Allocate enough column info suitable for the current number of
3782 files and display columns, and initialize the info to represent the
3783 narrowest possible columns. */
3786 init_column_info (void)
3789 size_t max_cols
= MIN (max_idx
, files_index
);
3791 /* Currently allocated columns in column_info. */
3792 static size_t column_info_alloc
;
3794 if (column_info_alloc
< max_cols
)
3796 size_t new_column_info_alloc
;
3799 if (max_cols
< max_idx
/ 2)
3801 /* The number of columns is far less than the display width
3802 allows. Grow the allocation, but only so that it's
3803 double the current requirements. If the display is
3804 extremely wide, this avoids allocating a lot of memory
3805 that is never needed. */
3806 column_info
= xnrealloc (column_info
, max_cols
,
3807 2 * sizeof *column_info
);
3808 new_column_info_alloc
= 2 * max_cols
;
3812 column_info
= xnrealloc (column_info
, max_idx
, sizeof *column_info
);
3813 new_column_info_alloc
= max_idx
;
3816 /* Allocate the new size_t objects by computing the triangle
3817 formula n * (n + 1) / 2, except that we don't need to
3818 allocate the part of the triangle that we've already
3819 allocated. Check for address arithmetic overflow. */
3821 size_t column_info_growth
= new_column_info_alloc
- column_info_alloc
;
3822 size_t s
= column_info_alloc
+ 1 + new_column_info_alloc
;
3823 size_t t
= s
* column_info_growth
;
3824 if (s
< new_column_info_alloc
|| t
/ column_info_growth
!= s
)
3826 p
= xnmalloc (t
/ 2, sizeof *p
);
3829 /* Grow the triangle by parceling out the cells just allocated. */
3830 for (i
= column_info_alloc
; i
< new_column_info_alloc
; i
++)
3832 column_info
[i
].col_arr
= p
;
3836 column_info_alloc
= new_column_info_alloc
;
3839 for (i
= 0; i
< max_cols
; ++i
)
3843 column_info
[i
].valid_len
= true;
3844 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
3845 for (j
= 0; j
<= i
; ++j
)
3846 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
3850 /* Calculate the number of columns needed to represent the current set
3851 of files in the current display width. */
3854 calculate_columns (bool by_columns
)
3856 size_t filesno
; /* Index into files. */
3857 size_t cols
; /* Number of files across. */
3859 /* Normally the maximum number of columns is determined by the
3860 screen width. But if few files are available this might limit it
3862 size_t max_cols
= MIN (max_idx
, files_index
);
3864 init_column_info ();
3866 /* Compute the maximum number of possible columns. */
3867 for (filesno
= 0; filesno
< files_index
; ++filesno
)
3869 size_t name_length
= length_of_file_name_and_frills (files
+ filesno
);
3872 for (i
= 0; i
< max_cols
; ++i
)
3874 if (column_info
[i
].valid_len
)
3876 size_t idx
= (by_columns
3877 ? filesno
/ ((files_index
+ i
) / (i
+ 1))
3878 : filesno
% (i
+ 1));
3879 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
3881 if (column_info
[i
].col_arr
[idx
] < real_length
)
3883 column_info
[i
].line_len
+= (real_length
3884 - column_info
[i
].col_arr
[idx
]);
3885 column_info
[i
].col_arr
[idx
] = real_length
;
3886 column_info
[i
].valid_len
= (column_info
[i
].line_len
3893 /* Find maximum allowed columns. */
3894 for (cols
= max_cols
; 1 < cols
; --cols
)
3896 if (column_info
[cols
- 1].valid_len
)
3907 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
3911 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
3913 List information about the FILEs (the current directory by default).\n\
3914 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3918 Mandatory arguments to long options are mandatory for short options too.\n\
3921 -a, --all do not hide entries starting with .\n\
3922 -A, --almost-all do not list implied . and ..\n\
3923 --author print the author of each file\n\
3924 -b, --escape print octal escapes for nongraphic characters\n\
3927 --block-size=SIZE use SIZE-byte blocks\n\
3928 -B, --ignore-backups do not list implied entries ending with ~\n\
3929 -c with -lt: sort by, and show, ctime (time of last\n\
3930 modification of file status information)\n\
3931 with -l: show ctime and sort by name\n\
3932 otherwise: sort by ctime\n\
3935 -C list entries by columns\n\
3936 --color[=WHEN] control whether color is used to distinguish file\n\
3937 types. WHEN may be `never', `always', or `auto'\n\
3938 -d, --directory list directory entries instead of contents,\n\
3939 and do not dereference symbolic links\n\
3940 -D, --dired generate output designed for Emacs' dired mode\n\
3943 -f do not sort, enable -aU, disable -lst\n\
3944 -F, --classify append indicator (one of */=@|) to entries\n\
3945 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3946 single-column -1, verbose -l, vertical -C\n\
3947 --full-time like -l --time-style=full-iso\n\
3950 -g like -l, but do not list owner\n\
3951 -G, --no-group inhibit display of group information\n\
3952 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3953 --si likewise, but use powers of 1000 not 1024\n\
3954 -H, --dereference-command-line\n\
3955 follow symbolic links listed on the command line\n\
3956 --dereference-command-line-symlink-to-dir\n\
3957 follow each command line symbolic link\n\
3958 that points to a directory\n\
3961 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3962 none (default), classify (-F), file-type (-p)\n\
3963 -i, --inode print index number of each file\n\
3964 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3965 -k like --block-size=1K\n\
3968 -l use a long listing format\n\
3969 -L, --dereference when showing file information for a symbolic\n\
3970 link, show information for the file the link\n\
3971 references rather than for the link itself\n\
3972 -m fill width with a comma separated list of entries\n\
3975 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3976 -N, --literal print raw entry names (don't treat e.g. control\n\
3977 characters specially)\n\
3978 -o like -l, but do not list group information\n\
3979 -p, --file-type append indicator (one of /=@|) to entries\n\
3982 -q, --hide-control-chars print ? instead of non graphic characters\n\
3983 --show-control-chars show non graphic characters as-is (default\n\
3984 unless program is `ls' and output is a terminal)\n\
3985 -Q, --quote-name enclose entry names in double quotes\n\
3986 --quoting-style=WORD use quoting style WORD for entry names:\n\
3987 literal, locale, shell, shell-always, c, escape\n\
3990 -r, --reverse reverse order while sorting\n\
3991 -R, --recursive list subdirectories recursively\n\
3992 -s, --size print size of each file, in blocks\n\
3995 -S sort by file size\n\
3996 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3998 status -c, time -t, atime -u, access -u, use -u\n\
3999 --time=WORD show time as WORD instead of modification time:\n\
4000 atime, access, use, ctime or status; use\n\
4001 specified time as sort key if --sort=time\n\
4004 --time-style=STYLE show times using style STYLE:\n\
4005 full-iso, long-iso, iso, locale, +FORMAT\n\
4006 FORMAT is interpreted like `date'; if FORMAT is\n\
4007 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4008 non-recent files and FORMAT2 to recent files;\n\
4009 if STYLE is prefixed with `posix-', STYLE\n\
4010 takes effect only outside the POSIX locale\n\
4011 -t sort by modification time\n\
4012 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4015 -u with -lt: sort by, and show, access time\n\
4016 with -l: show access time and sort by name\n\
4017 otherwise: sort by access time\n\
4018 -U do not sort; list entries in directory order\n\
4019 -v sort by version\n\
4022 -w, --width=COLS assume screen width instead of current value\n\
4023 -x list entries by lines instead of by columns\n\
4024 -X sort alphabetically by entry extension\n\
4025 -1 list one file per line\n\
4027 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
4028 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
4030 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4031 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4035 By default, color is not used to distinguish types of files. That is\n\
4036 equivalent to using --color=none. Using the --color option without the\n\
4037 optional WHEN argument is equivalent to using --color=always. With\n\
4038 --color=auto, color codes are output only if standard output is connected\n\
4039 to a terminal (tty).\n\
4041 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);