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 /* Colour 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 ((char *path
, char *linkname
));
167 static int compare_atime
__P ((struct fileinfo
*file1
,
168 struct fileinfo
*file2
));
169 static int rev_cmp_atime
__P ((struct fileinfo
*file2
,
170 struct fileinfo
*file1
));
171 static int compare_ctime
__P ((struct fileinfo
*file1
,
172 struct fileinfo
*file2
));
173 static int rev_cmp_ctime
__P ((struct fileinfo
*file2
,
174 struct fileinfo
*file1
));
175 static int compare_mtime
__P ((struct fileinfo
*file1
,
176 struct fileinfo
*file2
));
177 static int rev_cmp_mtime
__P ((struct fileinfo
*file2
,
178 struct fileinfo
*file1
));
179 static int compare_size
__P ((struct fileinfo
*file1
,
180 struct fileinfo
*file2
));
181 static int rev_cmp_size
__P ((struct fileinfo
*file2
,
182 struct fileinfo
*file1
));
183 static int compare_name
__P ((struct fileinfo
*file1
,
184 struct fileinfo
*file2
));
185 static int rev_cmp_name
__P ((struct fileinfo
*file2
,
186 struct fileinfo
*file1
));
187 static int compare_extension
__P ((struct fileinfo
*file1
,
188 struct fileinfo
*file2
));
189 static int rev_cmp_extension
__P ((struct fileinfo
*file2
,
190 struct fileinfo
*file1
));
191 static int decode_switches
__P ((int argc
, char **argv
));
192 static int file_interesting
__P ((register 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 ((char *name
));
196 static void print_color_indicator
__P ((char *name
, unsigned int mode
,
198 static void put_indicator
__P ((struct bin_str
*ind
));
199 static int length_of_file_name_and_frills
__P ((struct fileinfo
*f
));
200 static void add_ignore_pattern
__P ((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 ((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 ((struct fileinfo
*f
));
209 static void print_horizontal
__P ((void));
210 static void print_long_format
__P ((struct fileinfo
*f
));
211 static void print_many_per_line
__P ((void));
212 static void print_name_with_quoting
__P ((register 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 ((char *name
, 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_no
, /* 0: default or --color=no */
372 color_yes
, /* 1: --color=yes */
373 color_if_tty
/* 2: --color=tty */
376 /* Note that color_no and color_yes equals boolean values; they will
377 be assigned to print_with_color which is a boolean variable. */
381 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
382 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
385 static const char *const indicator_name
[]=
387 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
388 "bd", "cd", "mi", "or", "ex", NULL
393 struct bin_str ext
; /* The extension we're looking for */
394 struct bin_str seq
; /* The sequence to output when we do */
395 struct col_ext_type
*next
; /* Next in list */
399 struct col_ext_type
*col_ext_list
= NULL
;
401 /* Buffer for color sequences */
402 static char *color_buf
;
404 /* Nonzero means mention the inode number of each file. -i */
406 static int print_inode
;
408 /* Nonzero means when a symbolic link is found, display info on
409 the file linked to. -L */
411 static int trace_links
;
413 /* Nonzero means when a directory is found, display info on its
416 static int trace_dirs
;
418 /* Nonzero means when an argument is a directory name, display info
421 static int immediate_dirs
;
423 /* Nonzero means don't omit files whose names start with `.'. -A */
425 static int all_files
;
427 /* Nonzero means don't omit files `.' and `..'
428 This flag implies `all_files'. -a */
430 static int really_all_files
;
432 /* A linked list of shell-style globbing patterns. If a non-argument
433 file name matches any of these patterns, it is omitted.
434 Controlled by -I. Multiple -I options accumulate.
435 The -B option adds `*~' and `.*~' to this list. */
437 struct ignore_pattern
440 struct ignore_pattern
*next
;
443 static struct ignore_pattern
*ignore_patterns
;
445 /* Nonzero means quote nongraphic chars in file names. -b */
447 static int quote_funny_chars
;
449 /* Nonzero means output nongraphic chars in file names as `?'. -q */
451 static int qmark_funny_chars
;
453 /* Nonzero means output each file name using C syntax for a string.
454 Always accompanied by `quote_funny_chars'.
455 This mode, together with -x or -C or -m,
456 and without such frills as -F or -s,
457 is guaranteed to make it possible for a program receiving
458 the output to tell exactly what file names are present. -Q */
460 static int quote_as_string
;
462 /* The number of chars per hardware tab stop. -T */
465 /* Nonzero means we are listing the working directory because no
466 non-option arguments were given. */
468 static int dir_defaulted
;
470 /* Nonzero means print each directory name before listing it. */
472 static int print_dir_name
;
474 /* The line length to use for breaking lines in many-per-line format.
475 Can be set with -w. */
477 static int line_length
;
479 /* If nonzero, the file listing format requires that stat be called on
482 static int format_needs_stat
;
484 /* The exit status to use if we don't get any fatal errors. */
486 static int exit_status
;
488 /* If nonzero, display usage information and exit. */
489 static int show_help
;
491 /* If nonzero, print the version on standard output and exit. */
492 static int show_version
;
494 static struct option
const long_options
[] =
496 {"all", no_argument
, 0, 'a'},
497 {"escape", no_argument
, 0, 'b'},
498 {"directory", no_argument
, 0, 'd'},
499 {"dired", no_argument
, 0, 'D'},
500 {"full-time", no_argument
, &full_time
, 1},
501 {"inode", no_argument
, 0, 'i'},
502 {"kilobytes", no_argument
, 0, 'k'},
503 {"numeric-uid-gid", no_argument
, 0, 'n'},
504 {"no-group", no_argument
, 0, 'G'},
505 {"hide-control-chars", no_argument
, 0, 'q'},
506 {"reverse", no_argument
, 0, 'r'},
507 {"size", no_argument
, 0, 's'},
508 {"width", required_argument
, 0, 'w'},
509 {"almost-all", no_argument
, 0, 'A'},
510 {"ignore-backups", no_argument
, 0, 'B'},
511 {"classify", no_argument
, 0, 'F'},
512 {"file-type", no_argument
, 0, 'F'},
513 {"ignore", required_argument
, 0, 'I'},
514 {"dereference", no_argument
, 0, 'L'},
515 {"literal", no_argument
, 0, 'N'},
516 {"quote-name", no_argument
, 0, 'Q'},
517 {"recursive", no_argument
, 0, 'R'},
518 {"format", required_argument
, 0, 12},
519 {"sort", required_argument
, 0, 10},
520 {"tabsize", required_argument
, 0, 'T'},
521 {"time", required_argument
, 0, 11},
522 {"help", no_argument
, &show_help
, 1},
523 {"version", no_argument
, &show_version
, 1},
524 {"color", optional_argument
, 0, 13},
528 static char const *const format_args
[] =
530 "verbose", "long", "commas", "horizontal", "across",
531 "vertical", "single-column", 0
534 static enum format
const formats
[] =
536 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
537 many_per_line
, one_per_line
540 static char const *const sort_args
[] =
542 "none", "time", "size", "extension", 0
545 static enum sort_type
const sort_types
[] =
547 sort_none
, sort_time
, sort_size
, sort_extension
550 static char const *const time_args
[] =
552 "atime", "access", "use", "ctime", "status", 0
555 /* This zero-based index is used solely with the --dired option.
556 When that option is in effect, this counter is incremented for each
557 character of output generated by this program so that the beginning
558 and ending indices (in that output) of every file name can be recorded
559 and later output themselves. */
560 static size_t dired_pos
;
562 #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
564 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
565 #define FPUTS(s, stream, s_len) \
566 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
568 /* Like FPUTS, but for use when S is a literal string. */
569 #define FPUTS_LITERAL(s, stream) \
570 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
572 #define DIRED_INDENT() \
575 /* FIXME: remove the `&& format == long_format' clause. */ \
576 if (dired && format == long_format) \
577 FPUTS_LITERAL (" ", stdout); \
581 /* With --dired, store pairs of beginning and ending indices of filenames. */
582 static struct obstack dired_obstack
;
584 /* With --dired, store pairs of beginning and ending indices of any
585 directory names that appear as headers (just before `total' line)
586 for lists of directory entries. Such directory names are seen when
587 listing hierarchies using -R and when a directory is listed with at
588 least one other command line argument. */
589 static struct obstack subdired_obstack
;
591 /* Save the current index on the specified obstack, OBS. */
592 #define PUSH_CURRENT_DIRED_POS(obs) \
595 /* FIXME: remove the `&& format == long_format' clause. */ \
596 if (dired && format == long_format) \
597 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
601 static enum time_type
const time_types
[] =
603 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
606 static char const *const color_args
[] =
608 /* Note: "no" is a prefix of "none" so we don't include it. */
609 /* force and none are for compatibility with another color-ls version */
610 "yes", "force", "none", "tty", "if-tty", 0
613 static enum color_type
const color_types
[] =
615 color_yes
, color_yes
, color_no
, color_if_tty
, color_if_tty
619 /* Write to standard output the string PREFIX followed by a space-separated
620 list of the integers stored in OS all on one line. */
623 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
627 n_pos
= obstack_object_size (os
) / sizeof (size_t);
633 pos
= (size_t *) obstack_finish (os
);
634 fputs (prefix
, stdout
);
635 for (i
= 0; i
< n_pos
; i
++)
636 printf (" %d", (int) pos
[i
]);
637 fputs ("\n", stdout
);
642 main (int argc
, char **argv
)
645 register struct pending
*thispend
;
647 program_name
= argv
[0];
648 setlocale (LC_ALL
, "");
649 bindtextdomain (PACKAGE
, LOCALEDIR
);
650 textdomain (PACKAGE
);
656 current_time
= time ((time_t *) 0);
658 i
= decode_switches (argc
, argv
);
662 printf ("ls - %s\n", PACKAGE_VERSION
);
669 if (print_with_color
)
672 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
673 || format
== long_format
674 || trace_links
|| trace_dirs
|| indicator_style
!= none
675 || print_block_size
|| print_inode
|| print_with_color
;
677 if (dired
&& format
== long_format
)
679 obstack_init (&dired_obstack
);
680 obstack_init (&subdired_obstack
);
684 files
= (struct fileinfo
*) xmalloc (sizeof (struct fileinfo
) * nfiles
);
691 for (; i
< argc
; i
++)
692 gobble_file (argv
[i
], 1, "");
697 gobble_file (".", 1, "");
699 queue_directory (".", 0);
706 extract_dirs_from_files ("", 0);
707 /* `files_index' might be zero now. */
711 print_current_files ();
715 else if (pending_dirs
&& pending_dirs
->next
== 0)
720 thispend
= pending_dirs
;
721 pending_dirs
= pending_dirs
->next
;
722 print_dir (thispend
->name
, thispend
->realname
);
723 free (thispend
->name
);
724 if (thispend
->realname
)
725 free (thispend
->realname
);
730 if (dired
&& format
== long_format
)
732 /* No need to free these since we're about to exit. */
733 dired_dump_obstack ("//DIRED//", &dired_obstack
);
734 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
740 /* Set all the option flags according to the switches specified.
741 Return the index of the first non-option argument. */
744 decode_switches (int argc
, char **argv
)
751 qmark_funny_chars
= 0;
752 quote_funny_chars
= 0;
754 /* initialize all switches to default settings */
759 /* This is for the `dir' program. */
760 format
= many_per_line
;
761 quote_funny_chars
= 1;
765 /* This is for the `vdir' program. */
766 format
= long_format
;
767 quote_funny_chars
= 1;
771 /* This is for the `ls' program. */
774 format
= many_per_line
;
775 qmark_funny_chars
= 1;
779 format
= one_per_line
;
780 qmark_funny_chars
= 0;
788 time_type
= time_mtime
;
790 sort_type
= sort_name
;
793 print_block_size
= 0;
794 kilobyte_blocks
= getenv ("POSIXLY_CORRECT") == 0;
795 indicator_style
= none
;
801 really_all_files
= 0;
806 if ((p
= getenv ("COLUMNS")))
808 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
809 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
811 line_length
= (int) tmp_long
;
816 _("ignoring invalid width in enironment variable COLUMNS: %s"),
825 if (ioctl (1, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
!= 0)
826 line_length
= ws
.ws_col
;
830 /* Using the TABSIZE environment variable is not POSIX-approved.
831 Ignore it when POSIXLY_CORRECT is set. */
833 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
835 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
836 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
838 tabsize
= (int) tmp_long
;
843 _("ignoring invalid tab size in enironment variable TABSIZE: %s"),
848 while ((c
= getopt_long (argc
, argv
,
849 "abcdfgiklmnopqrstuw:xABCDFGI:LNQRST:UX1",
850 long_options
, (int *) 0)) != EOF
)
859 really_all_files
= 1;
863 quote_funny_chars
= 1;
864 qmark_funny_chars
= 0;
868 time_type
= time_ctime
;
869 sort_type
= sort_time
;
877 /* Same as enabling -a -U and disabling -l -s. */
879 really_all_files
= 1;
880 sort_type
= sort_none
;
882 if (format
== long_format
)
883 format
= (isatty (1) ? many_per_line
: one_per_line
);
884 print_block_size
= 0; /* disable -s */
885 print_with_color
= 0; /* disable ---color */
889 /* No effect. For BSD compatibility. */
901 format
= long_format
;
905 format
= with_commas
;
912 case 'o': /* Just like -l, but don't display group info. */
913 format
= long_format
;
918 indicator_style
= not_programs
;
922 qmark_funny_chars
= 1;
923 quote_funny_chars
= 0;
931 print_block_size
= 1;
935 sort_type
= sort_time
;
939 time_type
= time_atime
;
943 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
944 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
945 error (1, 0, _("invalid line width: %s"), optarg
);
946 line_length
= (int) tmp_long
;
958 add_ignore_pattern ("*~");
959 add_ignore_pattern (".*~");
963 format
= many_per_line
;
971 indicator_style
= all
;
974 case 'G': /* inhibit display of group info */
979 add_ignore_pattern (optarg
);
987 quote_funny_chars
= 0;
988 qmark_funny_chars
= 0;
993 quote_funny_chars
= 1;
994 qmark_funny_chars
= 0;
1002 sort_type
= sort_size
;
1006 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1007 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1008 error (1, 0, _("invalid tab size: %s"), optarg
);
1009 tabsize
= (int) tmp_long
;
1013 sort_type
= sort_none
;
1017 sort_type
= sort_extension
;
1021 format
= one_per_line
;
1024 case 10: /* --sort */
1025 i
= argmatch (optarg
, sort_args
);
1028 invalid_arg (_("sort type"), optarg
, i
);
1031 sort_type
= sort_types
[i
];
1034 case 11: /* --time */
1035 i
= argmatch (optarg
, time_args
);
1038 invalid_arg (_("time type"), optarg
, i
);
1041 time_type
= time_types
[i
];
1044 case 12: /* --format */
1045 i
= argmatch (optarg
, format_args
);
1048 invalid_arg (_("format type"), optarg
, i
);
1051 format
= formats
[i
];
1054 case 13: /* --color */
1057 i
= argmatch (optarg
, color_args
);
1060 invalid_arg (_("colorization criterion"), optarg
, i
);
1066 i
= color_yes
; /* Only --color -> --color=yes */
1068 if (i
== color_if_tty
)
1069 print_with_color
= isatty (1);
1071 print_with_color
= i
;
1073 if (print_with_color
)
1075 /* Don't use TAB characters in output. Some terminal
1076 emulators can't handle the combination of tabs and
1077 color codes on the same line. */
1078 tabsize
= line_length
;
1090 /* Parse a string as part of the LS_COLORS variable; this may involve
1091 decoding all kinds of escape characters. If equals_end is set an
1092 unescaped equal sign ends the string, otherwise only a : or \0
1093 does. Returns the number of characters output, or -1 on failure.
1095 The resulting string is *not* null-terminated, but may contain
1098 Note that both dest and src are char **; on return they point to
1099 the first free byte after the array and the character that ended
1100 the input string, respectively. */
1103 get_funky_string (char **dest
, const char **src
, int equals_end
)
1105 int num
; /* For numerical codes */
1106 int count
; /* Something to count with */
1108 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1113 p
= *src
; /* We don't want to double-indirect */
1114 q
= *dest
; /* the whole darn time. */
1116 count
= 0; /* No characters counted in yet. */
1119 state
= ST_GND
; /* Start in ground state. */
1120 while (state
< ST_END
)
1124 case ST_GND
: /* Ground state (no escapes) */
1129 state
= ST_END
; /* End of string */
1132 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1136 state
= ST_CARET
; /* Caret escape */
1142 state
= ST_END
; /* End */
1145 /* else fall through */
1153 case ST_BACKSLASH
: /* Backslash escaped character */
1164 state
= ST_OCTAL
; /* Octal sequence */
1169 state
= ST_HEX
; /* Hex sequence */
1172 case 'a': /* Bell */
1173 num
= 7; /* Not all C compilers know what \a means */
1175 case 'b': /* Backspace */
1178 case 'e': /* Escape */
1181 case 'f': /* Form feed */
1184 case 'n': /* Newline */
1187 case 'r': /* Carriage return */
1193 case 'v': /* Vtab */
1196 case '?': /* Delete */
1199 case '_': /* Space */
1202 case '\0': /* End of string */
1203 state
= ST_ERROR
; /* Error! */
1205 default: /* Escaped character like \ ^ : = */
1209 if (state
== ST_BACKSLASH
)
1218 case ST_OCTAL
: /* Octal sequence */
1219 if (*p
< '0' || *p
> '7')
1226 num
= (num
<< 3) + (*(p
++) - '0');
1229 case ST_HEX
: /* Hex sequence */
1242 num
= (num
<< 4) + (*(p
++) - '0');
1250 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1258 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1268 case ST_CARET
: /* Caret escape */
1269 state
= ST_GND
; /* Should be the next state... */
1270 if (*p
>= '@' && *p
<= '~')
1272 *(q
++) = *(p
++) & 037;
1275 else if ( *p
== '?' )
1292 return state
== ST_ERROR
? -1 : count
;
1296 parse_ls_color (void)
1298 const char *p
; /* Pointer to character being parsed */
1299 char *buf
; /* color_buf buffer pointer */
1300 int state
; /* State of parser */
1301 int ind_no
; /* Indicator number */
1302 char label
[3]; /* Indicator label */
1303 struct col_ext_type
*ext
; /* Extension we are working on */
1304 struct col_ext_type
*ext2
; /* Extra pointer */
1306 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1310 strcpy (label
, "??");
1312 /* This is an overly conservative estimate, but any possible
1313 LS_COLORS string will *not* generate a color_buf longer than
1314 itself, so it is a safe way of allocating a buffer in
1316 buf
= color_buf
= xstrdup (p
);
1323 case 1: /* First label character */
1331 /* Allocate new extension block and add to head of
1332 linked list (this way a later definition will
1333 override an earlier one, which can be useful for
1334 having terminal-specific defs override global). */
1336 ext
= (struct col_ext_type
*)
1337 xmalloc (sizeof (struct col_ext_type
));
1338 ext
->next
= col_ext_list
;
1342 ext
->ext
.string
= buf
;
1344 state
= (ext
->ext
.len
=
1345 get_funky_string (&buf
, &p
, 1)) < 0 ? -1 : 4;
1349 state
= 0; /* Done! */
1352 default: /* Assume it is file type label */
1359 case 2: /* Second label character */
1366 state
= -1; /* Error */
1369 case 3: /* Equal sign after indicator label */
1370 state
= -1; /* Assume failure... */
1371 if (*(p
++) == '=')/* It *should* be... */
1373 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
1375 if (strcmp (label
, indicator_name
[ind_no
]) == 0)
1377 color_indicator
[ind_no
].string
= buf
;
1378 state
= ((color_indicator
[ind_no
].len
=
1379 get_funky_string (&buf
, &p
, 0)) < 0 ?
1385 error (0, 0, _("unrecognized prefix: %s"), label
);
1389 case 4: /* Equal sign after *.ext */
1392 ext
->seq
.string
= buf
;
1393 state
= (ext
->seq
.len
=
1394 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1;
1404 struct col_ext_type
*e
;
1407 _("unparsable value for LS_COLORS environment variable"));
1409 for (e
= col_ext_list
; e
!= NULL
; /* empty */)
1415 print_with_color
= 0;
1419 /* Request that the directory named `name' have its contents listed later.
1420 If `realname' is nonzero, it will be used instead of `name' when the
1421 directory name is printed. This allows symbolic links to directories
1422 to be treated as regular directories but still be listed under their
1426 queue_directory (char *name
, char *realname
)
1428 struct pending
*new;
1430 new = (struct pending
*) xmalloc (sizeof (struct pending
));
1431 new->next
= pending_dirs
;
1433 new->name
= xstrdup (name
);
1435 new->realname
= xstrdup (realname
);
1440 /* Read directory `name', and list the files in it.
1441 If `realname' is nonzero, print its name instead of `name';
1442 this is used for symbolic links to directories. */
1445 print_dir (const char *name
, const char *realname
)
1447 register DIR *reading
;
1448 register struct dirent
*next
;
1449 register int total_blocks
= 0;
1452 reading
= opendir (name
);
1455 error (0, errno
, "%s", name
);
1460 /* Read the directory entries, and insert the subfiles into the `files'
1465 while ((next
= readdir (reading
)) != NULL
)
1466 if (file_interesting (next
))
1467 total_blocks
+= gobble_file (next
->d_name
, 0, name
);
1469 if (CLOSEDIR (reading
))
1471 error (0, errno
, "%s", name
);
1473 /* Don't return; print whatever we got. */
1476 /* Sort the directory contents. */
1479 /* If any member files are subdirectories, perhaps they should have their
1480 contents listed rather than being mentioned here as files. */
1483 extract_dirs_from_files (name
, 1);
1490 dir
= (realname
? realname
: name
);
1491 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1492 FPUTS (dir
, stdout
, strlen (dir
));
1493 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1494 FPUTS_LITERAL (":\n", stdout
);
1497 if (format
== long_format
|| print_block_size
)
1499 char buf
[6 + 20 + 1 + 1];
1502 sprintf (buf
, "total %u\n", total_blocks
);
1503 FPUTS (buf
, stdout
, strlen (buf
));
1507 print_current_files ();
1513 /* Add `pattern' to the list of patterns for which files that match are
1517 add_ignore_pattern (char *pattern
)
1519 register struct ignore_pattern
*ignore
;
1521 ignore
= (struct ignore_pattern
*) xmalloc (sizeof (struct ignore_pattern
));
1522 ignore
->pattern
= pattern
;
1523 /* Add it to the head of the linked list. */
1524 ignore
->next
= ignore_patterns
;
1525 ignore_patterns
= ignore
;
1528 /* Return nonzero if the file in `next' should be listed. */
1531 file_interesting (register struct dirent
*next
)
1533 register struct ignore_pattern
*ignore
;
1535 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
1536 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
1539 if (really_all_files
1540 || next
->d_name
[0] != '.'
1542 && next
->d_name
[1] != '\0'
1543 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
1549 /* Enter and remove entries in the table `files'. */
1551 /* Empty the table of files. */
1558 for (i
= 0; i
< files_index
; i
++)
1560 free (files
[i
].name
);
1561 if (files
[i
].linkname
)
1562 free (files
[i
].linkname
);
1566 block_size_size
= 4;
1569 /* Add a file to the current table of files.
1570 Verify that the file exists, and print an error message if it does not.
1571 Return the number of blocks that the file occupies. */
1574 gobble_file (const char *name
, int explicit_arg
, const char *dirname
)
1576 register int blocks
;
1578 register char *path
;
1580 if (files_index
== nfiles
)
1583 files
= (struct fileinfo
*) xrealloc (files
, sizeof (*files
) * nfiles
);
1586 files
[files_index
].linkname
= 0;
1587 files
[files_index
].linkmode
= 0;
1589 if (explicit_arg
|| format_needs_stat
)
1591 /* `path' is the absolute pathname of this file. */
1593 if (name
[0] == '/' || dirname
[0] == 0)
1594 path
= (char *) name
;
1597 path
= (char *) alloca (strlen (name
) + strlen (dirname
) + 2);
1598 attach (path
, dirname
, name
);
1603 val
= stat (path
, &files
[files_index
].stat
);
1605 /* Perhaps a symbolically-linked to file doesn't exist; stat
1606 the link instead. */
1607 val
= lstat (path
, &files
[files_index
].stat
);
1610 val
= lstat (path
, &files
[files_index
].stat
);
1613 error (0, errno
, "%s", path
);
1619 if (S_ISLNK (files
[files_index
].stat
.st_mode
)
1620 && (explicit_arg
|| format
== long_format
))
1623 struct stat linkstats
;
1625 get_link_name (path
, &files
[files_index
]);
1626 linkpath
= make_link_path (path
, files
[files_index
].linkname
);
1628 /* Avoid following symbolic links when possible, ie, when
1629 they won't be traced and when no indicator is needed. */
1631 && ((explicit_arg
&& format
!= long_format
)
1632 || indicator_style
!= none
)
1633 && stat (linkpath
, &linkstats
) == 0)
1635 /* Symbolic links to directories that are mentioned on the
1636 command line are automatically traced if not being
1638 if (explicit_arg
&& format
!= long_format
1639 && S_ISDIR (linkstats
.st_mode
))
1641 /* Substitute the linked-to directory's name, but
1642 save the real name in `linkname' for printing. */
1643 if (!immediate_dirs
)
1645 const char *tempname
= name
;
1647 linkpath
= files
[files_index
].linkname
;
1648 files
[files_index
].linkname
= (char *) tempname
;
1650 files
[files_index
].stat
= linkstats
;
1653 /* Get the linked-to file's mode for the filetype indicator
1654 in long listings. */
1655 files
[files_index
].linkmode
= linkstats
.st_mode
;
1663 if (S_ISLNK (files
[files_index
].stat
.st_mode
))
1664 files
[files_index
].filetype
= symbolic_link
;
1667 if (S_ISDIR (files
[files_index
].stat
.st_mode
))
1669 if (explicit_arg
&& !immediate_dirs
)
1670 files
[files_index
].filetype
= arg_directory
;
1672 files
[files_index
].filetype
= directory
;
1675 files
[files_index
].filetype
= normal
;
1677 blocks
= convert_blocks (ST_NBLOCKS (files
[files_index
].stat
),
1679 if (blocks
>= 10000 && block_size_size
< 5)
1680 block_size_size
= 5;
1681 if (blocks
>= 100000 && block_size_size
< 6)
1682 block_size_size
= 6;
1683 if (blocks
>= 1000000 && block_size_size
< 7)
1684 block_size_size
= 7;
1689 files
[files_index
].name
= xstrdup (name
);
1697 /* Put the name of the file that `filename' is a symbolic link to
1698 into the `linkname' field of `f'. */
1701 get_link_name (char *filename
, struct fileinfo
*f
)
1704 register int linksize
;
1706 linkbuf
= (char *) alloca (PATH_MAX
+ 2);
1707 /* Some automounters give incorrect st_size for mount points.
1708 I can't think of a good workaround for it, though. */
1709 linksize
= readlink (filename
, linkbuf
, PATH_MAX
+ 1);
1712 error (0, errno
, "%s", filename
);
1717 linkbuf
[linksize
] = '\0';
1718 f
->linkname
= xstrdup (linkbuf
);
1722 /* If `linkname' is a relative path and `path' contains one or more
1723 leading directories, return `linkname' with those directories
1724 prepended; otherwise, return a copy of `linkname'.
1725 If `linkname' is zero, return zero. */
1728 make_link_path (char *path
, char *linkname
)
1736 if (*linkname
== '/')
1737 return xstrdup (linkname
);
1739 /* The link is to a relative path. Prepend any leading path
1740 in `path' to the link name. */
1741 linkbuf
= strrchr (path
, '/');
1743 return xstrdup (linkname
);
1745 bufsiz
= linkbuf
- path
+ 1;
1746 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
1747 strncpy (linkbuf
, path
, bufsiz
);
1748 strcpy (linkbuf
+ bufsiz
, linkname
);
1753 /* Remove any entries from `files' that are for directories,
1754 and queue them to be listed as directories instead.
1755 `dirname' is the prefix to prepend to each dirname
1756 to make it correct relative to ls's working dir.
1757 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1758 This is desirable when processing directories recursively. */
1761 extract_dirs_from_files (const char *dirname
, int recursive
)
1764 register char *path
;
1767 dirlen
= strlen (dirname
) + 2;
1768 /* Queue the directories last one first, because queueing reverses the
1770 for (i
= files_index
- 1; i
>= 0; i
--)
1771 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
1772 && (!recursive
|| is_not_dot_or_dotdot (files
[i
].name
)))
1774 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
1776 queue_directory (files
[i
].name
, files
[i
].linkname
);
1780 path
= (char *) xmalloc (strlen (files
[i
].name
) + dirlen
);
1781 attach (path
, dirname
, files
[i
].name
);
1782 queue_directory (path
, files
[i
].linkname
);
1785 if (files
[i
].filetype
== arg_directory
)
1786 free (files
[i
].name
);
1789 /* Now delete the directories from the table, compacting all the remaining
1792 for (i
= 0, j
= 0; i
< files_index
; i
++)
1793 if (files
[i
].filetype
!= arg_directory
)
1794 files
[j
++] = files
[i
];
1798 /* Return nonzero if `name' doesn't end in `.' or `..'
1799 This is so we don't try to recurse on `././././. ...' */
1802 is_not_dot_or_dotdot (char *name
)
1806 t
= strrchr (name
, '/');
1812 || (name
[1] == '.' && name
[2] == '\0')))
1818 /* Sort the files now in the table. */
1833 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
1836 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
1839 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
1846 func
= sort_reverse
? rev_cmp_name
: compare_name
;
1848 case sort_extension
:
1849 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
1852 func
= sort_reverse
? rev_cmp_size
: compare_size
;
1858 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
1861 /* Comparison routines for sorting the files. */
1864 compare_ctime (struct fileinfo
*file1
, struct fileinfo
*file2
)
1866 return longdiff (file2
->stat
.st_ctime
, file1
->stat
.st_ctime
);
1870 rev_cmp_ctime (struct fileinfo
*file2
, struct fileinfo
*file1
)
1872 return longdiff (file2
->stat
.st_ctime
, file1
->stat
.st_ctime
);
1876 compare_mtime (struct fileinfo
*file1
, struct fileinfo
*file2
)
1878 return longdiff (file2
->stat
.st_mtime
, file1
->stat
.st_mtime
);
1882 rev_cmp_mtime (struct fileinfo
*file2
, struct fileinfo
*file1
)
1884 return longdiff (file2
->stat
.st_mtime
, file1
->stat
.st_mtime
);
1888 compare_atime (struct fileinfo
*file1
, struct fileinfo
*file2
)
1890 return longdiff (file2
->stat
.st_atime
, file1
->stat
.st_atime
);
1894 rev_cmp_atime (struct fileinfo
*file2
, struct fileinfo
*file1
)
1896 return longdiff (file2
->stat
.st_atime
, file1
->stat
.st_atime
);
1900 compare_size (struct fileinfo
*file1
, struct fileinfo
*file2
)
1902 return longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
1906 rev_cmp_size (struct fileinfo
*file2
, struct fileinfo
*file1
)
1908 return longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
1912 compare_name (struct fileinfo
*file1
, struct fileinfo
*file2
)
1914 return strcmp (file1
->name
, file2
->name
);
1918 rev_cmp_name (struct fileinfo
*file2
, struct fileinfo
*file1
)
1920 return strcmp (file1
->name
, file2
->name
);
1923 /* Compare file extensions. Files with no extension are `smallest'.
1924 If extensions are the same, compare by filenames instead. */
1927 compare_extension (struct fileinfo
*file1
, struct fileinfo
*file2
)
1929 register char *base1
, *base2
;
1932 base1
= strrchr (file1
->name
, '.');
1933 base2
= strrchr (file2
->name
, '.');
1934 if (base1
== 0 && base2
== 0)
1935 return strcmp (file1
->name
, file2
->name
);
1940 cmp
= strcmp (base1
, base2
);
1942 return strcmp (file1
->name
, file2
->name
);
1947 rev_cmp_extension (struct fileinfo
*file2
, struct fileinfo
*file1
)
1949 register char *base1
, *base2
;
1952 base1
= strrchr (file1
->name
, '.');
1953 base2
= strrchr (file2
->name
, '.');
1954 if (base1
== 0 && base2
== 0)
1955 return strcmp (file1
->name
, file2
->name
);
1960 cmp
= strcmp (base1
, base2
);
1962 return strcmp (file1
->name
, file2
->name
);
1966 /* List all the files now in the table. */
1969 print_current_files (void)
1976 for (i
= 0; i
< files_index
; i
++)
1978 print_file_name_and_frills (files
+ i
);
1984 print_many_per_line ();
1988 print_horizontal ();
1992 print_with_commas ();
1996 for (i
= 0; i
< files_index
; i
++)
1998 print_long_format (files
+ i
);
2006 print_long_format (struct fileinfo
*f
)
2011 /* 7 fields that may (worst case: 64-bit integral values) require 20 bytes,
2012 1 10-character mode string,
2013 1 24-character time string,
2014 9 spaces, one following each of these fields,
2015 and 1 trailing NUL byte. */
2016 char bigbuf
[7 * 20 + 10 + 24 + 9 + 1];
2020 mode_string (f
->stat
.st_mode
, modebuf
);
2026 when
= f
->stat
.st_ctime
;
2029 when
= f
->stat
.st_mtime
;
2032 when
= f
->stat
.st_atime
;
2036 strcpy (timebuf
, ctime (&when
));
2042 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
2043 || current_time
< when
- 60L * 60L) /* In the future. */
2045 /* The file is fairly old or in the future.
2046 POSIX says the cutoff is 6 months old;
2047 approximate this by 6*30 days.
2048 Allow a 1 hour slop factor for what is considered "the future",
2049 to allow for NFS server/client clock disagreement.
2050 Show the year instead of the time of day. */
2051 strcpy (timebuf
+ 11, timebuf
+ 19);
2060 sprintf (p
, "%*lu ", INODE_DIGITS
, (unsigned long) f
->stat
.st_ino
);
2064 if (print_block_size
)
2066 sprintf (p
, "%*u ", block_size_size
,
2067 (unsigned) convert_blocks (ST_NBLOCKS (f
->stat
),
2072 /* The space between the mode and the number of links is the POSIX
2073 "optional alternate access method flag". */
2074 sprintf (p
, "%s %3u ", modebuf
, (unsigned int) f
->stat
.st_nlink
);
2078 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_uid
);
2080 sprintf (p
, "%-8.8s ", getuser (f
->stat
.st_uid
));
2086 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_gid
);
2088 sprintf (p
, "%-8.8s ", getgroup (f
->stat
.st_gid
));
2092 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2093 sprintf (p
, "%3u, %3u ", (unsigned) major (f
->stat
.st_rdev
),
2094 (unsigned) minor (f
->stat
.st_rdev
));
2096 sprintf (p
, "%8lu ", (unsigned long) f
->stat
.st_size
);
2099 sprintf (p
, "%s ", full_time
? timebuf
: timebuf
+ 4);
2103 FPUTS (bigbuf
, stdout
, p
- bigbuf
);
2104 PUSH_CURRENT_DIRED_POS (&dired_obstack
);
2105 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
);
2106 PUSH_CURRENT_DIRED_POS (&dired_obstack
);
2108 if (f
->filetype
== symbolic_link
)
2112 FPUTS_LITERAL (" -> ", stdout
);
2113 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
-1);
2114 if (indicator_style
!= none
)
2115 print_type_indicator (f
->linkmode
);
2118 else if (indicator_style
!= none
)
2119 print_type_indicator (f
->stat
.st_mode
);
2122 /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
2123 Otherwise, return xmalloc'd storage containing the quoted version
2124 of P and set QUOTED_LENGTH to the length of the quoted P. */
2127 quote_filename (register const char *p
, size_t *quoted_length
)
2129 register unsigned char c
;
2134 if (!quote_as_string
&& !quote_funny_chars
&& !qmark_funny_chars
)
2136 *quoted_length
= strlen (p
);
2141 for (c
= *p
; c
; c
= *++p
)
2143 if (quote_funny_chars
)
2166 if (!ISPRINT (c
) && qmark_funny_chars
)
2173 if (!found_quotable
&& !quote_as_string
)
2175 *quoted_length
= p
- p0
;
2180 quoted
= xmalloc (4 * strlen (p
) + 1);
2183 #define SAVECHAR(c) *q++ = (c)
2184 #define SAVE_2_CHARS(c12) \
2185 do { *q++ = ((c12)[0]); \
2186 *q++ = ((c12)[1]); } while (0)
2188 if (quote_as_string
)
2193 if (quote_funny_chars
)
2198 SAVE_2_CHARS ("\\\\");
2202 SAVE_2_CHARS ("\\n");
2206 SAVE_2_CHARS ("\\b");
2210 SAVE_2_CHARS ("\\r");
2214 SAVE_2_CHARS ("\\t");
2218 SAVE_2_CHARS ("\\f");
2222 SAVE_2_CHARS ("\\ ");
2226 SAVE_2_CHARS ("\\\"");
2235 sprintf (buf
, "\\%03o", (unsigned int) c
);
2236 q
= stpcpy (q
, buf
);
2244 else if (!qmark_funny_chars
)
2251 if (quote_as_string
)
2254 *quoted_length
= q
- quoted
;
2262 print_name_with_quoting (register char *p
, unsigned int mode
, int linkok
)
2265 size_t quoted_length
;
2267 if (print_with_color
)
2268 print_color_indicator (p
, mode
, linkok
);
2270 quoted
= quote_filename (p
, "ed_length
);
2271 FPUTS (quoted
!= NULL
? quoted
: p
, stdout
, quoted_length
);
2275 if (print_with_color
)
2277 if (color_indicator
[C_END
].string
!= NULL
)
2278 put_indicator (&color_indicator
[C_END
]);
2281 put_indicator (&color_indicator
[C_LEFT
]);
2282 put_indicator (&color_indicator
[C_NORM
]);
2283 put_indicator (&color_indicator
[C_RIGHT
]);
2288 /* Print the file name of `f' with appropriate quoting.
2289 Also print file size, inode number, and filetype indicator character,
2290 as requested by switches. */
2293 print_file_name_and_frills (struct fileinfo
*f
)
2296 printf ("%*lu ", INODE_DIGITS
, (unsigned long) f
->stat
.st_ino
);
2298 if (print_block_size
)
2299 printf ("%*u ", block_size_size
,
2300 (unsigned) convert_blocks (ST_NBLOCKS (f
->stat
),
2303 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
);
2305 if (indicator_style
!= none
)
2306 print_type_indicator (f
->stat
.st_mode
);
2310 print_type_indicator (unsigned int mode
)
2321 if (S_ISFIFO (mode
))
2326 if (S_ISSOCK (mode
))
2330 if (S_ISREG (mode
) && indicator_style
== all
2331 && (mode
& (S_IEXEC
| S_IXGRP
| S_IXOTH
)))
2336 print_color_indicator (char *name
, unsigned int mode
, int linkok
)
2339 struct col_ext_type
*ext
; /* Color extension */
2340 int len
; /* Length of name */
2342 /* Is this a nonexistent file? If so, linkok == -1. */
2344 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
2351 /* Test if is is a recognized extension. */
2353 len
= strlen (name
);
2354 name
+= len
; /* Pointer to final \0. */
2355 for (ext
= col_ext_list
; ext
!= NULL
; ext
= ext
->next
)
2356 if (ext
->ext
.len
<= len
2357 && strncmp (name
-ext
->ext
.len
, ext
->ext
.string
, ext
->ext
.len
) == 0)
2366 else if (S_ISLNK (mode
))
2367 type
= (!linkok
&& color_indicator
[C_ORPHAN
].string
) ?
2372 else if (S_ISFIFO (mode
))
2377 else if (S_ISSOCK (mode
))
2382 else if (S_ISBLK (mode
))
2387 else if (S_ISCHR (mode
))
2391 if (type
== C_FILE
&& (mode
& (S_IEXEC
|S_IEXEC
>>3|S_IEXEC
>>6)) != 0)
2396 put_indicator (&color_indicator
[C_LEFT
]);
2397 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
2398 put_indicator (&color_indicator
[C_RIGHT
]);
2401 /* Output a color indicator (which may contain nulls). */
2403 put_indicator (struct bin_str
*ind
)
2410 for (i
= ind
->len
; i
> 0; --i
)
2415 length_of_file_name_and_frills (struct fileinfo
*f
)
2417 register char *p
= f
->name
;
2418 register unsigned char c
;
2419 register int len
= 0;
2422 len
+= INODE_DIGITS
+ 1;
2424 if (print_block_size
)
2425 len
+= 1 + block_size_size
;
2427 if (quote_as_string
)
2432 if (quote_funny_chars
)
2447 if (quote_as_string
)
2464 if (indicator_style
!= none
)
2466 unsigned filetype
= f
->stat
.st_mode
;
2468 if (S_ISREG (filetype
))
2470 if (indicator_style
== all
2471 && (f
->stat
.st_mode
& (S_IEXEC
| S_IEXEC
>> 3 | S_IEXEC
>> 6)))
2474 else if (S_ISDIR (filetype
)
2476 || S_ISLNK (filetype
)
2479 || S_ISFIFO (filetype
)
2482 || S_ISSOCK (filetype
)
2492 print_many_per_line (void)
2494 int filesno
; /* Index into files. */
2495 int row
; /* Current row. */
2496 int max_name_length
; /* Length of longest file name + frills. */
2497 int name_length
; /* Length of each file name + frills. */
2498 int pos
; /* Current character column. */
2499 int cols
; /* Number of files across. */
2500 int rows
; /* Maximum number of files down. */
2502 /* Compute the maximum file name length. */
2503 max_name_length
= 0;
2504 for (filesno
= 0; filesno
< files_index
; filesno
++)
2506 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2507 if (name_length
> max_name_length
)
2508 max_name_length
= name_length
;
2511 /* Allow at least two spaces between names. */
2512 max_name_length
+= 2;
2514 /* Calculate the maximum number of columns that will fit. */
2515 cols
= line_length
/ max_name_length
;
2518 /* Calculate the number of rows that will be in each column except possibly
2519 for a short column on the right. */
2520 rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
2521 /* Recalculate columns based on rows. */
2522 cols
= files_index
/ rows
+ (files_index
% rows
!= 0);
2524 for (row
= 0; row
< rows
; row
++)
2528 /* Print the next row. */
2531 print_file_name_and_frills (files
+ filesno
);
2532 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2535 if (filesno
>= files_index
)
2538 indent (pos
+ name_length
, pos
+ max_name_length
);
2539 pos
+= max_name_length
;
2546 print_horizontal (void)
2549 int max_name_length
;
2554 /* Compute the maximum file name length. */
2555 max_name_length
= 0;
2556 for (filesno
= 0; filesno
< files_index
; filesno
++)
2558 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2559 if (name_length
> max_name_length
)
2560 max_name_length
= name_length
;
2563 /* Allow two spaces between names. */
2564 max_name_length
+= 2;
2566 cols
= line_length
/ max_name_length
;
2573 for (filesno
= 0; filesno
< files_index
; filesno
++)
2577 if (filesno
% cols
== 0)
2584 indent (pos
+ name_length
, pos
+ max_name_length
);
2585 pos
+= max_name_length
;
2589 print_file_name_and_frills (files
+ filesno
);
2591 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2597 print_with_commas (void)
2604 for (filesno
= 0; filesno
< files_index
; filesno
++)
2608 pos
+= length_of_file_name_and_frills (files
+ filesno
);
2609 if (filesno
+ 1 < files_index
)
2610 pos
+= 2; /* For the comma and space */
2612 if (old_pos
!= 0 && pos
>= line_length
)
2618 print_file_name_and_frills (files
+ filesno
);
2619 if (filesno
+ 1 < files_index
)
2628 /* Assuming cursor is at position FROM, indent up to position TO.
2629 Use a TAB character instead of two or more spaces whenever possible. */
2632 indent (int from
, int to
)
2636 if (to
/ tabsize
> (from
+ 1) / tabsize
)
2639 from
+= tabsize
- from
% tabsize
;
2649 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2652 attach (char *dest
, const char *dirname
, const char *name
)
2654 const char *dirnamep
= dirname
;
2656 /* Copy dirname if it is not ".". */
2657 if (dirname
[0] != '.' || dirname
[1] != 0)
2660 *dest
++ = *dirnamep
++;
2661 /* Add '/' if `dirname' doesn't already end with it. */
2662 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
2674 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2678 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
2680 List information about the FILEs (the current directory by default).\n\
2681 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2683 -A, --almost-all do not list implied . and ..\n\
2684 -a, --all do not hide entries starting with .\n\
2685 -B, --ignore-backups do not list implied entries ending with ~\n\
2686 -b, --escape print octal escapes for nongraphic characters\n\
2687 -C list entries by columns\n\
2688 -c sort by change time; with -l: show ctime\n\
2689 --color[=WORD] colorize entries according to WORD\n\
2690 yes, no, or tty (if output is terminal)\n\
2691 -D, --dired generate output well suited to Emacs' dired mode\n\
2692 -d, --directory list directory entries instead of contents\n\
2693 -F, --classify append a character for typing each entry\n\
2694 -f do not sort, enable -aU, disable -lst\n\
2695 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2696 single-column -1, verbose -l, vertical -C\n\
2697 --full-time list both full date and full time\n"));
2700 -G, --no-group inhibit display of group information\n\
2702 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2703 -i, --inode print index number of each file\n\
2704 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
2705 -L, --dereference list entries pointed to by symbolic links\n\
2706 -l use a long listing format\n\
2707 -m fill width with a comma separated list of entries\n\
2708 -N, --literal do not quote entry names\n\
2709 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2710 -o use long listing format without group info\n\
2711 -p append a character for typing each entry\n\
2712 -Q, --quote-name enclose entry names in double quotes\n\
2713 -q, --hide-control-chars print ? instead of non graphic characters\n\
2714 -R, --recursive list subdirectories recursively\n\
2715 -r, --reverse reverse order while sorting\n\
2716 -S sort by file size\n"));
2719 -s, --size print block size of each file\n\
2720 --sort=WORD ctime -c, extension -X, none -U, size -S,\n\
2721 status -c, time -t\n\
2722 --time=WORD atime -u, access -u, use -u\n\
2723 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2724 -t sort by modification time; with -l: show mtime\n\
2725 -U do not sort; list entries in directory order\n\
2726 -u sort by last access time; with -l: show atime\n\
2727 -w, --width=COLS assume screen width instead of current value\n\
2728 -x list entries by lines instead of by columns\n\
2729 -X sort alphabetically by entry extension\n\
2730 -1 list one file per line\n\
2731 --help display this help and exit\n\
2732 --version output version information and exit\n"));