(open_maybe_create): New function.
[coreutils.git] / src / ls.c
blobcc37308e9ca54520b355dccbe73b840b3ae89478
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 #ifdef WINSIZE_IN_PTEM
59 # include <sys/stream.h>
60 # include <sys/ptem.h>
61 #endif
63 #include <stdio.h>
64 #include <grp.h>
65 #include <pwd.h>
66 #include <getopt.h>
68 #include "system.h"
69 #include <fnmatch.h>
71 #include "argmatch.h"
72 #include "error.h"
73 #include "human.h"
74 #include "filemode.h"
75 #include "ls.h"
76 #include "obstack.h"
77 #include "path-concat.h"
78 #include "quotearg.h"
79 #include "strverscmp.h"
80 #include "xstrtol.h"
82 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
83 : (ls_mode == LS_MULTI_COL \
84 ? "dir" : "vdir"))
86 #define AUTHORS "Richard Stallman and David MacKenzie"
88 #define obstack_chunk_alloc malloc
89 #define obstack_chunk_free free
91 /* Return an int indicating the result of comparing two integers.
92 Subtracting doesn't always work, due to overflow. */
93 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
95 /* The field width for inode numbers. On some hosts inode numbers are
96 64 bits, so columns won't line up exactly when a huge inode number
97 is encountered, but in practice 7 digits is usually enough. */
98 #ifndef INODE_DIGITS
99 # define INODE_DIGITS 7
100 #endif
102 #ifdef S_ISLNK
103 # define HAVE_SYMLINKS 1
104 #else
105 # define HAVE_SYMLINKS 0
106 #endif
108 /* If any of the S_* macros are undefined, define them here so each
109 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
110 #ifndef S_ISLNK
111 # define S_ISLNK(Mode) 0
112 #endif
114 #ifndef S_ISFIFO
115 # define S_ISFIFO(Mode) 0
116 #endif
118 #ifndef S_ISSOCK
119 # define S_ISSOCK(Mode) 0
120 #endif
122 #ifndef S_ISCHR
123 # define S_ISCHR(Mode) 0
124 #endif
126 #ifndef S_ISBLK
127 # define S_ISBLK(Mode) 0
128 #endif
130 #ifndef S_ISDOOR
131 # define S_ISDOOR(Mode) 0
132 #endif
134 enum filetype
136 symbolic_link,
137 directory,
138 arg_directory, /* Directory given as command line arg. */
139 normal /* All others. */
142 struct fileinfo
144 /* The file name. */
145 char *name;
147 struct stat stat;
149 /* For symbolic link, name of the file linked to, otherwise zero. */
150 char *linkname;
152 /* For symbolic link and long listing, st_mode of file linked to, otherwise
153 zero. */
154 unsigned int linkmode;
156 /* For symbolic link and color printing, 1 if linked-to file
157 exists, otherwise 0. */
158 int linkok;
160 enum filetype filetype;
163 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
165 /* Null is a valid character in a color indicator (think about Epson
166 printers, for example) so we have to use a length/buffer string
167 type. */
169 struct bin_str
171 int len; /* Number of bytes */
172 char *string; /* Pointer to the same */
175 #ifndef STDC_HEADERS
176 time_t time ();
177 #endif
179 char *getgroup ();
180 char *getuser ();
181 void strip_trailing_slashes ();
182 char *xstrdup ();
184 static size_t quote_name PARAMS ((FILE *out, const char *name,
185 struct quoting_options const *options));
186 static char *make_link_path PARAMS ((const char *path, const char *linkname));
187 static int compare_atime PARAMS ((const struct fileinfo *file1,
188 const struct fileinfo *file2));
189 static int rev_cmp_atime PARAMS ((const struct fileinfo *file2,
190 const struct fileinfo *file1));
191 static int compare_ctime PARAMS ((const struct fileinfo *file1,
192 const struct fileinfo *file2));
193 static int rev_cmp_ctime PARAMS ((const struct fileinfo *file2,
194 const struct fileinfo *file1));
195 static int compare_mtime PARAMS ((const struct fileinfo *file1,
196 const struct fileinfo *file2));
197 static int rev_cmp_mtime PARAMS ((const struct fileinfo *file2,
198 const struct fileinfo *file1));
199 static int compare_size PARAMS ((const struct fileinfo *file1,
200 const struct fileinfo *file2));
201 static int rev_cmp_size PARAMS ((const struct fileinfo *file2,
202 const struct fileinfo *file1));
203 static int compare_name PARAMS ((const struct fileinfo *file1,
204 const struct fileinfo *file2));
205 static int rev_cmp_name PARAMS ((const struct fileinfo *file2,
206 const struct fileinfo *file1));
207 static int compare_extension PARAMS ((const struct fileinfo *file1,
208 const struct fileinfo *file2));
209 static int rev_cmp_extension PARAMS ((const struct fileinfo *file2,
210 const struct fileinfo *file1));
211 static int compare_version PARAMS ((const struct fileinfo *file1,
212 const struct fileinfo *file2));
213 static int rev_cmp_version PARAMS ((const struct fileinfo *file2,
214 const struct fileinfo *file1));
215 static int decode_switches PARAMS ((int argc, char **argv));
216 static int file_interesting PARAMS ((const struct dirent *next));
217 static uintmax_t gobble_file PARAMS ((const char *name, int explicit_arg,
218 const char *dirname));
219 static void print_color_indicator PARAMS ((const char *name, unsigned int mode,
220 int linkok));
221 static void put_indicator PARAMS ((const struct bin_str *ind));
222 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
223 static void add_ignore_pattern PARAMS ((const char *pattern));
224 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
225 static void clear_files PARAMS ((void));
226 static void extract_dirs_from_files PARAMS ((const char *dirname,
227 int recursive));
228 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
229 static void indent PARAMS ((int from, int to));
230 static void init_column_info PARAMS ((void));
231 static void print_current_files PARAMS ((void));
232 static void print_dir PARAMS ((const char *name, const char *realname));
233 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
234 static void print_horizontal PARAMS ((void));
235 static void print_long_format PARAMS ((const struct fileinfo *f));
236 static void print_many_per_line PARAMS ((void));
237 static void print_name_with_quoting PARAMS ((const char *p, unsigned int mode,
238 int linkok,
239 struct obstack *stack));
240 static void prep_non_filename_text PARAMS ((void));
241 static void print_type_indicator PARAMS ((unsigned int mode));
242 static void print_with_commas PARAMS ((void));
243 static void queue_directory PARAMS ((const char *name, const char *realname));
244 static void sort_files PARAMS ((void));
245 static void parse_ls_color PARAMS ((void));
246 void usage PARAMS ((int status));
248 /* The name the program was run with, stripped of any leading path. */
249 char *program_name;
251 /* The table of files in the current directory:
253 `files' points to a vector of `struct fileinfo', one per file.
254 `nfiles' is the number of elements space has been allocated for.
255 `files_index' is the number actually in use. */
257 /* Address of block containing the files that are described. */
259 static struct fileinfo *files;
261 /* Length of block that `files' points to, measured in files. */
263 static int nfiles;
265 /* Index of first unused in `files'. */
267 static int files_index;
269 /* Record of one pending directory waiting to be listed. */
271 struct pending
273 char *name;
274 /* If the directory is actually the file pointed to by a symbolic link we
275 were told to list, `realname' will contain the name of the symbolic
276 link, otherwise zero. */
277 char *realname;
278 struct pending *next;
281 static struct pending *pending_dirs;
283 /* Current time (seconds since 1970). When we are printing a file's time,
284 include the year if it is more than 6 months before this time. */
286 static time_t current_time;
288 /* The number of digits to use for block sizes.
289 4, or more if needed for bigger numbers. */
291 static int block_size_size;
293 /* Option flags */
295 /* long_format for lots of info, one per line.
296 one_per_line for just names, one per line.
297 many_per_line for just names, many per line, sorted vertically.
298 horizontal for just names, many per line, sorted horizontally.
299 with_commas for just names, many per line, separated by commas.
301 -l, -1, -C, -x and -m control this parameter. */
303 enum format
305 long_format, /* -l */
306 one_per_line, /* -1 */
307 many_per_line, /* -C */
308 horizontal, /* -x */
309 with_commas /* -m */
312 static enum format format;
314 /* Type of time to print or sort by. Controlled by -c and -u. */
316 enum time_type
318 time_mtime, /* default */
319 time_ctime, /* -c */
320 time_atime /* -u */
323 static enum time_type time_type;
325 /* print the full time, otherwise the standard unix heuristics. */
327 static int full_time;
329 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
331 enum sort_type
333 sort_none, /* -U */
334 sort_name, /* default */
335 sort_extension, /* -X */
336 sort_time, /* -t */
337 sort_size, /* -S */
338 sort_version /* -v */
341 static enum sort_type sort_type;
343 /* Direction of sort.
344 0 means highest first if numeric,
345 lowest first if alphabetic;
346 these are the defaults.
347 1 means the opposite order in each case. -r */
349 static int sort_reverse;
351 /* Nonzero means to NOT display group information. -G */
353 static int inhibit_group;
355 /* Nonzero means print the user and group id's as numbers rather
356 than as names. -n */
358 static int numeric_ids;
360 /* Nonzero means mention the size in blocks of each file. -s */
362 static int print_block_size;
364 /* If positive, the units to use when printing sizes;
365 if negative, the human-readable base. */
366 static int output_block_size;
368 /* Precede each line of long output (per file) with a string like `m,n:'
369 where M is the number of characters after the `:' and before the
370 filename and N is the length of the filename. Using this format,
371 Emacs' dired mode starts up twice as fast, and can handle all
372 strange characters in file names. */
373 static int dired;
375 /* `none' means don't mention the type of files.
376 `classify' means mention file types and mark executables.
377 `file_type' means mention only file types.
379 Controlled by -F, -p, and --indicator-style. */
381 enum indicator_style
383 none, /* --indicator-style=none */
384 classify, /* -F, --indicator-style=classify */
385 file_type /* -p, --indicator-style=file-type */
388 static enum indicator_style indicator_style;
390 /* Names of indicator styles. */
391 static char const *const indicator_style_args[] =
393 "none", "classify", "file-type", 0
396 static enum indicator_style const indicator_style_types[]=
398 none, classify, file_type
401 /* Nonzero means use colors to mark types. Also define the different
402 colors as well as the stuff for the LS_COLORS environment variable.
403 The LS_COLORS variable is now in a termcap-like format. */
405 static int print_with_color;
407 enum color_type
409 color_never, /* 0: default or --color=never */
410 color_always, /* 1: --color=always */
411 color_if_tty /* 2: --color=tty */
414 enum indicator_no
416 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
417 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
420 static const char *const indicator_name[]=
422 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
423 "bd", "cd", "mi", "or", "ex", "do", NULL
426 struct color_ext_type
428 struct bin_str ext; /* The extension we're looking for */
429 struct bin_str seq; /* The sequence to output when we do */
430 struct color_ext_type *next; /* Next in list */
433 static struct bin_str color_indicator[] =
435 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
436 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
437 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
438 { LEN_STR_PAIR ("0") }, /* no: Normal */
439 { LEN_STR_PAIR ("0") }, /* fi: File: default */
440 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
441 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
442 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
443 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
444 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
445 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
446 { 0, NULL }, /* mi: Missing file: undefined */
447 { 0, NULL }, /* or: Orphanned symlink: undefined */
448 { LEN_STR_PAIR ("01;32") } /* ex: Executable: bright green */
451 /* FIXME: comment */
452 static struct color_ext_type *color_ext_list = NULL;
454 /* Buffer for color sequences */
455 static char *color_buf;
457 /* Nonzero means mention the inode number of each file. -i */
459 static int print_inode;
461 /* Nonzero means when a symbolic link is found, display info on
462 the file linked to. -L */
464 static int trace_links;
466 /* Nonzero means when a directory is found, display info on its
467 contents. -R */
469 static int trace_dirs;
471 /* Nonzero means when an argument is a directory name, display info
472 on it itself. -d */
474 static int immediate_dirs;
476 /* Nonzero means don't omit files whose names start with `.'. -A */
478 static int all_files;
480 /* Nonzero means don't omit files `.' and `..'
481 This flag implies `all_files'. -a */
483 static int really_all_files;
485 /* A linked list of shell-style globbing patterns. If a non-argument
486 file name matches any of these patterns, it is omitted.
487 Controlled by -I. Multiple -I options accumulate.
488 The -B option adds `*~' and `.*~' to this list. */
490 struct ignore_pattern
492 const char *pattern;
493 struct ignore_pattern *next;
496 static struct ignore_pattern *ignore_patterns;
498 /* Nonzero means output nongraphic chars in file names as `?'.
499 (-q, --hide-control-chars)
500 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
501 independent. The algorithm is: first, obey the quoting style to get a
502 string representing the file name; then, if qmark_funny_chars is set,
503 replace all nonprintable chars in that string with `?'. It's necessary
504 to replace nonprintable chars even in quoted strings, because we don't
505 want to mess up the terminal if control chars get sent to it, and some
506 quoting methods pass through control chars as-is. */
507 static int qmark_funny_chars;
509 /* Quoting options for file and dir name output. */
511 static struct quoting_options *filename_quoting_options;
512 static struct quoting_options *dirname_quoting_options;
514 /* The number of chars per hardware tab stop. Setting this to zero
515 inhibits the use of TAB characters for separating columns. -T */
516 static int tabsize;
518 /* Nonzero means we are listing the working directory because no
519 non-option arguments were given. */
521 static int dir_defaulted;
523 /* Nonzero means print each directory name before listing it. */
525 static int print_dir_name;
527 /* The line length to use for breaking lines in many-per-line format.
528 Can be set with -w. */
530 static int line_length;
532 /* If nonzero, the file listing format requires that stat be called on
533 each file. */
535 static int format_needs_stat;
537 /* The exit status to use if we don't get any fatal errors. */
539 static int exit_status;
541 static struct option const long_options[] =
543 {"all", no_argument, 0, 'a'},
544 {"escape", no_argument, 0, 'b'},
545 {"directory", no_argument, 0, 'd'},
546 {"dired", no_argument, 0, 'D'},
547 {"full-time", no_argument, &full_time, 1},
548 {"human-readable", no_argument, 0, 'h'},
549 {"inode", no_argument, 0, 'i'},
550 {"kilobytes", no_argument, 0, 'k'},
551 {"numeric-uid-gid", no_argument, 0, 'n'},
552 {"no-group", no_argument, 0, 'G'},
553 {"hide-control-chars", no_argument, 0, 'q'},
554 {"reverse", no_argument, 0, 'r'},
555 {"size", no_argument, 0, 's'},
556 {"width", required_argument, 0, 'w'},
557 {"almost-all", no_argument, 0, 'A'},
558 {"ignore-backups", no_argument, 0, 'B'},
559 {"classify", no_argument, 0, 'F'},
560 {"file-type", no_argument, 0, 'F'},
561 {"si", no_argument, 0, 'H'},
562 {"ignore", required_argument, 0, 'I'},
563 {"indicator-style", required_argument, 0, 14},
564 {"dereference", no_argument, 0, 'L'},
565 {"literal", no_argument, 0, 'N'},
566 {"quote-name", no_argument, 0, 'Q'},
567 {"quoting-style", required_argument, 0, 15},
568 {"recursive", no_argument, 0, 'R'},
569 {"format", required_argument, 0, 12},
570 {"show-control-chars", no_argument, 0, 16},
571 {"sort", required_argument, 0, 10},
572 {"tabsize", required_argument, 0, 'T'},
573 {"time", required_argument, 0, 11},
574 {"color", optional_argument, 0, 13},
575 {"block-size", required_argument, 0, 17},
576 {GETOPT_HELP_OPTION_DECL},
577 {GETOPT_VERSION_OPTION_DECL},
578 {NULL, 0, NULL, 0}
581 static char const *const format_args[] =
583 "verbose", "long", "commas", "horizontal", "across",
584 "vertical", "single-column", 0
587 static enum format const format_types[] =
589 long_format, long_format, with_commas, horizontal, horizontal,
590 many_per_line, one_per_line
593 static char const *const sort_args[] =
595 "none", "time", "size", "extension", "version", 0
598 static enum sort_type const sort_types[] =
600 sort_none, sort_time, sort_size, sort_extension, sort_version
603 static char const *const time_args[] =
605 "atime", "access", "use", "ctime", "status", 0
608 static enum time_type const time_types[] =
610 time_atime, time_atime, time_atime, time_ctime, time_ctime
613 static char const *const color_args[] =
615 /* force and none are for compatibility with another color-ls version */
616 "always", "yes", "force",
617 "never", "no", "none",
618 "auto", "tty", "if-tty", 0
621 static enum color_type const color_types[] =
623 color_always, color_always, color_always,
624 color_never, color_never, color_never,
625 color_if_tty, color_if_tty, color_if_tty
628 /* Information about filling a column. */
629 struct column_info
631 int valid_len;
632 int line_len;
633 int *col_arr;
636 /* Array with information about column filledness. */
637 static struct column_info *column_info;
639 /* Maximum number of columns ever possible for this display. */
640 static int max_idx;
642 /* The minimum width of a colum is 3: 1 character for the name and 2
643 for the separating white space. */
644 #define MIN_COLUMN_WIDTH 3
647 /* This zero-based index is used solely with the --dired option.
648 When that option is in effect, this counter is incremented for each
649 character of output generated by this program so that the beginning
650 and ending indices (in that output) of every file name can be recorded
651 and later output themselves. */
652 static size_t dired_pos;
654 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
656 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
657 #define DIRED_FPUTS(s, stream, s_len) \
658 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
660 /* Like DIRED_FPUTS, but for use when S is a literal string. */
661 #define DIRED_FPUTS_LITERAL(s, stream) \
662 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
664 #define DIRED_INDENT() \
665 do \
667 /* FIXME: remove the `&& format == long_format' clause. */ \
668 if (dired && format == long_format) \
669 DIRED_FPUTS_LITERAL (" ", stdout); \
671 while (0)
673 /* With --dired, store pairs of beginning and ending indices of filenames. */
674 static struct obstack dired_obstack;
676 /* With --dired, store pairs of beginning and ending indices of any
677 directory names that appear as headers (just before `total' line)
678 for lists of directory entries. Such directory names are seen when
679 listing hierarchies using -R and when a directory is listed with at
680 least one other command line argument. */
681 static struct obstack subdired_obstack;
683 /* Save the current index on the specified obstack, OBS. */
684 #define PUSH_CURRENT_DIRED_POS(obs) \
685 do \
687 /* FIXME: remove the `&& format == long_format' clause. */ \
688 if (dired && format == long_format) \
689 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
691 while (0)
694 /* Write to standard output PREFIX, followed by the quoting style and
695 a space-separated list of the integers stored in OS all on one line. */
697 static void
698 dired_dump_obstack (const char *prefix, struct obstack *os)
700 int n_pos;
702 n_pos = obstack_object_size (os) / sizeof (dired_pos);
703 if (n_pos > 0)
705 int i;
706 size_t *pos;
708 pos = (size_t *) obstack_finish (os);
709 fputs (prefix, stdout);
710 for (i = 0; i < n_pos; i++)
711 printf (" %d", (int) pos[i]);
712 fputs ("\n", stdout);
717 main (int argc, char **argv)
719 register int i;
720 register struct pending *thispend;
722 program_name = argv[0];
723 setlocale (LC_ALL, "");
724 bindtextdomain (PACKAGE, LOCALEDIR);
725 textdomain (PACKAGE);
727 exit_status = 0;
728 dir_defaulted = 1;
729 print_dir_name = 1;
730 pending_dirs = 0;
731 current_time = time ((time_t *) 0);
733 i = decode_switches (argc, argv);
735 if (print_with_color)
737 parse_ls_color ();
738 prep_non_filename_text ();
741 format_needs_stat = sort_type == sort_time || sort_type == sort_size
742 || format == long_format
743 || trace_links || trace_dirs || indicator_style != none
744 || print_block_size || print_inode || print_with_color;
746 if (dired && format == long_format)
748 obstack_init (&dired_obstack);
749 obstack_init (&subdired_obstack);
752 nfiles = 100;
753 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
754 files_index = 0;
756 clear_files ();
758 if (i < argc)
759 dir_defaulted = 0;
760 for (; i < argc; i++)
762 strip_trailing_slashes (argv[i]);
763 gobble_file (argv[i], 1, "");
766 if (dir_defaulted)
768 if (immediate_dirs)
769 gobble_file (".", 1, "");
770 else
771 queue_directory (".", 0);
774 if (files_index)
776 sort_files ();
777 if (!immediate_dirs)
778 extract_dirs_from_files ("", 0);
779 /* `files_index' might be zero now. */
781 if (files_index)
783 print_current_files ();
784 if (pending_dirs)
785 DIRED_PUTCHAR ('\n');
787 else if (pending_dirs && pending_dirs->next == 0)
788 print_dir_name = 0;
790 while (pending_dirs)
792 thispend = pending_dirs;
793 pending_dirs = pending_dirs->next;
794 print_dir (thispend->name, thispend->realname);
795 free (thispend->name);
796 if (thispend->realname)
797 free (thispend->realname);
798 free (thispend);
799 print_dir_name = 1;
802 if (dired && format == long_format)
804 /* No need to free these since we're about to exit. */
805 dired_dump_obstack ("//DIRED//", &dired_obstack);
806 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
807 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
808 ARGMATCH_TO_ARGUMENT (filename_quoting_options,
809 quoting_style_args, quoting_style_vals));
812 /* Restore default color before exiting */
813 if (print_with_color)
815 put_indicator (&color_indicator[C_LEFT]);
816 put_indicator (&color_indicator[C_RIGHT]);
819 close_stdout ();
820 exit (exit_status);
823 /* Set all the option flags according to the switches specified.
824 Return the index of the first non-option argument. */
826 static int
827 decode_switches (int argc, char **argv)
829 register char const *p;
830 int c;
831 int i;
832 long int tmp_long;
834 qmark_funny_chars = 0;
836 /* initialize all switches to default settings */
838 switch (ls_mode)
840 case LS_MULTI_COL:
841 /* This is for the `dir' program. */
842 format = many_per_line;
843 set_quoting_style (NULL, escape_quoting_style);
844 break;
846 case LS_LONG_FORMAT:
847 /* This is for the `vdir' program. */
848 format = long_format;
849 set_quoting_style (NULL, escape_quoting_style);
850 break;
852 case LS_LS:
853 /* This is for the `ls' program. */
854 if (isatty (1))
856 format = many_per_line;
857 /* See description of qmark_funny_chars, above. */
858 qmark_funny_chars = 1;
860 else
862 format = one_per_line;
863 qmark_funny_chars = 0;
865 break;
867 default:
868 abort ();
871 time_type = time_mtime;
872 full_time = 0;
873 sort_type = sort_name;
874 sort_reverse = 0;
875 numeric_ids = 0;
876 print_block_size = 0;
877 indicator_style = none;
878 print_inode = 0;
879 trace_links = 0;
880 trace_dirs = 0;
881 immediate_dirs = 0;
882 all_files = 0;
883 really_all_files = 0;
884 ignore_patterns = 0;
886 /* FIXME: Shouldn't we complain on wrong values? */
887 if ((p = getenv ("QUOTING_STYLE"))
888 && 0 <= (i = ARGCASEMATCH (p, quoting_style_args, quoting_style_vals)))
889 set_quoting_style (NULL, quoting_style_vals[i]);
891 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
893 line_length = 80;
894 if ((p = getenv ("COLUMNS")) && *p)
896 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
897 && 0 < tmp_long && tmp_long <= INT_MAX)
899 line_length = (int) tmp_long;
901 else
903 error (0, 0,
904 _("ignoring invalid width in environment variable COLUMNS: %s"),
905 quotearg (p));
909 #ifdef TIOCGWINSZ
911 struct winsize ws;
913 if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
914 line_length = ws.ws_col;
916 #endif
918 /* Using the TABSIZE environment variable is not POSIX-approved.
919 Ignore it when POSIXLY_CORRECT is set. */
920 tabsize = 8;
921 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
923 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
924 && 0 <= tmp_long && tmp_long <= INT_MAX)
926 tabsize = (int) tmp_long;
928 else
930 error (0, 0,
931 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
932 quotearg (p));
936 while ((c = getopt_long (argc, argv,
937 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
938 long_options, NULL)) != -1)
940 switch (c)
942 case 0:
943 break;
945 case 'a':
946 all_files = 1;
947 really_all_files = 1;
948 break;
950 case 'b':
951 set_quoting_style (NULL, escape_quoting_style);
952 break;
954 case 'c':
955 time_type = time_ctime;
956 sort_type = sort_time;
957 break;
959 case 'd':
960 immediate_dirs = 1;
961 break;
963 case 'f':
964 /* Same as enabling -a -U and disabling -l -s. */
965 all_files = 1;
966 really_all_files = 1;
967 sort_type = sort_none;
968 /* disable -l */
969 if (format == long_format)
970 format = (isatty (1) ? many_per_line : one_per_line);
971 print_block_size = 0; /* disable -s */
972 print_with_color = 0; /* disable --color */
973 break;
975 case 'g':
976 /* No effect. For BSD compatibility. */
977 break;
979 case 'h':
980 output_block_size = -1024;
981 break;
983 case 'H':
984 output_block_size = -1000;
985 break;
987 case 'i':
988 print_inode = 1;
989 break;
991 case 'k':
992 output_block_size = 1024;
993 break;
995 case 'l':
996 format = long_format;
997 break;
999 case 'm':
1000 format = with_commas;
1001 break;
1003 case 'n':
1004 numeric_ids = 1;
1005 break;
1007 case 'o': /* Just like -l, but don't display group info. */
1008 format = long_format;
1009 inhibit_group = 1;
1010 break;
1012 case 'p':
1013 indicator_style = file_type;
1014 break;
1016 case 'q':
1017 qmark_funny_chars = 1;
1018 break;
1020 case 'r':
1021 sort_reverse = 1;
1022 break;
1024 case 's':
1025 print_block_size = 1;
1026 break;
1028 case 't':
1029 sort_type = sort_time;
1030 break;
1032 case 'u':
1033 sort_type = sort_time;
1034 time_type = time_atime;
1035 break;
1037 case 'v':
1038 sort_type = sort_version;
1039 break;
1041 case 'w':
1042 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1043 || tmp_long <= 0 || tmp_long > INT_MAX)
1044 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1045 quotearg (optarg));
1046 line_length = (int) tmp_long;
1047 break;
1049 case 'x':
1050 format = horizontal;
1051 break;
1053 case 'A':
1054 really_all_files = 0;
1055 all_files = 1;
1056 break;
1058 case 'B':
1059 add_ignore_pattern ("*~");
1060 add_ignore_pattern (".*~");
1061 break;
1063 case 'C':
1064 format = many_per_line;
1065 break;
1067 case 'D':
1068 dired = 1;
1069 break;
1071 case 'F':
1072 indicator_style = classify;
1073 break;
1075 case 'G': /* inhibit display of group info */
1076 inhibit_group = 1;
1077 break;
1079 case 'I':
1080 add_ignore_pattern (optarg);
1081 break;
1083 case 'L':
1084 trace_links = 1;
1085 break;
1087 case 'N':
1088 set_quoting_style (NULL, literal_quoting_style);
1089 break;
1091 case 'Q':
1092 set_quoting_style (NULL, c_quoting_style);
1093 break;
1095 case 'R':
1096 trace_dirs = 1;
1097 break;
1099 case 'S':
1100 sort_type = sort_size;
1101 break;
1103 case 'T':
1104 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1105 || tmp_long < 0 || tmp_long > INT_MAX)
1106 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1107 quotearg (optarg));
1108 tabsize = (int) tmp_long;
1109 break;
1111 case 'U':
1112 sort_type = sort_none;
1113 break;
1115 case 'X':
1116 sort_type = sort_extension;
1117 break;
1119 case '1':
1120 format = one_per_line;
1121 break;
1123 case 10: /* --sort */
1124 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1125 break;
1127 case 11: /* --time */
1128 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1129 break;
1131 case 12: /* --format */
1132 format = XARGMATCH ("--format", optarg, format_args, format_types);
1133 break;
1135 case 13: /* --color */
1136 if (optarg)
1137 i = XARGMATCH ("--color", optarg, color_args, color_types);
1138 else
1139 /* Using --color with no argument is equivalent to using
1140 --color=always. */
1141 i = color_always;
1143 print_with_color = (i == color_always
1144 || (i == color_if_tty
1145 && isatty (STDOUT_FILENO)));
1147 if (print_with_color)
1149 /* Don't use TAB characters in output. Some terminal
1150 emulators can't handle the combination of tabs and
1151 color codes on the same line. */
1152 tabsize = 0;
1154 break;
1156 case 14: /* --indicator-style */
1157 indicator_style = XARGMATCH ("--indicator-style", optarg,
1158 indicator_style_args,
1159 indicator_style_types);
1160 break;
1162 case 15: /* --quoting-style */
1163 set_quoting_style (NULL,
1164 XARGMATCH ("--quoting-style", optarg,
1165 quoting_style_args,
1166 quoting_style_vals));
1167 break;
1169 case 16:
1170 qmark_funny_chars = 0;
1171 break;
1173 case 17:
1174 human_block_size (optarg, 1, &output_block_size);
1175 break;
1177 case_GETOPT_HELP_CHAR;
1179 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1181 default:
1182 usage (EXIT_FAILURE);
1186 filename_quoting_options = clone_quoting_options (NULL);
1187 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1188 set_char_quoting (filename_quoting_options, ' ', 1);
1189 if (indicator_style != none)
1190 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1191 set_char_quoting (filename_quoting_options, *p, 1);
1193 dirname_quoting_options = clone_quoting_options (NULL);
1194 set_char_quoting (dirname_quoting_options, ':', 1);
1196 return optind;
1199 /* Parse a string as part of the LS_COLORS variable; this may involve
1200 decoding all kinds of escape characters. If equals_end is set an
1201 unescaped equal sign ends the string, otherwise only a : or \0
1202 does. Returns the number of characters output, or -1 on failure.
1204 The resulting string is *not* null-terminated, but may contain
1205 embedded nulls.
1207 Note that both dest and src are char **; on return they point to
1208 the first free byte after the array and the character that ended
1209 the input string, respectively. */
1211 static int
1212 get_funky_string (char **dest, const char **src, int equals_end)
1214 int num; /* For numerical codes */
1215 int count; /* Something to count with */
1216 enum {
1217 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1218 } state;
1219 const char *p;
1220 char *q;
1222 p = *src; /* We don't want to double-indirect */
1223 q = *dest; /* the whole darn time. */
1225 count = 0; /* No characters counted in yet. */
1226 num = 0;
1228 state = ST_GND; /* Start in ground state. */
1229 while (state < ST_END)
1231 switch (state)
1233 case ST_GND: /* Ground state (no escapes) */
1234 switch (*p)
1236 case ':':
1237 case '\0':
1238 state = ST_END; /* End of string */
1239 break;
1240 case '\\':
1241 state = ST_BACKSLASH; /* Backslash scape sequence */
1242 ++p;
1243 break;
1244 case '^':
1245 state = ST_CARET; /* Caret escape */
1246 ++p;
1247 break;
1248 case '=':
1249 if (equals_end)
1251 state = ST_END; /* End */
1252 break;
1254 /* else fall through */
1255 default:
1256 *(q++) = *(p++);
1257 ++count;
1258 break;
1260 break;
1262 case ST_BACKSLASH: /* Backslash escaped character */
1263 switch (*p)
1265 case '0':
1266 case '1':
1267 case '2':
1268 case '3':
1269 case '4':
1270 case '5':
1271 case '6':
1272 case '7':
1273 state = ST_OCTAL; /* Octal sequence */
1274 num = *p - '0';
1275 break;
1276 case 'x':
1277 case 'X':
1278 state = ST_HEX; /* Hex sequence */
1279 num = 0;
1280 break;
1281 case 'a': /* Bell */
1282 num = 7; /* Not all C compilers know what \a means */
1283 break;
1284 case 'b': /* Backspace */
1285 num = '\b';
1286 break;
1287 case 'e': /* Escape */
1288 num = 27;
1289 break;
1290 case 'f': /* Form feed */
1291 num = '\f';
1292 break;
1293 case 'n': /* Newline */
1294 num = '\n';
1295 break;
1296 case 'r': /* Carriage return */
1297 num = '\r';
1298 break;
1299 case 't': /* Tab */
1300 num = '\t';
1301 break;
1302 case 'v': /* Vtab */
1303 num = '\v';
1304 break;
1305 case '?': /* Delete */
1306 num = 127;
1307 break;
1308 case '_': /* Space */
1309 num = ' ';
1310 break;
1311 case '\0': /* End of string */
1312 state = ST_ERROR; /* Error! */
1313 break;
1314 default: /* Escaped character like \ ^ : = */
1315 num = *p;
1316 break;
1318 if (state == ST_BACKSLASH)
1320 *(q++) = num;
1321 ++count;
1322 state = ST_GND;
1324 ++p;
1325 break;
1327 case ST_OCTAL: /* Octal sequence */
1328 if (*p < '0' || *p > '7')
1330 *(q++) = num;
1331 ++count;
1332 state = ST_GND;
1334 else
1335 num = (num << 3) + (*(p++) - '0');
1336 break;
1338 case ST_HEX: /* Hex sequence */
1339 switch (*p)
1341 case '0':
1342 case '1':
1343 case '2':
1344 case '3':
1345 case '4':
1346 case '5':
1347 case '6':
1348 case '7':
1349 case '8':
1350 case '9':
1351 num = (num << 4) + (*(p++) - '0');
1352 break;
1353 case 'a':
1354 case 'b':
1355 case 'c':
1356 case 'd':
1357 case 'e':
1358 case 'f':
1359 num = (num << 4) + (*(p++) - 'a') + 10;
1360 break;
1361 case 'A':
1362 case 'B':
1363 case 'C':
1364 case 'D':
1365 case 'E':
1366 case 'F':
1367 num = (num << 4) + (*(p++) - 'A') + 10;
1368 break;
1369 default:
1370 *(q++) = num;
1371 ++count;
1372 state = ST_GND;
1373 break;
1375 break;
1377 case ST_CARET: /* Caret escape */
1378 state = ST_GND; /* Should be the next state... */
1379 if (*p >= '@' && *p <= '~')
1381 *(q++) = *(p++) & 037;
1382 ++count;
1384 else if (*p == '?')
1386 *(q++) = 127;
1387 ++count;
1389 else
1390 state = ST_ERROR;
1391 break;
1393 default:
1394 abort ();
1398 *dest = q;
1399 *src = p;
1401 return state == ST_ERROR ? -1 : count;
1404 static void
1405 parse_ls_color (void)
1407 const char *p; /* Pointer to character being parsed */
1408 char *buf; /* color_buf buffer pointer */
1409 int state; /* State of parser */
1410 int ind_no; /* Indicator number */
1411 char label[3]; /* Indicator label */
1412 struct color_ext_type *ext; /* Extension we are working on */
1414 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1415 return;
1417 ext = NULL;
1418 strcpy (label, "??");
1420 /* This is an overly conservative estimate, but any possible
1421 LS_COLORS string will *not* generate a color_buf longer than
1422 itself, so it is a safe way of allocating a buffer in
1423 advance. */
1424 buf = color_buf = xstrdup (p);
1426 state = 1;
1427 while (state > 0)
1429 switch (state)
1431 case 1: /* First label character */
1432 switch (*p)
1434 case ':':
1435 ++p;
1436 break;
1438 case '*':
1439 /* Allocate new extension block and add to head of
1440 linked list (this way a later definition will
1441 override an earlier one, which can be useful for
1442 having terminal-specific defs override global). */
1444 ext = (struct color_ext_type *)
1445 xmalloc (sizeof (struct color_ext_type));
1446 ext->next = color_ext_list;
1447 color_ext_list = ext;
1449 ++p;
1450 ext->ext.string = buf;
1452 state = (ext->ext.len =
1453 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1454 break;
1456 case '\0':
1457 state = 0; /* Done! */
1458 break;
1460 default: /* Assume it is file type label */
1461 label[0] = *(p++);
1462 state = 2;
1463 break;
1465 break;
1467 case 2: /* Second label character */
1468 if (*p)
1470 label[1] = *(p++);
1471 state = 3;
1473 else
1474 state = -1; /* Error */
1475 break;
1477 case 3: /* Equal sign after indicator label */
1478 state = -1; /* Assume failure... */
1479 if (*(p++) == '=')/* It *should* be... */
1481 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1483 if (STREQ (label, indicator_name[ind_no]))
1485 color_indicator[ind_no].string = buf;
1486 state = ((color_indicator[ind_no].len =
1487 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1488 break;
1491 if (state == -1)
1492 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1494 break;
1496 case 4: /* Equal sign after *.ext */
1497 if (*(p++) == '=')
1499 ext->seq.string = buf;
1500 state = (ext->seq.len =
1501 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1503 else
1504 state = -1;
1505 break;
1509 if (state < 0)
1511 struct color_ext_type *e;
1512 struct color_ext_type *e2;
1514 error (0, 0,
1515 _("unparsable value for LS_COLORS environment variable"));
1516 free (color_buf);
1517 for (e = color_ext_list; e != NULL; /* empty */)
1519 e2 = e;
1520 e = e->next;
1521 free (e2);
1523 print_with_color = 0;
1527 /* Request that the directory named `name' have its contents listed later.
1528 If `realname' is nonzero, it will be used instead of `name' when the
1529 directory name is printed. This allows symbolic links to directories
1530 to be treated as regular directories but still be listed under their
1531 real names. */
1533 static void
1534 queue_directory (const char *name, const char *realname)
1536 struct pending *new;
1538 new = (struct pending *) xmalloc (sizeof (struct pending));
1539 new->next = pending_dirs;
1540 pending_dirs = new;
1541 new->name = xstrdup (name);
1542 if (realname)
1543 new->realname = xstrdup (realname);
1544 else
1545 new->realname = 0;
1548 /* Read directory `name', and list the files in it.
1549 If `realname' is nonzero, print its name instead of `name';
1550 this is used for symbolic links to directories. */
1552 static void
1553 print_dir (const char *name, const char *realname)
1555 register DIR *reading;
1556 register struct dirent *next;
1557 register uintmax_t total_blocks = 0;
1559 errno = 0;
1560 reading = opendir (name);
1561 if (!reading)
1563 error (0, errno, "%s", quotearg_colon (name));
1564 exit_status = 1;
1565 return;
1568 /* Read the directory entries, and insert the subfiles into the `files'
1569 table. */
1571 clear_files ();
1573 while ((next = readdir (reading)) != NULL)
1574 if (file_interesting (next))
1575 total_blocks += gobble_file (next->d_name, 0, name);
1577 if (CLOSEDIR (reading))
1579 error (0, errno, "%s", quotearg_colon (name));
1580 exit_status = 1;
1581 /* Don't return; print whatever we got. */
1584 /* Sort the directory contents. */
1585 sort_files ();
1587 /* If any member files are subdirectories, perhaps they should have their
1588 contents listed rather than being mentioned here as files. */
1590 if (trace_dirs)
1591 extract_dirs_from_files (name, 1);
1593 if (trace_dirs || print_dir_name)
1595 DIRED_INDENT ();
1596 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1597 dired_pos += quote_name (stdout, realname ? realname : name,
1598 dirname_quoting_options);
1599 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1600 DIRED_FPUTS_LITERAL (":\n", stdout);
1603 if (format == long_format || print_block_size)
1605 const char *p;
1606 char buf[LONGEST_HUMAN_READABLE + 1];
1608 DIRED_INDENT ();
1609 p = _("total");
1610 DIRED_FPUTS (p, stdout, strlen (p));
1611 DIRED_PUTCHAR (' ');
1612 p = human_readable (total_blocks, buf, ST_NBLOCKSIZE, output_block_size);
1613 DIRED_FPUTS (p, stdout, strlen (p));
1614 DIRED_PUTCHAR ('\n');
1617 if (files_index)
1618 print_current_files ();
1620 if (pending_dirs)
1621 DIRED_PUTCHAR ('\n');
1624 /* Add `pattern' to the list of patterns for which files that match are
1625 not listed. */
1627 static void
1628 add_ignore_pattern (const char *pattern)
1630 register struct ignore_pattern *ignore;
1632 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1633 ignore->pattern = pattern;
1634 /* Add it to the head of the linked list. */
1635 ignore->next = ignore_patterns;
1636 ignore_patterns = ignore;
1639 /* Return nonzero if the file in `next' should be listed. */
1641 static int
1642 file_interesting (const struct dirent *next)
1644 register struct ignore_pattern *ignore;
1646 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1647 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1648 return 0;
1650 if (really_all_files
1651 || next->d_name[0] != '.'
1652 || (all_files
1653 && next->d_name[1] != '\0'
1654 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1655 return 1;
1657 return 0;
1660 /* Enter and remove entries in the table `files'. */
1662 /* Empty the table of files. */
1664 static void
1665 clear_files (void)
1667 register int i;
1669 for (i = 0; i < files_index; i++)
1671 free (files[i].name);
1672 if (files[i].linkname)
1673 free (files[i].linkname);
1676 files_index = 0;
1677 block_size_size = 4;
1680 /* Add a file to the current table of files.
1681 Verify that the file exists, and print an error message if it does not.
1682 Return the number of blocks that the file occupies. */
1684 static uintmax_t
1685 gobble_file (const char *name, int explicit_arg, const char *dirname)
1687 register uintmax_t blocks;
1688 register int val;
1689 register char *path;
1691 if (files_index == nfiles)
1693 nfiles *= 2;
1694 files = (struct fileinfo *) xrealloc ((char *) files,
1695 sizeof (*files) * nfiles);
1698 files[files_index].linkname = 0;
1699 files[files_index].linkmode = 0;
1700 files[files_index].linkok = 0;
1702 if (explicit_arg || format_needs_stat)
1704 /* `path' is the absolute pathname of this file. */
1706 if (name[0] == '/' || dirname[0] == 0)
1707 path = (char *) name;
1708 else
1710 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1711 attach (path, dirname, name);
1714 if (trace_links)
1716 val = stat (path, &files[files_index].stat);
1717 if (val < 0)
1718 /* Perhaps a symbolically-linked to file doesn't exist; stat
1719 the link instead. */
1720 val = lstat (path, &files[files_index].stat);
1722 else
1724 val = lstat (path, &files[files_index].stat);
1727 if (val < 0)
1729 error (0, errno, "%s", quotearg_colon (path));
1730 exit_status = 1;
1731 return 0;
1734 if (S_ISLNK (files[files_index].stat.st_mode)
1735 && (explicit_arg || format == long_format || print_with_color))
1737 char *linkpath;
1738 struct stat linkstats;
1740 get_link_name (path, &files[files_index]);
1741 linkpath = make_link_path (path, files[files_index].linkname);
1743 /* Avoid following symbolic links when possible, ie, when
1744 they won't be traced and when no indicator is needed. */
1745 if (linkpath
1746 && ((explicit_arg && format != long_format)
1747 || indicator_style != none
1748 || print_with_color)
1749 && stat (linkpath, &linkstats) == 0)
1751 files[files_index].linkok = 1;
1753 /* Symbolic links to directories that are mentioned on the
1754 command line are automatically traced if not being
1755 listed as files. */
1756 if (explicit_arg && format != long_format
1757 && S_ISDIR (linkstats.st_mode))
1759 /* Substitute the linked-to directory's name, but
1760 save the real name in `linkname' for printing. */
1761 if (!immediate_dirs)
1763 const char *tempname = name;
1764 name = linkpath;
1765 linkpath = files[files_index].linkname;
1766 files[files_index].linkname = (char *) tempname;
1768 files[files_index].stat = linkstats;
1770 else
1772 /* Get the linked-to file's mode for the filetype indicator
1773 in long listings. */
1774 files[files_index].linkmode = linkstats.st_mode;
1775 files[files_index].linkok = 1;
1778 if (linkpath)
1779 free (linkpath);
1782 if (S_ISLNK (files[files_index].stat.st_mode))
1783 files[files_index].filetype = symbolic_link;
1784 else if (S_ISDIR (files[files_index].stat.st_mode))
1786 if (explicit_arg && !immediate_dirs)
1787 files[files_index].filetype = arg_directory;
1788 else
1789 files[files_index].filetype = directory;
1791 else
1792 files[files_index].filetype = normal;
1794 blocks = ST_NBLOCKS (files[files_index].stat);
1796 char buf[LONGEST_HUMAN_READABLE + 1];
1797 int len = strlen (human_readable (blocks, buf, ST_NBLOCKSIZE,
1798 output_block_size));
1799 if (block_size_size < len)
1800 block_size_size = len < 7 ? len : 7;
1803 else
1804 blocks = 0;
1806 files[files_index].name = xstrdup (name);
1807 files_index++;
1809 return blocks;
1812 #if HAVE_SYMLINKS
1814 /* Put the name of the file that `filename' is a symbolic link to
1815 into the `linkname' field of `f'. */
1817 static void
1818 get_link_name (const char *filename, struct fileinfo *f)
1820 char *linkbuf;
1821 register int linksize;
1823 linkbuf = (char *) alloca (PATH_MAX + 2);
1824 /* Some automounters give incorrect st_size for mount points.
1825 I can't think of a good workaround for it, though. */
1826 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1827 if (linksize < 0)
1829 error (0, errno, "%s", quotearg_colon (filename));
1830 exit_status = 1;
1832 else
1834 linkbuf[linksize] = '\0';
1835 f->linkname = xstrdup (linkbuf);
1839 /* If `linkname' is a relative path and `path' contains one or more
1840 leading directories, return `linkname' with those directories
1841 prepended; otherwise, return a copy of `linkname'.
1842 If `linkname' is zero, return zero. */
1844 static char *
1845 make_link_path (const char *path, const char *linkname)
1847 char *linkbuf;
1848 int bufsiz;
1850 if (linkname == 0)
1851 return 0;
1853 if (*linkname == '/')
1854 return xstrdup (linkname);
1856 /* The link is to a relative path. Prepend any leading path
1857 in `path' to the link name. */
1858 linkbuf = strrchr (path, '/');
1859 if (linkbuf == 0)
1860 return xstrdup (linkname);
1862 bufsiz = linkbuf - path + 1;
1863 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1864 strncpy (linkbuf, path, bufsiz);
1865 strcpy (linkbuf + bufsiz, linkname);
1866 return linkbuf;
1868 #endif
1870 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1871 This is so we don't try to recurse on `././././. ...' */
1873 static int
1874 basename_is_dot_or_dotdot (const char *name)
1876 char *base = base_name (name);
1877 return DOT_OR_DOTDOT (base);
1880 /* Remove any entries from `files' that are for directories,
1881 and queue them to be listed as directories instead.
1882 `dirname' is the prefix to prepend to each dirname
1883 to make it correct relative to ls's working dir.
1884 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1885 This is desirable when processing directories recursively. */
1887 static void
1888 extract_dirs_from_files (const char *dirname, int recursive)
1890 register int i, j;
1891 int dirlen;
1893 dirlen = strlen (dirname) + 2;
1894 /* Queue the directories last one first, because queueing reverses the
1895 order. */
1896 for (i = files_index - 1; i >= 0; i--)
1897 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1898 && (!recursive || !basename_is_dot_or_dotdot (files[i].name)))
1900 if (files[i].name[0] == '/' || dirname[0] == 0)
1902 queue_directory (files[i].name, files[i].linkname);
1904 else
1906 char *path = path_concat (dirname, files[i].name, NULL);
1907 queue_directory (path, files[i].linkname);
1908 free (path);
1910 if (files[i].filetype == arg_directory)
1911 free (files[i].name);
1914 /* Now delete the directories from the table, compacting all the remaining
1915 entries. */
1917 for (i = 0, j = 0; i < files_index; i++)
1918 if (files[i].filetype != arg_directory)
1919 files[j++] = files[i];
1920 files_index = j;
1923 /* Sort the files now in the table. */
1925 static void
1926 sort_files (void)
1928 int (*func) ();
1930 switch (sort_type)
1932 case sort_none:
1933 return;
1934 case sort_time:
1935 switch (time_type)
1937 case time_ctime:
1938 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1939 break;
1940 case time_mtime:
1941 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1942 break;
1943 case time_atime:
1944 func = sort_reverse ? rev_cmp_atime : compare_atime;
1945 break;
1946 default:
1947 abort ();
1949 break;
1950 case sort_name:
1951 func = sort_reverse ? rev_cmp_name : compare_name;
1952 break;
1953 case sort_extension:
1954 func = sort_reverse ? rev_cmp_extension : compare_extension;
1955 break;
1956 case sort_size:
1957 func = sort_reverse ? rev_cmp_size : compare_size;
1958 break;
1959 case sort_version:
1960 func = sort_reverse ? rev_cmp_version : compare_version;
1961 break;
1962 default:
1963 abort ();
1966 qsort (files, files_index, sizeof (struct fileinfo), func);
1969 /* Comparison routines for sorting the files. */
1971 static int
1972 compare_ctime (const struct fileinfo *file1, const struct fileinfo *file2)
1974 int diff = CTIME_CMP (file2->stat, file1->stat);
1975 if (diff == 0)
1976 diff = strcmp (file1->name, file2->name);
1977 return diff;
1980 static int
1981 rev_cmp_ctime (const struct fileinfo *file2, const struct fileinfo *file1)
1983 int diff = CTIME_CMP (file2->stat, file1->stat);
1984 if (diff == 0)
1985 diff = strcmp (file1->name, file2->name);
1986 return diff;
1989 static int
1990 compare_mtime (const struct fileinfo *file1, const struct fileinfo *file2)
1992 int diff = MTIME_CMP (file2->stat, file1->stat);
1993 if (diff == 0)
1994 diff = strcmp (file1->name, file2->name);
1995 return diff;
1998 static int
1999 rev_cmp_mtime (const struct fileinfo *file2, const struct fileinfo *file1)
2001 int diff = MTIME_CMP (file2->stat, file1->stat);
2002 if (diff == 0)
2003 diff = strcmp (file1->name, file2->name);
2004 return diff;
2007 static int
2008 compare_atime (const struct fileinfo *file1, const struct fileinfo *file2)
2010 int diff = ATIME_CMP (file2->stat, file1->stat);
2011 if (diff == 0)
2012 diff = strcmp (file1->name, file2->name);
2013 return diff;
2016 static int
2017 rev_cmp_atime (const struct fileinfo *file2, const struct fileinfo *file1)
2019 int diff = ATIME_CMP (file2->stat, file1->stat);
2020 if (diff == 0)
2021 diff = strcmp (file1->name, file2->name);
2022 return diff;
2025 static int
2026 compare_size (const struct fileinfo *file1, const struct fileinfo *file2)
2028 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2029 if (diff == 0)
2030 diff = strcmp (file1->name, file2->name);
2031 return diff;
2034 static int
2035 rev_cmp_size (const struct fileinfo *file2, const struct fileinfo *file1)
2037 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2038 if (diff == 0)
2039 diff = strcmp (file1->name, file2->name);
2040 return diff;
2043 static int
2044 compare_version (const struct fileinfo *file1, const struct fileinfo *file2)
2046 return strverscmp (file1->name, file2->name);
2049 static int
2050 rev_cmp_version (const struct fileinfo *file2, const struct fileinfo *file1)
2052 return strverscmp (file1->name, file2->name);
2055 static int
2056 compare_name (const struct fileinfo *file1, const struct fileinfo *file2)
2058 return strcmp (file1->name, file2->name);
2061 static int
2062 rev_cmp_name (const struct fileinfo *file2, const struct fileinfo *file1)
2064 return strcmp (file1->name, file2->name);
2067 /* Compare file extensions. Files with no extension are `smallest'.
2068 If extensions are the same, compare by filenames instead. */
2070 static int
2071 compare_extension (const struct fileinfo *file1, const struct fileinfo *file2)
2073 register char *base1, *base2;
2074 register int cmp;
2076 base1 = strrchr (file1->name, '.');
2077 base2 = strrchr (file2->name, '.');
2078 if (base1 == 0 && base2 == 0)
2079 return strcmp (file1->name, file2->name);
2080 if (base1 == 0)
2081 return -1;
2082 if (base2 == 0)
2083 return 1;
2084 cmp = strcmp (base1, base2);
2085 if (cmp == 0)
2086 return strcmp (file1->name, file2->name);
2087 return cmp;
2090 static int
2091 rev_cmp_extension (const struct fileinfo *file2, const struct fileinfo *file1)
2093 register char *base1, *base2;
2094 register int cmp;
2096 base1 = strrchr (file1->name, '.');
2097 base2 = strrchr (file2->name, '.');
2098 if (base1 == 0 && base2 == 0)
2099 return strcmp (file1->name, file2->name);
2100 if (base1 == 0)
2101 return -1;
2102 if (base2 == 0)
2103 return 1;
2104 cmp = strcmp (base1, base2);
2105 if (cmp == 0)
2106 return strcmp (file1->name, file2->name);
2107 return cmp;
2110 /* List all the files now in the table. */
2112 static void
2113 print_current_files (void)
2115 register int i;
2117 switch (format)
2119 case one_per_line:
2120 for (i = 0; i < files_index; i++)
2122 print_file_name_and_frills (files + i);
2123 putchar ('\n');
2125 break;
2127 case many_per_line:
2128 init_column_info ();
2129 print_many_per_line ();
2130 break;
2132 case horizontal:
2133 init_column_info ();
2134 print_horizontal ();
2135 break;
2137 case with_commas:
2138 print_with_commas ();
2139 break;
2141 case long_format:
2142 for (i = 0; i < files_index; i++)
2144 print_long_format (files + i);
2145 DIRED_PUTCHAR ('\n');
2147 break;
2151 static void
2152 print_long_format (const struct fileinfo *f)
2154 char modebuf[11];
2156 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2157 1 10-byte mode string,
2158 1 24-byte time string (may be longer in some locales -- see below)
2159 or LONGEST_HUMAN_READABLE integer,
2160 9 spaces, one following each of these fields, and
2161 1 trailing NUL byte. */
2162 char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2163 + (LONGEST_HUMAN_READABLE < 24 ? 24 : LONGEST_HUMAN_READABLE)
2164 + 9 + 1];
2165 char *buf = init_bigbuf;
2166 size_t bufsize = sizeof (init_bigbuf);
2167 size_t s;
2168 char *p;
2169 time_t when;
2170 struct tm *when_local;
2171 const char *fmt;
2172 char *user_name;
2174 #if HAVE_ST_DM_MODE
2175 /* Cray DMF: look at the file's migrated, not real, status */
2176 mode_string (f->stat.st_dm_mode, modebuf);
2177 #else
2178 mode_string (f->stat.st_mode, modebuf);
2179 #endif
2181 modebuf[10] = '\0';
2183 switch (time_type)
2185 case time_ctime:
2186 when = f->stat.st_ctime;
2187 break;
2188 case time_mtime:
2189 when = f->stat.st_mtime;
2190 break;
2191 case time_atime:
2192 when = f->stat.st_atime;
2193 break;
2196 if (full_time)
2198 fmt = "%a %b %d %H:%M:%S %Y";
2200 else
2202 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
2203 || current_time < when - 60L * 60L) /* In the future. */
2205 /* The file is fairly old or in the future.
2206 POSIX says the cutoff is 6 months old;
2207 approximate this by 6*30 days.
2208 Allow a 1 hour slop factor for what is considered "the future",
2209 to allow for NFS server/client clock disagreement.
2210 Show the year instead of the time of day. */
2211 fmt = "%b %e %Y";
2213 else
2215 fmt = "%b %e %H:%M";
2219 p = buf;
2221 if (print_inode)
2223 char hbuf[LONGEST_HUMAN_READABLE + 1];
2224 sprintf (p, "%*s ", INODE_DIGITS,
2225 human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2226 p += strlen (p);
2229 if (print_block_size)
2231 char hbuf[LONGEST_HUMAN_READABLE + 1];
2232 sprintf (p, "%*s ", block_size_size,
2233 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2234 ST_NBLOCKSIZE, output_block_size));
2235 p += strlen (p);
2238 /* The space between the mode and the number of links is the POSIX
2239 "optional alternate access method flag". */
2240 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
2241 p += strlen (p);
2243 user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2244 if (user_name)
2245 sprintf (p, "%-8.8s ", user_name);
2246 else
2247 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
2248 p += strlen (p);
2250 if (!inhibit_group)
2252 char *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2253 if (group_name)
2254 sprintf (p, "%-8.8s ", group_name);
2255 else
2256 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
2257 p += strlen (p);
2260 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2261 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
2262 (unsigned) minor (f->stat.st_rdev));
2263 else
2265 char hbuf[LONGEST_HUMAN_READABLE + 1];
2266 sprintf (p, "%8s ",
2267 human_readable ((uintmax_t) f->stat.st_size, hbuf, 1,
2268 output_block_size < 0 ? output_block_size : 1));
2271 p += strlen (p);
2273 /* Use strftime rather than ctime, because the former can produce
2274 locale-dependent names for the weekday (%a) and month (%b). */
2276 if ((when_local = localtime (&when)))
2278 while (! (s = strftime (p, buf + bufsize - p - 1, fmt, when_local)))
2280 char *newbuf = (char *) alloca (bufsize *= 2);
2281 memcpy (newbuf, buf, p - buf);
2282 p = newbuf + (p - buf);
2283 buf = newbuf;
2286 p += s;
2287 *p++ = ' ';
2289 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2290 *p = '\0';
2292 else
2294 /* The time cannot be represented as a local time;
2295 print it as a huge integer number of seconds. */
2296 char hbuf[LONGEST_HUMAN_READABLE + 1];
2297 int width = full_time ? 24 : 12;
2299 if (when < 0)
2301 const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2302 int sign_width = width - strlen (num);
2303 sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2305 else
2306 sprintf (p, "%*s ", width,
2307 human_readable ((uintmax_t) when, hbuf, 1, 1));
2309 p += strlen (p);
2312 DIRED_INDENT ();
2313 DIRED_FPUTS (buf, stdout, p - buf);
2314 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok,
2315 &dired_obstack);
2317 if (f->filetype == symbolic_link)
2319 if (f->linkname)
2321 DIRED_FPUTS_LITERAL (" -> ", stdout);
2322 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2323 NULL);
2324 if (indicator_style != none)
2325 print_type_indicator (f->linkmode);
2328 else if (indicator_style != none)
2329 print_type_indicator (f->stat.st_mode);
2332 /* Output to OUT a quoted representation of the file name P,
2333 using OPTIONS to control quoting.
2334 Return the number of characters in P's quoted representation. */
2336 static size_t
2337 quote_name (FILE *out, const char *p, struct quoting_options const *options)
2339 char smallbuf[BUFSIZ];
2340 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, p, -1, options);
2341 char *buf;
2343 if (len < sizeof smallbuf)
2344 buf = smallbuf;
2345 else
2347 buf = (char *) alloca (len + 1);
2348 quotearg_buffer (buf, len + 1, p, -1, options);
2351 if (qmark_funny_chars)
2353 size_t i;
2354 for (i = 0; i < len; i++)
2355 if (! ISPRINT ((unsigned char) buf[i]))
2356 buf[i] = '?';
2359 fwrite (buf, 1, len, out);
2360 return len;
2363 static void
2364 print_name_with_quoting (const char *p, unsigned int mode, int linkok,
2365 struct obstack *stack)
2367 if (print_with_color)
2368 print_color_indicator (p, mode, linkok);
2370 if (stack)
2371 PUSH_CURRENT_DIRED_POS (stack);
2373 dired_pos += quote_name (stdout, p, filename_quoting_options);
2375 if (stack)
2376 PUSH_CURRENT_DIRED_POS (stack);
2378 if (print_with_color)
2379 prep_non_filename_text ();
2382 static void
2383 prep_non_filename_text (void)
2385 if (color_indicator[C_END].string != NULL)
2386 put_indicator (&color_indicator[C_END]);
2387 else
2389 put_indicator (&color_indicator[C_LEFT]);
2390 put_indicator (&color_indicator[C_NORM]);
2391 put_indicator (&color_indicator[C_RIGHT]);
2395 /* Print the file name of `f' with appropriate quoting.
2396 Also print file size, inode number, and filetype indicator character,
2397 as requested by switches. */
2399 static void
2400 print_file_name_and_frills (const struct fileinfo *f)
2402 char buf[LONGEST_HUMAN_READABLE + 1];
2404 if (print_inode)
2405 printf ("%*s ", INODE_DIGITS,
2406 human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
2408 if (print_block_size)
2409 printf ("%*s ", block_size_size,
2410 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), buf,
2411 ST_NBLOCKSIZE, output_block_size));
2413 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok, NULL);
2415 if (indicator_style != none)
2416 print_type_indicator (f->stat.st_mode);
2419 static void
2420 print_type_indicator (unsigned int mode)
2422 int c;
2424 if (S_ISREG (mode))
2426 if (indicator_style == classify && (mode & S_IXUGO))
2427 c ='*';
2428 else
2429 c = 0;
2431 else
2433 if (S_ISDIR (mode))
2434 c = '/';
2435 else if (S_ISLNK (mode))
2436 c = '@';
2437 else if (S_ISFIFO (mode))
2438 c = '|';
2439 else if (S_ISSOCK (mode))
2440 c = '=';
2441 else if (S_ISDOOR (mode))
2442 c = '>';
2443 else
2444 c = 0;
2447 if (c)
2448 DIRED_PUTCHAR (c);
2451 static void
2452 print_color_indicator (const char *name, unsigned int mode, int linkok)
2454 int type = C_FILE;
2455 struct color_ext_type *ext; /* Color extension */
2456 size_t len; /* Length of name */
2458 /* Is this a nonexistent file? If so, linkok == -1. */
2460 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
2462 ext = NULL;
2463 type = C_MISSING;
2465 else
2467 if (S_ISDIR (mode))
2468 type = C_DIR;
2469 else if (S_ISLNK (mode))
2470 type = ((!linkok && color_indicator[C_ORPHAN].string)
2471 ? C_ORPHAN : C_LINK);
2472 else if (S_ISFIFO (mode))
2473 type = C_FIFO;
2474 else if (S_ISSOCK (mode))
2475 type = C_SOCK;
2476 else if (S_ISBLK (mode))
2477 type = C_BLK;
2478 else if (S_ISCHR (mode))
2479 type = C_CHR;
2480 else if (S_ISDOOR (mode))
2481 type = C_DOOR;
2483 if (type == C_FILE && (mode & S_IXUGO) != 0)
2484 type = C_EXEC;
2486 /* Check the file's suffix only if still classified as C_FILE. */
2487 ext = NULL;
2488 if (type == C_FILE)
2490 /* Test if NAME has a recognized suffix. */
2492 len = strlen (name);
2493 name += len; /* Pointer to final \0. */
2494 for (ext = color_ext_list; ext != NULL; ext = ext->next)
2496 if ((size_t) ext->ext.len <= len
2497 && strncmp (name - ext->ext.len, ext->ext.string,
2498 ext->ext.len) == 0)
2499 break;
2504 put_indicator (&color_indicator[C_LEFT]);
2505 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
2506 put_indicator (&color_indicator[C_RIGHT]);
2509 /* Output a color indicator (which may contain nulls). */
2510 static void
2511 put_indicator (const struct bin_str *ind)
2513 register int i;
2514 register char *p;
2516 p = ind->string;
2518 for (i = ind->len; i > 0; --i)
2519 putchar (*(p++));
2522 static int
2523 length_of_file_name_and_frills (const struct fileinfo *f)
2525 register int len = 0;
2527 if (print_inode)
2528 len += INODE_DIGITS + 1;
2530 if (print_block_size)
2531 len += 1 + block_size_size;
2533 len += quotearg_buffer (0, 0, f->name, -1, filename_quoting_options);
2535 if (indicator_style != none)
2537 unsigned filetype = f->stat.st_mode;
2539 if (S_ISREG (filetype))
2541 if (indicator_style == classify
2542 && (f->stat.st_mode & S_IXUGO))
2543 len += 1;
2545 else if (S_ISDIR (filetype)
2546 || S_ISLNK (filetype)
2547 || S_ISFIFO (filetype)
2548 || S_ISSOCK (filetype)
2549 || S_ISDOOR (filetype)
2551 len += 1;
2554 return len;
2557 static void
2558 print_many_per_line (void)
2560 struct column_info *line_fmt;
2561 int filesno; /* Index into files. */
2562 int row; /* Current row. */
2563 int max_name_length; /* Length of longest file name + frills. */
2564 int name_length; /* Length of each file name + frills. */
2565 int pos; /* Current character column. */
2566 int cols; /* Number of files across. */
2567 int rows; /* Maximum number of files down. */
2568 int max_cols;
2570 /* Normally the maximum number of columns is determined by the
2571 screen width. But if few files are available this might limit it
2572 as well. */
2573 max_cols = max_idx > files_index ? files_index : max_idx;
2575 /* Compute the maximum number of possible columns. */
2576 for (filesno = 0; filesno < files_index; ++filesno)
2578 int i;
2580 name_length = length_of_file_name_and_frills (files + filesno);
2582 for (i = 0; i < max_cols; ++i)
2584 if (column_info[i].valid_len)
2586 int idx = filesno / ((files_index + i) / (i + 1));
2587 int real_length = name_length + (idx == i ? 0 : 2);
2589 if (real_length > column_info[i].col_arr[idx])
2591 column_info[i].line_len += (real_length
2592 - column_info[i].col_arr[idx]);
2593 column_info[i].col_arr[idx] = real_length;
2594 column_info[i].valid_len = column_info[i].line_len < line_length;
2600 /* Find maximum allowed columns. */
2601 for (cols = max_cols; cols > 1; --cols)
2603 if (column_info[cols - 1].valid_len)
2604 break;
2607 line_fmt = &column_info[cols - 1];
2609 /* Calculate the number of rows that will be in each column except possibly
2610 for a short column on the right. */
2611 rows = files_index / cols + (files_index % cols != 0);
2613 for (row = 0; row < rows; row++)
2615 int col = 0;
2616 filesno = row;
2617 pos = 0;
2618 /* Print the next row. */
2619 while (1)
2621 print_file_name_and_frills (files + filesno);
2622 name_length = length_of_file_name_and_frills (files + filesno);
2623 max_name_length = line_fmt->col_arr[col++];
2625 filesno += rows;
2626 if (filesno >= files_index)
2627 break;
2629 indent (pos + name_length, pos + max_name_length);
2630 pos += max_name_length;
2632 putchar ('\n');
2636 static void
2637 print_horizontal (void)
2639 struct column_info *line_fmt;
2640 int filesno;
2641 int max_name_length;
2642 int name_length;
2643 int cols;
2644 int pos;
2645 int max_cols;
2647 /* Normally the maximum number of columns is determined by the
2648 screen width. But if few files are available this might limit it
2649 as well. */
2650 max_cols = max_idx > files_index ? files_index : max_idx;
2652 /* Compute the maximum file name length. */
2653 max_name_length = 0;
2654 for (filesno = 0; filesno < files_index; ++filesno)
2656 int i;
2658 name_length = length_of_file_name_and_frills (files + filesno);
2660 for (i = 0; i < max_cols; ++i)
2662 if (column_info[i].valid_len)
2664 int idx = filesno % (i + 1);
2665 int real_length = name_length + (idx == i ? 0 : 2);
2667 if (real_length > column_info[i].col_arr[idx])
2669 column_info[i].line_len += (real_length
2670 - column_info[i].col_arr[idx]);
2671 column_info[i].col_arr[idx] = real_length;
2672 column_info[i].valid_len = column_info[i].line_len < line_length;
2678 /* Find maximum allowed columns. */
2679 for (cols = max_cols; cols > 1; --cols)
2681 if (column_info[cols - 1].valid_len)
2682 break;
2685 line_fmt = &column_info[cols - 1];
2687 pos = 0;
2689 /* Print first entry. */
2690 print_file_name_and_frills (files);
2691 name_length = length_of_file_name_and_frills (files);
2692 max_name_length = line_fmt->col_arr[0];
2694 /* Now the rest. */
2695 for (filesno = 1; filesno < files_index; ++filesno)
2697 int col = filesno % cols;
2699 if (col == 0)
2701 putchar ('\n');
2702 pos = 0;
2704 else
2706 indent (pos + name_length, pos + max_name_length);
2707 pos += max_name_length;
2710 print_file_name_and_frills (files + filesno);
2712 name_length = length_of_file_name_and_frills (files + filesno);
2713 max_name_length = line_fmt->col_arr[col];
2715 putchar ('\n');
2718 static void
2719 print_with_commas (void)
2721 int filesno;
2722 int pos, old_pos;
2724 pos = 0;
2726 for (filesno = 0; filesno < files_index; filesno++)
2728 old_pos = pos;
2730 pos += length_of_file_name_and_frills (files + filesno);
2731 if (filesno + 1 < files_index)
2732 pos += 2; /* For the comma and space */
2734 if (old_pos != 0 && pos >= line_length)
2736 putchar ('\n');
2737 pos -= old_pos;
2740 print_file_name_and_frills (files + filesno);
2741 if (filesno + 1 < files_index)
2743 putchar (',');
2744 putchar (' ');
2747 putchar ('\n');
2750 /* Assuming cursor is at position FROM, indent up to position TO.
2751 Use a TAB character instead of two or more spaces whenever possible. */
2753 static void
2754 indent (int from, int to)
2756 while (from < to)
2758 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
2760 putchar ('\t');
2761 from += tabsize - from % tabsize;
2763 else
2765 putchar (' ');
2766 from++;
2771 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2772 /* FIXME: maybe remove this function someday. See about using a
2773 non-malloc'ing version of path_concat. */
2775 static void
2776 attach (char *dest, const char *dirname, const char *name)
2778 const char *dirnamep = dirname;
2780 /* Copy dirname if it is not ".". */
2781 if (dirname[0] != '.' || dirname[1] != 0)
2783 while (*dirnamep)
2784 *dest++ = *dirnamep++;
2785 /* Add '/' if `dirname' doesn't already end with it. */
2786 if (dirnamep > dirname && dirnamep[-1] != '/')
2787 *dest++ = '/';
2789 while (*name)
2790 *dest++ = *name++;
2791 *dest = 0;
2794 static void
2795 init_column_info (void)
2797 int i;
2798 int allocate = 0;
2800 max_idx = line_length / MIN_COLUMN_WIDTH;
2801 if (max_idx == 0)
2802 max_idx = 1;
2804 if (column_info == NULL)
2806 column_info = (struct column_info *) xmalloc (max_idx
2807 * sizeof (struct column_info));
2808 allocate = 1;
2811 for (i = 0; i < max_idx; ++i)
2813 int j;
2815 column_info[i].valid_len = 1;
2816 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
2818 if (allocate)
2819 column_info[i].col_arr = (int *) xmalloc ((i + 1) * sizeof (int));
2821 for (j = 0; j <= i; ++j)
2822 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
2826 void
2827 usage (int status)
2829 if (status != 0)
2830 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2831 program_name);
2832 else
2834 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2835 printf (_("\
2836 List information about the FILEs (the current directory by default).\n\
2837 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2839 -a, --all do not hide entries starting with .\n\
2840 -A, --almost-all do not list implied . and ..\n\
2841 -b, --escape print octal escapes for nongraphic characters\n\
2842 --block-size=SIZE use SIZE-byte blocks\n\
2843 -B, --ignore-backups do not list implied entries ending with ~\n\
2844 -c sort by change time; with -l: show ctime\n\
2845 -C list entries by columns\n\
2846 --color[=WHEN] control whether color is used to distinguish file\n\
2847 types. WHEN may be `never', `always', or `auto'\n\
2848 -d, --directory list directory entries instead of contents\n\
2849 -D, --dired generate output designed for Emacs' dired mode\n\
2850 -f do not sort, enable -aU, disable -lst\n\
2851 -F, --classify append indicator (one of */=@|) to entries\n\
2852 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2853 single-column -1, verbose -l, vertical -C\n\
2854 --full-time list both full date and full time\n"));
2856 printf (_("\
2857 -g (ignored)\n\
2858 -G, --no-group inhibit display of group information\n\
2859 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2860 -H, --si likewise, but use powers of 1000 not 1024\n\
2861 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2862 none (default), classify (-F), file-type (-p)\n\
2863 -i, --inode print index number of each file\n\
2864 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2865 -k, --kilobytes like --block-size=1024\n\
2866 -l use a long listing format\n\
2867 -L, --dereference list entries pointed to by symbolic links\n\
2868 -m fill width with a comma separated list of entries\n\
2869 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2870 -N, --literal print raw entry names (don't treat e.g. control\n\
2871 characters specially)\n\
2872 -o use long listing format without group info\n\
2873 -p, --file-type append indicator (one of /=@|) to entries\n\
2874 -q, --hide-control-chars print ? instead of non graphic characters\n\
2875 --show-control-chars show non graphic characters as-is (default)\n\
2876 -Q, --quote-name enclose entry names in double quotes\n\
2877 --quoting-style=WORD use quoting style WORD for entry names:\n\
2878 literal, shell, shell-always, c, escape\n\
2879 -r, --reverse reverse order while sorting\n\
2880 -R, --recursive list subdirectories recursively\n\
2881 -s, --size print size of each file, in blocks\n"));
2883 printf (_("\
2884 -S sort by file size\n\
2885 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2886 version -v\n\
2887 status -c, time -t, atime -u, access -u, use -u\n\
2888 --time=WORD show time as WORD instead of modification time:\n\
2889 atime, access, use, ctime or status; use\n\
2890 specified time as sort key if --sort=time\n\
2891 -t sort by modification time\n\
2892 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2893 -u sort by last access time; with -l: show atime\n\
2894 -U do not sort; list entries in directory order\n\
2895 -v sort by version\n\
2896 -w, --width=COLS assume screen width instead of current value\n\
2897 -x list entries by lines instead of by columns\n\
2898 -X sort alphabetically by entry extension\n\
2899 -1 list one file per line\n\
2900 --help display this help and exit\n\
2901 --version output version information and exit\n\
2903 By default, color is not used to distinguish types of files. That is\n\
2904 equivalent to using --color=none. Using the --color option without the\n\
2905 optional WHEN argument is equivalent to using --color=always. With\n\
2906 --color=auto, color codes are output only if standard output is connected\n\
2907 to a terminal (tty).\n\
2908 "));
2909 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
2910 close_stdout ();
2912 exit (status);