1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 95, 1996 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* If the macro MULTI_COL is defined,
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 the macro LONG_FORMAT is defined,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
28 If neither is defined,
29 the output format depends on whether the output
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
44 #include <sys/types.h>
47 # include <sys/ioctl.h>
56 /* limits.h must come before system.h because limits.h on some systems
57 undefs PATH_MAX, whereas system.h includes pathmax.h which sets
71 #define obstack_chunk_alloc xmalloc
72 #define obstack_chunk_free free
75 # define INT_MAX 2147483647
78 /* Return an int indicating the result of comparing two longs. */
79 #if (INT_MAX <= 65535)
80 # define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
82 # define longdiff(a, b) ((a) - (b))
85 /* The maximum number of digits required to print an inode number
86 in an unsigned format. */
88 # define INODE_DIGITS 7
95 arg_directory
, /* Directory given as command line arg. */
96 normal
/* All others. */
106 /* For symbolic link, name of the file linked to, otherwise zero. */
109 /* For symbolic link and long listing, st_mode of file linked to, otherwise
111 unsigned int linkmode
;
113 /* For symbolic link and color printing, 1 if linked-to file
114 exits, otherwise 0. */
117 enum filetype filetype
;
120 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
122 /* Null is a valid character in a color indicator (think about Epson
123 printers, for example) so we have to use a length/buffer string
128 unsigned int len
; /* Number of bytes */
129 char *string
; /* Pointer to the same */
132 struct bin_str color_indicator
[] =
134 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
135 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
136 { 0, NULL
}, /* ec: End color (replaces lc+no+rc) */
137 { LEN_STR_PAIR ("0") }, /* no: Normal */
138 { LEN_STR_PAIR ("0") }, /* fi: File: default */
139 { LEN_STR_PAIR ("32") }, /* di: Directory: green */
140 { LEN_STR_PAIR ("36") }, /* ln: Symlink: cyan */
141 { LEN_STR_PAIR ("31") }, /* pi: Pipe: red */
142 { LEN_STR_PAIR ("33") }, /* so: Socket: yellow/brown */
143 { LEN_STR_PAIR ("44;37") }, /* bd: Block device: white on blue */
144 { LEN_STR_PAIR ("44;37") }, /* cd: Char device: white on blue */
145 { 0, NULL
}, /* mi: Missing file: undefined */
146 { 0, NULL
}, /* or: Orphanned symlink: undefined */
147 { LEN_STR_PAIR ("35") } /* ex: Executable: purple */
166 static char *make_link_path
__P ((const char *path
, const char *linkname
));
167 static int compare_atime
__P ((const struct fileinfo
*file1
,
168 const struct fileinfo
*file2
));
169 static int rev_cmp_atime
__P ((const struct fileinfo
*file2
,
170 const struct fileinfo
*file1
));
171 static int compare_ctime
__P ((const struct fileinfo
*file1
,
172 const struct fileinfo
*file2
));
173 static int rev_cmp_ctime
__P ((const struct fileinfo
*file2
,
174 const struct fileinfo
*file1
));
175 static int compare_mtime
__P ((const struct fileinfo
*file1
,
176 const struct fileinfo
*file2
));
177 static int rev_cmp_mtime
__P ((const struct fileinfo
*file2
,
178 const struct fileinfo
*file1
));
179 static int compare_size
__P ((const struct fileinfo
*file1
,
180 const struct fileinfo
*file2
));
181 static int rev_cmp_size
__P ((const struct fileinfo
*file2
,
182 const struct fileinfo
*file1
));
183 static int compare_name
__P ((const struct fileinfo
*file1
,
184 const struct fileinfo
*file2
));
185 static int rev_cmp_name
__P ((const struct fileinfo
*file2
,
186 const struct fileinfo
*file1
));
187 static int compare_extension
__P ((const struct fileinfo
*file1
,
188 const struct fileinfo
*file2
));
189 static int rev_cmp_extension
__P ((const struct fileinfo
*file2
,
190 const struct fileinfo
*file1
));
191 static int decode_switches
__P ((int argc
, char **argv
));
192 static int file_interesting
__P ((const struct dirent
*next
));
193 static int gobble_file
__P ((const char *name
, int explicit_arg
,
194 const char *dirname
));
195 static int is_not_dot_or_dotdot
__P ((const char *name
));
196 static void print_color_indicator
__P ((const char *name
, unsigned int mode
,
198 static void put_indicator
__P ((const struct bin_str
*ind
));
199 static int length_of_file_name_and_frills
__P ((const struct fileinfo
*f
));
200 static void add_ignore_pattern
__P ((const char *pattern
));
201 static void attach
__P ((char *dest
, const char *dirname
, const char *name
));
202 static void clear_files
__P ((void));
203 static void extract_dirs_from_files
__P ((const char *dirname
, int recursive
));
204 static void get_link_name
__P ((const char *filename
, struct fileinfo
*f
));
205 static void indent
__P ((int from
, int to
));
206 static void print_current_files
__P ((void));
207 static void print_dir
__P ((const char *name
, const char *realname
));
208 static void print_file_name_and_frills
__P ((const struct fileinfo
*f
));
209 static void print_horizontal
__P ((void));
210 static void print_long_format
__P ((const struct fileinfo
*f
));
211 static void print_many_per_line
__P ((void));
212 static void print_name_with_quoting
__P ((const char *p
, unsigned int mode
,
214 static void print_type_indicator
__P ((unsigned int mode
));
215 static void print_with_commas
__P ((void));
216 static void queue_directory
__P ((const char *name
, const char *realname
));
217 static void sort_files
__P ((void));
218 static void parse_ls_color
__P ((void));
219 static void usage
__P ((int status
));
221 /* The name the program was run with, stripped of any leading path. */
224 /* The table of files in the current directory:
226 `files' points to a vector of `struct fileinfo', one per file.
227 `nfiles' is the number of elements space has been allocated for.
228 `files_index' is the number actually in use. */
230 /* Address of block containing the files that are described. */
232 static struct fileinfo
*files
;
234 /* Length of block that `files' points to, measured in files. */
238 /* Index of first unused in `files'. */
240 static int files_index
;
242 /* Record of one pending directory waiting to be listed. */
247 /* If the directory is actually the file pointed to by a symbolic link we
248 were told to list, `realname' will contain the name of the symbolic
249 link, otherwise zero. */
251 struct pending
*next
;
254 static struct pending
*pending_dirs
;
256 /* Current time (seconds since 1970). When we are printing a file's time,
257 include the year if it is more than 6 months before this time. */
259 static time_t current_time
;
261 /* The number of digits to use for block sizes.
262 4, or more if needed for bigger numbers. */
264 static int block_size_size
;
268 /* long_format for lots of info, one per line.
269 one_per_line for just names, one per line.
270 many_per_line for just names, many per line, sorted vertically.
271 horizontal for just names, many per line, sorted horizontally.
272 with_commas for just names, many per line, separated by commas.
274 -l, -1, -C, -x and -m control this parameter. */
278 long_format
, /* -l */
279 one_per_line
, /* -1 */
280 many_per_line
, /* -C */
285 static enum format format
;
287 /* Type of time to print or sort by. Controlled by -c and -u. */
291 time_mtime
, /* default */
296 static enum time_type time_type
;
298 /* print the full time, otherwise the standard unix heuristics. */
302 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X. */
307 sort_name
, /* default */
308 sort_extension
, /* -X */
313 static enum sort_type sort_type
;
315 /* Direction of sort.
316 0 means highest first if numeric,
317 lowest first if alphabetic;
318 these are the defaults.
319 1 means the opposite order in each case. -r */
321 static int sort_reverse
;
323 /* Nonzero means to NOT display group information. -G */
327 /* Nonzero means print the user and group id's as numbers rather
330 static int numeric_users
;
332 /* Nonzero means mention the size in 512 byte blocks of each file. -s */
334 static int print_block_size
;
336 /* Nonzero means show file sizes in kilobytes instead of blocks
337 (the size of which is system-dependent). -k */
339 static int kilobyte_blocks
;
341 /* Precede each line of long output (per file) with a string like `m,n:'
342 where M is the number of characters after the `:' and before the
343 filename and N is the length of the filename. Using this format,
344 Emacs' dired mode starts up twice as fast, and can handle all
345 strange characters in file names. */
348 /* `none' means don't mention the type of files.
349 `all' means mention the types of all files.
350 `not_programs' means do so except for executables.
352 Controlled by -F and -p. */
358 not_programs
/* -p */
361 static enum indicator_style indicator_style
;
363 /* Nonzero means use colors to mark types. Also define the different
364 colors as well as the stuff for the LS_COLORS environment variable.
365 The LS_COLORS variable is now in a termcap-like format. */
367 static int print_with_color
;
371 color_never
, /* 0: default or --color=never */
372 color_always
, /* 1: --color=always */
373 color_if_tty
/* 2: --color=tty */
378 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
379 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
382 static const char *const indicator_name
[]=
384 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
385 "bd", "cd", "mi", "or", "ex", NULL
390 struct bin_str ext
; /* The extension we're looking for */
391 struct bin_str seq
; /* The sequence to output when we do */
392 struct col_ext_type
*next
; /* Next in list */
396 struct col_ext_type
*col_ext_list
= NULL
;
398 /* Buffer for color sequences */
399 static char *color_buf
;
401 /* Nonzero means mention the inode number of each file. -i */
403 static int print_inode
;
405 /* Nonzero means when a symbolic link is found, display info on
406 the file linked to. -L */
408 static int trace_links
;
410 /* Nonzero means when a directory is found, display info on its
413 static int trace_dirs
;
415 /* Nonzero means when an argument is a directory name, display info
418 static int immediate_dirs
;
420 /* Nonzero means don't omit files whose names start with `.'. -A */
422 static int all_files
;
424 /* Nonzero means don't omit files `.' and `..'
425 This flag implies `all_files'. -a */
427 static int really_all_files
;
429 /* A linked list of shell-style globbing patterns. If a non-argument
430 file name matches any of these patterns, it is omitted.
431 Controlled by -I. Multiple -I options accumulate.
432 The -B option adds `*~' and `.*~' to this list. */
434 struct ignore_pattern
437 struct ignore_pattern
*next
;
440 static struct ignore_pattern
*ignore_patterns
;
442 /* Nonzero means quote nongraphic chars in file names. -b */
444 static int quote_funny_chars
;
446 /* Nonzero means output nongraphic chars in file names as `?'. -q */
448 static int qmark_funny_chars
;
450 /* Nonzero means output each file name using C syntax for a string.
451 Always accompanied by `quote_funny_chars'.
452 This mode, together with -x or -C or -m,
453 and without such frills as -F or -s,
454 is guaranteed to make it possible for a program receiving
455 the output to tell exactly what file names are present. -Q */
457 static int quote_as_string
;
459 /* The number of chars per hardware tab stop. Setting this to zero
460 inhibits the use of TAB characters for separating columns. -T */
463 /* Nonzero means we are listing the working directory because no
464 non-option arguments were given. */
466 static int dir_defaulted
;
468 /* Nonzero means print each directory name before listing it. */
470 static int print_dir_name
;
472 /* The line length to use for breaking lines in many-per-line format.
473 Can be set with -w. */
475 static int line_length
;
477 /* If nonzero, the file listing format requires that stat be called on
480 static int format_needs_stat
;
482 /* The exit status to use if we don't get any fatal errors. */
484 static int exit_status
;
486 /* If nonzero, display usage information and exit. */
487 static int show_help
;
489 /* If nonzero, print the version on standard output and exit. */
490 static int show_version
;
492 static struct option
const long_options
[] =
494 {"all", no_argument
, 0, 'a'},
495 {"escape", no_argument
, 0, 'b'},
496 {"directory", no_argument
, 0, 'd'},
497 {"dired", no_argument
, 0, 'D'},
498 {"full-time", no_argument
, &full_time
, 1},
499 {"inode", no_argument
, 0, 'i'},
500 {"kilobytes", no_argument
, 0, 'k'},
501 {"numeric-uid-gid", no_argument
, 0, 'n'},
502 {"no-group", no_argument
, 0, 'G'},
503 {"hide-control-chars", no_argument
, 0, 'q'},
504 {"reverse", no_argument
, 0, 'r'},
505 {"size", no_argument
, 0, 's'},
506 {"width", required_argument
, 0, 'w'},
507 {"almost-all", no_argument
, 0, 'A'},
508 {"ignore-backups", no_argument
, 0, 'B'},
509 {"classify", no_argument
, 0, 'F'},
510 {"file-type", no_argument
, 0, 'F'},
511 {"ignore", required_argument
, 0, 'I'},
512 {"dereference", no_argument
, 0, 'L'},
513 {"literal", no_argument
, 0, 'N'},
514 {"quote-name", no_argument
, 0, 'Q'},
515 {"recursive", no_argument
, 0, 'R'},
516 {"format", required_argument
, 0, 12},
517 {"sort", required_argument
, 0, 10},
518 {"tabsize", required_argument
, 0, 'T'},
519 {"time", required_argument
, 0, 11},
520 {"help", no_argument
, &show_help
, 1},
521 {"version", no_argument
, &show_version
, 1},
522 {"color", optional_argument
, 0, 13},
526 static char const *const format_args
[] =
528 "verbose", "long", "commas", "horizontal", "across",
529 "vertical", "single-column", 0
532 static enum format
const formats
[] =
534 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
535 many_per_line
, one_per_line
538 static char const *const sort_args
[] =
540 "none", "time", "size", "extension", 0
543 static enum sort_type
const sort_types
[] =
545 sort_none
, sort_time
, sort_size
, sort_extension
548 static char const *const time_args
[] =
550 "atime", "access", "use", "ctime", "status", 0
553 /* This zero-based index is used solely with the --dired option.
554 When that option is in effect, this counter is incremented for each
555 character of output generated by this program so that the beginning
556 and ending indices (in that output) of every file name can be recorded
557 and later output themselves. */
558 static size_t dired_pos
;
560 #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
562 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
563 #define FPUTS(s, stream, s_len) \
564 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
566 /* Like FPUTS, but for use when S is a literal string. */
567 #define FPUTS_LITERAL(s, stream) \
568 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
570 #define DIRED_INDENT() \
573 /* FIXME: remove the `&& format == long_format' clause. */ \
574 if (dired && format == long_format) \
575 FPUTS_LITERAL (" ", stdout); \
579 /* With --dired, store pairs of beginning and ending indices of filenames. */
580 static struct obstack dired_obstack
;
582 /* With --dired, store pairs of beginning and ending indices of any
583 directory names that appear as headers (just before `total' line)
584 for lists of directory entries. Such directory names are seen when
585 listing hierarchies using -R and when a directory is listed with at
586 least one other command line argument. */
587 static struct obstack subdired_obstack
;
589 /* Save the current index on the specified obstack, OBS. */
590 #define PUSH_CURRENT_DIRED_POS(obs) \
593 /* FIXME: remove the `&& format == long_format' clause. */ \
594 if (dired && format == long_format) \
595 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
599 static enum time_type
const time_types
[] =
601 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
604 static char const *const color_args
[] =
606 /* Note: "no" is a prefix of "none" so we don't include it. */
607 /* force and none are for compatibility with another color-ls version */
608 "always", "yes", "force",
610 "auto", "tty", "if-tty", 0
613 static enum color_type
const color_types
[] =
615 color_always
, color_always
, color_always
,
616 color_never
, color_never
,
617 color_if_tty
, color_if_tty
, color_if_tty
621 /* Write to standard output the string PREFIX followed by a space-separated
622 list of the integers stored in OS all on one line. */
625 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
629 n_pos
= obstack_object_size (os
) / sizeof (size_t);
635 pos
= (size_t *) obstack_finish (os
);
636 fputs (prefix
, stdout
);
637 for (i
= 0; i
< n_pos
; i
++)
638 printf (" %d", (int) pos
[i
]);
639 fputs ("\n", stdout
);
644 main (int argc
, char **argv
)
647 register struct pending
*thispend
;
649 program_name
= argv
[0];
650 setlocale (LC_ALL
, "");
651 bindtextdomain (PACKAGE
, LOCALEDIR
);
652 textdomain (PACKAGE
);
658 current_time
= time ((time_t *) 0);
660 i
= decode_switches (argc
, argv
);
664 printf ("ls - %s\n", PACKAGE_VERSION
);
671 if (print_with_color
)
674 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
675 || format
== long_format
676 || trace_links
|| trace_dirs
|| indicator_style
!= none
677 || print_block_size
|| print_inode
|| print_with_color
;
679 if (dired
&& format
== long_format
)
681 obstack_init (&dired_obstack
);
682 obstack_init (&subdired_obstack
);
686 files
= (struct fileinfo
*) xmalloc (sizeof (struct fileinfo
) * nfiles
);
693 for (; i
< argc
; i
++)
694 gobble_file (argv
[i
], 1, "");
699 gobble_file (".", 1, "");
701 queue_directory (".", 0);
708 extract_dirs_from_files ("", 0);
709 /* `files_index' might be zero now. */
713 print_current_files ();
717 else if (pending_dirs
&& pending_dirs
->next
== 0)
722 thispend
= pending_dirs
;
723 pending_dirs
= pending_dirs
->next
;
724 print_dir (thispend
->name
, thispend
->realname
);
725 free (thispend
->name
);
726 if (thispend
->realname
)
727 free (thispend
->realname
);
732 if (dired
&& format
== long_format
)
734 /* No need to free these since we're about to exit. */
735 dired_dump_obstack ("//DIRED//", &dired_obstack
);
736 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
742 /* Set all the option flags according to the switches specified.
743 Return the index of the first non-option argument. */
746 decode_switches (int argc
, char **argv
)
753 qmark_funny_chars
= 0;
754 quote_funny_chars
= 0;
756 /* initialize all switches to default settings */
761 /* This is for the `dir' program. */
762 format
= many_per_line
;
763 quote_funny_chars
= 1;
767 /* This is for the `vdir' program. */
768 format
= long_format
;
769 quote_funny_chars
= 1;
773 /* This is for the `ls' program. */
776 format
= many_per_line
;
777 qmark_funny_chars
= 1;
781 format
= one_per_line
;
782 qmark_funny_chars
= 0;
790 time_type
= time_mtime
;
792 sort_type
= sort_name
;
795 print_block_size
= 0;
796 kilobyte_blocks
= getenv ("POSIXLY_CORRECT") == 0;
797 indicator_style
= none
;
803 really_all_files
= 0;
808 if ((p
= getenv ("COLUMNS")))
810 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
811 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
813 line_length
= (int) tmp_long
;
818 _("ignoring invalid width in environment variable COLUMNS: %s"),
827 if (ioctl (1, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
!= 0)
828 line_length
= ws
.ws_col
;
832 /* Using the TABSIZE environment variable is not POSIX-approved.
833 Ignore it when POSIXLY_CORRECT is set. */
835 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
837 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
838 && 0 <= tmp_long
&& tmp_long
<= INT_MAX
)
840 tabsize
= (int) tmp_long
;
845 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
850 while ((c
= getopt_long (argc
, argv
,
851 "abcdfgiklmnopqrstuw:xABCDFGI:LNQRST:UX1",
852 long_options
, (int *) 0)) != EOF
)
861 really_all_files
= 1;
865 quote_funny_chars
= 1;
866 qmark_funny_chars
= 0;
870 time_type
= time_ctime
;
871 sort_type
= sort_time
;
879 /* Same as enabling -a -U and disabling -l -s. */
881 really_all_files
= 1;
882 sort_type
= sort_none
;
884 if (format
== long_format
)
885 format
= (isatty (1) ? many_per_line
: one_per_line
);
886 print_block_size
= 0; /* disable -s */
887 print_with_color
= 0; /* disable --color */
891 /* No effect. For BSD compatibility. */
903 format
= long_format
;
907 format
= with_commas
;
914 case 'o': /* Just like -l, but don't display group info. */
915 format
= long_format
;
920 indicator_style
= not_programs
;
924 qmark_funny_chars
= 1;
925 quote_funny_chars
= 0;
933 print_block_size
= 1;
937 sort_type
= sort_time
;
941 time_type
= time_atime
;
945 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
946 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
947 error (1, 0, _("invalid line width: %s"), optarg
);
948 line_length
= (int) tmp_long
;
960 add_ignore_pattern ("*~");
961 add_ignore_pattern (".*~");
965 format
= many_per_line
;
973 indicator_style
= all
;
976 case 'G': /* inhibit display of group info */
981 add_ignore_pattern (optarg
);
989 quote_funny_chars
= 0;
990 qmark_funny_chars
= 0;
995 quote_funny_chars
= 1;
996 qmark_funny_chars
= 0;
1004 sort_type
= sort_size
;
1008 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1009 || tmp_long
< 0 || tmp_long
> INT_MAX
)
1010 error (1, 0, _("invalid tab size: %s"), optarg
);
1011 tabsize
= (int) tmp_long
;
1015 sort_type
= sort_none
;
1019 sort_type
= sort_extension
;
1023 format
= one_per_line
;
1026 case 10: /* --sort */
1027 i
= argmatch (optarg
, sort_args
);
1030 invalid_arg (_("sort type"), optarg
, i
);
1033 sort_type
= sort_types
[i
];
1036 case 11: /* --time */
1037 i
= argmatch (optarg
, time_args
);
1040 invalid_arg (_("time type"), optarg
, i
);
1043 time_type
= time_types
[i
];
1046 case 12: /* --format */
1047 i
= argmatch (optarg
, format_args
);
1050 invalid_arg (_("format type"), optarg
, i
);
1053 format
= formats
[i
];
1056 case 13: /* --color */
1059 i
= argmatch (optarg
, color_args
);
1062 invalid_arg (_("colorization criterion"), optarg
, i
);
1069 /* Using --color with no argument is equivalent to using
1074 print_with_color
= (i
== color_always
1075 || (i
== color_if_tty
1076 && isatty (STDOUT_FILENO
)));
1078 if (print_with_color
)
1080 /* Don't use TAB characters in output. Some terminal
1081 emulators can't handle the combination of tabs and
1082 color codes on the same line. */
1095 /* Parse a string as part of the LS_COLORS variable; this may involve
1096 decoding all kinds of escape characters. If equals_end is set an
1097 unescaped equal sign ends the string, otherwise only a : or \0
1098 does. Returns the number of characters output, or -1 on failure.
1100 The resulting string is *not* null-terminated, but may contain
1103 Note that both dest and src are char **; on return they point to
1104 the first free byte after the array and the character that ended
1105 the input string, respectively. */
1108 get_funky_string (char **dest
, const char **src
, int equals_end
)
1110 int num
; /* For numerical codes */
1111 int count
; /* Something to count with */
1113 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1118 p
= *src
; /* We don't want to double-indirect */
1119 q
= *dest
; /* the whole darn time. */
1121 count
= 0; /* No characters counted in yet. */
1124 state
= ST_GND
; /* Start in ground state. */
1125 while (state
< ST_END
)
1129 case ST_GND
: /* Ground state (no escapes) */
1134 state
= ST_END
; /* End of string */
1137 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1141 state
= ST_CARET
; /* Caret escape */
1147 state
= ST_END
; /* End */
1150 /* else fall through */
1158 case ST_BACKSLASH
: /* Backslash escaped character */
1169 state
= ST_OCTAL
; /* Octal sequence */
1174 state
= ST_HEX
; /* Hex sequence */
1177 case 'a': /* Bell */
1178 num
= 7; /* Not all C compilers know what \a means */
1180 case 'b': /* Backspace */
1183 case 'e': /* Escape */
1186 case 'f': /* Form feed */
1189 case 'n': /* Newline */
1192 case 'r': /* Carriage return */
1198 case 'v': /* Vtab */
1201 case '?': /* Delete */
1204 case '_': /* Space */
1207 case '\0': /* End of string */
1208 state
= ST_ERROR
; /* Error! */
1210 default: /* Escaped character like \ ^ : = */
1214 if (state
== ST_BACKSLASH
)
1223 case ST_OCTAL
: /* Octal sequence */
1224 if (*p
< '0' || *p
> '7')
1231 num
= (num
<< 3) + (*(p
++) - '0');
1234 case ST_HEX
: /* Hex sequence */
1247 num
= (num
<< 4) + (*(p
++) - '0');
1255 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1263 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1273 case ST_CARET
: /* Caret escape */
1274 state
= ST_GND
; /* Should be the next state... */
1275 if (*p
>= '@' && *p
<= '~')
1277 *(q
++) = *(p
++) & 037;
1280 else if ( *p
== '?' )
1297 return state
== ST_ERROR
? -1 : count
;
1301 parse_ls_color (void)
1303 const char *p
; /* Pointer to character being parsed */
1304 char *buf
; /* color_buf buffer pointer */
1305 int state
; /* State of parser */
1306 int ind_no
; /* Indicator number */
1307 char label
[3]; /* Indicator label */
1308 struct col_ext_type
*ext
; /* Extension we are working on */
1309 struct col_ext_type
*ext2
; /* Extra pointer */
1311 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1315 strcpy (label
, "??");
1317 /* This is an overly conservative estimate, but any possible
1318 LS_COLORS string will *not* generate a color_buf longer than
1319 itself, so it is a safe way of allocating a buffer in
1321 buf
= color_buf
= xstrdup (p
);
1328 case 1: /* First label character */
1336 /* Allocate new extension block and add to head of
1337 linked list (this way a later definition will
1338 override an earlier one, which can be useful for
1339 having terminal-specific defs override global). */
1341 ext
= (struct col_ext_type
*)
1342 xmalloc (sizeof (struct col_ext_type
));
1343 ext
->next
= col_ext_list
;
1347 ext
->ext
.string
= buf
;
1349 state
= (ext
->ext
.len
=
1350 get_funky_string (&buf
, &p
, 1)) < 0 ? -1 : 4;
1354 state
= 0; /* Done! */
1357 default: /* Assume it is file type label */
1364 case 2: /* Second label character */
1371 state
= -1; /* Error */
1374 case 3: /* Equal sign after indicator label */
1375 state
= -1; /* Assume failure... */
1376 if (*(p
++) == '=')/* It *should* be... */
1378 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
1380 if (STREQ (label
, indicator_name
[ind_no
]))
1382 color_indicator
[ind_no
].string
= buf
;
1383 state
= ((color_indicator
[ind_no
].len
=
1384 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1);
1389 error (0, 0, _("unrecognized prefix: %s"), label
);
1393 case 4: /* Equal sign after *.ext */
1396 ext
->seq
.string
= buf
;
1397 state
= (ext
->seq
.len
=
1398 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1;
1408 struct col_ext_type
*e
;
1411 _("unparsable value for LS_COLORS environment variable"));
1413 for (e
= col_ext_list
; e
!= NULL
; /* empty */)
1419 print_with_color
= 0;
1423 /* Request that the directory named `name' have its contents listed later.
1424 If `realname' is nonzero, it will be used instead of `name' when the
1425 directory name is printed. This allows symbolic links to directories
1426 to be treated as regular directories but still be listed under their
1430 queue_directory (const char *name
, const char *realname
)
1432 struct pending
*new;
1434 new = (struct pending
*) xmalloc (sizeof (struct pending
));
1435 new->next
= pending_dirs
;
1437 new->name
= xstrdup (name
);
1439 new->realname
= xstrdup (realname
);
1444 /* Read directory `name', and list the files in it.
1445 If `realname' is nonzero, print its name instead of `name';
1446 this is used for symbolic links to directories. */
1449 print_dir (const char *name
, const char *realname
)
1451 register DIR *reading
;
1452 register struct dirent
*next
;
1453 register int total_blocks
= 0;
1456 reading
= opendir (name
);
1459 error (0, errno
, "%s", name
);
1464 /* Read the directory entries, and insert the subfiles into the `files'
1469 while ((next
= readdir (reading
)) != NULL
)
1470 if (file_interesting (next
))
1471 total_blocks
+= gobble_file (next
->d_name
, 0, name
);
1473 if (CLOSEDIR (reading
))
1475 error (0, errno
, "%s", name
);
1477 /* Don't return; print whatever we got. */
1480 /* Sort the directory contents. */
1483 /* If any member files are subdirectories, perhaps they should have their
1484 contents listed rather than being mentioned here as files. */
1487 extract_dirs_from_files (name
, 1);
1494 dir
= (realname
? realname
: name
);
1495 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1496 FPUTS (dir
, stdout
, strlen (dir
));
1497 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1498 FPUTS_LITERAL (":\n", stdout
);
1501 if (format
== long_format
|| print_block_size
)
1503 char buf
[6 + 20 + 1 + 1];
1506 sprintf (buf
, "total %u\n", total_blocks
);
1507 FPUTS (buf
, stdout
, strlen (buf
));
1511 print_current_files ();
1517 /* Add `pattern' to the list of patterns for which files that match are
1521 add_ignore_pattern (const char *pattern
)
1523 register struct ignore_pattern
*ignore
;
1525 ignore
= (struct ignore_pattern
*) xmalloc (sizeof (struct ignore_pattern
));
1526 ignore
->pattern
= pattern
;
1527 /* Add it to the head of the linked list. */
1528 ignore
->next
= ignore_patterns
;
1529 ignore_patterns
= ignore
;
1532 /* Return nonzero if the file in `next' should be listed. */
1535 file_interesting (const struct dirent
*next
)
1537 register struct ignore_pattern
*ignore
;
1539 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
1540 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
1543 if (really_all_files
1544 || next
->d_name
[0] != '.'
1546 && next
->d_name
[1] != '\0'
1547 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
1553 /* Enter and remove entries in the table `files'. */
1555 /* Empty the table of files. */
1562 for (i
= 0; i
< files_index
; i
++)
1564 free (files
[i
].name
);
1565 if (files
[i
].linkname
)
1566 free (files
[i
].linkname
);
1570 block_size_size
= 4;
1573 /* Add a file to the current table of files.
1574 Verify that the file exists, and print an error message if it does not.
1575 Return the number of blocks that the file occupies. */
1578 gobble_file (const char *name
, int explicit_arg
, const char *dirname
)
1580 register int blocks
;
1582 register char *path
;
1584 if (files_index
== nfiles
)
1587 files
= (struct fileinfo
*) xrealloc (files
, sizeof (*files
) * nfiles
);
1590 files
[files_index
].linkname
= 0;
1591 files
[files_index
].linkmode
= 0;
1593 if (explicit_arg
|| format_needs_stat
)
1595 /* `path' is the absolute pathname of this file. */
1597 if (name
[0] == '/' || dirname
[0] == 0)
1598 path
= (char *) name
;
1601 path
= (char *) alloca (strlen (name
) + strlen (dirname
) + 2);
1602 attach (path
, dirname
, name
);
1607 val
= stat (path
, &files
[files_index
].stat
);
1609 /* Perhaps a symbolically-linked to file doesn't exist; stat
1610 the link instead. */
1611 val
= lstat (path
, &files
[files_index
].stat
);
1614 val
= lstat (path
, &files
[files_index
].stat
);
1617 error (0, errno
, "%s", path
);
1623 if (S_ISLNK (files
[files_index
].stat
.st_mode
)
1624 && (explicit_arg
|| format
== long_format
))
1627 struct stat linkstats
;
1629 get_link_name (path
, &files
[files_index
]);
1630 linkpath
= make_link_path (path
, files
[files_index
].linkname
);
1632 /* Avoid following symbolic links when possible, ie, when
1633 they won't be traced and when no indicator is needed. */
1635 && ((explicit_arg
&& format
!= long_format
)
1636 || indicator_style
!= none
)
1637 && stat (linkpath
, &linkstats
) == 0)
1639 /* Symbolic links to directories that are mentioned on the
1640 command line are automatically traced if not being
1642 if (explicit_arg
&& format
!= long_format
1643 && S_ISDIR (linkstats
.st_mode
))
1645 /* Substitute the linked-to directory's name, but
1646 save the real name in `linkname' for printing. */
1647 if (!immediate_dirs
)
1649 const char *tempname
= name
;
1651 linkpath
= files
[files_index
].linkname
;
1652 files
[files_index
].linkname
= (char *) tempname
;
1654 files
[files_index
].stat
= linkstats
;
1657 /* Get the linked-to file's mode for the filetype indicator
1658 in long listings. */
1659 files
[files_index
].linkmode
= linkstats
.st_mode
;
1667 if (S_ISLNK (files
[files_index
].stat
.st_mode
))
1668 files
[files_index
].filetype
= symbolic_link
;
1671 if (S_ISDIR (files
[files_index
].stat
.st_mode
))
1673 if (explicit_arg
&& !immediate_dirs
)
1674 files
[files_index
].filetype
= arg_directory
;
1676 files
[files_index
].filetype
= directory
;
1679 files
[files_index
].filetype
= normal
;
1681 blocks
= convert_blocks (ST_NBLOCKS (files
[files_index
].stat
),
1683 if (blocks
>= 10000 && block_size_size
< 5)
1684 block_size_size
= 5;
1685 if (blocks
>= 100000 && block_size_size
< 6)
1686 block_size_size
= 6;
1687 if (blocks
>= 1000000 && block_size_size
< 7)
1688 block_size_size
= 7;
1693 files
[files_index
].name
= xstrdup (name
);
1701 /* Put the name of the file that `filename' is a symbolic link to
1702 into the `linkname' field of `f'. */
1705 get_link_name (const char *filename
, struct fileinfo
*f
)
1708 register int linksize
;
1710 linkbuf
= (char *) alloca (PATH_MAX
+ 2);
1711 /* Some automounters give incorrect st_size for mount points.
1712 I can't think of a good workaround for it, though. */
1713 linksize
= readlink (filename
, linkbuf
, PATH_MAX
+ 1);
1716 error (0, errno
, "%s", filename
);
1721 linkbuf
[linksize
] = '\0';
1722 f
->linkname
= xstrdup (linkbuf
);
1726 /* If `linkname' is a relative path and `path' contains one or more
1727 leading directories, return `linkname' with those directories
1728 prepended; otherwise, return a copy of `linkname'.
1729 If `linkname' is zero, return zero. */
1732 make_link_path (const char *path
, const char *linkname
)
1740 if (*linkname
== '/')
1741 return xstrdup (linkname
);
1743 /* The link is to a relative path. Prepend any leading path
1744 in `path' to the link name. */
1745 linkbuf
= strrchr (path
, '/');
1747 return xstrdup (linkname
);
1749 bufsiz
= linkbuf
- path
+ 1;
1750 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
1751 strncpy (linkbuf
, path
, bufsiz
);
1752 strcpy (linkbuf
+ bufsiz
, linkname
);
1757 /* Remove any entries from `files' that are for directories,
1758 and queue them to be listed as directories instead.
1759 `dirname' is the prefix to prepend to each dirname
1760 to make it correct relative to ls's working dir.
1761 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1762 This is desirable when processing directories recursively. */
1765 extract_dirs_from_files (const char *dirname
, int recursive
)
1768 register char *path
;
1771 dirlen
= strlen (dirname
) + 2;
1772 /* Queue the directories last one first, because queueing reverses the
1774 for (i
= files_index
- 1; i
>= 0; i
--)
1775 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
1776 && (!recursive
|| is_not_dot_or_dotdot (files
[i
].name
)))
1778 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
1780 queue_directory (files
[i
].name
, files
[i
].linkname
);
1784 path
= (char *) xmalloc (strlen (files
[i
].name
) + dirlen
);
1785 attach (path
, dirname
, files
[i
].name
);
1786 queue_directory (path
, files
[i
].linkname
);
1789 if (files
[i
].filetype
== arg_directory
)
1790 free (files
[i
].name
);
1793 /* Now delete the directories from the table, compacting all the remaining
1796 for (i
= 0, j
= 0; i
< files_index
; i
++)
1797 if (files
[i
].filetype
!= arg_directory
)
1798 files
[j
++] = files
[i
];
1802 /* Return nonzero if `name' doesn't end in `.' or `..'
1803 This is so we don't try to recurse on `././././. ...' */
1806 is_not_dot_or_dotdot (const char *name
)
1810 t
= strrchr (name
, '/');
1816 || (name
[1] == '.' && name
[2] == '\0')))
1822 /* Sort the files now in the table. */
1837 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
1840 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
1843 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
1850 func
= sort_reverse
? rev_cmp_name
: compare_name
;
1852 case sort_extension
:
1853 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
1856 func
= sort_reverse
? rev_cmp_size
: compare_size
;
1862 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
1865 /* Comparison routines for sorting the files. */
1868 compare_ctime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1870 return longdiff (file2
->stat
.st_ctime
, file1
->stat
.st_ctime
);
1874 rev_cmp_ctime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1876 return longdiff (file2
->stat
.st_ctime
, file1
->stat
.st_ctime
);
1880 compare_mtime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1882 return longdiff (file2
->stat
.st_mtime
, file1
->stat
.st_mtime
);
1886 rev_cmp_mtime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1888 return longdiff (file2
->stat
.st_mtime
, file1
->stat
.st_mtime
);
1892 compare_atime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1894 return longdiff (file2
->stat
.st_atime
, file1
->stat
.st_atime
);
1898 rev_cmp_atime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1900 return longdiff (file2
->stat
.st_atime
, file1
->stat
.st_atime
);
1904 compare_size (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1906 return longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
1910 rev_cmp_size (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1912 return longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
1916 compare_name (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1918 return strcmp (file1
->name
, file2
->name
);
1922 rev_cmp_name (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1924 return strcmp (file1
->name
, file2
->name
);
1927 /* Compare file extensions. Files with no extension are `smallest'.
1928 If extensions are the same, compare by filenames instead. */
1931 compare_extension (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1933 register char *base1
, *base2
;
1936 base1
= strrchr (file1
->name
, '.');
1937 base2
= strrchr (file2
->name
, '.');
1938 if (base1
== 0 && base2
== 0)
1939 return strcmp (file1
->name
, file2
->name
);
1944 cmp
= strcmp (base1
, base2
);
1946 return strcmp (file1
->name
, file2
->name
);
1951 rev_cmp_extension (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1953 register char *base1
, *base2
;
1956 base1
= strrchr (file1
->name
, '.');
1957 base2
= strrchr (file2
->name
, '.');
1958 if (base1
== 0 && base2
== 0)
1959 return strcmp (file1
->name
, file2
->name
);
1964 cmp
= strcmp (base1
, base2
);
1966 return strcmp (file1
->name
, file2
->name
);
1970 /* List all the files now in the table. */
1973 print_current_files (void)
1980 for (i
= 0; i
< files_index
; i
++)
1982 print_file_name_and_frills (files
+ i
);
1988 print_many_per_line ();
1992 print_horizontal ();
1996 print_with_commas ();
2000 for (i
= 0; i
< files_index
; i
++)
2002 print_long_format (files
+ i
);
2010 print_long_format (const struct fileinfo
*f
)
2015 /* 7 fields that may (worst case: 64-bit integral values) require 20 bytes,
2016 1 10-character mode string,
2017 1 24-character time string,
2018 9 spaces, one following each of these fields,
2019 and 1 trailing NUL byte. */
2020 char bigbuf
[7 * 20 + 10 + 24 + 9 + 1];
2024 mode_string (f
->stat
.st_mode
, modebuf
);
2030 when
= f
->stat
.st_ctime
;
2033 when
= f
->stat
.st_mtime
;
2036 when
= f
->stat
.st_atime
;
2040 strcpy (timebuf
, ctime (&when
));
2046 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
2047 || current_time
< when
- 60L * 60L) /* In the future. */
2049 /* The file is fairly old or in the future.
2050 POSIX says the cutoff is 6 months old;
2051 approximate this by 6*30 days.
2052 Allow a 1 hour slop factor for what is considered "the future",
2053 to allow for NFS server/client clock disagreement.
2054 Show the year instead of the time of day. */
2055 strcpy (timebuf
+ 11, timebuf
+ 19);
2064 sprintf (p
, "%*lu ", INODE_DIGITS
, (unsigned long) f
->stat
.st_ino
);
2068 if (print_block_size
)
2070 sprintf (p
, "%*u ", block_size_size
,
2071 (unsigned) convert_blocks (ST_NBLOCKS (f
->stat
),
2076 /* The space between the mode and the number of links is the POSIX
2077 "optional alternate access method flag". */
2078 sprintf (p
, "%s %3u ", modebuf
, (unsigned int) f
->stat
.st_nlink
);
2082 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_uid
);
2084 sprintf (p
, "%-8.8s ", getuser (f
->stat
.st_uid
));
2090 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_gid
);
2092 sprintf (p
, "%-8.8s ", getgroup (f
->stat
.st_gid
));
2096 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2097 sprintf (p
, "%3u, %3u ", (unsigned) major (f
->stat
.st_rdev
),
2098 (unsigned) minor (f
->stat
.st_rdev
));
2100 sprintf (p
, "%8lu ", (unsigned long) f
->stat
.st_size
);
2103 sprintf (p
, "%s ", full_time
? timebuf
: timebuf
+ 4);
2107 FPUTS (bigbuf
, stdout
, p
- bigbuf
);
2108 PUSH_CURRENT_DIRED_POS (&dired_obstack
);
2109 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
);
2110 PUSH_CURRENT_DIRED_POS (&dired_obstack
);
2112 if (f
->filetype
== symbolic_link
)
2116 FPUTS_LITERAL (" -> ", stdout
);
2117 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
-1);
2118 if (indicator_style
!= none
)
2119 print_type_indicator (f
->linkmode
);
2122 else if (indicator_style
!= none
)
2123 print_type_indicator (f
->stat
.st_mode
);
2126 /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
2127 Otherwise, return xmalloc'd storage containing the quoted version
2128 of P and set QUOTED_LENGTH to the length of the quoted P. */
2131 quote_filename (register const char *p
, size_t *quoted_length
)
2133 register unsigned char c
;
2138 if (!quote_as_string
&& !quote_funny_chars
&& !qmark_funny_chars
)
2140 *quoted_length
= strlen (p
);
2145 for (c
= *p
; c
; c
= *++p
)
2147 if (quote_funny_chars
)
2170 if (!ISPRINT (c
) && qmark_funny_chars
)
2177 if (!found_quotable
&& !quote_as_string
)
2179 *quoted_length
= p
- p0
;
2184 quoted
= xmalloc (4 * strlen (p
) + 1);
2187 #define SAVECHAR(c) *q++ = (c)
2188 #define SAVE_2_CHARS(c12) \
2189 do { *q++ = ((c12)[0]); \
2190 *q++ = ((c12)[1]); } while (0)
2192 if (quote_as_string
)
2197 if (quote_funny_chars
)
2202 SAVE_2_CHARS ("\\\\");
2206 SAVE_2_CHARS ("\\n");
2210 SAVE_2_CHARS ("\\b");
2214 SAVE_2_CHARS ("\\r");
2218 SAVE_2_CHARS ("\\t");
2222 SAVE_2_CHARS ("\\f");
2226 SAVE_2_CHARS ("\\ ");
2230 SAVE_2_CHARS ("\\\"");
2239 sprintf (buf
, "\\%03o", (unsigned int) c
);
2240 q
= stpcpy (q
, buf
);
2248 else if (!qmark_funny_chars
)
2255 if (quote_as_string
)
2258 *quoted_length
= q
- quoted
;
2266 print_name_with_quoting (const char *p
, unsigned int mode
, int linkok
)
2269 size_t quoted_length
;
2271 if (print_with_color
)
2272 print_color_indicator (p
, mode
, linkok
);
2274 quoted
= quote_filename (p
, "ed_length
);
2275 FPUTS (quoted
!= NULL
? quoted
: p
, stdout
, quoted_length
);
2279 if (print_with_color
)
2281 if (color_indicator
[C_END
].string
!= NULL
)
2282 put_indicator (&color_indicator
[C_END
]);
2285 put_indicator (&color_indicator
[C_LEFT
]);
2286 put_indicator (&color_indicator
[C_NORM
]);
2287 put_indicator (&color_indicator
[C_RIGHT
]);
2292 /* Print the file name of `f' with appropriate quoting.
2293 Also print file size, inode number, and filetype indicator character,
2294 as requested by switches. */
2297 print_file_name_and_frills (const struct fileinfo
*f
)
2300 printf ("%*lu ", INODE_DIGITS
, (unsigned long) f
->stat
.st_ino
);
2302 if (print_block_size
)
2303 printf ("%*u ", block_size_size
,
2304 (unsigned) convert_blocks (ST_NBLOCKS (f
->stat
),
2307 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
);
2309 if (indicator_style
!= none
)
2310 print_type_indicator (f
->stat
.st_mode
);
2314 print_type_indicator (unsigned int mode
)
2325 if (S_ISFIFO (mode
))
2330 if (S_ISSOCK (mode
))
2334 if (S_ISREG (mode
) && indicator_style
== all
2335 && (mode
& (S_IEXEC
| S_IXGRP
| S_IXOTH
)))
2340 print_color_indicator (const char *name
, unsigned int mode
, int linkok
)
2343 struct col_ext_type
*ext
; /* Color extension */
2344 size_t len
; /* Length of name */
2346 /* Is this a nonexistent file? If so, linkok == -1. */
2348 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
2355 /* Test if is is a recognized extension. */
2357 len
= strlen (name
);
2358 name
+= len
; /* Pointer to final \0. */
2359 for (ext
= col_ext_list
; ext
!= NULL
; ext
= ext
->next
)
2360 if (ext
->ext
.len
<= len
2361 && strncmp (name
- ext
->ext
.len
, ext
->ext
.string
,
2371 else if (S_ISLNK (mode
))
2372 type
= ((!linkok
&& color_indicator
[C_ORPHAN
].string
)
2373 ? C_ORPHAN
: C_LINK
);
2377 else if (S_ISFIFO (mode
))
2382 else if (S_ISSOCK (mode
))
2387 else if (S_ISBLK (mode
))
2392 else if (S_ISCHR (mode
))
2396 if (type
== C_FILE
&& (mode
& (S_IEXEC
|S_IEXEC
>>3|S_IEXEC
>>6)) != 0)
2401 put_indicator (&color_indicator
[C_LEFT
]);
2402 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
2403 put_indicator (&color_indicator
[C_RIGHT
]);
2406 /* Output a color indicator (which may contain nulls). */
2408 put_indicator (const struct bin_str
*ind
)
2415 for (i
= ind
->len
; i
> 0; --i
)
2420 length_of_file_name_and_frills (const struct fileinfo
*f
)
2422 register char *p
= f
->name
;
2423 register unsigned char c
;
2424 register int len
= 0;
2427 len
+= INODE_DIGITS
+ 1;
2429 if (print_block_size
)
2430 len
+= 1 + block_size_size
;
2432 if (quote_as_string
)
2437 if (quote_funny_chars
)
2452 if (quote_as_string
)
2469 if (indicator_style
!= none
)
2471 unsigned filetype
= f
->stat
.st_mode
;
2473 if (S_ISREG (filetype
))
2475 if (indicator_style
== all
2476 && (f
->stat
.st_mode
& (S_IEXEC
| S_IEXEC
>> 3 | S_IEXEC
>> 6)))
2479 else if (S_ISDIR (filetype
)
2481 || S_ISLNK (filetype
)
2484 || S_ISFIFO (filetype
)
2487 || S_ISSOCK (filetype
)
2497 print_many_per_line (void)
2499 int filesno
; /* Index into files. */
2500 int row
; /* Current row. */
2501 int max_name_length
; /* Length of longest file name + frills. */
2502 int name_length
; /* Length of each file name + frills. */
2503 int pos
; /* Current character column. */
2504 int cols
; /* Number of files across. */
2505 int rows
; /* Maximum number of files down. */
2507 /* Compute the maximum file name length. */
2508 max_name_length
= 0;
2509 for (filesno
= 0; filesno
< files_index
; filesno
++)
2511 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2512 if (name_length
> max_name_length
)
2513 max_name_length
= name_length
;
2516 /* Allow at least two spaces between names. */
2517 max_name_length
+= 2;
2519 /* Calculate the maximum number of columns that will fit. */
2520 cols
= line_length
/ max_name_length
;
2523 /* Calculate the number of rows that will be in each column except possibly
2524 for a short column on the right. */
2525 rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
2526 /* Recalculate columns based on rows. */
2527 cols
= files_index
/ rows
+ (files_index
% rows
!= 0);
2529 for (row
= 0; row
< rows
; row
++)
2533 /* Print the next row. */
2536 print_file_name_and_frills (files
+ filesno
);
2537 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2540 if (filesno
>= files_index
)
2543 indent (pos
+ name_length
, pos
+ max_name_length
);
2544 pos
+= max_name_length
;
2551 print_horizontal (void)
2554 int max_name_length
;
2559 /* Compute the maximum file name length. */
2560 max_name_length
= 0;
2561 for (filesno
= 0; filesno
< files_index
; filesno
++)
2563 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2564 if (name_length
> max_name_length
)
2565 max_name_length
= name_length
;
2568 /* Allow two spaces between names. */
2569 max_name_length
+= 2;
2571 cols
= line_length
/ max_name_length
;
2578 for (filesno
= 0; filesno
< files_index
; filesno
++)
2582 if (filesno
% cols
== 0)
2589 indent (pos
+ name_length
, pos
+ max_name_length
);
2590 pos
+= max_name_length
;
2594 print_file_name_and_frills (files
+ filesno
);
2596 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2602 print_with_commas (void)
2609 for (filesno
= 0; filesno
< files_index
; filesno
++)
2613 pos
+= length_of_file_name_and_frills (files
+ filesno
);
2614 if (filesno
+ 1 < files_index
)
2615 pos
+= 2; /* For the comma and space */
2617 if (old_pos
!= 0 && pos
>= line_length
)
2623 print_file_name_and_frills (files
+ filesno
);
2624 if (filesno
+ 1 < files_index
)
2633 /* Assuming cursor is at position FROM, indent up to position TO.
2634 Use a TAB character instead of two or more spaces whenever possible. */
2637 indent (int from
, int to
)
2641 if (tabsize
> 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
2644 from
+= tabsize
- from
% tabsize
;
2654 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2657 attach (char *dest
, const char *dirname
, const char *name
)
2659 const char *dirnamep
= dirname
;
2661 /* Copy dirname if it is not ".". */
2662 if (dirname
[0] != '.' || dirname
[1] != 0)
2665 *dest
++ = *dirnamep
++;
2666 /* Add '/' if `dirname' doesn't already end with it. */
2667 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
2679 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2683 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
2685 List information about the FILEs (the current directory by default).\n\
2686 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2688 -A, --almost-all do not list implied . and ..\n\
2689 -a, --all do not hide entries starting with .\n\
2690 -B, --ignore-backups do not list implied entries ending with ~\n\
2691 -b, --escape print octal escapes for nongraphic characters\n\
2692 -C list entries by columns\n\
2693 -c sort by change time; with -l: show ctime\n\
2694 --color[=WHEN] control whether color is used to distinguish file\n\
2695 types. WHEN may be `never', `always', or `auto'\n\
2696 -D, --dired generate output designed for Emacs' dired mode\n\
2697 -d, --directory list directory entries instead of contents\n\
2698 -F, --classify append a character for typing each entry\n\
2699 -f do not sort, enable -aU, disable -lst\n\
2700 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2701 single-column -1, verbose -l, vertical -C\n\
2702 --full-time list both full date and full time\n"));
2705 -G, --no-group inhibit display of group information\n\
2707 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2708 -i, --inode print index number of each file\n\
2709 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
2710 -L, --dereference list entries pointed to by symbolic links\n\
2711 -l use a long listing format\n\
2712 -m fill width with a comma separated list of entries\n\
2713 -N, --literal print raw entry names (don't treat e.g. control\n\
2714 characters specially)\n\
2715 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2716 -o use long listing format without group info\n\
2717 -p append a character for typing each entry\n\
2718 -Q, --quote-name enclose entry names in double quotes\n\
2719 -q, --hide-control-chars print ? instead of non graphic characters\n\
2720 -R, --recursive list subdirectories recursively\n\
2721 -r, --reverse reverse order while sorting\n\
2722 -S sort by file size\n"));
2725 -s, --size print block size of each file\n\
2726 --sort=WORD ctime -c, extension -X, none -U, size -S,\n\
2727 status -c, time -t\n\
2728 --time=WORD atime -u, access -u, use -u\n\
2729 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2730 -t sort by modification time; with -l: show mtime\n\
2731 -U do not sort; list entries in directory order\n\
2732 -u sort by last access time; with -l: show atime\n\
2733 -w, --width=COLS assume screen width instead of current value\n\
2734 -x list entries by lines instead of by columns\n\
2735 -X sort alphabetically by entry extension\n\
2736 -1 list one file per line\n\
2737 --help display this help and exit\n\
2738 --version output version information and exit\n\
2740 By default, color is not used to distinguish types of files. That is\n\
2741 equivalent to using --color=none. Using the --color option without the\n\
2742 optional WHEN argument is equivalent to using --color=always. With\n\
2743 --color=auto, color codes are output only if standard output is connected\n\
2744 to a terminal (tty).\n\