*** empty log message ***
[coreutils.git] / src / ls.c
blob1e7c3bfb9134c635b931317af7183cc673d71511
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 #if HAVE_SYS_ACL_H
64 # include <sys/acl.h>
65 #endif
67 #include <stdio.h>
68 #include <assert.h>
69 #include <grp.h>
70 #include <pwd.h>
71 #include <getopt.h>
73 #include "system.h"
74 #include <fnmatch.h>
76 #include "argmatch.h"
77 #include "error.h"
78 #include "human.h"
79 #include "filemode.h"
80 #include "ls.h"
81 #include "obstack.h"
82 #include "path-concat.h"
83 #include "quotearg.h"
84 #include "strverscmp.h"
85 #include "xstrtol.h"
87 /* Use access control lists only under all the following conditions.
88 Some systems (OSF4, Irix5, Irix6) have the acl function, but not
89 sys/acl.h or don't define the GETACLCNT macro. */
90 #if HAVE_SYS_ACL_H && HAVE_ACL && defined GETACLCNT
91 # define USE_ACL 1
92 #endif
94 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
95 : (ls_mode == LS_MULTI_COL \
96 ? "dir" : "vdir"))
98 #define AUTHORS "Richard Stallman and David MacKenzie"
100 #define obstack_chunk_alloc malloc
101 #define obstack_chunk_free free
103 /* Return an int indicating the result of comparing two integers.
104 Subtracting doesn't always work, due to overflow. */
105 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
107 /* The field width for inode numbers. On some hosts inode numbers are
108 64 bits, so columns won't line up exactly when a huge inode number
109 is encountered, but in practice 7 digits is usually enough. */
110 #ifndef INODE_DIGITS
111 # define INODE_DIGITS 7
112 #endif
114 #ifdef S_ISLNK
115 # define HAVE_SYMLINKS 1
116 #else
117 # define HAVE_SYMLINKS 0
118 #endif
120 /* If any of the S_* macros are undefined, define them here so each
121 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
122 #ifndef S_ISLNK
123 # define S_ISLNK(Mode) 0
124 #endif
126 #ifndef S_ISFIFO
127 # define S_ISFIFO(Mode) 0
128 #endif
130 #ifndef S_ISSOCK
131 # define S_ISSOCK(Mode) 0
132 #endif
134 #ifndef S_ISCHR
135 # define S_ISCHR(Mode) 0
136 #endif
138 #ifndef S_ISBLK
139 # define S_ISBLK(Mode) 0
140 #endif
142 #ifndef S_ISDOOR
143 # define S_ISDOOR(Mode) 0
144 #endif
146 enum filetype
148 symbolic_link,
149 directory,
150 arg_directory, /* Directory given as command line arg. */
151 normal /* All others. */
154 struct fileinfo
156 /* The file name. */
157 char *name;
159 struct stat stat;
161 /* For symbolic link, name of the file linked to, otherwise zero. */
162 char *linkname;
164 /* For symbolic link and long listing, st_mode of file linked to, otherwise
165 zero. */
166 unsigned int linkmode;
168 /* For symbolic link and color printing, 1 if linked-to file
169 exists, otherwise 0. */
170 int linkok;
172 enum filetype filetype;
174 #if USE_ACL
175 /* For long listings, nonzero if the file has an access control list,
176 otherwise zero. */
177 int have_acl;
178 #endif
181 #if USE_ACL
182 # define FILE_HAS_ACL(F) ((F)->have_acl)
183 #else
184 # define FILE_HAS_ACL(F) 0
185 #endif
187 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
189 /* Null is a valid character in a color indicator (think about Epson
190 printers, for example) so we have to use a length/buffer string
191 type. */
193 struct bin_str
195 int len; /* Number of bytes */
196 char *string; /* Pointer to the same */
199 #ifndef STDC_HEADERS
200 time_t time ();
201 #endif
203 char *getgroup ();
204 char *getuser ();
205 void strip_trailing_slashes ();
206 char *xstrdup ();
208 static size_t quote_name PARAMS ((FILE *out, const char *name,
209 struct quoting_options const *options));
210 static char *make_link_path PARAMS ((const char *path, const char *linkname));
211 static int compare_atime PARAMS ((const struct fileinfo *file1,
212 const struct fileinfo *file2));
213 static int rev_cmp_atime PARAMS ((const struct fileinfo *file2,
214 const struct fileinfo *file1));
215 static int compare_ctime PARAMS ((const struct fileinfo *file1,
216 const struct fileinfo *file2));
217 static int rev_cmp_ctime PARAMS ((const struct fileinfo *file2,
218 const struct fileinfo *file1));
219 static int compare_mtime PARAMS ((const struct fileinfo *file1,
220 const struct fileinfo *file2));
221 static int rev_cmp_mtime PARAMS ((const struct fileinfo *file2,
222 const struct fileinfo *file1));
223 static int compare_size PARAMS ((const struct fileinfo *file1,
224 const struct fileinfo *file2));
225 static int rev_cmp_size PARAMS ((const struct fileinfo *file2,
226 const struct fileinfo *file1));
227 static int compare_name PARAMS ((const struct fileinfo *file1,
228 const struct fileinfo *file2));
229 static int rev_cmp_name PARAMS ((const struct fileinfo *file2,
230 const struct fileinfo *file1));
231 static int compare_extension PARAMS ((const struct fileinfo *file1,
232 const struct fileinfo *file2));
233 static int rev_cmp_extension PARAMS ((const struct fileinfo *file2,
234 const struct fileinfo *file1));
235 static int compare_version PARAMS ((const struct fileinfo *file1,
236 const struct fileinfo *file2));
237 static int rev_cmp_version PARAMS ((const struct fileinfo *file2,
238 const struct fileinfo *file1));
239 static int decode_switches PARAMS ((int argc, char **argv));
240 static int file_interesting PARAMS ((const struct dirent *next));
241 static uintmax_t gobble_file PARAMS ((const char *name, int explicit_arg,
242 const char *dirname));
243 static void print_color_indicator PARAMS ((const char *name, unsigned int mode,
244 int linkok));
245 static void put_indicator PARAMS ((const struct bin_str *ind));
246 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
247 static void add_ignore_pattern PARAMS ((const char *pattern));
248 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
249 static void clear_files PARAMS ((void));
250 static void extract_dirs_from_files PARAMS ((const char *dirname,
251 int recursive));
252 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
253 static void indent PARAMS ((int from, int to));
254 static void init_column_info PARAMS ((void));
255 static void print_current_files PARAMS ((void));
256 static void print_dir PARAMS ((const char *name, const char *realname));
257 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
258 static void print_horizontal PARAMS ((void));
259 static void print_long_format PARAMS ((const struct fileinfo *f));
260 static void print_many_per_line PARAMS ((void));
261 static void print_name_with_quoting PARAMS ((const char *p, unsigned int mode,
262 int linkok,
263 struct obstack *stack));
264 static void prep_non_filename_text PARAMS ((void));
265 static void print_type_indicator PARAMS ((unsigned int mode));
266 static void print_with_commas PARAMS ((void));
267 static void queue_directory PARAMS ((const char *name, const char *realname));
268 static void sort_files PARAMS ((void));
269 static void parse_ls_color PARAMS ((void));
270 void usage PARAMS ((int status));
272 /* The name the program was run with, stripped of any leading path. */
273 char *program_name;
275 /* The table of files in the current directory:
277 `files' points to a vector of `struct fileinfo', one per file.
278 `nfiles' is the number of elements space has been allocated for.
279 `files_index' is the number actually in use. */
281 /* Address of block containing the files that are described. */
283 static struct fileinfo *files;
285 /* Length of block that `files' points to, measured in files. */
287 static int nfiles;
289 /* Index of first unused in `files'. */
291 static int files_index;
293 /* Record of one pending directory waiting to be listed. */
295 struct pending
297 char *name;
298 /* If the directory is actually the file pointed to by a symbolic link we
299 were told to list, `realname' will contain the name of the symbolic
300 link, otherwise zero. */
301 char *realname;
302 struct pending *next;
305 static struct pending *pending_dirs;
307 /* Current time (seconds since 1970). When we are printing a file's time,
308 include the year if it is more than 6 months before this time. */
310 static time_t current_time;
312 /* The number of digits to use for block sizes.
313 4, or more if needed for bigger numbers. */
315 static int block_size_size;
317 /* Option flags */
319 /* long_format for lots of info, one per line.
320 one_per_line for just names, one per line.
321 many_per_line for just names, many per line, sorted vertically.
322 horizontal for just names, many per line, sorted horizontally.
323 with_commas for just names, many per line, separated by commas.
325 -l, -1, -C, -x and -m control this parameter. */
327 enum format
329 long_format, /* -l */
330 one_per_line, /* -1 */
331 many_per_line, /* -C */
332 horizontal, /* -x */
333 with_commas /* -m */
336 static enum format format;
338 /* Type of time to print or sort by. Controlled by -c and -u. */
340 enum time_type
342 time_mtime, /* default */
343 time_ctime, /* -c */
344 time_atime /* -u */
347 static enum time_type time_type;
349 /* print the full time, otherwise the standard unix heuristics. */
351 static int full_time;
353 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
355 enum sort_type
357 sort_none, /* -U */
358 sort_name, /* default */
359 sort_extension, /* -X */
360 sort_time, /* -t */
361 sort_size, /* -S */
362 sort_version /* -v */
365 static enum sort_type sort_type;
367 /* Direction of sort.
368 0 means highest first if numeric,
369 lowest first if alphabetic;
370 these are the defaults.
371 1 means the opposite order in each case. -r */
373 static int sort_reverse;
375 /* Nonzero means to NOT display group information. -G */
377 static int inhibit_group;
379 /* Nonzero means print the user and group id's as numbers rather
380 than as names. -n */
382 static int numeric_ids;
384 /* Nonzero means mention the size in blocks of each file. -s */
386 static int print_block_size;
388 /* If positive, the units to use when printing sizes;
389 if negative, the human-readable base. */
390 static int output_block_size;
392 /* Precede each line of long output (per file) with a string like `m,n:'
393 where M is the number of characters after the `:' and before the
394 filename and N is the length of the filename. Using this format,
395 Emacs' dired mode starts up twice as fast, and can handle all
396 strange characters in file names. */
397 static int dired;
399 /* `none' means don't mention the type of files.
400 `classify' means mention file types and mark executables.
401 `file_type' means mention only file types.
403 Controlled by -F, -p, and --indicator-style. */
405 enum indicator_style
407 none, /* --indicator-style=none */
408 classify, /* -F, --indicator-style=classify */
409 file_type /* -p, --indicator-style=file-type */
412 static enum indicator_style indicator_style;
414 /* Names of indicator styles. */
415 static char const *const indicator_style_args[] =
417 "none", "classify", "file-type", 0
420 static enum indicator_style const indicator_style_types[]=
422 none, classify, file_type
425 /* Nonzero means use colors to mark types. Also define the different
426 colors as well as the stuff for the LS_COLORS environment variable.
427 The LS_COLORS variable is now in a termcap-like format. */
429 static int print_with_color;
431 enum color_type
433 color_never, /* 0: default or --color=never */
434 color_always, /* 1: --color=always */
435 color_if_tty /* 2: --color=tty */
438 enum indicator_no
440 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
441 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
444 static const char *const indicator_name[]=
446 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
447 "bd", "cd", "mi", "or", "ex", "do", NULL
450 struct color_ext_type
452 struct bin_str ext; /* The extension we're looking for */
453 struct bin_str seq; /* The sequence to output when we do */
454 struct color_ext_type *next; /* Next in list */
457 static struct bin_str color_indicator[] =
459 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
460 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
461 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
462 { LEN_STR_PAIR ("0") }, /* no: Normal */
463 { LEN_STR_PAIR ("0") }, /* fi: File: default */
464 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
465 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
466 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
467 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
468 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
469 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
470 { 0, NULL }, /* mi: Missing file: undefined */
471 { 0, NULL }, /* or: Orphanned symlink: undefined */
472 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
473 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
476 /* FIXME: comment */
477 static struct color_ext_type *color_ext_list = NULL;
479 /* Buffer for color sequences */
480 static char *color_buf;
482 /* Nonzero means mention the inode number of each file. -i */
484 static int print_inode;
486 /* Nonzero means when a symbolic link is found, display info on
487 the file linked to. -L */
489 static int trace_links;
491 /* Nonzero means when a directory is found, display info on its
492 contents. -R */
494 static int trace_dirs;
496 /* Nonzero means when an argument is a directory name, display info
497 on it itself. -d */
499 static int immediate_dirs;
501 /* Nonzero means don't omit files whose names start with `.'. -A */
503 static int all_files;
505 /* Nonzero means don't omit files `.' and `..'
506 This flag implies `all_files'. -a */
508 static int really_all_files;
510 /* A linked list of shell-style globbing patterns. If a non-argument
511 file name matches any of these patterns, it is omitted.
512 Controlled by -I. Multiple -I options accumulate.
513 The -B option adds `*~' and `.*~' to this list. */
515 struct ignore_pattern
517 const char *pattern;
518 struct ignore_pattern *next;
521 static struct ignore_pattern *ignore_patterns;
523 /* Nonzero means output nongraphic chars in file names as `?'.
524 (-q, --hide-control-chars)
525 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
526 independent. The algorithm is: first, obey the quoting style to get a
527 string representing the file name; then, if qmark_funny_chars is set,
528 replace all nonprintable chars in that string with `?'. It's necessary
529 to replace nonprintable chars even in quoted strings, because we don't
530 want to mess up the terminal if control chars get sent to it, and some
531 quoting methods pass through control chars as-is. */
532 static int qmark_funny_chars;
534 /* Quoting options for file and dir name output. */
536 static struct quoting_options *filename_quoting_options;
537 static struct quoting_options *dirname_quoting_options;
539 /* The number of chars per hardware tab stop. Setting this to zero
540 inhibits the use of TAB characters for separating columns. -T */
541 static int tabsize;
543 /* Nonzero means we are listing the working directory because no
544 non-option arguments were given. */
546 static int dir_defaulted;
548 /* Nonzero means print each directory name before listing it. */
550 static int print_dir_name;
552 /* The line length to use for breaking lines in many-per-line format.
553 Can be set with -w. */
555 static int line_length;
557 /* If nonzero, the file listing format requires that stat be called on
558 each file. */
560 static int format_needs_stat;
562 /* The exit status to use if we don't get any fatal errors. */
564 static int exit_status;
566 static struct option const long_options[] =
568 {"all", no_argument, 0, 'a'},
569 {"escape", no_argument, 0, 'b'},
570 {"directory", no_argument, 0, 'd'},
571 {"dired", no_argument, 0, 'D'},
572 {"full-time", no_argument, &full_time, 1},
573 {"human-readable", no_argument, 0, 'h'},
574 {"inode", no_argument, 0, 'i'},
575 {"kilobytes", no_argument, 0, 'k'},
576 {"numeric-uid-gid", no_argument, 0, 'n'},
577 {"no-group", no_argument, 0, 'G'},
578 {"hide-control-chars", no_argument, 0, 'q'},
579 {"reverse", no_argument, 0, 'r'},
580 {"size", no_argument, 0, 's'},
581 {"width", required_argument, 0, 'w'},
582 {"almost-all", no_argument, 0, 'A'},
583 {"ignore-backups", no_argument, 0, 'B'},
584 {"classify", no_argument, 0, 'F'},
585 {"file-type", no_argument, 0, 'F'},
586 {"si", no_argument, 0, 'H'},
587 {"ignore", required_argument, 0, 'I'},
588 {"indicator-style", required_argument, 0, 14},
589 {"dereference", no_argument, 0, 'L'},
590 {"literal", no_argument, 0, 'N'},
591 {"quote-name", no_argument, 0, 'Q'},
592 {"quoting-style", required_argument, 0, 15},
593 {"recursive", no_argument, 0, 'R'},
594 {"format", required_argument, 0, 12},
595 {"show-control-chars", no_argument, 0, 16},
596 {"sort", required_argument, 0, 10},
597 {"tabsize", required_argument, 0, 'T'},
598 {"time", required_argument, 0, 11},
599 {"color", optional_argument, 0, 13},
600 {"block-size", required_argument, 0, 17},
601 {GETOPT_HELP_OPTION_DECL},
602 {GETOPT_VERSION_OPTION_DECL},
603 {NULL, 0, NULL, 0}
606 static char const *const format_args[] =
608 "verbose", "long", "commas", "horizontal", "across",
609 "vertical", "single-column", 0
612 static enum format const format_types[] =
614 long_format, long_format, with_commas, horizontal, horizontal,
615 many_per_line, one_per_line
618 static char const *const sort_args[] =
620 "none", "time", "size", "extension", "version", 0
623 static enum sort_type const sort_types[] =
625 sort_none, sort_time, sort_size, sort_extension, sort_version
628 static char const *const time_args[] =
630 "atime", "access", "use", "ctime", "status", 0
633 static enum time_type const time_types[] =
635 time_atime, time_atime, time_atime, time_ctime, time_ctime
638 static char const *const color_args[] =
640 /* force and none are for compatibility with another color-ls version */
641 "always", "yes", "force",
642 "never", "no", "none",
643 "auto", "tty", "if-tty", 0
646 static enum color_type const color_types[] =
648 color_always, color_always, color_always,
649 color_never, color_never, color_never,
650 color_if_tty, color_if_tty, color_if_tty
653 /* Information about filling a column. */
654 struct column_info
656 int valid_len;
657 int line_len;
658 int *col_arr;
661 /* Array with information about column filledness. */
662 static struct column_info *column_info;
664 /* Maximum number of columns ever possible for this display. */
665 static int max_idx;
667 /* The minimum width of a colum is 3: 1 character for the name and 2
668 for the separating white space. */
669 #define MIN_COLUMN_WIDTH 3
672 /* This zero-based index is used solely with the --dired option.
673 When that option is in effect, this counter is incremented for each
674 character of output generated by this program so that the beginning
675 and ending indices (in that output) of every file name can be recorded
676 and later output themselves. */
677 static size_t dired_pos;
679 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
681 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
682 #define DIRED_FPUTS(s, stream, s_len) \
683 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
685 /* Like DIRED_FPUTS, but for use when S is a literal string. */
686 #define DIRED_FPUTS_LITERAL(s, stream) \
687 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
689 #define DIRED_INDENT() \
690 do \
692 /* FIXME: remove the `&& format == long_format' clause. */ \
693 if (dired && format == long_format) \
694 DIRED_FPUTS_LITERAL (" ", stdout); \
696 while (0)
698 /* With --dired, store pairs of beginning and ending indices of filenames. */
699 static struct obstack dired_obstack;
701 /* With --dired, store pairs of beginning and ending indices of any
702 directory names that appear as headers (just before `total' line)
703 for lists of directory entries. Such directory names are seen when
704 listing hierarchies using -R and when a directory is listed with at
705 least one other command line argument. */
706 static struct obstack subdired_obstack;
708 /* Save the current index on the specified obstack, OBS. */
709 #define PUSH_CURRENT_DIRED_POS(obs) \
710 do \
712 /* FIXME: remove the `&& format == long_format' clause. */ \
713 if (dired && format == long_format) \
714 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
716 while (0)
719 /* Write to standard output PREFIX, followed by the quoting style and
720 a space-separated list of the integers stored in OS all on one line. */
722 static void
723 dired_dump_obstack (const char *prefix, struct obstack *os)
725 int n_pos;
727 n_pos = obstack_object_size (os) / sizeof (dired_pos);
728 if (n_pos > 0)
730 int i;
731 size_t *pos;
733 pos = (size_t *) obstack_finish (os);
734 fputs (prefix, stdout);
735 for (i = 0; i < n_pos; i++)
736 printf (" %d", (int) pos[i]);
737 fputs ("\n", stdout);
742 main (int argc, char **argv)
744 register int i;
745 register struct pending *thispend;
747 program_name = argv[0];
748 setlocale (LC_ALL, "");
749 bindtextdomain (PACKAGE, LOCALEDIR);
750 textdomain (PACKAGE);
752 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
753 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
755 exit_status = 0;
756 dir_defaulted = 1;
757 print_dir_name = 1;
758 pending_dirs = 0;
759 current_time = time ((time_t *) 0);
761 i = decode_switches (argc, argv);
763 if (print_with_color)
765 parse_ls_color ();
766 prep_non_filename_text ();
769 format_needs_stat = sort_type == sort_time || sort_type == sort_size
770 || format == long_format
771 || trace_links || trace_dirs || indicator_style != none
772 || print_block_size || print_inode || print_with_color;
774 if (dired && format == long_format)
776 obstack_init (&dired_obstack);
777 obstack_init (&subdired_obstack);
780 nfiles = 100;
781 files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
782 files_index = 0;
784 clear_files ();
786 if (i < argc)
787 dir_defaulted = 0;
788 for (; i < argc; i++)
790 strip_trailing_slashes (argv[i]);
791 gobble_file (argv[i], 1, "");
794 if (dir_defaulted)
796 if (immediate_dirs)
797 gobble_file (".", 1, "");
798 else
799 queue_directory (".", 0);
802 if (files_index)
804 sort_files ();
805 if (!immediate_dirs)
806 extract_dirs_from_files ("", 0);
807 /* `files_index' might be zero now. */
809 if (files_index)
811 print_current_files ();
812 if (pending_dirs)
813 DIRED_PUTCHAR ('\n');
815 else if (pending_dirs && pending_dirs->next == 0)
816 print_dir_name = 0;
818 while (pending_dirs)
820 thispend = pending_dirs;
821 pending_dirs = pending_dirs->next;
822 print_dir (thispend->name, thispend->realname);
823 free (thispend->name);
824 if (thispend->realname)
825 free (thispend->realname);
826 free (thispend);
827 print_dir_name = 1;
830 if (dired && format == long_format)
832 /* No need to free these since we're about to exit. */
833 dired_dump_obstack ("//DIRED//", &dired_obstack);
834 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
835 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
836 ARGMATCH_TO_ARGUMENT (filename_quoting_options,
837 quoting_style_args, quoting_style_vals));
840 /* Restore default color before exiting */
841 if (print_with_color)
843 put_indicator (&color_indicator[C_LEFT]);
844 put_indicator (&color_indicator[C_RIGHT]);
847 close_stdout ();
848 exit (exit_status);
851 /* Set all the option flags according to the switches specified.
852 Return the index of the first non-option argument. */
854 static int
855 decode_switches (int argc, char **argv)
857 register char const *p;
858 int c;
859 int i;
860 long int tmp_long;
862 qmark_funny_chars = 0;
864 /* initialize all switches to default settings */
866 switch (ls_mode)
868 case LS_MULTI_COL:
869 /* This is for the `dir' program. */
870 format = many_per_line;
871 set_quoting_style (NULL, escape_quoting_style);
872 break;
874 case LS_LONG_FORMAT:
875 /* This is for the `vdir' program. */
876 format = long_format;
877 set_quoting_style (NULL, escape_quoting_style);
878 break;
880 case LS_LS:
881 /* This is for the `ls' program. */
882 if (isatty (STDOUT_FILENO))
884 format = many_per_line;
885 /* See description of qmark_funny_chars, above. */
886 qmark_funny_chars = 1;
888 else
890 format = one_per_line;
891 qmark_funny_chars = 0;
893 break;
895 default:
896 abort ();
899 time_type = time_mtime;
900 full_time = 0;
901 sort_type = sort_name;
902 sort_reverse = 0;
903 numeric_ids = 0;
904 print_block_size = 0;
905 indicator_style = none;
906 print_inode = 0;
907 trace_links = 0;
908 trace_dirs = 0;
909 immediate_dirs = 0;
910 all_files = 0;
911 really_all_files = 0;
912 ignore_patterns = 0;
914 /* FIXME: Shouldn't we complain on wrong values? */
915 if ((p = getenv ("QUOTING_STYLE"))
916 && 0 <= (i = ARGCASEMATCH (p, quoting_style_args, quoting_style_vals)))
917 set_quoting_style (NULL, quoting_style_vals[i]);
919 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
921 line_length = 80;
922 if ((p = getenv ("COLUMNS")) && *p)
924 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
925 && 0 < tmp_long && tmp_long <= INT_MAX)
927 line_length = (int) tmp_long;
929 else
931 error (0, 0,
932 _("ignoring invalid width in environment variable COLUMNS: %s"),
933 quotearg (p));
937 #ifdef TIOCGWINSZ
939 struct winsize ws;
941 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
942 line_length = ws.ws_col;
944 #endif
946 /* Using the TABSIZE environment variable is not POSIX-approved.
947 Ignore it when POSIXLY_CORRECT is set. */
948 tabsize = 8;
949 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
951 if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
952 && 0 <= tmp_long && tmp_long <= INT_MAX)
954 tabsize = (int) tmp_long;
956 else
958 error (0, 0,
959 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
960 quotearg (p));
964 while ((c = getopt_long (argc, argv,
965 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
966 long_options, NULL)) != -1)
968 switch (c)
970 case 0:
971 break;
973 case 'a':
974 all_files = 1;
975 really_all_files = 1;
976 break;
978 case 'b':
979 set_quoting_style (NULL, escape_quoting_style);
980 break;
982 case 'c':
983 time_type = time_ctime;
984 sort_type = sort_time;
985 break;
987 case 'd':
988 immediate_dirs = 1;
989 break;
991 case 'f':
992 /* Same as enabling -a -U and disabling -l -s. */
993 all_files = 1;
994 really_all_files = 1;
995 sort_type = sort_none;
996 /* disable -l */
997 if (format == long_format)
998 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
999 print_block_size = 0; /* disable -s */
1000 print_with_color = 0; /* disable --color */
1001 break;
1003 case 'g':
1004 /* No effect. For BSD compatibility. */
1005 break;
1007 case 'h':
1008 output_block_size = -1024;
1009 break;
1011 case 'H':
1012 output_block_size = -1000;
1013 break;
1015 case 'i':
1016 print_inode = 1;
1017 break;
1019 case 'k':
1020 output_block_size = 1024;
1021 break;
1023 case 'l':
1024 format = long_format;
1025 break;
1027 case 'm':
1028 format = with_commas;
1029 break;
1031 case 'n':
1032 numeric_ids = 1;
1033 break;
1035 case 'o': /* Just like -l, but don't display group info. */
1036 format = long_format;
1037 inhibit_group = 1;
1038 break;
1040 case 'p':
1041 indicator_style = file_type;
1042 break;
1044 case 'q':
1045 qmark_funny_chars = 1;
1046 break;
1048 case 'r':
1049 sort_reverse = 1;
1050 break;
1052 case 's':
1053 print_block_size = 1;
1054 break;
1056 case 't':
1057 sort_type = sort_time;
1058 break;
1060 case 'u':
1061 sort_type = sort_time;
1062 time_type = time_atime;
1063 break;
1065 case 'v':
1066 sort_type = sort_version;
1067 break;
1069 case 'w':
1070 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1071 || tmp_long <= 0 || tmp_long > INT_MAX)
1072 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1073 quotearg (optarg));
1074 line_length = (int) tmp_long;
1075 break;
1077 case 'x':
1078 format = horizontal;
1079 break;
1081 case 'A':
1082 really_all_files = 0;
1083 all_files = 1;
1084 break;
1086 case 'B':
1087 add_ignore_pattern ("*~");
1088 add_ignore_pattern (".*~");
1089 break;
1091 case 'C':
1092 format = many_per_line;
1093 break;
1095 case 'D':
1096 dired = 1;
1097 break;
1099 case 'F':
1100 indicator_style = classify;
1101 break;
1103 case 'G': /* inhibit display of group info */
1104 inhibit_group = 1;
1105 break;
1107 case 'I':
1108 add_ignore_pattern (optarg);
1109 break;
1111 case 'L':
1112 trace_links = 1;
1113 break;
1115 case 'N':
1116 set_quoting_style (NULL, literal_quoting_style);
1117 break;
1119 case 'Q':
1120 set_quoting_style (NULL, c_quoting_style);
1121 break;
1123 case 'R':
1124 trace_dirs = 1;
1125 break;
1127 case 'S':
1128 sort_type = sort_size;
1129 break;
1131 case 'T':
1132 if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1133 || tmp_long < 0 || tmp_long > INT_MAX)
1134 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1135 quotearg (optarg));
1136 tabsize = (int) tmp_long;
1137 break;
1139 case 'U':
1140 sort_type = sort_none;
1141 break;
1143 case 'X':
1144 sort_type = sort_extension;
1145 break;
1147 case '1':
1148 format = one_per_line;
1149 break;
1151 case 10: /* --sort */
1152 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1153 break;
1155 case 11: /* --time */
1156 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1157 break;
1159 case 12: /* --format */
1160 format = XARGMATCH ("--format", optarg, format_args, format_types);
1161 break;
1163 case 13: /* --color */
1164 if (optarg)
1165 i = XARGMATCH ("--color", optarg, color_args, color_types);
1166 else
1167 /* Using --color with no argument is equivalent to using
1168 --color=always. */
1169 i = color_always;
1171 print_with_color = (i == color_always
1172 || (i == color_if_tty
1173 && isatty (STDOUT_FILENO)));
1175 if (print_with_color)
1177 /* Don't use TAB characters in output. Some terminal
1178 emulators can't handle the combination of tabs and
1179 color codes on the same line. */
1180 tabsize = 0;
1182 break;
1184 case 14: /* --indicator-style */
1185 indicator_style = XARGMATCH ("--indicator-style", optarg,
1186 indicator_style_args,
1187 indicator_style_types);
1188 break;
1190 case 15: /* --quoting-style */
1191 set_quoting_style (NULL,
1192 XARGMATCH ("--quoting-style", optarg,
1193 quoting_style_args,
1194 quoting_style_vals));
1195 break;
1197 case 16:
1198 qmark_funny_chars = 0;
1199 break;
1201 case 17:
1202 human_block_size (optarg, 1, &output_block_size);
1203 break;
1205 case_GETOPT_HELP_CHAR;
1207 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1209 default:
1210 usage (EXIT_FAILURE);
1214 filename_quoting_options = clone_quoting_options (NULL);
1215 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1216 set_char_quoting (filename_quoting_options, ' ', 1);
1217 if (indicator_style != none)
1218 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1219 set_char_quoting (filename_quoting_options, *p, 1);
1221 dirname_quoting_options = clone_quoting_options (NULL);
1222 set_char_quoting (dirname_quoting_options, ':', 1);
1224 return optind;
1227 /* Parse a string as part of the LS_COLORS variable; this may involve
1228 decoding all kinds of escape characters. If equals_end is set an
1229 unescaped equal sign ends the string, otherwise only a : or \0
1230 does. Returns the number of characters output, or -1 on failure.
1232 The resulting string is *not* null-terminated, but may contain
1233 embedded nulls.
1235 Note that both dest and src are char **; on return they point to
1236 the first free byte after the array and the character that ended
1237 the input string, respectively. */
1239 static int
1240 get_funky_string (char **dest, const char **src, int equals_end)
1242 int num; /* For numerical codes */
1243 int count; /* Something to count with */
1244 enum {
1245 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1246 } state;
1247 const char *p;
1248 char *q;
1250 p = *src; /* We don't want to double-indirect */
1251 q = *dest; /* the whole darn time. */
1253 count = 0; /* No characters counted in yet. */
1254 num = 0;
1256 state = ST_GND; /* Start in ground state. */
1257 while (state < ST_END)
1259 switch (state)
1261 case ST_GND: /* Ground state (no escapes) */
1262 switch (*p)
1264 case ':':
1265 case '\0':
1266 state = ST_END; /* End of string */
1267 break;
1268 case '\\':
1269 state = ST_BACKSLASH; /* Backslash scape sequence */
1270 ++p;
1271 break;
1272 case '^':
1273 state = ST_CARET; /* Caret escape */
1274 ++p;
1275 break;
1276 case '=':
1277 if (equals_end)
1279 state = ST_END; /* End */
1280 break;
1282 /* else fall through */
1283 default:
1284 *(q++) = *(p++);
1285 ++count;
1286 break;
1288 break;
1290 case ST_BACKSLASH: /* Backslash escaped character */
1291 switch (*p)
1293 case '0':
1294 case '1':
1295 case '2':
1296 case '3':
1297 case '4':
1298 case '5':
1299 case '6':
1300 case '7':
1301 state = ST_OCTAL; /* Octal sequence */
1302 num = *p - '0';
1303 break;
1304 case 'x':
1305 case 'X':
1306 state = ST_HEX; /* Hex sequence */
1307 num = 0;
1308 break;
1309 case 'a': /* Bell */
1310 num = 7; /* Not all C compilers know what \a means */
1311 break;
1312 case 'b': /* Backspace */
1313 num = '\b';
1314 break;
1315 case 'e': /* Escape */
1316 num = 27;
1317 break;
1318 case 'f': /* Form feed */
1319 num = '\f';
1320 break;
1321 case 'n': /* Newline */
1322 num = '\n';
1323 break;
1324 case 'r': /* Carriage return */
1325 num = '\r';
1326 break;
1327 case 't': /* Tab */
1328 num = '\t';
1329 break;
1330 case 'v': /* Vtab */
1331 num = '\v';
1332 break;
1333 case '?': /* Delete */
1334 num = 127;
1335 break;
1336 case '_': /* Space */
1337 num = ' ';
1338 break;
1339 case '\0': /* End of string */
1340 state = ST_ERROR; /* Error! */
1341 break;
1342 default: /* Escaped character like \ ^ : = */
1343 num = *p;
1344 break;
1346 if (state == ST_BACKSLASH)
1348 *(q++) = num;
1349 ++count;
1350 state = ST_GND;
1352 ++p;
1353 break;
1355 case ST_OCTAL: /* Octal sequence */
1356 if (*p < '0' || *p > '7')
1358 *(q++) = num;
1359 ++count;
1360 state = ST_GND;
1362 else
1363 num = (num << 3) + (*(p++) - '0');
1364 break;
1366 case ST_HEX: /* Hex sequence */
1367 switch (*p)
1369 case '0':
1370 case '1':
1371 case '2':
1372 case '3':
1373 case '4':
1374 case '5':
1375 case '6':
1376 case '7':
1377 case '8':
1378 case '9':
1379 num = (num << 4) + (*(p++) - '0');
1380 break;
1381 case 'a':
1382 case 'b':
1383 case 'c':
1384 case 'd':
1385 case 'e':
1386 case 'f':
1387 num = (num << 4) + (*(p++) - 'a') + 10;
1388 break;
1389 case 'A':
1390 case 'B':
1391 case 'C':
1392 case 'D':
1393 case 'E':
1394 case 'F':
1395 num = (num << 4) + (*(p++) - 'A') + 10;
1396 break;
1397 default:
1398 *(q++) = num;
1399 ++count;
1400 state = ST_GND;
1401 break;
1403 break;
1405 case ST_CARET: /* Caret escape */
1406 state = ST_GND; /* Should be the next state... */
1407 if (*p >= '@' && *p <= '~')
1409 *(q++) = *(p++) & 037;
1410 ++count;
1412 else if (*p == '?')
1414 *(q++) = 127;
1415 ++count;
1417 else
1418 state = ST_ERROR;
1419 break;
1421 default:
1422 abort ();
1426 *dest = q;
1427 *src = p;
1429 return state == ST_ERROR ? -1 : count;
1432 static void
1433 parse_ls_color (void)
1435 const char *p; /* Pointer to character being parsed */
1436 char *buf; /* color_buf buffer pointer */
1437 int state; /* State of parser */
1438 int ind_no; /* Indicator number */
1439 char label[3]; /* Indicator label */
1440 struct color_ext_type *ext; /* Extension we are working on */
1442 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1443 return;
1445 ext = NULL;
1446 strcpy (label, "??");
1448 /* This is an overly conservative estimate, but any possible
1449 LS_COLORS string will *not* generate a color_buf longer than
1450 itself, so it is a safe way of allocating a buffer in
1451 advance. */
1452 buf = color_buf = xstrdup (p);
1454 state = 1;
1455 while (state > 0)
1457 switch (state)
1459 case 1: /* First label character */
1460 switch (*p)
1462 case ':':
1463 ++p;
1464 break;
1466 case '*':
1467 /* Allocate new extension block and add to head of
1468 linked list (this way a later definition will
1469 override an earlier one, which can be useful for
1470 having terminal-specific defs override global). */
1472 ext = (struct color_ext_type *)
1473 xmalloc (sizeof (struct color_ext_type));
1474 ext->next = color_ext_list;
1475 color_ext_list = ext;
1477 ++p;
1478 ext->ext.string = buf;
1480 state = (ext->ext.len =
1481 get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1482 break;
1484 case '\0':
1485 state = 0; /* Done! */
1486 break;
1488 default: /* Assume it is file type label */
1489 label[0] = *(p++);
1490 state = 2;
1491 break;
1493 break;
1495 case 2: /* Second label character */
1496 if (*p)
1498 label[1] = *(p++);
1499 state = 3;
1501 else
1502 state = -1; /* Error */
1503 break;
1505 case 3: /* Equal sign after indicator label */
1506 state = -1; /* Assume failure... */
1507 if (*(p++) == '=')/* It *should* be... */
1509 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1511 if (STREQ (label, indicator_name[ind_no]))
1513 color_indicator[ind_no].string = buf;
1514 state = ((color_indicator[ind_no].len =
1515 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1516 break;
1519 if (state == -1)
1520 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1522 break;
1524 case 4: /* Equal sign after *.ext */
1525 if (*(p++) == '=')
1527 ext->seq.string = buf;
1528 state = (ext->seq.len =
1529 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1531 else
1532 state = -1;
1533 break;
1537 if (state < 0)
1539 struct color_ext_type *e;
1540 struct color_ext_type *e2;
1542 error (0, 0,
1543 _("unparsable value for LS_COLORS environment variable"));
1544 free (color_buf);
1545 for (e = color_ext_list; e != NULL; /* empty */)
1547 e2 = e;
1548 e = e->next;
1549 free (e2);
1551 print_with_color = 0;
1555 /* Request that the directory named `name' have its contents listed later.
1556 If `realname' is nonzero, it will be used instead of `name' when the
1557 directory name is printed. This allows symbolic links to directories
1558 to be treated as regular directories but still be listed under their
1559 real names. */
1561 static void
1562 queue_directory (const char *name, const char *realname)
1564 struct pending *new;
1566 new = (struct pending *) xmalloc (sizeof (struct pending));
1567 new->next = pending_dirs;
1568 pending_dirs = new;
1569 new->name = xstrdup (name);
1570 if (realname)
1571 new->realname = xstrdup (realname);
1572 else
1573 new->realname = 0;
1576 /* Read directory `name', and list the files in it.
1577 If `realname' is nonzero, print its name instead of `name';
1578 this is used for symbolic links to directories. */
1580 static void
1581 print_dir (const char *name, const char *realname)
1583 register DIR *reading;
1584 register struct dirent *next;
1585 register uintmax_t total_blocks = 0;
1587 errno = 0;
1588 reading = opendir (name);
1589 if (!reading)
1591 error (0, errno, "%s", quotearg_colon (name));
1592 exit_status = 1;
1593 return;
1596 /* Read the directory entries, and insert the subfiles into the `files'
1597 table. */
1599 clear_files ();
1601 while ((next = readdir (reading)) != NULL)
1602 if (file_interesting (next))
1603 total_blocks += gobble_file (next->d_name, 0, name);
1605 if (CLOSEDIR (reading))
1607 error (0, errno, "%s", quotearg_colon (name));
1608 exit_status = 1;
1609 /* Don't return; print whatever we got. */
1612 /* Sort the directory contents. */
1613 sort_files ();
1615 /* If any member files are subdirectories, perhaps they should have their
1616 contents listed rather than being mentioned here as files. */
1618 if (trace_dirs)
1619 extract_dirs_from_files (name, 1);
1621 if (trace_dirs || print_dir_name)
1623 DIRED_INDENT ();
1624 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1625 dired_pos += quote_name (stdout, realname ? realname : name,
1626 dirname_quoting_options);
1627 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
1628 DIRED_FPUTS_LITERAL (":\n", stdout);
1631 if (format == long_format || print_block_size)
1633 const char *p;
1634 char buf[LONGEST_HUMAN_READABLE + 1];
1636 DIRED_INDENT ();
1637 p = _("total");
1638 DIRED_FPUTS (p, stdout, strlen (p));
1639 DIRED_PUTCHAR (' ');
1640 p = human_readable (total_blocks, buf, ST_NBLOCKSIZE, output_block_size);
1641 DIRED_FPUTS (p, stdout, strlen (p));
1642 DIRED_PUTCHAR ('\n');
1645 if (files_index)
1646 print_current_files ();
1648 if (pending_dirs)
1649 DIRED_PUTCHAR ('\n');
1652 /* Add `pattern' to the list of patterns for which files that match are
1653 not listed. */
1655 static void
1656 add_ignore_pattern (const char *pattern)
1658 register struct ignore_pattern *ignore;
1660 ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
1661 ignore->pattern = pattern;
1662 /* Add it to the head of the linked list. */
1663 ignore->next = ignore_patterns;
1664 ignore_patterns = ignore;
1667 /* Return nonzero if the file in `next' should be listed. */
1669 static int
1670 file_interesting (const struct dirent *next)
1672 register struct ignore_pattern *ignore;
1674 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
1675 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
1676 return 0;
1678 if (really_all_files
1679 || next->d_name[0] != '.'
1680 || (all_files
1681 && next->d_name[1] != '\0'
1682 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
1683 return 1;
1685 return 0;
1688 /* Enter and remove entries in the table `files'. */
1690 /* Empty the table of files. */
1692 static void
1693 clear_files (void)
1695 register int i;
1697 for (i = 0; i < files_index; i++)
1699 free (files[i].name);
1700 if (files[i].linkname)
1701 free (files[i].linkname);
1704 files_index = 0;
1705 block_size_size = 4;
1708 /* Add a file to the current table of files.
1709 Verify that the file exists, and print an error message if it does not.
1710 Return the number of blocks that the file occupies. */
1712 static uintmax_t
1713 gobble_file (const char *name, int explicit_arg, const char *dirname)
1715 register uintmax_t blocks;
1716 register int val;
1717 register char *path;
1719 if (files_index == nfiles)
1721 nfiles *= 2;
1722 files = (struct fileinfo *) xrealloc ((char *) files,
1723 sizeof (*files) * nfiles);
1726 files[files_index].linkname = 0;
1727 files[files_index].linkmode = 0;
1728 files[files_index].linkok = 0;
1730 if (explicit_arg || format_needs_stat)
1732 /* `path' is the absolute pathname of this file. */
1734 if (name[0] == '/' || dirname[0] == 0)
1735 path = (char *) name;
1736 else
1738 path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
1739 attach (path, dirname, name);
1742 if (trace_links)
1744 val = stat (path, &files[files_index].stat);
1745 if (val < 0)
1747 /* Perhaps a symbolically-linked to file doesn't exist; stat
1748 the link instead. */
1749 val = lstat (path, &files[files_index].stat);
1752 else
1754 val = lstat (path, &files[files_index].stat);
1755 #if USE_ACL
1756 files[files_index].have_acl = (acl (path, GETACLCNT, 0, NULL) > 4);
1757 #endif
1760 if (val < 0)
1762 error (0, errno, "%s", quotearg_colon (path));
1763 exit_status = 1;
1764 return 0;
1767 if (S_ISLNK (files[files_index].stat.st_mode)
1768 && (explicit_arg || format == long_format || print_with_color))
1770 char *linkpath;
1771 struct stat linkstats;
1773 get_link_name (path, &files[files_index]);
1774 linkpath = make_link_path (path, files[files_index].linkname);
1776 /* Avoid following symbolic links when possible, ie, when
1777 they won't be traced and when no indicator is needed. */
1778 if (linkpath
1779 && ((explicit_arg && format != long_format)
1780 || indicator_style != none
1781 || print_with_color)
1782 && stat (linkpath, &linkstats) == 0)
1784 files[files_index].linkok = 1;
1786 /* Symbolic links to directories that are mentioned on the
1787 command line are automatically traced if not being
1788 listed as files. */
1789 if (explicit_arg && format != long_format
1790 && S_ISDIR (linkstats.st_mode))
1792 /* Substitute the linked-to directory's name, but
1793 save the real name in `linkname' for printing. */
1794 if (!immediate_dirs)
1796 const char *tempname = name;
1797 name = linkpath;
1798 linkpath = files[files_index].linkname;
1799 files[files_index].linkname = (char *) tempname;
1801 files[files_index].stat = linkstats;
1803 else
1805 /* Get the linked-to file's mode for the filetype indicator
1806 in long listings. */
1807 files[files_index].linkmode = linkstats.st_mode;
1808 files[files_index].linkok = 1;
1811 if (linkpath)
1812 free (linkpath);
1815 if (S_ISLNK (files[files_index].stat.st_mode))
1816 files[files_index].filetype = symbolic_link;
1817 else if (S_ISDIR (files[files_index].stat.st_mode))
1819 if (explicit_arg && !immediate_dirs)
1820 files[files_index].filetype = arg_directory;
1821 else
1822 files[files_index].filetype = directory;
1824 else
1825 files[files_index].filetype = normal;
1827 blocks = ST_NBLOCKS (files[files_index].stat);
1829 char buf[LONGEST_HUMAN_READABLE + 1];
1830 int len = strlen (human_readable (blocks, buf, ST_NBLOCKSIZE,
1831 output_block_size));
1832 if (block_size_size < len)
1833 block_size_size = len < 7 ? len : 7;
1836 else
1837 blocks = 0;
1839 files[files_index].name = xstrdup (name);
1840 files_index++;
1842 return blocks;
1845 #if HAVE_SYMLINKS
1847 /* Put the name of the file that `filename' is a symbolic link to
1848 into the `linkname' field of `f'. */
1850 static void
1851 get_link_name (const char *filename, struct fileinfo *f)
1853 char *linkbuf;
1854 register int linksize;
1856 linkbuf = (char *) alloca (PATH_MAX + 2);
1857 /* Some automounters give incorrect st_size for mount points.
1858 I can't think of a good workaround for it, though. */
1859 linksize = readlink (filename, linkbuf, PATH_MAX + 1);
1860 if (linksize < 0)
1862 error (0, errno, "%s", quotearg_colon (filename));
1863 exit_status = 1;
1865 else
1867 linkbuf[linksize] = '\0';
1868 f->linkname = xstrdup (linkbuf);
1872 /* If `linkname' is a relative path and `path' contains one or more
1873 leading directories, return `linkname' with those directories
1874 prepended; otherwise, return a copy of `linkname'.
1875 If `linkname' is zero, return zero. */
1877 static char *
1878 make_link_path (const char *path, const char *linkname)
1880 char *linkbuf;
1881 int bufsiz;
1883 if (linkname == 0)
1884 return 0;
1886 if (*linkname == '/')
1887 return xstrdup (linkname);
1889 /* The link is to a relative path. Prepend any leading path
1890 in `path' to the link name. */
1891 linkbuf = strrchr (path, '/');
1892 if (linkbuf == 0)
1893 return xstrdup (linkname);
1895 bufsiz = linkbuf - path + 1;
1896 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
1897 strncpy (linkbuf, path, bufsiz);
1898 strcpy (linkbuf + bufsiz, linkname);
1899 return linkbuf;
1901 #endif
1903 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1904 This is so we don't try to recurse on `././././. ...' */
1906 static int
1907 basename_is_dot_or_dotdot (const char *name)
1909 char *base = base_name (name);
1910 return DOT_OR_DOTDOT (base);
1913 /* Remove any entries from `files' that are for directories,
1914 and queue them to be listed as directories instead.
1915 `dirname' is the prefix to prepend to each dirname
1916 to make it correct relative to ls's working dir.
1917 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1918 This is desirable when processing directories recursively. */
1920 static void
1921 extract_dirs_from_files (const char *dirname, int recursive)
1923 register int i, j;
1924 int dirlen;
1926 dirlen = strlen (dirname) + 2;
1927 /* Queue the directories last one first, because queueing reverses the
1928 order. */
1929 for (i = files_index - 1; i >= 0; i--)
1930 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
1931 && (!recursive || !basename_is_dot_or_dotdot (files[i].name)))
1933 if (files[i].name[0] == '/' || dirname[0] == 0)
1935 queue_directory (files[i].name, files[i].linkname);
1937 else
1939 char *path = path_concat (dirname, files[i].name, NULL);
1940 queue_directory (path, files[i].linkname);
1941 free (path);
1943 if (files[i].filetype == arg_directory)
1944 free (files[i].name);
1947 /* Now delete the directories from the table, compacting all the remaining
1948 entries. */
1950 for (i = 0, j = 0; i < files_index; i++)
1951 if (files[i].filetype != arg_directory)
1952 files[j++] = files[i];
1953 files_index = j;
1956 /* Sort the files now in the table. */
1958 static void
1959 sort_files (void)
1961 int (*func) ();
1963 switch (sort_type)
1965 case sort_none:
1966 return;
1967 case sort_time:
1968 switch (time_type)
1970 case time_ctime:
1971 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
1972 break;
1973 case time_mtime:
1974 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
1975 break;
1976 case time_atime:
1977 func = sort_reverse ? rev_cmp_atime : compare_atime;
1978 break;
1979 default:
1980 abort ();
1982 break;
1983 case sort_name:
1984 func = sort_reverse ? rev_cmp_name : compare_name;
1985 break;
1986 case sort_extension:
1987 func = sort_reverse ? rev_cmp_extension : compare_extension;
1988 break;
1989 case sort_size:
1990 func = sort_reverse ? rev_cmp_size : compare_size;
1991 break;
1992 case sort_version:
1993 func = sort_reverse ? rev_cmp_version : compare_version;
1994 break;
1995 default:
1996 abort ();
1999 qsort (files, files_index, sizeof (struct fileinfo), func);
2002 /* Comparison routines for sorting the files. */
2004 static int
2005 compare_ctime (const struct fileinfo *file1, const struct fileinfo *file2)
2007 int diff = CTIME_CMP (file2->stat, file1->stat);
2008 if (diff == 0)
2009 diff = strcmp (file1->name, file2->name);
2010 return diff;
2013 static int
2014 rev_cmp_ctime (const struct fileinfo *file2, const struct fileinfo *file1)
2016 int diff = CTIME_CMP (file2->stat, file1->stat);
2017 if (diff == 0)
2018 diff = strcmp (file1->name, file2->name);
2019 return diff;
2022 static int
2023 compare_mtime (const struct fileinfo *file1, const struct fileinfo *file2)
2025 int diff = MTIME_CMP (file2->stat, file1->stat);
2026 if (diff == 0)
2027 diff = strcmp (file1->name, file2->name);
2028 return diff;
2031 static int
2032 rev_cmp_mtime (const struct fileinfo *file2, const struct fileinfo *file1)
2034 int diff = MTIME_CMP (file2->stat, file1->stat);
2035 if (diff == 0)
2036 diff = strcmp (file1->name, file2->name);
2037 return diff;
2040 static int
2041 compare_atime (const struct fileinfo *file1, const struct fileinfo *file2)
2043 int diff = ATIME_CMP (file2->stat, file1->stat);
2044 if (diff == 0)
2045 diff = strcmp (file1->name, file2->name);
2046 return diff;
2049 static int
2050 rev_cmp_atime (const struct fileinfo *file2, const struct fileinfo *file1)
2052 int diff = ATIME_CMP (file2->stat, file1->stat);
2053 if (diff == 0)
2054 diff = strcmp (file1->name, file2->name);
2055 return diff;
2058 static int
2059 compare_size (const struct fileinfo *file1, const struct fileinfo *file2)
2061 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2062 if (diff == 0)
2063 diff = strcmp (file1->name, file2->name);
2064 return diff;
2067 static int
2068 rev_cmp_size (const struct fileinfo *file2, const struct fileinfo *file1)
2070 int diff = longdiff (file2->stat.st_size, file1->stat.st_size);
2071 if (diff == 0)
2072 diff = strcmp (file1->name, file2->name);
2073 return diff;
2076 static int
2077 compare_version (const struct fileinfo *file1, const struct fileinfo *file2)
2079 return strverscmp (file1->name, file2->name);
2082 static int
2083 rev_cmp_version (const struct fileinfo *file2, const struct fileinfo *file1)
2085 return strverscmp (file1->name, file2->name);
2088 static int
2089 compare_name (const struct fileinfo *file1, const struct fileinfo *file2)
2091 return strcmp (file1->name, file2->name);
2094 static int
2095 rev_cmp_name (const struct fileinfo *file2, const struct fileinfo *file1)
2097 return strcmp (file1->name, file2->name);
2100 /* Compare file extensions. Files with no extension are `smallest'.
2101 If extensions are the same, compare by filenames instead. */
2103 static int
2104 compare_extension (const struct fileinfo *file1, const struct fileinfo *file2)
2106 register char *base1, *base2;
2107 register int cmp;
2109 base1 = strrchr (file1->name, '.');
2110 base2 = strrchr (file2->name, '.');
2111 if (base1 == 0 && base2 == 0)
2112 return strcmp (file1->name, file2->name);
2113 if (base1 == 0)
2114 return -1;
2115 if (base2 == 0)
2116 return 1;
2117 cmp = strcmp (base1, base2);
2118 if (cmp == 0)
2119 return strcmp (file1->name, file2->name);
2120 return cmp;
2123 static int
2124 rev_cmp_extension (const struct fileinfo *file2, const struct fileinfo *file1)
2126 register char *base1, *base2;
2127 register int cmp;
2129 base1 = strrchr (file1->name, '.');
2130 base2 = strrchr (file2->name, '.');
2131 if (base1 == 0 && base2 == 0)
2132 return strcmp (file1->name, file2->name);
2133 if (base1 == 0)
2134 return -1;
2135 if (base2 == 0)
2136 return 1;
2137 cmp = strcmp (base1, base2);
2138 if (cmp == 0)
2139 return strcmp (file1->name, file2->name);
2140 return cmp;
2143 /* List all the files now in the table. */
2145 static void
2146 print_current_files (void)
2148 register int i;
2150 switch (format)
2152 case one_per_line:
2153 for (i = 0; i < files_index; i++)
2155 print_file_name_and_frills (files + i);
2156 putchar ('\n');
2158 break;
2160 case many_per_line:
2161 init_column_info ();
2162 print_many_per_line ();
2163 break;
2165 case horizontal:
2166 init_column_info ();
2167 print_horizontal ();
2168 break;
2170 case with_commas:
2171 print_with_commas ();
2172 break;
2174 case long_format:
2175 for (i = 0; i < files_index; i++)
2177 print_long_format (files + i);
2178 DIRED_PUTCHAR ('\n');
2180 break;
2184 static void
2185 print_long_format (const struct fileinfo *f)
2187 char modebuf[12];
2189 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2190 1 10-byte mode string,
2191 1 24-byte time string (may be longer in some locales -- see below)
2192 or LONGEST_HUMAN_READABLE integer,
2193 9 spaces, one following each of these fields, and
2194 1 trailing NUL byte. */
2195 char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2196 + (LONGEST_HUMAN_READABLE < 24 ? 24 : LONGEST_HUMAN_READABLE)
2197 + 9 + 1];
2198 char *buf = init_bigbuf;
2199 size_t bufsize = sizeof (init_bigbuf);
2200 size_t s;
2201 char *p;
2202 time_t when;
2203 struct tm *when_local;
2204 const char *fmt;
2205 char *user_name;
2207 #if HAVE_ST_DM_MODE
2208 /* Cray DMF: look at the file's migrated, not real, status */
2209 mode_string (f->stat.st_dm_mode, modebuf);
2210 #else
2211 mode_string (f->stat.st_mode, modebuf);
2212 #endif
2214 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2215 modebuf[11] = '\0';
2217 switch (time_type)
2219 case time_ctime:
2220 when = f->stat.st_ctime;
2221 break;
2222 case time_mtime:
2223 when = f->stat.st_mtime;
2224 break;
2225 case time_atime:
2226 when = f->stat.st_atime;
2227 break;
2230 if (full_time)
2232 fmt = "%a %b %d %H:%M:%S %Y";
2234 else
2236 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
2237 || current_time < when - 60L * 60L) /* In the future. */
2239 /* The file is fairly old or in the future.
2240 POSIX says the cutoff is 6 months old;
2241 approximate this by 6*30 days.
2242 Allow a 1 hour slop factor for what is considered "the future",
2243 to allow for NFS server/client clock disagreement.
2244 Show the year instead of the time of day. */
2245 fmt = "%b %e %Y";
2247 else
2249 fmt = "%b %e %H:%M";
2253 p = buf;
2255 if (print_inode)
2257 char hbuf[LONGEST_HUMAN_READABLE + 1];
2258 sprintf (p, "%*s ", INODE_DIGITS,
2259 human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2260 p += strlen (p);
2263 if (print_block_size)
2265 char hbuf[LONGEST_HUMAN_READABLE + 1];
2266 sprintf (p, "%*s ", block_size_size,
2267 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2268 ST_NBLOCKSIZE, output_block_size));
2269 p += strlen (p);
2272 /* The last byte of the mode string is the POSIX
2273 "optional alternate access method flag". */
2274 sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
2275 p += strlen (p);
2277 user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2278 if (user_name)
2279 sprintf (p, "%-8.8s ", user_name);
2280 else
2281 sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
2282 p += strlen (p);
2284 if (!inhibit_group)
2286 char *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2287 if (group_name)
2288 sprintf (p, "%-8.8s ", group_name);
2289 else
2290 sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
2291 p += strlen (p);
2294 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2295 sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
2296 (unsigned) minor (f->stat.st_rdev));
2297 else
2299 char hbuf[LONGEST_HUMAN_READABLE + 1];
2300 sprintf (p, "%8s ",
2301 human_readable ((uintmax_t) f->stat.st_size, hbuf, 1,
2302 output_block_size < 0 ? output_block_size : 1));
2305 p += strlen (p);
2307 /* Use strftime rather than ctime, because the former can produce
2308 locale-dependent names for the weekday (%a) and month (%b). */
2310 if ((when_local = localtime (&when)))
2312 while (! (s = strftime (p, buf + bufsize - p - 1, fmt, when_local)))
2314 char *newbuf = (char *) alloca (bufsize *= 2);
2315 memcpy (newbuf, buf, p - buf);
2316 p = newbuf + (p - buf);
2317 buf = newbuf;
2320 p += s;
2321 *p++ = ' ';
2323 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2324 *p = '\0';
2326 else
2328 /* The time cannot be represented as a local time;
2329 print it as a huge integer number of seconds. */
2330 char hbuf[LONGEST_HUMAN_READABLE + 1];
2331 int width = full_time ? 24 : 12;
2333 if (when < 0)
2335 const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2336 int sign_width = width - strlen (num);
2337 sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2339 else
2340 sprintf (p, "%*s ", width,
2341 human_readable ((uintmax_t) when, hbuf, 1, 1));
2343 p += strlen (p);
2346 DIRED_INDENT ();
2347 DIRED_FPUTS (buf, stdout, p - buf);
2348 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok,
2349 &dired_obstack);
2351 if (f->filetype == symbolic_link)
2353 if (f->linkname)
2355 DIRED_FPUTS_LITERAL (" -> ", stdout);
2356 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2357 NULL);
2358 if (indicator_style != none)
2359 print_type_indicator (f->linkmode);
2362 else if (indicator_style != none)
2363 print_type_indicator (f->stat.st_mode);
2366 /* Output to OUT a quoted representation of the file name P,
2367 using OPTIONS to control quoting.
2368 Return the number of characters in P's quoted representation. */
2370 static size_t
2371 quote_name (FILE *out, const char *p, struct quoting_options const *options)
2373 char smallbuf[BUFSIZ];
2374 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, p, -1, options);
2375 char *buf;
2377 if (len < sizeof smallbuf)
2378 buf = smallbuf;
2379 else
2381 buf = (char *) alloca (len + 1);
2382 quotearg_buffer (buf, len + 1, p, -1, options);
2385 if (qmark_funny_chars)
2387 size_t i;
2388 for (i = 0; i < len; i++)
2389 if (! ISPRINT ((unsigned char) buf[i]))
2390 buf[i] = '?';
2393 fwrite (buf, 1, len, out);
2394 return len;
2397 static void
2398 print_name_with_quoting (const char *p, unsigned int mode, int linkok,
2399 struct obstack *stack)
2401 if (print_with_color)
2402 print_color_indicator (p, mode, linkok);
2404 if (stack)
2405 PUSH_CURRENT_DIRED_POS (stack);
2407 dired_pos += quote_name (stdout, p, filename_quoting_options);
2409 if (stack)
2410 PUSH_CURRENT_DIRED_POS (stack);
2412 if (print_with_color)
2413 prep_non_filename_text ();
2416 static void
2417 prep_non_filename_text (void)
2419 if (color_indicator[C_END].string != NULL)
2420 put_indicator (&color_indicator[C_END]);
2421 else
2423 put_indicator (&color_indicator[C_LEFT]);
2424 put_indicator (&color_indicator[C_NORM]);
2425 put_indicator (&color_indicator[C_RIGHT]);
2429 /* Print the file name of `f' with appropriate quoting.
2430 Also print file size, inode number, and filetype indicator character,
2431 as requested by switches. */
2433 static void
2434 print_file_name_and_frills (const struct fileinfo *f)
2436 char buf[LONGEST_HUMAN_READABLE + 1];
2438 if (print_inode)
2439 printf ("%*s ", INODE_DIGITS,
2440 human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
2442 if (print_block_size)
2443 printf ("%*s ", block_size_size,
2444 human_readable ((uintmax_t) ST_NBLOCKS (f->stat), buf,
2445 ST_NBLOCKSIZE, output_block_size));
2447 print_name_with_quoting (f->name, f->stat.st_mode, f->linkok, NULL);
2449 if (indicator_style != none)
2450 print_type_indicator (f->stat.st_mode);
2453 static void
2454 print_type_indicator (unsigned int mode)
2456 int c;
2458 if (S_ISREG (mode))
2460 if (indicator_style == classify && (mode & S_IXUGO))
2461 c ='*';
2462 else
2463 c = 0;
2465 else
2467 if (S_ISDIR (mode))
2468 c = '/';
2469 else if (S_ISLNK (mode))
2470 c = '@';
2471 else if (S_ISFIFO (mode))
2472 c = '|';
2473 else if (S_ISSOCK (mode))
2474 c = '=';
2475 else if (S_ISDOOR (mode))
2476 c = '>';
2477 else
2478 c = 0;
2481 if (c)
2482 DIRED_PUTCHAR (c);
2485 static void
2486 print_color_indicator (const char *name, unsigned int mode, int linkok)
2488 int type = C_FILE;
2489 struct color_ext_type *ext; /* Color extension */
2490 size_t len; /* Length of name */
2492 /* Is this a nonexistent file? If so, linkok == -1. */
2494 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
2496 ext = NULL;
2497 type = C_MISSING;
2499 else
2501 if (S_ISDIR (mode))
2502 type = C_DIR;
2503 else if (S_ISLNK (mode))
2504 type = ((!linkok && color_indicator[C_ORPHAN].string)
2505 ? C_ORPHAN : C_LINK);
2506 else if (S_ISFIFO (mode))
2507 type = C_FIFO;
2508 else if (S_ISSOCK (mode))
2509 type = C_SOCK;
2510 else if (S_ISBLK (mode))
2511 type = C_BLK;
2512 else if (S_ISCHR (mode))
2513 type = C_CHR;
2514 else if (S_ISDOOR (mode))
2515 type = C_DOOR;
2517 if (type == C_FILE && (mode & S_IXUGO) != 0)
2518 type = C_EXEC;
2520 /* Check the file's suffix only if still classified as C_FILE. */
2521 ext = NULL;
2522 if (type == C_FILE)
2524 /* Test if NAME has a recognized suffix. */
2526 len = strlen (name);
2527 name += len; /* Pointer to final \0. */
2528 for (ext = color_ext_list; ext != NULL; ext = ext->next)
2530 if ((size_t) ext->ext.len <= len
2531 && strncmp (name - ext->ext.len, ext->ext.string,
2532 ext->ext.len) == 0)
2533 break;
2538 put_indicator (&color_indicator[C_LEFT]);
2539 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
2540 put_indicator (&color_indicator[C_RIGHT]);
2543 /* Output a color indicator (which may contain nulls). */
2544 static void
2545 put_indicator (const struct bin_str *ind)
2547 register int i;
2548 register char *p;
2550 p = ind->string;
2552 for (i = ind->len; i > 0; --i)
2553 putchar (*(p++));
2556 static int
2557 length_of_file_name_and_frills (const struct fileinfo *f)
2559 register int len = 0;
2561 if (print_inode)
2562 len += INODE_DIGITS + 1;
2564 if (print_block_size)
2565 len += 1 + block_size_size;
2567 len += quotearg_buffer (0, 0, f->name, -1, filename_quoting_options);
2569 if (indicator_style != none)
2571 unsigned filetype = f->stat.st_mode;
2573 if (S_ISREG (filetype))
2575 if (indicator_style == classify
2576 && (f->stat.st_mode & S_IXUGO))
2577 len += 1;
2579 else if (S_ISDIR (filetype)
2580 || S_ISLNK (filetype)
2581 || S_ISFIFO (filetype)
2582 || S_ISSOCK (filetype)
2583 || S_ISDOOR (filetype)
2585 len += 1;
2588 return len;
2591 static void
2592 print_many_per_line (void)
2594 struct column_info *line_fmt;
2595 int filesno; /* Index into files. */
2596 int row; /* Current row. */
2597 int max_name_length; /* Length of longest file name + frills. */
2598 int name_length; /* Length of each file name + frills. */
2599 int pos; /* Current character column. */
2600 int cols; /* Number of files across. */
2601 int rows; /* Maximum number of files down. */
2602 int max_cols;
2604 /* Normally the maximum number of columns is determined by the
2605 screen width. But if few files are available this might limit it
2606 as well. */
2607 max_cols = max_idx > files_index ? files_index : max_idx;
2609 /* Compute the maximum number of possible columns. */
2610 for (filesno = 0; filesno < files_index; ++filesno)
2612 int i;
2614 name_length = length_of_file_name_and_frills (files + filesno);
2616 for (i = 0; i < max_cols; ++i)
2618 if (column_info[i].valid_len)
2620 int idx = filesno / ((files_index + i) / (i + 1));
2621 int real_length = name_length + (idx == i ? 0 : 2);
2623 if (real_length > column_info[i].col_arr[idx])
2625 column_info[i].line_len += (real_length
2626 - column_info[i].col_arr[idx]);
2627 column_info[i].col_arr[idx] = real_length;
2628 column_info[i].valid_len = column_info[i].line_len < line_length;
2634 /* Find maximum allowed columns. */
2635 for (cols = max_cols; cols > 1; --cols)
2637 if (column_info[cols - 1].valid_len)
2638 break;
2641 line_fmt = &column_info[cols - 1];
2643 /* Calculate the number of rows that will be in each column except possibly
2644 for a short column on the right. */
2645 rows = files_index / cols + (files_index % cols != 0);
2647 for (row = 0; row < rows; row++)
2649 int col = 0;
2650 filesno = row;
2651 pos = 0;
2652 /* Print the next row. */
2653 while (1)
2655 print_file_name_and_frills (files + filesno);
2656 name_length = length_of_file_name_and_frills (files + filesno);
2657 max_name_length = line_fmt->col_arr[col++];
2659 filesno += rows;
2660 if (filesno >= files_index)
2661 break;
2663 indent (pos + name_length, pos + max_name_length);
2664 pos += max_name_length;
2666 putchar ('\n');
2670 static void
2671 print_horizontal (void)
2673 struct column_info *line_fmt;
2674 int filesno;
2675 int max_name_length;
2676 int name_length;
2677 int cols;
2678 int pos;
2679 int max_cols;
2681 /* Normally the maximum number of columns is determined by the
2682 screen width. But if few files are available this might limit it
2683 as well. */
2684 max_cols = max_idx > files_index ? files_index : max_idx;
2686 /* Compute the maximum file name length. */
2687 max_name_length = 0;
2688 for (filesno = 0; filesno < files_index; ++filesno)
2690 int i;
2692 name_length = length_of_file_name_and_frills (files + filesno);
2694 for (i = 0; i < max_cols; ++i)
2696 if (column_info[i].valid_len)
2698 int idx = filesno % (i + 1);
2699 int real_length = name_length + (idx == i ? 0 : 2);
2701 if (real_length > column_info[i].col_arr[idx])
2703 column_info[i].line_len += (real_length
2704 - column_info[i].col_arr[idx]);
2705 column_info[i].col_arr[idx] = real_length;
2706 column_info[i].valid_len = column_info[i].line_len < line_length;
2712 /* Find maximum allowed columns. */
2713 for (cols = max_cols; cols > 1; --cols)
2715 if (column_info[cols - 1].valid_len)
2716 break;
2719 line_fmt = &column_info[cols - 1];
2721 pos = 0;
2723 /* Print first entry. */
2724 print_file_name_and_frills (files);
2725 name_length = length_of_file_name_and_frills (files);
2726 max_name_length = line_fmt->col_arr[0];
2728 /* Now the rest. */
2729 for (filesno = 1; filesno < files_index; ++filesno)
2731 int col = filesno % cols;
2733 if (col == 0)
2735 putchar ('\n');
2736 pos = 0;
2738 else
2740 indent (pos + name_length, pos + max_name_length);
2741 pos += max_name_length;
2744 print_file_name_and_frills (files + filesno);
2746 name_length = length_of_file_name_and_frills (files + filesno);
2747 max_name_length = line_fmt->col_arr[col];
2749 putchar ('\n');
2752 static void
2753 print_with_commas (void)
2755 int filesno;
2756 int pos, old_pos;
2758 pos = 0;
2760 for (filesno = 0; filesno < files_index; filesno++)
2762 old_pos = pos;
2764 pos += length_of_file_name_and_frills (files + filesno);
2765 if (filesno + 1 < files_index)
2766 pos += 2; /* For the comma and space */
2768 if (old_pos != 0 && pos >= line_length)
2770 putchar ('\n');
2771 pos -= old_pos;
2774 print_file_name_and_frills (files + filesno);
2775 if (filesno + 1 < files_index)
2777 putchar (',');
2778 putchar (' ');
2781 putchar ('\n');
2784 /* Assuming cursor is at position FROM, indent up to position TO.
2785 Use a TAB character instead of two or more spaces whenever possible. */
2787 static void
2788 indent (int from, int to)
2790 while (from < to)
2792 if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
2794 putchar ('\t');
2795 from += tabsize - from % tabsize;
2797 else
2799 putchar (' ');
2800 from++;
2805 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2806 /* FIXME: maybe remove this function someday. See about using a
2807 non-malloc'ing version of path_concat. */
2809 static void
2810 attach (char *dest, const char *dirname, const char *name)
2812 const char *dirnamep = dirname;
2814 /* Copy dirname if it is not ".". */
2815 if (dirname[0] != '.' || dirname[1] != 0)
2817 while (*dirnamep)
2818 *dest++ = *dirnamep++;
2819 /* Add '/' if `dirname' doesn't already end with it. */
2820 if (dirnamep > dirname && dirnamep[-1] != '/')
2821 *dest++ = '/';
2823 while (*name)
2824 *dest++ = *name++;
2825 *dest = 0;
2828 static void
2829 init_column_info (void)
2831 int i;
2832 int allocate = 0;
2834 max_idx = line_length / MIN_COLUMN_WIDTH;
2835 if (max_idx == 0)
2836 max_idx = 1;
2838 if (column_info == NULL)
2840 column_info = (struct column_info *) xmalloc (max_idx
2841 * sizeof (struct column_info));
2842 allocate = 1;
2845 for (i = 0; i < max_idx; ++i)
2847 int j;
2849 column_info[i].valid_len = 1;
2850 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
2852 if (allocate)
2853 column_info[i].col_arr = (int *) xmalloc ((i + 1) * sizeof (int));
2855 for (j = 0; j <= i; ++j)
2856 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
2860 void
2861 usage (int status)
2863 if (status != 0)
2864 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2865 program_name);
2866 else
2868 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
2869 printf (_("\
2870 List information about the FILEs (the current directory by default).\n\
2871 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2873 -a, --all do not hide entries starting with .\n\
2874 -A, --almost-all do not list implied . and ..\n\
2875 -b, --escape print octal escapes for nongraphic characters\n\
2876 --block-size=SIZE use SIZE-byte blocks\n\
2877 -B, --ignore-backups do not list implied entries ending with ~\n\
2878 -c sort by change time; with -l: show ctime\n\
2879 -C list entries by columns\n\
2880 --color[=WHEN] control whether color is used to distinguish file\n\
2881 types. WHEN may be `never', `always', or `auto'\n\
2882 -d, --directory list directory entries instead of contents\n\
2883 -D, --dired generate output designed for Emacs' dired mode\n\
2884 -f do not sort, enable -aU, disable -lst\n\
2885 -F, --classify append indicator (one of */=@|) to entries\n\
2886 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2887 single-column -1, verbose -l, vertical -C\n\
2888 --full-time list both full date and full time\n"));
2890 printf (_("\
2891 -g (ignored)\n\
2892 -G, --no-group inhibit display of group information\n\
2893 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2894 -H, --si likewise, but use powers of 1000 not 1024\n\
2895 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2896 none (default), classify (-F), file-type (-p)\n\
2897 -i, --inode print index number of each file\n\
2898 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2899 -k, --kilobytes like --block-size=1024\n\
2900 -l use a long listing format\n\
2901 -L, --dereference list entries pointed to by symbolic links\n\
2902 -m fill width with a comma separated list of entries\n\
2903 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2904 -N, --literal print raw entry names (don't treat e.g. control\n\
2905 characters specially)\n\
2906 -o use long listing format without group info\n\
2907 -p, --file-type append indicator (one of /=@|) to entries\n\
2908 -q, --hide-control-chars print ? instead of non graphic characters\n\
2909 (This is the default unless the output is a\n\
2910 terminal and the program is `ls'; otherwise,\n\
2911 the default is --show-control-chars)\n\
2912 --show-control-chars show non graphic characters as-is (default)\n\
2913 -Q, --quote-name enclose entry names in double quotes\n\
2914 --quoting-style=WORD use quoting style WORD for entry names:\n\
2915 literal, shell, shell-always, c, escape\n\
2916 -r, --reverse reverse order while sorting\n\
2917 -R, --recursive list subdirectories recursively\n\
2918 -s, --size print size of each file, in blocks\n"));
2920 printf (_("\
2921 -S sort by file size\n\
2922 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2923 version -v\n\
2924 status -c, time -t, atime -u, access -u, use -u\n\
2925 --time=WORD show time as WORD instead of modification time:\n\
2926 atime, access, use, ctime or status; use\n\
2927 specified time as sort key if --sort=time\n\
2928 -t sort by modification time\n\
2929 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2930 -u sort by last access time; with -l: show atime\n\
2931 -U do not sort; list entries in directory order\n\
2932 -v sort by version\n\
2933 -w, --width=COLS assume screen width instead of current value\n\
2934 -x list entries by lines instead of by columns\n\
2935 -X sort alphabetically by entry extension\n\
2936 -1 list one file per line\n\
2937 --help display this help and exit\n\
2938 --version output version information and exit\n\
2940 By default, color is not used to distinguish types of files. That is\n\
2941 equivalent to using --color=none. Using the --color option without the\n\
2942 optional WHEN argument is equivalent to using --color=always. With\n\
2943 --color=auto, color codes are output only if standard output is connected\n\
2944 to a terminal (tty).\n\
2945 "));
2946 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
2947 close_stdout ();
2949 exit (status);