*** empty log message ***
[coreutils.git] / src / ls.c
blob7cbfadbd8d43117b2bb96eab593fa84c02cf0bdf
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-1999 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_INTTYPES_H
47 # include <inttypes.h>
48 #endif
50 #if HAVE_TERMIOS_H
51 # include <termios.h>
52 #endif
54 #ifdef GWINSZ_IN_SYS_IOCTL
55 # include <sys/ioctl.h>
56 #endif
58 #include <stdio.h>
59 #include <grp.h>
60 #include <pwd.h>
61 #include <getopt.h>
63 #include "system.h"
64 #include <fnmatch.h>
66 #include "obstack.h"
67 #include "ls.h"
68 #include "closeout.h"
69 #include "error.h"
70 #include "human.h"
71 #include "argmatch.h"
72 #include "xstrtol.h"
73 #include "strverscmp.h"
74 #include "quotearg.h"
75 #include "filemode.h"
76 #include "path-concat.h"
78 #define obstack_chunk_alloc malloc
79 #define obstack_chunk_free free
81 /* Return an int indicating the result of comparing two integers.
82 Subtracting doesn't always work, due to overflow. */
83 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
85 /* The field width for inode numbers. On some hosts inode numbers are
86 64 bits, so columns won't line up exactly when a huge inode number
87 is encountered, but in practice 7 digits is usually enough. */
88 #ifndef INODE_DIGITS
89 # define INODE_DIGITS 7
90 #endif
92 #ifdef S_ISLNK
93 # define HAVE_SYMLINKS 1
94 #else
95 # define HAVE_SYMLINKS 0
96 #endif
98 /* If any of the S_* macros are undefined, define them here so each
99 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
100 #ifndef S_ISLNK
101 # define S_ISLNK(Mode) 0
102 #endif
104 #ifndef S_ISFIFO
105 # define S_ISFIFO(Mode) 0
106 #endif
108 #ifndef S_ISSOCK
109 # define S_ISSOCK(Mode) 0
110 #endif
112 #ifndef S_ISCHR
113 # define S_ISCHR(Mode) 0
114 #endif
116 #ifndef S_ISBLK
117 # define S_ISBLK(Mode) 0
118 #endif
120 #ifndef S_ISDOOR
121 # define S_ISDOOR(Mode) 0
122 #endif
124 enum filetype
126 symbolic_link,
127 directory,
128 arg_directory, /* Directory given as command line arg. */
129 normal /* All others. */
132 struct fileinfo
134 /* The file name. */
135 char *name;
137 struct stat stat;
139 /* For symbolic link, name of the file linked to, otherwise zero. */
140 char *linkname;
142 /* For symbolic link and long listing, st_mode of file linked to, otherwise
143 zero. */
144 unsigned int linkmode;
146 /* For symbolic link and color printing, 1 if linked-to file
147 exists, otherwise 0. */
148 int linkok;
150 enum filetype filetype;
153 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
155 /* Null is a valid character in a color indicator (think about Epson
156 printers, for example) so we have to use a length/buffer string
157 type. */
159 struct bin_str
161 int len; /* Number of bytes */
162 char *string; /* Pointer to the same */
165 #ifndef STDC_HEADERS
166 time_t time ();
167 #endif
169 char *getgroup ();
170 char *getuser ();
171 void strip_trailing_slashes ();
172 char *xstrdup ();
174 static size_t quote_name PARAMS ((FILE *out, const char *name,
175 struct quoting_options const *options));
176 static char *make_link_path PARAMS ((const char *path, const char *linkname));
177 static int compare_atime PARAMS ((const struct fileinfo *file1,
178 const struct fileinfo *file2));
179 static int rev_cmp_atime PARAMS ((const struct fileinfo *file2,
180 const struct fileinfo *file1));
181 static int compare_ctime PARAMS ((const struct fileinfo *file1,
182 const struct fileinfo *file2));
183 static int rev_cmp_ctime PARAMS ((const struct fileinfo *file2,
184 const struct fileinfo *file1));
185 static int compare_mtime PARAMS ((const struct fileinfo *file1,
186 const struct fileinfo *file2));
187 static int rev_cmp_mtime PARAMS ((const struct fileinfo *file2,
188 const struct fileinfo *file1));
189 static int compare_size PARAMS ((const struct fileinfo *file1,
190 const struct fileinfo *file2));
191 static int rev_cmp_size PARAMS ((const struct fileinfo *file2,
192 const struct fileinfo *file1));
193 static int compare_name PARAMS ((const struct fileinfo *file1,
194 const struct fileinfo *file2));
195 static int rev_cmp_name PARAMS ((const struct fileinfo *file2,
196 const struct fileinfo *file1));
197 static int compare_extension PARAMS ((const struct fileinfo *file1,
198 const struct fileinfo *file2));
199 static int rev_cmp_extension PARAMS ((const struct fileinfo *file2,
200 const struct fileinfo *file1));
201 static int compare_version PARAMS ((const struct fileinfo *file1,
202 const struct fileinfo *file2));
203 static int rev_cmp_version PARAMS ((const struct fileinfo *file2,
204 const struct fileinfo *file1));
205 static int decode_switches PARAMS ((int argc, char **argv));
206 static int file_interesting PARAMS ((const struct dirent *next));
207 static uintmax_t gobble_file PARAMS ((const char *name, int explicit_arg,
208 const char *dirname));
209 static void print_color_indicator PARAMS ((const char *name, unsigned int mode,
210 int linkok));
211 static void put_indicator PARAMS ((const struct bin_str *ind));
212 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
213 static void add_ignore_pattern PARAMS ((const char *pattern));
214 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
215 static void clear_files PARAMS ((void));
216 static void extract_dirs_from_files PARAMS ((const char *dirname,
217 int recursive));
218 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
219 static void indent PARAMS ((int from, int to));
220 static void init_column_info PARAMS ((void));
221 static void print_current_files PARAMS ((void));
222 static void print_dir PARAMS ((const char *name, const char *realname));
223 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
224 static void print_horizontal PARAMS ((void));
225 static void print_long_format PARAMS ((const struct fileinfo *f));
226 static void print_many_per_line PARAMS ((void));
227 static void print_name_with_quoting PARAMS ((const char *p, unsigned int mode,
228 int linkok,
229 struct obstack *stack));
230 static void prep_non_filename_text PARAMS ((void));
231 static void print_type_indicator PARAMS ((unsigned int mode));
232 static void print_with_commas PARAMS ((void));
233 static void queue_directory PARAMS ((const char *name, const char *realname));
234 static void sort_files PARAMS ((void));
235 static void parse_ls_color PARAMS ((void));
236 void usage PARAMS ((int status));
238 /* The name the program was run with, stripped of any leading path. */
239 char *program_name;
241 /* The table of files in the current directory:
243 `files' points to a vector of `struct fileinfo', one per file.
244 `nfiles' is the number of elements space has been allocated for.
245 `files_index' is the number actually in use. */
247 /* Address of block containing the files that are described. */
249 static struct fileinfo *files;
251 /* Length of block that `files' points to, measured in files. */
253 static int nfiles;
255 /* Index of first unused in `files'. */
257 static int files_index;
259 /* Record of one pending directory waiting to be listed. */
261 struct pending
263 char *name;
264 /* If the directory is actually the file pointed to by a symbolic link we
265 were told to list, `realname' will contain the name of the symbolic
266 link, otherwise zero. */
267 char *realname;
268 struct pending *next;
271 static struct pending *pending_dirs;
273 /* Current time (seconds since 1970). When we are printing a file's time,
274 include the year if it is more than 6 months before this time. */
276 static time_t current_time;
278 /* The number of digits to use for block sizes.
279 4, or more if needed for bigger numbers. */
281 static int block_size_size;
283 /* Option flags */
285 /* long_format for lots of info, one per line.
286 one_per_line for just names, one per line.
287 many_per_line for just names, many per line, sorted vertically.
288 horizontal for just names, many per line, sorted horizontally.
289 with_commas for just names, many per line, separated by commas.
291 -l, -1, -C, -x and -m control this parameter. */
293 enum format
295 long_format, /* -l */
296 one_per_line, /* -1 */
297 many_per_line, /* -C */
298 horizontal, /* -x */
299 with_commas /* -m */
302 static enum format format;
304 /* Type of time to print or sort by. Controlled by -c and -u. */
306 enum time_type
308 time_mtime, /* default */
309 time_ctime, /* -c */
310 time_atime /* -u */
313 static enum time_type time_type;
315 /* print the full time, otherwise the standard unix heuristics. */
317 static int full_time;
319 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
321 enum sort_type
323 sort_none, /* -U */
324 sort_name, /* default */
325 sort_extension, /* -X */
326 sort_time, /* -t */
327 sort_size, /* -S */
328 sort_version /* -v */
331 static enum sort_type sort_type;
333 /* Direction of sort.
334 0 means highest first if numeric,
335 lowest first if alphabetic;
336 these are the defaults.
337 1 means the opposite order in each case. -r */
339 static int sort_reverse;
341 /* Nonzero means to NOT display group information. -G */
343 static int inhibit_group;
345 /* Nonzero means print the user and group id's as numbers rather
346 than as names. -n */
348 static int numeric_ids;
350 /* Nonzero means mention the size in blocks of each file. -s */
352 static int print_block_size;
354 /* If positive, the units to use when printing sizes;
355 if negative, the human-readable base. */
356 static int output_block_size;
358 /* Precede each line of long output (per file) with a string like `m,n:'
359 where M is the number of characters after the `:' and before the
360 filename and N is the length of the filename. Using this format,
361 Emacs' dired mode starts up twice as fast, and can handle all
362 strange characters in file names. */
363 static int dired;
365 /* `none' means don't mention the type of files.
366 `classify' means mention file types and mark executables.
367 `file_type' means mention only file types.
369 Controlled by -F, -p, and --indicator-style. */
371 enum indicator_style
373 none, /* --indicator-style=none */
374 classify, /* -F, --indicator-style=classify */
375 file_type /* -p, --indicator-style=file-type */
378 static enum indicator_style indicator_style;
380 /* Names of indicator styles. */
381 static char const *const indicator_style_args[] =
383 "none", "classify", "file-type", 0
386 static enum indicator_style const indicator_style_types[]=
388 none, classify, file_type
391 /* Nonzero means use colors to mark types. Also define the different
392 colors as well as the stuff for the LS_COLORS environment variable.
393 The LS_COLORS variable is now in a termcap-like format. */
395 static int print_with_color;
397 enum color_type
399 color_never, /* 0: default or --color=never */
400 color_always, /* 1: --color=always */
401 color_if_tty /* 2: --color=tty */
404 enum indicator_no
406 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
407 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
410 static const char *const indicator_name[]=
412 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
413 "bd", "cd", "mi", "or", "ex", "do", NULL
416 struct color_ext_type
418 struct bin_str ext; /* The extension we're looking for */
419 struct bin_str seq; /* The sequence to output when we do */
420 struct color_ext_type *next; /* Next in list */
423 static struct bin_str color_indicator[] =
425 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
426 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
427 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
428 { LEN_STR_PAIR ("0") }, /* no: Normal */
429 { LEN_STR_PAIR ("0") }, /* fi: File: default */
430 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
431 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
432 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
433 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
434 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
435 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
436 { 0, NULL }, /* mi: Missing file: undefined */
437 { 0, NULL }, /* or: Orphanned symlink: undefined */
438 { LEN_STR_PAIR ("01;32") } /* ex: Executable: bright green */
441 /* FIXME: comment */
442 static struct color_ext_type *color_ext_list = NULL;
444 /* Buffer for color sequences */
445 static char *color_buf;
447 /* Nonzero means mention the inode number of each file. -i */
449 static int print_inode;
451 /* Nonzero means when a symbolic link is found, display info on
452 the file linked to. -L */
454 static int trace_links;
456 /* Nonzero means when a directory is found, display info on its
457 contents. -R */
459 static int trace_dirs;
461 /* Nonzero means when an argument is a directory name, display info
462 on it itself. -d */
464 static int immediate_dirs;
466 /* Nonzero means don't omit files whose names start with `.'. -A */
468 static int all_files;
470 /* Nonzero means don't omit files `.' and `..'
471 This flag implies `all_files'. -a */
473 static int really_all_files;
475 /* A linked list of shell-style globbing patterns. If a non-argument
476 file name matches any of these patterns, it is omitted.
477 Controlled by -I. Multiple -I options accumulate.
478 The -B option adds `*~' and `.*~' to this list. */
480 struct ignore_pattern
482 const char *pattern;
483 struct ignore_pattern *next;
486 static struct ignore_pattern *ignore_patterns;
488 /* Nonzero means output nongraphic chars in file names as `?'.
489 (-q, --hide-control-chars)
490 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
491 independent. The algorithm is: first, obey the quoting style to get a
492 string representing the file name; then, if qmark_funny_chars is set,
493 replace all nonprintable chars in that string with `?'. It's necessary
494 to replace nonprintable chars even in quoted strings, because we don't
495 want to mess up the terminal if control chars get sent to it, and some
496 quoting methods pass through control chars as-is. */
497 static int qmark_funny_chars;
499 /* Quoting options for file and dir name output. */
501 static struct quoting_options *filename_quoting_options;
502 static struct quoting_options *dirname_quoting_options;
504 /* The number of chars per hardware tab stop. Setting this to zero
505 inhibits the use of TAB characters for separating columns. -T */
506 static int tabsize;
508 /* Nonzero means we are listing the working directory because no
509 non-option arguments were given. */
511 static int dir_defaulted;
513 /* Nonzero means print each directory name before listing it. */
515 static int print_dir_name;
517 /* The line length to use for breaking lines in many-per-line format.
518 Can be set with -w. */
520 static int line_length;
522 /* If nonzero, the file listing format requires that stat be called on
523 each file. */
525 static int format_needs_stat;
527 /* The exit status to use if we don't get any fatal errors. */
529 static int exit_status;
531 /* If nonzero, display usage information and exit. */
532 static int show_help;
534 /* If nonzero, print the version on standard output and exit. */
535 static int show_version;
537 static struct option const long_options[] =
539 {"all", no_argument, 0, 'a'},
540 {"escape", no_argument, 0, 'b'},
541 {"directory", no_argument, 0, 'd'},
542 {"dired", no_argument, 0, 'D'},
543 {"full-time", no_argument, &full_time, 1},
544 {"human-readable", no_argument, 0, 'h'},
545 {"inode", no_argument, 0, 'i'},
546 {"kilobytes", no_argument, 0, 'k'},
547 {"numeric-uid-gid", no_argument, 0, 'n'},
548 {"no-group", no_argument, 0, 'G'},
549 {"hide-control-chars", no_argument, 0, 'q'},
550 {"reverse", no_argument, 0, 'r'},
551 {"size", no_argument, 0, 's'},
552 {"width", required_argument, 0, 'w'},
553 {"almost-all", no_argument, 0, 'A'},
554 {"ignore-backups", no_argument, 0, 'B'},
555 {"classify", no_argument, 0, 'F'},
556 {"file-type", no_argument, 0, 'F'},
557 {"si", no_argument, 0, 'H'},
558 {"ignore", required_argument, 0, 'I'},
559 {"indicator-style", required_argument, 0, 14},
560 {"dereference", no_argument, 0, 'L'},
561 {"literal", no_argument, 0, 'N'},
562 {"quote-name", no_argument, 0, 'Q'},
563 {"quoting-style", required_argument, 0, 15},
564 {"recursive", no_argument, 0, 'R'},
565 {"format", required_argument, 0, 12},
566 {"show-control-chars", no_argument, 0, 16},
567 {"sort", required_argument, 0, 10},
568 {"tabsize", required_argument, 0, 'T'},
569 {"time", required_argument, 0, 11},
570 {"help", no_argument, &show_help, 1},
571 {"version", no_argument, &show_version, 1},
572 {"color", optional_argument, 0, 13},
573 {"block-size", required_argument, 0, 17},
574 {NULL, 0, NULL, 0}
577 static char const *const format_args[] =
579 "verbose", "long", "commas", "horizontal", "across",
580 "vertical", "single-column", 0
583 static enum format const format_types[] =
585 long_format, long_format, with_commas, horizontal, horizontal,
586 many_per_line, one_per_line
589 static char const *const sort_args[] =
591 "none", "time", "size", "extension", "version", 0
594 static enum sort_type const sort_types[] =
596 sort_none, sort_time, sort_size, sort_extension, sort_version
599 static char const *const time_args[] =
601 "atime", "access", "use", "ctime", "status", 0
604 static enum time_type const time_types[] =
606 time_atime, time_atime, time_atime, time_ctime, time_ctime
609 static char const *const color_args[] =
611 /* force and none are for compatibility with another color-ls version */
612 "always", "yes", "force",
613 "never", "no", "none",
614 "auto", "tty", "if-tty", 0
617 static enum color_type const color_types[] =
619 color_always, color_always, color_always,
620 color_never, color_never, color_never,
621 color_if_tty, color_if_tty, color_if_tty
624 /* Information about filling a column. */
625 struct column_info
627 int valid_len;
628 int line_len;
629 int *col_arr;
632 /* Array with information about column filledness. */
633 static struct column_info *column_info;
635 /* Maximum number of columns ever possible for this display. */
636 static int max_idx;
638 /* The minimum width of a colum is 3: 1 character for the name and 2
639 for the separating white space. */
640 #define MIN_COLUMN_WIDTH 3
643 /* This zero-based index is used solely with the --dired option.
644 When that option is in effect, this counter is incremented for each
645 character of output generated by this program so that the beginning
646 and ending indices (in that output) of every file name can be recorded
647 and later output themselves. */
648 static size_t dired_pos;
650 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
652 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
653 #define DIRED_FPUTS(s, stream, s_len) \
654 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
656 /* Like DIRED_FPUTS, but for use when S is a literal string. */
657 #define DIRED_FPUTS_LITERAL(s, stream) \
658 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
660 #define DIRED_INDENT() \
661 do \
663 /* FIXME: remove the `&& format == long_format' clause. */ \
664 if (dired && format == long_format) \
665 DIRED_FPUTS_LITERAL (" ", stdout); \
667 while (0)
669 /* With --dired, store pairs of beginning and ending indices of filenames. */
670 static struct obstack dired_obstack;
672 /* With --dired, store pairs of beginning and ending indices of any
673 directory names that appear as headers (just before `total' line)
674 for lists of directory entries. Such directory names are seen when
675 listing hierarchies using -R and when a directory is listed with at
676 least one other command line argument. */
677 static struct obstack subdired_obstack;
679 /* Save the current index on the specified obstack, OBS. */
680 #define PUSH_CURRENT_DIRED_POS(obs) \
681 do \
683 /* FIXME: remove the `&& format == long_format' clause. */ \
684 if (dired && format == long_format) \
685 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
687 while (0)
690 /* Write to standard output PREFIX, followed by the quoting style and
691 a space-separated list of the integers stored in OS all on one line. */
693 static void
694 dired_dump_obstack (const char *prefix, struct obstack *os)
696 int n_pos;
698 n_pos = obstack_object_size (os) / sizeof (dired_pos);
699 if (n_pos > 0)
701 int i;
702 size_t *pos;
704 pos = (size_t *) obstack_finish (os);
705 fputs (prefix, stdout);
706 for (i = 0; i < n_pos; i++)
707 printf (" %d", (int) pos[i]);
708 fputs ("\n", stdout);
713 main (int argc, char **argv)
715 register int i;
716 register struct pending *thispend;
718 program_name = argv[0];
719 setlocale (LC_ALL, "");
720 bindtextdomain (PACKAGE, LOCALEDIR);
721 textdomain (PACKAGE);
723 exit_status = 0;
724 dir_defaulted = 1;
725 print_dir_name = 1;
726 pending_dirs = 0;
727 current_time = time ((time_t *) 0);
729 i = decode_switches (argc, argv);
731 if (show_version)
733 printf ("%s (%s) %s\n",
734 (ls_mode == LS_LS ? "ls"
735 : (ls_mode == LS_MULTI_COL ? "dir" : "vdir")),
736 GNU_PACKAGE, VERSION);
737 close_stdout ();
738 exit (EXIT_SUCCESS);
741 if (show_help)
742 usage (EXIT_SUCCESS);
744 if (print_with_color)
746 parse_ls_color ();
747 prep_non_filename_text ();
750 format_needs_stat = sort_type == sort_time || sort_type == sort_size
751 || format == long_format
752 || trace_links || trace_dirs || indicator_style != none
753 || print_block_size || print_inode || print_with_color;
755 if (dired && format == long_format)
757 obstack_init (&dired_obstack);
758 obstack_init (&subdired_obstack);
761 nfiles = 100;
762 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
763 files_index = 0;
765 clear_files ();
767 if (i < argc)
768 dir_defaulted = 0;
769 for (; i < argc; i++)
771 strip_trailing_slashes (argv[i]);
772 gobble_file (argv[i], 1, "");
775 if (dir_defaulted)
777 if (immediate_dirs)
778 gobble_file (".", 1, "");
779 else
780 queue_directory (".", 0);
783 if (files_index)
785 sort_files ();
786 if (!immediate_dirs)
787 extract_dirs_from_files ("", 0);
788 /* `files_index' might be zero now. */
790 if (files_index)
792 print_current_files ();
793 if (pending_dirs)
794 DIRED_PUTCHAR ('\n');
796 else if (pending_dirs && pending_dirs->next == 0)
797 print_dir_name = 0;
799 while (pending_dirs)
801 thispend = pending_dirs;
802 pending_dirs = pending_dirs->next;
803 print_dir (thispend->name, thispend->realname);
804 free (thispend->name);
805 if (thispend->realname)
806 free (thispend->realname);
807 free (thispend);
808 print_dir_name = 1;
811 if (dired && format == long_format)
813 /* No need to free these since we're about to exit. */
814 dired_dump_obstack ("//DIRED//", &dired_obstack);
815 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
816 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
817 ARGMATCH_TO_ARGUMENT (filename_quoting_options,
818 quoting_style_args, quoting_style_vals));
821 /* Restore default color before exiting */
822 if (print_with_color)
824 put_indicator (&color_indicator[C_LEFT]);
825 put_indicator (&color_indicator[C_RIGHT]);
828 close_stdout ();
829 exit (exit_status);
832 /* Set all the option flags according to the switches specified.
833 Return the index of the first non-option argument. */
835 static int
836 decode_switches (int argc, char **argv)
838 register char const *p;
839 int c;
840 int i;
841 long int tmp_long;
843 qmark_funny_chars = 0;
845 /* initialize all switches to default settings */
847 switch (ls_mode)
849 case LS_MULTI_COL:
850 /* This is for the `dir' program. */
851 format = many_per_line;
852 set_quoting_style (NULL, escape_quoting_style);
853 break;
855 case LS_LONG_FORMAT:
856 /* This is for the `vdir' program. */
857 format = long_format;
858 set_quoting_style (NULL, escape_quoting_style);
859 break;
861 case LS_LS:
862 /* This is for the `ls' program. */
863 if (isatty (1))
865 format = many_per_line;
866 /* See description of qmark_funny_chars, above. */
867 qmark_funny_chars = 1;
869 else
871 format = one_per_line;
872 qmark_funny_chars = 0;
874 break;
876 default:
877 abort ();
880 time_type = time_mtime;
881 full_time = 0;
882 sort_type = sort_name;
883 sort_reverse = 0;
884 numeric_ids = 0;
885 print_block_size = 0;
886 indicator_style = none;
887 print_inode = 0;
888 trace_links = 0;
889 trace_dirs = 0;
890 immediate_dirs = 0;
891 all_files = 0;
892 really_all_files = 0;
893 ignore_patterns = 0;
895 /* FIXME: Shouldn't we complain on wrong values? */
896 if ((p = getenv ("QUOTING_STYLE"))
897 && 0 <= (i = ARGCASEMATCH (p, quoting_style_args, quoting_style_vals)))
898 set_quoting_style (NULL, quoting_style_vals[i]);
900 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
902 line_length = 80;
903 if ((p = getenv ("COLUMNS")) && *p)
905 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
906 && 0 < tmp_long && tmp_long <= INT_MAX)
908 line_length = (int) tmp_long;
910 else
912 error (0, 0,
913 _("ignoring invalid width in environment variable COLUMNS: %s"),
914 quotearg (p));
918 #ifdef TIOCGWINSZ
920 struct winsize ws;
922 if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
923 line_length = ws.ws_col;
925 #endif
927 /* Using the TABSIZE environment variable is not POSIX-approved.
928 Ignore it when POSIXLY_CORRECT is set. */
929 tabsize = 8;
930 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
932 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
933 && 0 <= tmp_long && tmp_long <= INT_MAX)
935 tabsize = (int) tmp_long;
937 else
939 error (0, 0,
940 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
941 quotearg (p));
945 while ((c = getopt_long (argc, argv,
946 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
947 long_options, NULL)) != -1)
949 switch (c)
951 case 0:
952 break;
954 case 'a':
955 all_files = 1;
956 really_all_files = 1;
957 break;
959 case 'b':
960 set_quoting_style (NULL, escape_quoting_style);
961 break;
963 case 'c':
964 time_type = time_ctime;
965 sort_type = sort_time;
966 break;
968 case 'd':
969 immediate_dirs = 1;
970 break;
972 case 'f':
973 /* Same as enabling -a -U and disabling -l -s. */
974 all_files = 1;
975 really_all_files = 1;
976 sort_type = sort_none;
977 /* disable -l */
978 if (format == long_format)
979 format = (isatty (1) ? many_per_line : one_per_line);
980 print_block_size = 0; /* disable -s */
981 print_with_color = 0; /* disable --color */
982 break;
984 case 'g':
985 /* No effect. For BSD compatibility. */
986 break;
988 case 'h':
989 output_block_size = -1024;
990 break;
992 case 'H':
993 output_block_size = -1000;
994 break;
996 case 'i':
997 print_inode = 1;
998 break;
1000 case 'k':
1001 output_block_size = 1024;
1002 break;
1004 case 'l':
1005 format = long_format;
1006 break;
1008 case 'm':
1009 format = with_commas;
1010 break;
1012 case 'n':
1013 numeric_ids = 1;
1014 break;
1016 case 'o': /* Just like -l, but don't display group info. */
1017 format = long_format;
1018 inhibit_group = 1;
1019 break;
1021 case 'p':
1022 indicator_style = file_type;
1023 break;
1025 case 'q':
1026 qmark_funny_chars = 1;
1027 break;
1029 case 'r':
1030 sort_reverse = 1;
1031 break;
1033 case 's':
1034 print_block_size = 1;
1035 break;
1037 case 't':
1038 sort_type = sort_time;
1039 break;
1041 case 'u':
1042 sort_type = sort_time;
1043 time_type = time_atime;
1044 break;
1046 case 'v':
1047 sort_type = sort_version;
1048 break;
1050 case 'w':
1051 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1052 || tmp_long <= 0 || tmp_long > INT_MAX)
1053 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1054 quotearg (optarg));
1055 line_length = (int) tmp_long;
1056 break;
1058 case 'x':
1059 format = horizontal;
1060 break;
1062 case 'A':
1063 really_all_files = 0;
1064 all_files = 1;
1065 break;
1067 case 'B':
1068 add_ignore_pattern ("*~");
1069 add_ignore_pattern (".*~");
1070 break;
1072 case 'C':
1073 format = many_per_line;
1074 break;
1076 case 'D':
1077 dired = 1;
1078 break;
1080 case 'F':
1081 indicator_style = classify;
1082 break;
1084 case 'G': /* inhibit display of group info */
1085 inhibit_group = 1;
1086 break;
1088 case 'I':
1089 add_ignore_pattern (optarg);
1090 break;
1092 case 'L':
1093 trace_links = 1;
1094 break;
1096 case 'N':
1097 set_quoting_style (NULL, literal_quoting_style);
1098 break;
1100 case 'Q':
1101 set_quoting_style (NULL, c_quoting_style);
1102 break;
1104 case 'R':
1105 trace_dirs = 1;
1106 break;
1108 case 'S':
1109 sort_type = sort_size;
1110 break;
1112 case 'T':
1113 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1114 || tmp_long < 0 || tmp_long > INT_MAX)
1115 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1116 quotearg (optarg));
1117 tabsize = (int) tmp_long;
1118 break;
1120 case 'U':
1121 sort_type = sort_none;
1122 break;
1124 case 'X':
1125 sort_type = sort_extension;
1126 break;
1128 case '1':
1129 format = one_per_line;
1130 break;
1132 case 10: /* --sort */
1133 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1134 break;
1136 case 11: /* --time */
1137 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1138 break;
1140 case 12: /* --format */
1141 format = XARGMATCH ("--format", optarg, format_args, format_types);
1142 break;
1144 case 13: /* --color */
1145 if (optarg)
1146 i = XARGMATCH ("--color", optarg, color_args, color_types);
1147 else
1148 /* Using --color with no argument is equivalent to using
1149 --color=always. */
1150 i = color_always;
1152 print_with_color = (i == color_always
1153 || (i == color_if_tty
1154 && isatty (STDOUT_FILENO)));
1156 if (print_with_color)
1158 /* Don't use TAB characters in output. Some terminal
1159 emulators can't handle the combination of tabs and
1160 color codes on the same line. */
1161 tabsize = 0;
1163 break;
1165 case 14: /* --indicator-style */
1166 indicator_style = XARGMATCH ("--indicator-style", optarg,
1167 indicator_style_args,
1168 indicator_style_types);
1169 break;
1171 case 15: /* --quoting-style */
1172 set_quoting_style (NULL,
1173 XARGMATCH ("--quoting-style", optarg,
1174 quoting_style_args,
1175 quoting_style_vals));
1176 break;
1178 case 16:
1179 qmark_funny_chars = 0;
1180 break;
1182 case 17:
1183 human_block_size (optarg, 1, &output_block_size);
1184 break;
1186 default:
1187 usage (EXIT_FAILURE);
1191 filename_quoting_options = clone_quoting_options (NULL);
1192 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1193 set_char_quoting (filename_quoting_options, ' ', 1);
1194 if (indicator_style != none)
1195 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1196 set_char_quoting (filename_quoting_options, *p, 1);
1198 dirname_quoting_options = clone_quoting_options (NULL);
1199 set_char_quoting (dirname_quoting_options, ':', 1);
1201 return optind;
1204 /* Parse a string as part of the LS_COLORS variable; this may involve
1205 decoding all kinds of escape characters. If equals_end is set an
1206 unescaped equal sign ends the string, otherwise only a : or \0
1207 does. Returns the number of characters output, or -1 on failure.
1209 The resulting string is *not* null-terminated, but may contain
1210 embedded nulls.
1212 Note that both dest and src are char **; on return they point to
1213 the first free byte after the array and the character that ended
1214 the input string, respectively. */
1216 static int
1217 get_funky_string (char **dest, const char **src, int equals_end)
1219 int num; /* For numerical codes */
1220 int count; /* Something to count with */
1221 enum {
1222 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1223 } state;
1224 const char *p;
1225 char *q;
1227 p = *src; /* We don't want to double-indirect */
1228 q = *dest; /* the whole darn time. */
1230 count = 0; /* No characters counted in yet. */
1231 num = 0;
1233 state = ST_GND; /* Start in ground state. */
1234 while (state < ST_END)
1236 switch (state)
1238 case ST_GND: /* Ground state (no escapes) */
1239 switch (*p)
1241 case ':':
1242 case '\0':
1243 state = ST_END; /* End of string */
1244 break;
1245 case '\\':
1246 state = ST_BACKSLASH; /* Backslash scape sequence */
1247 ++p;
1248 break;
1249 case '^':
1250 state = ST_CARET; /* Caret escape */
1251 ++p;
1252 break;
1253 case '=':
1254 if (equals_end)
1256 state = ST_END; /* End */
1257 break;
1259 /* else fall through */
1260 default:
1261 *(q++) = *(p++);
1262 ++count;
1263 break;
1265 break;
1267 case ST_BACKSLASH: /* Backslash escaped character */
1268 switch (*p)
1270 case '0':
1271 case '1':
1272 case '2':
1273 case '3':
1274 case '4':
1275 case '5':
1276 case '6':
1277 case '7':
1278 state = ST_OCTAL; /* Octal sequence */
1279 num = *p - '0';
1280 break;
1281 case 'x':
1282 case 'X':
1283 state = ST_HEX; /* Hex sequence */
1284 num = 0;
1285 break;
1286 case 'a': /* Bell */
1287 num = 7; /* Not all C compilers know what \a means */
1288 break;
1289 case 'b': /* Backspace */
1290 num = '\b';
1291 break;
1292 case 'e': /* Escape */
1293 num = 27;
1294 break;
1295 case 'f': /* Form feed */
1296 num = '\f';
1297 break;
1298 case 'n': /* Newline */
1299 num = '\n';
1300 break;
1301 case 'r': /* Carriage return */
1302 num = '\r';
1303 break;
1304 case 't': /* Tab */
1305 num = '\t';
1306 break;
1307 case 'v': /* Vtab */
1308 num = '\v';
1309 break;
1310 case '?': /* Delete */
1311 num = 127;
1312 break;
1313 case '_': /* Space */
1314 num = ' ';
1315 break;
1316 case '\0': /* End of string */
1317 state = ST_ERROR; /* Error! */
1318 break;
1319 default: /* Escaped character like \ ^ : = */
1320 num = *p;
1321 break;
1323 if (state == ST_BACKSLASH)
1325 *(q++) = num;
1326 ++count;
1327 state = ST_GND;
1329 ++p;
1330 break;
1332 case ST_OCTAL: /* Octal sequence */
1333 if (*p < '0' || *p > '7')
1335 *(q++) = num;
1336 ++count;
1337 state = ST_GND;
1339 else
1340 num = (num << 3) + (*(p++) - '0');
1341 break;
1343 case ST_HEX: /* Hex sequence */
1344 switch (*p)
1346 case '0':
1347 case '1':
1348 case '2':
1349 case '3':
1350 case '4':
1351 case '5':
1352 case '6':
1353 case '7':
1354 case '8':
1355 case '9':
1356 num = (num << 4) + (*(p++) - '0');
1357 break;
1358 case 'a':
1359 case 'b':
1360 case 'c':
1361 case 'd':
1362 case 'e':
1363 case 'f':
1364 num = (num << 4) + (*(p++) - 'a') + 10;
1365 break;
1366 case 'A':
1367 case 'B':
1368 case 'C':
1369 case 'D':
1370 case 'E':
1371 case 'F':
1372 num = (num << 4) + (*(p++) - 'A') + 10;
1373 break;
1374 default:
1375 *(q++) = num;
1376 ++count;
1377 state = ST_GND;
1378 break;
1380 break;
1382 case ST_CARET: /* Caret escape */
1383 state = ST_GND; /* Should be the next state... */
1384 if (*p >= '@' && *p <= '~')
1386 *(q++) = *(p++) & 037;
1387 ++count;
1389 else if (*p == '?')
1391 *(q++) = 127;
1392 ++count;
1394 else
1395 state = ST_ERROR;
1396 break;
1398 default:
1399 abort ();
1403 *dest = q;
1404 *src = p;
1406 return state == ST_ERROR ? -1 : count;
1409 static void
1410 parse_ls_color (void)
1412 const char *p; /* Pointer to character being parsed */
1413 char *buf; /* color_buf buffer pointer */
1414 int state; /* State of parser */
1415 int ind_no; /* Indicator number */
1416 char label[3]; /* Indicator label */
1417 struct color_ext_type *ext; /* Extension we are working on */
1419 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1420 return;
1422 ext = NULL;
1423 strcpy (label, "??");
1425 /* This is an overly conservative estimate, but any possible
1426 LS_COLORS string will *not* generate a color_buf longer than
1427 itself, so it is a safe way of allocating a buffer in
1428 advance. */
1429 buf = color_buf = xstrdup (p);
1431 state = 1;
1432 while (state > 0)
1434 switch (state)
1436 case 1: /* First label character */
1437 switch (*p)
1439 case ':':
1440 ++p;
1441 break;
1443 case '*':
1444 /* Allocate new extension block and add to head of
1445 linked list (this way a later definition will
1446 override an earlier one, which can be useful for
1447 having terminal-specific defs override global). */
1449 ext = (struct color_ext_type *)
1450 xmalloc (sizeof (struct color_ext_type));
1451 ext->next = color_ext_list;
1452 color_ext_list = ext;
1454 ++p;
1455 ext->ext.string = buf;
1457 state = (ext->ext.len =
1458 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1459 break;
1461 case '\0':
1462 state = 0; /* Done! */
1463 break;
1465 default: /* Assume it is file type label */
1466 label[0] = *(p++);
1467 state = 2;
1468 break;
1470 break;
1472 case 2: /* Second label character */
1473 if (*p)
1475 label[1] = *(p++);
1476 state = 3;
1478 else
1479 state = -1; /* Error */
1480 break;
1482 case 3: /* Equal sign after indicator label */
1483 state = -1; /* Assume failure... */
1484 if (*(p++) == '=')/* It *should* be... */
1486 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1488 if (STREQ (label, indicator_name[ind_no]))
1490 color_indicator[ind_no].string = buf;
1491 state = ((color_indicator[ind_no].len =
1492 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1493 break;
1496 if (state == -1)
1497 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1499 break;
1501 case 4: /* Equal sign after *.ext */
1502 if (*(p++) == '=')
1504 ext->seq.string = buf;
1505 state = (ext->seq.len =
1506 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1508 else
1509 state = -1;
1510 break;
1514 if (state < 0)
1516 struct color_ext_type *e;
1517 struct color_ext_type *e2;
1519 error (0, 0,
1520 _("unparsable value for LS_COLORS environment variable"));
1521 free (color_buf);
1522 for (e = color_ext_list; e != NULL; /* empty */)
1524 e2 = e;
1525 e = e->next;
1526 free (e2);
1528 print_with_color = 0;
1532 /* Request that the directory named `name' have its contents listed later.
1533 If `realname' is nonzero, it will be used instead of `name' when the
1534 directory name is printed. This allows symbolic links to directories
1535 to be treated as regular directories but still be listed under their
1536 real names. */
1538 static void
1539 queue_directory (const char *name, const char *realname)
1541 struct pending *new;
1543 new = (struct pending *) xmalloc (sizeof (struct pending));
1544 new->next = pending_dirs;
1545 pending_dirs = new;
1546 new->name = xstrdup (name);
1547 if (realname)
1548 new->realname = xstrdup (realname);
1549 else
1550 new->realname = 0;
1553 /* Read directory `name', and list the files in it.
1554 If `realname' is nonzero, print its name instead of `name';
1555 this is used for symbolic links to directories. */
1557 static void
1558 print_dir (const char *name, const char *realname)
1560 register DIR *reading;
1561 register struct dirent *next;
1562 register uintmax_t total_blocks = 0;
1564 errno = 0;
1565 reading = opendir (name);
1566 if (!reading)
1568 error (0, errno, "%s", quotearg_colon (name));
1569 exit_status = 1;
1570 return;
1573 /* Read the directory entries, and insert the subfiles into the `files'
1574 table. */
1576 clear_files ();
1578 while ((next = readdir (reading)) != NULL)
1579 if (file_interesting (next))
1580 total_blocks += gobble_file (next->d_name, 0, name);
1582 if (CLOSEDIR (reading))
1584 error (0, errno, "%s", quotearg_colon (name));
1585 exit_status = 1;
1586 /* Don't return; print whatever we got. */
1589 /* Sort the directory contents. */
1590 sort_files ();
1592 /* If any member files are subdirectories, perhaps they should have their
1593 contents listed rather than being mentioned here as files. */
1595 if (trace_dirs)
1596 extract_dirs_from_files (name, 1);
1598 if (trace_dirs || print_dir_name)
1600 DIRED_INDENT ();
1601 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1602 dired_pos += quote_name (stdout, realname ? realname : name,
1603 dirname_quoting_options);
1604 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1605 DIRED_FPUTS_LITERAL (":\n", stdout);
1608 if (format == long_format || print_block_size)
1610 const char *p;
1611 char buf[LONGEST_HUMAN_READABLE + 1];
1613 DIRED_INDENT ();
1614 p = _("total");
1615 DIRED_FPUTS (p, stdout, strlen (p));
1616 DIRED_PUTCHAR (' ');
1617 p = human_readable (total_blocks, buf, ST_NBLOCKSIZE, output_block_size);
1618 DIRED_FPUTS (p, stdout, strlen (p));
1619 DIRED_PUTCHAR ('\n');
1622 if (files_index)
1623 print_current_files ();
1625 if (pending_dirs)
1626 DIRED_PUTCHAR ('\n');
1629 /* Add `pattern' to the list of patterns for which files that match are
1630 not listed. */
1632 static void
1633 add_ignore_pattern (const char *pattern)
1635 register struct ignore_pattern *ignore;
1637 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1638 ignore->pattern = pattern;
1639 /* Add it to the head of the linked list. */
1640 ignore->next = ignore_patterns;
1641 ignore_patterns = ignore;
1644 /* Return nonzero if the file in `next' should be listed. */
1646 static int
1647 file_interesting (const struct dirent *next)
1649 register struct ignore_pattern *ignore;
1651 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1652 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1653 return 0;
1655 if (really_all_files
1656 || next->d_name[0] != '.'
1657 || (all_files
1658 && next->d_name[1] != '\0'
1659 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1660 return 1;
1662 return 0;
1665 /* Enter and remove entries in the table `files'. */
1667 /* Empty the table of files. */
1669 static void
1670 clear_files (void)
1672 register int i;
1674 for (i = 0; i < files_index; i++)
1676 free (files[i].name);
1677 if (files[i].linkname)
1678 free (files[i].linkname);
1681 files_index = 0;
1682 block_size_size = 4;
1685 /* Add a file to the current table of files.
1686 Verify that the file exists, and print an error message if it does not.
1687 Return the number of blocks that the file occupies. */
1689 static uintmax_t
1690 gobble_file (const char *name, int explicit_arg, const char *dirname)
1692 register uintmax_t blocks;
1693 register int val;
1694 register char *path;
1696 if (files_index == nfiles)
1698 nfiles *= 2;
1699 files = (struct fileinfo *) xrealloc ((char *) files,
1700 sizeof (*files) * nfiles);
1703 files[files_index].linkname = 0;
1704 files[files_index].linkmode = 0;
1705 files[files_index].linkok = 0;
1707 if (explicit_arg || format_needs_stat)
1709 /* `path' is the absolute pathname of this file. */
1711 if (name[0] == '/' || dirname[0] == 0)
1712 path = (char *) name;
1713 else
1715 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1716 attach (path, dirname, name);
1719 if (trace_links)
1721 val = stat (path, &files[files_index].stat);
1722 if (val < 0)
1723 /* Perhaps a symbolically-linked to file doesn't exist; stat
1724 the link instead. */
1725 val = lstat (path, &files[files_index].stat);
1727 else
1729 val = lstat (path, &files[files_index].stat);
1732 if (val < 0)
1734 error (0, errno, "%s", quotearg_colon (path));
1735 exit_status = 1;
1736 return 0;
1739 if (S_ISLNK (files[files_index].stat.st_mode)
1740 && (explicit_arg || format == long_format || print_with_color))
1742 char *linkpath;
1743 struct stat linkstats;
1745 get_link_name (path, &files[files_index]);
1746 linkpath = make_link_path (path, files[files_index].linkname);
1748 /* Avoid following symbolic links when possible, ie, when
1749 they won't be traced and when no indicator is needed. */
1750 if (linkpath
1751 && ((explicit_arg && format != long_format)
1752 || indicator_style != none
1753 || print_with_color)
1754 && stat (linkpath, &linkstats) == 0)
1756 files[files_index].linkok = 1;
1758 /* Symbolic links to directories that are mentioned on the
1759 command line are automatically traced if not being
1760 listed as files. */
1761 if (explicit_arg && format != long_format
1762 && S_ISDIR (linkstats.st_mode))
1764 /* Substitute the linked-to directory's name, but
1765 save the real name in `linkname' for printing. */
1766 if (!immediate_dirs)
1768 const char *tempname = name;
1769 name = linkpath;
1770 linkpath = files[files_index].linkname;
1771 files[files_index].linkname = (char *) tempname;
1773 files[files_index].stat = linkstats;
1775 else
1777 /* Get the linked-to file's mode for the filetype indicator
1778 in long listings. */
1779 files[files_index].linkmode = linkstats.st_mode;
1780 files[files_index].linkok = 1;
1783 if (linkpath)
1784 free (linkpath);
1787 if (S_ISLNK (files[files_index].stat.st_mode))
1788 files[files_index].filetype = symbolic_link;
1789 else if (S_ISDIR (files[files_index].stat.st_mode))
1791 if (explicit_arg && !immediate_dirs)
1792 files[files_index].filetype = arg_directory;
1793 else
1794 files[files_index].filetype = directory;
1796 else
1797 files[files_index].filetype = normal;
1799 blocks = ST_NBLOCKS (files[files_index].stat);
1801 char buf[LONGEST_HUMAN_READABLE + 1];
1802 int len = strlen (human_readable (blocks, buf, ST_NBLOCKSIZE,
1803 output_block_size));
1804 if (block_size_size < len)
1805 block_size_size = len < 7 ? len : 7;
1808 else
1809 blocks = 0;
1811 files[files_index].name = xstrdup (name);
1812 files_index++;
1814 return blocks;
1817 #if HAVE_SYMLINKS
1819 /* Put the name of the file that `filename' is a symbolic link to
1820 into the `linkname' field of `f'. */
1822 static void
1823 get_link_name (const char *filename, struct fileinfo *f)
1825 char *linkbuf;
1826 register int linksize;
1828 linkbuf = (char *) alloca (PATH_MAX + 2);
1829 /* Some automounters give incorrect st_size for mount points.
1830 I can't think of a good workaround for it, though. */
1831 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1832 if (linksize < 0)
1834 error (0, errno, "%s", quotearg_colon (filename));
1835 exit_status = 1;
1837 else
1839 linkbuf[linksize] = '\0';
1840 f->linkname = xstrdup (linkbuf);
1844 /* If `linkname' is a relative path and `path' contains one or more
1845 leading directories, return `linkname' with those directories
1846 prepended; otherwise, return a copy of `linkname'.
1847 If `linkname' is zero, return zero. */
1849 static char *
1850 make_link_path (const char *path, const char *linkname)
1852 char *linkbuf;
1853 int bufsiz;
1855 if (linkname == 0)
1856 return 0;
1858 if (*linkname == '/')
1859 return xstrdup (linkname);
1861 /* The link is to a relative path. Prepend any leading path
1862 in `path' to the link name. */
1863 linkbuf = strrchr (path, '/');
1864 if (linkbuf == 0)
1865 return xstrdup (linkname);
1867 bufsiz = linkbuf - path + 1;
1868 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1869 strncpy (linkbuf, path, bufsiz);
1870 strcpy (linkbuf + bufsiz, linkname);
1871 return linkbuf;
1873 #endif
1875 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1876 This is so we don't try to recurse on `././././. ...' */
1878 static int
1879 basename_is_dot_or_dotdot (const char *name)
1881 char *base = base_name (name);
1882 return DOT_OR_DOTDOT (base);
1885 /* Remove any entries from `files' that are for directories,
1886 and queue them to be listed as directories instead.
1887 `dirname' is the prefix to prepend to each dirname
1888 to make it correct relative to ls's working dir.
1889 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1890 This is desirable when processing directories recursively. */
1892 static void
1893 extract_dirs_from_files (const char *dirname, int recursive)
1895 register int i, j;
1896 int dirlen;
1898 dirlen = strlen (dirname) + 2;
1899 /* Queue the directories last one first, because queueing reverses the
1900 order. */
1901 for (i = files_index - 1; i >= 0; i--)
1902 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1903 && (!recursive || !basename_is_dot_or_dotdot (files[i].name)))
1905 if (files[i].name[0] == '/' || dirname[0] == 0)
1907 queue_directory (files[i].name, files[i].linkname);
1909 else
1911 char *path = path_concat (dirname, files[i].name, NULL);
1912 queue_directory (path, files[i].linkname);
1913 free (path);
1915 if (files[i].filetype == arg_directory)
1916 free (files[i].name);
1919 /* Now delete the directories from the table, compacting all the remaining
1920 entries. */
1922 for (i = 0, j = 0; i < files_index; i++)
1923 if (files[i].filetype != arg_directory)
1924 files[j++] = files[i];
1925 files_index = j;
1928 /* Sort the files now in the table. */
1930 static void
1931 sort_files (void)
1933 int (*func) ();
1935 switch (sort_type)
1937 case sort_none:
1938 return;
1939 case sort_time:
1940 switch (time_type)
1942 case time_ctime:
1943 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1944 break;
1945 case time_mtime:
1946 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1947 break;
1948 case time_atime:
1949 func = sort_reverse ? rev_cmp_atime : compare_atime;
1950 break;
1951 default:
1952 abort ();
1954 break;
1955 case sort_name:
1956 func = sort_reverse ? rev_cmp_name : compare_name;
1957 break;
1958 case sort_extension:
1959 func = sort_reverse ? rev_cmp_extension : compare_extension;
1960 break;
1961 case sort_size:
1962 func = sort_reverse ? rev_cmp_size : compare_size;
1963 break;
1964 case sort_version:
1965 func = sort_reverse ? rev_cmp_version : compare_version;
1966 break;
1967 default:
1968 abort ();
1971 qsort (files, files_index, sizeof (struct fileinfo), func);
1974 /* Comparison routines for sorting the files. */
1976 static int
1977 compare_ctime (const struct fileinfo *file1, const struct fileinfo *file2)
1979 int diff = CTIME_CMP (file2->stat, file1->stat);
1980 if (diff == 0)
1981 diff = strcmp (file1->name, file2->name);
1982 return diff;
1985 static int
1986 rev_cmp_ctime (const struct fileinfo *file2, const struct fileinfo *file1)
1988 int diff = CTIME_CMP (file2->stat, file1->stat);
1989 if (diff == 0)
1990 diff = strcmp (file1->name, file2->name);
1991 return diff;
1994 static int
1995 compare_mtime (const struct fileinfo *file1, const struct fileinfo *file2)
1997 int diff = MTIME_CMP (file2->stat, file1->stat);
1998 if (diff == 0)
1999 diff = strcmp (file1->name, file2->name);
2000 return diff;
2003 static int
2004 rev_cmp_mtime (const struct fileinfo *file2, const struct fileinfo *file1)
2006 int diff = MTIME_CMP (file2->stat, file1->stat);
2007 if (diff == 0)
2008 diff = strcmp (file1->name, file2->name);
2009 return diff;
2012 static int
2013 compare_atime (const struct fileinfo *file1, const struct fileinfo *file2)
2015 int diff = ATIME_CMP (file2->stat, file1->stat);
2016 if (diff == 0)
2017 diff = strcmp (file1->name, file2->name);
2018 return diff;
2021 static int
2022 rev_cmp_atime (const struct fileinfo *file2, const struct fileinfo *file1)
2024 int diff = ATIME_CMP (file2->stat, file1->stat);
2025 if (diff == 0)
2026 diff = strcmp (file1->name, file2->name);
2027 return diff;
2030 static int
2031 compare_size (const struct fileinfo *file1, const struct fileinfo *file2)
2033 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2034 if (diff == 0)
2035 diff = strcmp (file1->name, file2->name);
2036 return diff;
2039 static int
2040 rev_cmp_size (const struct fileinfo *file2, const struct fileinfo *file1)
2042 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2043 if (diff == 0)
2044 diff = strcmp (file1->name, file2->name);
2045 return diff;
2048 static int
2049 compare_version (const struct fileinfo *file1, const struct fileinfo *file2)
2051 return strverscmp (file1->name, file2->name);
2054 static int
2055 rev_cmp_version (const struct fileinfo *file2, const struct fileinfo *file1)
2057 return strverscmp (file1->name, file2->name);
2060 static int
2061 compare_name (const struct fileinfo *file1, const struct fileinfo *file2)
2063 return strcmp (file1->name, file2->name);
2066 static int
2067 rev_cmp_name (const struct fileinfo *file2, const struct fileinfo *file1)
2069 return strcmp (file1->name, file2->name);
2072 /* Compare file extensions. Files with no extension are `smallest'.
2073 If extensions are the same, compare by filenames instead. */
2075 static int
2076 compare_extension (const struct fileinfo *file1, const struct fileinfo *file2)
2078 register char *base1, *base2;
2079 register int cmp;
2081 base1 = strrchr (file1->name, '.');
2082 base2 = strrchr (file2->name, '.');
2083 if (base1 == 0 && base2 == 0)
2084 return strcmp (file1->name, file2->name);
2085 if (base1 == 0)
2086 return -1;
2087 if (base2 == 0)
2088 return 1;
2089 cmp = strcmp (base1, base2);
2090 if (cmp == 0)
2091 return strcmp (file1->name, file2->name);
2092 return cmp;
2095 static int
2096 rev_cmp_extension (const struct fileinfo *file2, const struct fileinfo *file1)
2098 register char *base1, *base2;
2099 register int cmp;
2101 base1 = strrchr (file1->name, '.');
2102 base2 = strrchr (file2->name, '.');
2103 if (base1 == 0 && base2 == 0)
2104 return strcmp (file1->name, file2->name);
2105 if (base1 == 0)
2106 return -1;
2107 if (base2 == 0)
2108 return 1;
2109 cmp = strcmp (base1, base2);
2110 if (cmp == 0)
2111 return strcmp (file1->name, file2->name);
2112 return cmp;
2115 /* List all the files now in the table. */
2117 static void
2118 print_current_files (void)
2120 register int i;
2122 switch (format)
2124 case one_per_line:
2125 for (i = 0; i < files_index; i++)
2127 print_file_name_and_frills (files + i);
2128 putchar ('\n');
2130 break;
2132 case many_per_line:
2133 init_column_info ();
2134 print_many_per_line ();
2135 break;
2137 case horizontal:
2138 init_column_info ();
2139 print_horizontal ();
2140 break;
2142 case with_commas:
2143 print_with_commas ();
2144 break;
2146 case long_format:
2147 for (i = 0; i < files_index; i++)
2149 print_long_format (files + i);
2150 DIRED_PUTCHAR ('\n');
2152 break;
2156 static void
2157 print_long_format (const struct fileinfo *f)
2159 char modebuf[11];
2161 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2162 1 10-byte mode string,
2163 1 24-byte time string (may be longer in some locales -- see below)
2164 or LONGEST_HUMAN_READABLE integer,
2165 9 spaces, one following each of these fields, and
2166 1 trailing NUL byte. */
2167 char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2168 + (LONGEST_HUMAN_READABLE < 24 ? 24 : LONGEST_HUMAN_READABLE)
2169 + 9 + 1];
2170 char *buf = init_bigbuf;
2171 size_t bufsize = sizeof (init_bigbuf);
2172 size_t s;
2173 char *p;
2174 time_t when;
2175 struct tm *when_local;
2176 const char *fmt;
2177 char *user_name;
2179 #if HAVE_ST_DM_MODE
2180 /* Cray DMF: look at the file's migrated, not real, status */
2181 mode_string (f->stat.st_dm_mode, modebuf);
2182 #else
2183 mode_string (f->stat.st_mode, modebuf);
2184 #endif
2186 modebuf[10] = '\0';
2188 switch (time_type)
2190 case time_ctime:
2191 when = f->stat.st_ctime;
2192 break;
2193 case time_mtime:
2194 when = f->stat.st_mtime;
2195 break;
2196 case time_atime:
2197 when = f->stat.st_atime;
2198 break;
2201 if (full_time)
2203 fmt = "%a %b %d %H:%M:%S %Y";
2205 else
2207 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
2208 || current_time < when - 60L * 60L) /* In the future. */
2210 /* The file is fairly old or in the future.
2211 POSIX says the cutoff is 6 months old;
2212 approximate this by 6*30 days.
2213 Allow a 1 hour slop factor for what is considered "the future",
2214 to allow for NFS server/client clock disagreement.
2215 Show the year instead of the time of day. */
2216 fmt = "%b %e %Y";
2218 else
2220 fmt = "%b %e %H:%M";
2224 p = buf;
2226 if (print_inode)
2228 char hbuf[LONGEST_HUMAN_READABLE + 1];
2229 sprintf (p, "%*s ", INODE_DIGITS,
2230 human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2231 p += strlen (p);
2234 if (print_block_size)
2236 char hbuf[LONGEST_HUMAN_READABLE + 1];
2237 sprintf (p, "%*s ", block_size_size,
2238 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2239 ST_NBLOCKSIZE, output_block_size));
2240 p += strlen (p);
2243 /* The space between the mode and the number of links is the POSIX
2244 "optional alternate access method flag". */
2245 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
2246 p += strlen (p);
2248 user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2249 if (user_name)
2250 sprintf (p, "%-8.8s ", user_name);
2251 else
2252 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
2253 p += strlen (p);
2255 if (!inhibit_group)
2257 char *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2258 if (group_name)
2259 sprintf (p, "%-8.8s ", group_name);
2260 else
2261 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
2262 p += strlen (p);
2265 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2266 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
2267 (unsigned) minor (f->stat.st_rdev));
2268 else
2270 char hbuf[LONGEST_HUMAN_READABLE + 1];
2271 sprintf (p, "%8s ",
2272 human_readable ((uintmax_t) f->stat.st_size, hbuf, 1,
2273 output_block_size < 0 ? output_block_size : 1));
2276 p += strlen (p);
2278 /* Use strftime rather than ctime, because the former can produce
2279 locale-dependent names for the weekday (%a) and month (%b). */
2281 if ((when_local = localtime (&when)))
2283 while (! (s = strftime (p, buf + bufsize - p - 1, fmt, when_local)))
2285 char *newbuf = (char *) alloca (bufsize *= 2);
2286 memcpy (newbuf, buf, p - buf);
2287 p = newbuf + (p - buf);
2288 buf = newbuf;
2291 p += s;
2292 *p++ = ' ';
2294 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2295 *p = '\0';
2297 else
2299 /* The time cannot be represented as a local time;
2300 print it as a huge integer number of seconds. */
2301 char hbuf[LONGEST_HUMAN_READABLE + 1];
2302 int width = full_time ? 24 : 12;
2304 if (when < 0)
2306 const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2307 int sign_width = width - strlen (num);
2308 sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2310 else
2311 sprintf (p, "%*s ", width,
2312 human_readable ((uintmax_t) when, hbuf, 1, 1));
2314 p += strlen (p);
2317 DIRED_INDENT ();
2318 DIRED_FPUTS (buf, stdout, p - buf);
2319 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok,
2320 &dired_obstack);
2322 if (f->filetype == symbolic_link)
2324 if (f->linkname)
2326 DIRED_FPUTS_LITERAL (" -> ", stdout);
2327 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2328 NULL);
2329 if (indicator_style != none)
2330 print_type_indicator (f->linkmode);
2333 else if (indicator_style != none)
2334 print_type_indicator (f->stat.st_mode);
2337 /* Output to OUT a quoted representation of the file name P,
2338 using OPTIONS to control quoting.
2339 Return the number of characters in P's quoted representation. */
2341 static size_t
2342 quote_name (FILE *out, const char *p, struct quoting_options const *options)
2344 char smallbuf[BUFSIZ];
2345 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, p, -1, options);
2346 char *buf;
2348 if (len < sizeof smallbuf)
2349 buf = smallbuf;
2350 else
2352 buf = (char *) alloca (len + 1);
2353 quotearg_buffer (buf, len + 1, p, -1, options);
2356 if (qmark_funny_chars)
2358 size_t i;
2359 for (i = 0; i < len; i++)
2360 if (! ISPRINT ((unsigned char) buf[i]))
2361 buf[i] = '?';
2364 fwrite (buf, 1, len, out);
2365 return len;
2368 static void
2369 print_name_with_quoting (const char *p, unsigned int mode, int linkok,
2370 struct obstack *stack)
2372 if (print_with_color)
2373 print_color_indicator (p, mode, linkok);
2375 if (stack)
2376 PUSH_CURRENT_DIRED_POS (stack);
2378 dired_pos += quote_name (stdout, p, filename_quoting_options);
2380 if (stack)
2381 PUSH_CURRENT_DIRED_POS (stack);
2383 if (print_with_color)
2384 prep_non_filename_text ();
2387 static void
2388 prep_non_filename_text (void)
2390 if (color_indicator[C_END].string != NULL)
2391 put_indicator (&color_indicator[C_END]);
2392 else
2394 put_indicator (&color_indicator[C_LEFT]);
2395 put_indicator (&color_indicator[C_NORM]);
2396 put_indicator (&color_indicator[C_RIGHT]);
2400 /* Print the file name of `f' with appropriate quoting.
2401 Also print file size, inode number, and filetype indicator character,
2402 as requested by switches. */
2404 static void
2405 print_file_name_and_frills (const struct fileinfo *f)
2407 char buf[LONGEST_HUMAN_READABLE + 1];
2409 if (print_inode)
2410 printf ("%*s ", INODE_DIGITS,
2411 human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
2413 if (print_block_size)
2414 printf ("%*s ", block_size_size,
2415 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), buf,
2416 ST_NBLOCKSIZE, output_block_size));
2418 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok, NULL);
2420 if (indicator_style != none)
2421 print_type_indicator (f->stat.st_mode);
2424 static void
2425 print_type_indicator (unsigned int mode)
2427 int c;
2429 if (S_ISREG (mode))
2431 if (indicator_style == classify && (mode & S_IXUGO))
2432 c ='*';
2433 else
2434 c = 0;
2436 else
2438 if (S_ISDIR (mode))
2439 c = '/';
2440 else if (S_ISLNK (mode))
2441 c = '@';
2442 else if (S_ISFIFO (mode))
2443 c = '|';
2444 else if (S_ISSOCK (mode))
2445 c = '=';
2446 else if (S_ISDOOR (mode))
2447 c = '>';
2448 else
2449 c = 0;
2452 if (c)
2453 DIRED_PUTCHAR (c);
2456 static void
2457 print_color_indicator (const char *name, unsigned int mode, int linkok)
2459 int type = C_FILE;
2460 struct color_ext_type *ext; /* Color extension */
2461 size_t len; /* Length of name */
2463 /* Is this a nonexistent file? If so, linkok == -1. */
2465 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
2467 ext = NULL;
2468 type = C_MISSING;
2470 else
2472 if (S_ISDIR (mode))
2473 type = C_DIR;
2474 else if (S_ISLNK (mode))
2475 type = ((!linkok && color_indicator[C_ORPHAN].string)
2476 ? C_ORPHAN : C_LINK);
2477 else if (S_ISFIFO (mode))
2478 type = C_FIFO;
2479 else if (S_ISSOCK (mode))
2480 type = C_SOCK;
2481 else if (S_ISBLK (mode))
2482 type = C_BLK;
2483 else if (S_ISCHR (mode))
2484 type = C_CHR;
2485 else if (S_ISDOOR (mode))
2486 type = C_DOOR;
2488 if (type == C_FILE && (mode & S_IXUGO) != 0)
2489 type = C_EXEC;
2491 /* Check the file's suffix only if still classified as C_FILE. */
2492 ext = NULL;
2493 if (type == C_FILE)
2495 /* Test if NAME has a recognized suffix. */
2497 len = strlen (name);
2498 name += len; /* Pointer to final \0. */
2499 for (ext = color_ext_list; ext != NULL; ext = ext->next)
2501 if ((size_t) ext->ext.len <= len
2502 && strncmp (name - ext->ext.len, ext->ext.string,
2503 ext->ext.len) == 0)
2504 break;
2509 put_indicator (&color_indicator[C_LEFT]);
2510 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
2511 put_indicator (&color_indicator[C_RIGHT]);
2514 /* Output a color indicator (which may contain nulls). */
2515 static void
2516 put_indicator (const struct bin_str *ind)
2518 register int i;
2519 register char *p;
2521 p = ind->string;
2523 for (i = ind->len; i > 0; --i)
2524 putchar (*(p++));
2527 static int
2528 length_of_file_name_and_frills (const struct fileinfo *f)
2530 register int len = 0;
2532 if (print_inode)
2533 len += INODE_DIGITS + 1;
2535 if (print_block_size)
2536 len += 1 + block_size_size;
2538 len += quotearg_buffer (0, 0, f->name, -1, filename_quoting_options);
2540 if (indicator_style != none)
2542 unsigned filetype = f->stat.st_mode;
2544 if (S_ISREG (filetype))
2546 if (indicator_style == classify
2547 && (f->stat.st_mode & S_IXUGO))
2548 len += 1;
2550 else if (S_ISDIR (filetype)
2551 || S_ISLNK (filetype)
2552 || S_ISFIFO (filetype)
2553 || S_ISSOCK (filetype)
2554 || S_ISDOOR (filetype)
2556 len += 1;
2559 return len;
2562 static void
2563 print_many_per_line (void)
2565 struct column_info *line_fmt;
2566 int filesno; /* Index into files. */
2567 int row; /* Current row. */
2568 int max_name_length; /* Length of longest file name + frills. */
2569 int name_length; /* Length of each file name + frills. */
2570 int pos; /* Current character column. */
2571 int cols; /* Number of files across. */
2572 int rows; /* Maximum number of files down. */
2573 int max_cols;
2575 /* Normally the maximum number of columns is determined by the
2576 screen width. But if few files are available this might limit it
2577 as well. */
2578 max_cols = max_idx > files_index ? files_index : max_idx;
2580 /* Compute the maximum number of possible columns. */
2581 for (filesno = 0; filesno < files_index; ++filesno)
2583 int i;
2585 name_length = length_of_file_name_and_frills (files + filesno);
2587 for (i = 0; i < max_cols; ++i)
2589 if (column_info[i].valid_len)
2591 int idx = filesno / ((files_index + i) / (i + 1));
2592 int real_length = name_length + (idx == i ? 0 : 2);
2594 if (real_length > column_info[i].col_arr[idx])
2596 column_info[i].line_len += (real_length
2597 - column_info[i].col_arr[idx]);
2598 column_info[i].col_arr[idx] = real_length;
2599 column_info[i].valid_len = column_info[i].line_len < line_length;
2605 /* Find maximum allowed columns. */
2606 for (cols = max_cols; cols > 1; --cols)
2608 if (column_info[cols - 1].valid_len)
2609 break;
2612 line_fmt = &column_info[cols - 1];
2614 /* Calculate the number of rows that will be in each column except possibly
2615 for a short column on the right. */
2616 rows = files_index / cols + (files_index % cols != 0);
2618 for (row = 0; row < rows; row++)
2620 int col = 0;
2621 filesno = row;
2622 pos = 0;
2623 /* Print the next row. */
2624 while (1)
2626 print_file_name_and_frills (files + filesno);
2627 name_length = length_of_file_name_and_frills (files + filesno);
2628 max_name_length = line_fmt->col_arr[col++];
2630 filesno += rows;
2631 if (filesno >= files_index)
2632 break;
2634 indent (pos + name_length, pos + max_name_length);
2635 pos += max_name_length;
2637 putchar ('\n');
2641 static void
2642 print_horizontal (void)
2644 struct column_info *line_fmt;
2645 int filesno;
2646 int max_name_length;
2647 int name_length;
2648 int cols;
2649 int pos;
2650 int max_cols;
2652 /* Normally the maximum number of columns is determined by the
2653 screen width. But if few files are available this might limit it
2654 as well. */
2655 max_cols = max_idx > files_index ? files_index : max_idx;
2657 /* Compute the maximum file name length. */
2658 max_name_length = 0;
2659 for (filesno = 0; filesno < files_index; ++filesno)
2661 int i;
2663 name_length = length_of_file_name_and_frills (files + filesno);
2665 for (i = 0; i < max_cols; ++i)
2667 if (column_info[i].valid_len)
2669 int idx = filesno % (i + 1);
2670 int real_length = name_length + (idx == i ? 0 : 2);
2672 if (real_length > column_info[i].col_arr[idx])
2674 column_info[i].line_len += (real_length
2675 - column_info[i].col_arr[idx]);
2676 column_info[i].col_arr[idx] = real_length;
2677 column_info[i].valid_len = column_info[i].line_len < line_length;
2683 /* Find maximum allowed columns. */
2684 for (cols = max_cols; cols > 1; --cols)
2686 if (column_info[cols - 1].valid_len)
2687 break;
2690 line_fmt = &column_info[cols - 1];
2692 pos = 0;
2694 /* Print first entry. */
2695 print_file_name_and_frills (files);
2696 name_length = length_of_file_name_and_frills (files);
2697 max_name_length = line_fmt->col_arr[0];
2699 /* Now the rest. */
2700 for (filesno = 1; filesno < files_index; ++filesno)
2702 int col = filesno % cols;
2704 if (col == 0)
2706 putchar ('\n');
2707 pos = 0;
2709 else
2711 indent (pos + name_length, pos + max_name_length);
2712 pos += max_name_length;
2715 print_file_name_and_frills (files + filesno);
2717 name_length = length_of_file_name_and_frills (files + filesno);
2718 max_name_length = line_fmt->col_arr[col];
2720 putchar ('\n');
2723 static void
2724 print_with_commas (void)
2726 int filesno;
2727 int pos, old_pos;
2729 pos = 0;
2731 for (filesno = 0; filesno < files_index; filesno++)
2733 old_pos = pos;
2735 pos += length_of_file_name_and_frills (files + filesno);
2736 if (filesno + 1 < files_index)
2737 pos += 2; /* For the comma and space */
2739 if (old_pos != 0 && pos >= line_length)
2741 putchar ('\n');
2742 pos -= old_pos;
2745 print_file_name_and_frills (files + filesno);
2746 if (filesno + 1 < files_index)
2748 putchar (',');
2749 putchar (' ');
2752 putchar ('\n');
2755 /* Assuming cursor is at position FROM, indent up to position TO.
2756 Use a TAB character instead of two or more spaces whenever possible. */
2758 static void
2759 indent (int from, int to)
2761 while (from < to)
2763 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
2765 putchar ('\t');
2766 from += tabsize - from % tabsize;
2768 else
2770 putchar (' ');
2771 from++;
2776 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2777 /* FIXME: maybe remove this function someday. See about using a
2778 non-malloc'ing version of path_concat. */
2780 static void
2781 attach (char *dest, const char *dirname, const char *name)
2783 const char *dirnamep = dirname;
2785 /* Copy dirname if it is not ".". */
2786 if (dirname[0] != '.' || dirname[1] != 0)
2788 while (*dirnamep)
2789 *dest++ = *dirnamep++;
2790 /* Add '/' if `dirname' doesn't already end with it. */
2791 if (dirnamep > dirname && dirnamep[-1] != '/')
2792 *dest++ = '/';
2794 while (*name)
2795 *dest++ = *name++;
2796 *dest = 0;
2799 static void
2800 init_column_info (void)
2802 int i;
2803 int allocate = 0;
2805 max_idx = line_length / MIN_COLUMN_WIDTH;
2806 if (max_idx == 0)
2807 max_idx = 1;
2809 if (column_info == NULL)
2811 column_info = (struct column_info *) xmalloc (max_idx
2812 * sizeof (struct column_info));
2813 allocate = 1;
2816 for (i = 0; i < max_idx; ++i)
2818 int j;
2820 column_info[i].valid_len = 1;
2821 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
2823 if (allocate)
2824 column_info[i].col_arr = (int *) xmalloc ((i + 1) * sizeof (int));
2826 for (j = 0; j <= i; ++j)
2827 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
2831 void
2832 usage (int status)
2834 if (status != 0)
2835 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2836 program_name);
2837 else
2839 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2840 printf (_("\
2841 List information about the FILEs (the current directory by default).\n\
2842 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2844 -a, --all do not hide entries starting with .\n\
2845 -A, --almost-all do not list implied . and ..\n\
2846 -b, --escape print octal escapes for nongraphic characters\n\
2847 --block-size=SIZE use SIZE-byte blocks\n\
2848 -B, --ignore-backups do not list implied entries ending with ~\n\
2849 -c sort by change time; with -l: show ctime\n\
2850 -C list entries by columns\n\
2851 --color[=WHEN] control whether color is used to distinguish file\n\
2852 types. WHEN may be `never', `always', or `auto'\n\
2853 -d, --directory list directory entries instead of contents\n\
2854 -D, --dired generate output designed for Emacs' dired mode\n\
2855 -f do not sort, enable -aU, disable -lst\n\
2856 -F, --classify append indicator (one of */=@|) to entries\n\
2857 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2858 single-column -1, verbose -l, vertical -C\n\
2859 --full-time list both full date and full time\n"));
2861 printf (_("\
2862 -g (ignored)\n\
2863 -G, --no-group inhibit display of group information\n\
2864 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2865 -H, --si likewise, but use powers of 1000 not 1024\n\
2866 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2867 none (default), classify (-F), file-type (-p)\n\
2868 -i, --inode print index number of each file\n\
2869 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2870 -k, --kilobytes like --block-size=1024\n\
2871 -l use a long listing format\n\
2872 -L, --dereference list entries pointed to by symbolic links\n\
2873 -m fill width with a comma separated list of entries\n\
2874 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2875 -N, --literal print raw entry names (don't treat e.g. control\n\
2876 characters specially)\n\
2877 -o use long listing format without group info\n\
2878 -p, --file-type append indicator (one of /=@|) to entries\n\
2879 -q, --hide-control-chars print ? instead of non graphic characters\n\
2880 --show-control-chars show non graphic characters as-is (default)\n\
2881 -Q, --quote-name enclose entry names in double quotes\n\
2882 --quoting-style=WORD use quoting style WORD for entry names:\n\
2883 literal, shell, shell-always, c, escape\n\
2884 -r, --reverse reverse order while sorting\n\
2885 -R, --recursive list subdirectories recursively\n\
2886 -s, --size print size of each file, in blocks\n"));
2888 printf (_("\
2889 -S sort by file size\n\
2890 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2891 version -v\n\
2892 status -c, time -t, atime -u, access -u, use -u\n\
2893 --time=WORD show time as WORD instead of modification time:\n\
2894 atime, access, use, ctime or status; use\n\
2895 specified time as sort key if --sort=time\n\
2896 -t sort by modification time\n\
2897 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2898 -u sort by last access time; with -l: show atime\n\
2899 -U do not sort; list entries in directory order\n\
2900 -v sort by version\n\
2901 -w, --width=COLS assume screen width instead of current value\n\
2902 -x list entries by lines instead of by columns\n\
2903 -X sort alphabetically by entry extension\n\
2904 -1 list one file per line\n\
2905 --help display this help and exit\n\
2906 --version output version information and exit\n\
2908 By default, color is not used to distinguish types of files. That is\n\
2909 equivalent to using --color=none. Using the --color option without the\n\
2910 optional WHEN argument is equivalent to using --color=always. With\n\
2911 --color=auto, color codes are output only if standard output is connected\n\
2912 to a terminal (tty).\n\
2913 "));
2914 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
2915 close_stdout ();
2917 exit (status);