1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-1999 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* If ls_mode is LS_MULTI_COL,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
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 <inttypes.h>
54 #ifdef GWINSZ_IN_SYS_IOCTL
55 # include <sys/ioctl.h>
73 #include "strverscmp.h"
76 #include "path-concat.h"
78 #define obstack_chunk_alloc malloc
79 #define obstack_chunk_free free
81 /* Return an int indicating the result of comparing two integers.
82 Subtracting doesn't always work, due to overflow. */
83 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
85 /* The field width for inode numbers. On some hosts inode numbers are
86 64 bits, so columns won't line up exactly when a huge inode number
87 is encountered, but in practice 7 digits is usually enough. */
89 # define INODE_DIGITS 7
93 # define HAVE_SYMLINKS 1
95 # define HAVE_SYMLINKS 0
98 /* If any of the S_* macros are undefined, define them here so each
99 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
101 # define S_ISLNK(Mode) 0
105 # define S_ISFIFO(Mode) 0
109 # define S_ISSOCK(Mode) 0
113 # define S_ISCHR(Mode) 0
117 # define S_ISBLK(Mode) 0
121 # define S_ISDOOR(Mode) 0
128 arg_directory
, /* Directory given as command line arg. */
129 normal
/* All others. */
139 /* For symbolic link, name of the file linked to, otherwise zero. */
142 /* For symbolic link and long listing, st_mode of file linked to, otherwise
144 unsigned int linkmode
;
146 /* For symbolic link and color printing, 1 if linked-to file
147 exists, otherwise 0. */
150 enum filetype filetype
;
153 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
155 /* Null is a valid character in a color indicator (think about Epson
156 printers, for example) so we have to use a length/buffer string
161 int len
; /* Number of bytes */
162 char *string
; /* Pointer to the same */
171 void strip_trailing_slashes ();
174 static size_t quote_name
PARAMS ((FILE *out
, const char *name
,
175 struct quoting_options
const *options
));
176 static char *make_link_path
PARAMS ((const char *path
, const char *linkname
));
177 static int compare_atime
PARAMS ((const struct fileinfo
*file1
,
178 const struct fileinfo
*file2
));
179 static int rev_cmp_atime
PARAMS ((const struct fileinfo
*file2
,
180 const struct fileinfo
*file1
));
181 static int compare_ctime
PARAMS ((const struct fileinfo
*file1
,
182 const struct fileinfo
*file2
));
183 static int rev_cmp_ctime
PARAMS ((const struct fileinfo
*file2
,
184 const struct fileinfo
*file1
));
185 static int compare_mtime
PARAMS ((const struct fileinfo
*file1
,
186 const struct fileinfo
*file2
));
187 static int rev_cmp_mtime
PARAMS ((const struct fileinfo
*file2
,
188 const struct fileinfo
*file1
));
189 static int compare_size
PARAMS ((const struct fileinfo
*file1
,
190 const struct fileinfo
*file2
));
191 static int rev_cmp_size
PARAMS ((const struct fileinfo
*file2
,
192 const struct fileinfo
*file1
));
193 static int compare_name
PARAMS ((const struct fileinfo
*file1
,
194 const struct fileinfo
*file2
));
195 static int rev_cmp_name
PARAMS ((const struct fileinfo
*file2
,
196 const struct fileinfo
*file1
));
197 static int compare_extension
PARAMS ((const struct fileinfo
*file1
,
198 const struct fileinfo
*file2
));
199 static int rev_cmp_extension
PARAMS ((const struct fileinfo
*file2
,
200 const struct fileinfo
*file1
));
201 static int compare_version
PARAMS ((const struct fileinfo
*file1
,
202 const struct fileinfo
*file2
));
203 static int rev_cmp_version
PARAMS ((const struct fileinfo
*file2
,
204 const struct fileinfo
*file1
));
205 static int decode_switches
PARAMS ((int argc
, char **argv
));
206 static int file_interesting
PARAMS ((const struct dirent
*next
));
207 static uintmax_t gobble_file
PARAMS ((const char *name
, int explicit_arg
,
208 const char *dirname
));
209 static void print_color_indicator
PARAMS ((const char *name
, unsigned int mode
,
211 static void put_indicator
PARAMS ((const struct bin_str
*ind
));
212 static int length_of_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
213 static void add_ignore_pattern
PARAMS ((const char *pattern
));
214 static void attach
PARAMS ((char *dest
, const char *dirname
, const char *name
));
215 static void clear_files
PARAMS ((void));
216 static void extract_dirs_from_files
PARAMS ((const char *dirname
,
218 static void get_link_name
PARAMS ((const char *filename
, struct fileinfo
*f
));
219 static void indent
PARAMS ((int from
, int to
));
220 static void init_column_info
PARAMS ((void));
221 static void print_current_files
PARAMS ((void));
222 static void print_dir
PARAMS ((const char *name
, const char *realname
));
223 static void print_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
224 static void print_horizontal
PARAMS ((void));
225 static void print_long_format
PARAMS ((const struct fileinfo
*f
));
226 static void print_many_per_line
PARAMS ((void));
227 static void print_name_with_quoting
PARAMS ((const char *p
, unsigned int mode
,
229 struct obstack
*stack
));
230 static void prep_non_filename_text
PARAMS ((void));
231 static void print_type_indicator
PARAMS ((unsigned int mode
));
232 static void print_with_commas
PARAMS ((void));
233 static void queue_directory
PARAMS ((const char *name
, const char *realname
));
234 static void sort_files
PARAMS ((void));
235 static void parse_ls_color
PARAMS ((void));
236 void usage
PARAMS ((int status
));
238 /* The name the program was run with, stripped of any leading path. */
241 /* The table of files in the current directory:
243 `files' points to a vector of `struct fileinfo', one per file.
244 `nfiles' is the number of elements space has been allocated for.
245 `files_index' is the number actually in use. */
247 /* Address of block containing the files that are described. */
249 static struct fileinfo
*files
;
251 /* Length of block that `files' points to, measured in files. */
255 /* Index of first unused in `files'. */
257 static int files_index
;
259 /* Record of one pending directory waiting to be listed. */
264 /* If the directory is actually the file pointed to by a symbolic link we
265 were told to list, `realname' will contain the name of the symbolic
266 link, otherwise zero. */
268 struct pending
*next
;
271 static struct pending
*pending_dirs
;
273 /* Current time (seconds since 1970). When we are printing a file's time,
274 include the year if it is more than 6 months before this time. */
276 static time_t current_time
;
278 /* The number of digits to use for block sizes.
279 4, or more if needed for bigger numbers. */
281 static int block_size_size
;
285 /* long_format for lots of info, one per line.
286 one_per_line for just names, one per line.
287 many_per_line for just names, many per line, sorted vertically.
288 horizontal for just names, many per line, sorted horizontally.
289 with_commas for just names, many per line, separated by commas.
291 -l, -1, -C, -x and -m control this parameter. */
295 long_format
, /* -l */
296 one_per_line
, /* -1 */
297 many_per_line
, /* -C */
302 static enum format format
;
304 /* Type of time to print or sort by. Controlled by -c and -u. */
308 time_mtime
, /* default */
313 static enum time_type time_type
;
315 /* print the full time, otherwise the standard unix heuristics. */
317 static int full_time
;
319 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
324 sort_name
, /* default */
325 sort_extension
, /* -X */
328 sort_version
/* -v */
331 static enum sort_type sort_type
;
333 /* Direction of sort.
334 0 means highest first if numeric,
335 lowest first if alphabetic;
336 these are the defaults.
337 1 means the opposite order in each case. -r */
339 static int sort_reverse
;
341 /* Nonzero means to NOT display group information. -G */
343 static int inhibit_group
;
345 /* Nonzero means print the user and group id's as numbers rather
348 static int numeric_ids
;
350 /* Nonzero means mention the size in blocks of each file. -s */
352 static int print_block_size
;
354 /* If positive, the units to use when printing sizes;
355 if negative, the human-readable base. */
356 static int output_block_size
;
358 /* Precede each line of long output (per file) with a string like `m,n:'
359 where M is the number of characters after the `:' and before the
360 filename and N is the length of the filename. Using this format,
361 Emacs' dired mode starts up twice as fast, and can handle all
362 strange characters in file names. */
365 /* `none' means don't mention the type of files.
366 `classify' means mention file types and mark executables.
367 `file_type' means mention only file types.
369 Controlled by -F, -p, and --indicator-style. */
373 none
, /* --indicator-style=none */
374 classify
, /* -F, --indicator-style=classify */
375 file_type
/* -p, --indicator-style=file-type */
378 static enum indicator_style indicator_style
;
380 /* Names of indicator styles. */
381 static char const *const indicator_style_args
[] =
383 "none", "classify", "file-type", 0
386 static enum indicator_style
const indicator_style_types
[]=
388 none
, classify
, file_type
391 /* Nonzero means use colors to mark types. Also define the different
392 colors as well as the stuff for the LS_COLORS environment variable.
393 The LS_COLORS variable is now in a termcap-like format. */
395 static int print_with_color
;
399 color_never
, /* 0: default or --color=never */
400 color_always
, /* 1: --color=always */
401 color_if_tty
/* 2: --color=tty */
406 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
407 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
410 static const char *const indicator_name
[]=
412 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
413 "bd", "cd", "mi", "or", "ex", "do", NULL
416 struct color_ext_type
418 struct bin_str ext
; /* The extension we're looking for */
419 struct bin_str seq
; /* The sequence to output when we do */
420 struct color_ext_type
*next
; /* Next in list */
423 static struct bin_str color_indicator
[] =
425 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
426 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
427 { 0, NULL
}, /* ec: End color (replaces lc+no+rc) */
428 { LEN_STR_PAIR ("0") }, /* no: Normal */
429 { LEN_STR_PAIR ("0") }, /* fi: File: default */
430 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
431 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
432 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
433 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
434 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
435 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
436 { 0, NULL
}, /* mi: Missing file: undefined */
437 { 0, NULL
}, /* or: Orphanned symlink: undefined */
438 { LEN_STR_PAIR ("01;32") } /* ex: Executable: bright green */
442 static struct color_ext_type
*color_ext_list
= NULL
;
444 /* Buffer for color sequences */
445 static char *color_buf
;
447 /* Nonzero means mention the inode number of each file. -i */
449 static int print_inode
;
451 /* Nonzero means when a symbolic link is found, display info on
452 the file linked to. -L */
454 static int trace_links
;
456 /* Nonzero means when a directory is found, display info on its
459 static int trace_dirs
;
461 /* Nonzero means when an argument is a directory name, display info
464 static int immediate_dirs
;
466 /* Nonzero means don't omit files whose names start with `.'. -A */
468 static int all_files
;
470 /* Nonzero means don't omit files `.' and `..'
471 This flag implies `all_files'. -a */
473 static int really_all_files
;
475 /* A linked list of shell-style globbing patterns. If a non-argument
476 file name matches any of these patterns, it is omitted.
477 Controlled by -I. Multiple -I options accumulate.
478 The -B option adds `*~' and `.*~' to this list. */
480 struct ignore_pattern
483 struct ignore_pattern
*next
;
486 static struct ignore_pattern
*ignore_patterns
;
488 /* Nonzero means output nongraphic chars in file names as `?'.
489 (-q, --hide-control-chars)
490 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
491 independent. The algorithm is: first, obey the quoting style to get a
492 string representing the file name; then, if qmark_funny_chars is set,
493 replace all nonprintable chars in that string with `?'. It's necessary
494 to replace nonprintable chars even in quoted strings, because we don't
495 want to mess up the terminal if control chars get sent to it, and some
496 quoting methods pass through control chars as-is. */
497 static int qmark_funny_chars
;
499 /* Quoting options for file and dir name output. */
501 static struct quoting_options
*filename_quoting_options
;
502 static struct quoting_options
*dirname_quoting_options
;
504 /* The number of chars per hardware tab stop. Setting this to zero
505 inhibits the use of TAB characters for separating columns. -T */
508 /* Nonzero means we are listing the working directory because no
509 non-option arguments were given. */
511 static int dir_defaulted
;
513 /* Nonzero means print each directory name before listing it. */
515 static int print_dir_name
;
517 /* The line length to use for breaking lines in many-per-line format.
518 Can be set with -w. */
520 static int line_length
;
522 /* If nonzero, the file listing format requires that stat be called on
525 static int format_needs_stat
;
527 /* The exit status to use if we don't get any fatal errors. */
529 static int exit_status
;
531 /* If nonzero, display usage information and exit. */
532 static int show_help
;
534 /* If nonzero, print the version on standard output and exit. */
535 static int show_version
;
537 static struct option
const long_options
[] =
539 {"all", no_argument
, 0, 'a'},
540 {"escape", no_argument
, 0, 'b'},
541 {"directory", no_argument
, 0, 'd'},
542 {"dired", no_argument
, 0, 'D'},
543 {"full-time", no_argument
, &full_time
, 1},
544 {"human-readable", no_argument
, 0, 'h'},
545 {"inode", no_argument
, 0, 'i'},
546 {"kilobytes", no_argument
, 0, 'k'},
547 {"numeric-uid-gid", no_argument
, 0, 'n'},
548 {"no-group", no_argument
, 0, 'G'},
549 {"hide-control-chars", no_argument
, 0, 'q'},
550 {"reverse", no_argument
, 0, 'r'},
551 {"size", no_argument
, 0, 's'},
552 {"width", required_argument
, 0, 'w'},
553 {"almost-all", no_argument
, 0, 'A'},
554 {"ignore-backups", no_argument
, 0, 'B'},
555 {"classify", no_argument
, 0, 'F'},
556 {"file-type", no_argument
, 0, 'F'},
557 {"si", no_argument
, 0, 'H'},
558 {"ignore", required_argument
, 0, 'I'},
559 {"indicator-style", required_argument
, 0, 14},
560 {"dereference", no_argument
, 0, 'L'},
561 {"literal", no_argument
, 0, 'N'},
562 {"quote-name", no_argument
, 0, 'Q'},
563 {"quoting-style", required_argument
, 0, 15},
564 {"recursive", no_argument
, 0, 'R'},
565 {"format", required_argument
, 0, 12},
566 {"show-control-chars", no_argument
, 0, 16},
567 {"sort", required_argument
, 0, 10},
568 {"tabsize", required_argument
, 0, 'T'},
569 {"time", required_argument
, 0, 11},
570 {"help", no_argument
, &show_help
, 1},
571 {"version", no_argument
, &show_version
, 1},
572 {"color", optional_argument
, 0, 13},
573 {"block-size", required_argument
, 0, 17},
577 static char const *const format_args
[] =
579 "verbose", "long", "commas", "horizontal", "across",
580 "vertical", "single-column", 0
583 static enum format
const format_types
[] =
585 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
586 many_per_line
, one_per_line
589 static char const *const sort_args
[] =
591 "none", "time", "size", "extension", "version", 0
594 static enum sort_type
const sort_types
[] =
596 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
599 static char const *const time_args
[] =
601 "atime", "access", "use", "ctime", "status", 0
604 static enum time_type
const time_types
[] =
606 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
609 static char const *const color_args
[] =
611 /* force and none are for compatibility with another color-ls version */
612 "always", "yes", "force",
613 "never", "no", "none",
614 "auto", "tty", "if-tty", 0
617 static enum color_type
const color_types
[] =
619 color_always
, color_always
, color_always
,
620 color_never
, color_never
, color_never
,
621 color_if_tty
, color_if_tty
, color_if_tty
624 /* Information about filling a column. */
632 /* Array with information about column filledness. */
633 static struct column_info
*column_info
;
635 /* Maximum number of columns ever possible for this display. */
638 /* The minimum width of a colum is 3: 1 character for the name and 2
639 for the separating white space. */
640 #define MIN_COLUMN_WIDTH 3
643 /* This zero-based index is used solely with the --dired option.
644 When that option is in effect, this counter is incremented for each
645 character of output generated by this program so that the beginning
646 and ending indices (in that output) of every file name can be recorded
647 and later output themselves. */
648 static size_t dired_pos
;
650 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
652 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
653 #define DIRED_FPUTS(s, stream, s_len) \
654 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
656 /* Like DIRED_FPUTS, but for use when S is a literal string. */
657 #define DIRED_FPUTS_LITERAL(s, stream) \
658 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
660 #define DIRED_INDENT() \
663 /* FIXME: remove the `&& format == long_format' clause. */ \
664 if (dired && format == long_format) \
665 DIRED_FPUTS_LITERAL (" ", stdout); \
669 /* With --dired, store pairs of beginning and ending indices of filenames. */
670 static struct obstack dired_obstack
;
672 /* With --dired, store pairs of beginning and ending indices of any
673 directory names that appear as headers (just before `total' line)
674 for lists of directory entries. Such directory names are seen when
675 listing hierarchies using -R and when a directory is listed with at
676 least one other command line argument. */
677 static struct obstack subdired_obstack
;
679 /* Save the current index on the specified obstack, OBS. */
680 #define PUSH_CURRENT_DIRED_POS(obs) \
683 /* FIXME: remove the `&& format == long_format' clause. */ \
684 if (dired && format == long_format) \
685 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
690 /* Write to standard output PREFIX, followed by the quoting style and
691 a space-separated list of the integers stored in OS all on one line. */
694 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
698 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
704 pos
= (size_t *) obstack_finish (os
);
705 fputs (prefix
, stdout
);
706 for (i
= 0; i
< n_pos
; i
++)
707 printf (" %d", (int) pos
[i
]);
708 fputs ("\n", stdout
);
713 main (int argc
, char **argv
)
716 register struct pending
*thispend
;
718 program_name
= argv
[0];
719 setlocale (LC_ALL
, "");
720 bindtextdomain (PACKAGE
, LOCALEDIR
);
721 textdomain (PACKAGE
);
727 current_time
= time ((time_t *) 0);
729 i
= decode_switches (argc
, argv
);
733 printf ("%s (%s) %s\n",
734 (ls_mode
== LS_LS
? "ls"
735 : (ls_mode
== LS_MULTI_COL
? "dir" : "vdir")),
736 GNU_PACKAGE
, VERSION
);
742 usage (EXIT_SUCCESS
);
744 if (print_with_color
)
747 prep_non_filename_text ();
750 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
751 || format
== long_format
752 || trace_links
|| trace_dirs
|| indicator_style
!= none
753 || print_block_size
|| print_inode
|| print_with_color
;
755 if (dired
&& format
== long_format
)
757 obstack_init (&dired_obstack
);
758 obstack_init (&subdired_obstack
);
762 files
= (struct fileinfo
*) xmalloc (sizeof (struct fileinfo
) * nfiles
);
769 for (; i
< argc
; i
++)
771 strip_trailing_slashes (argv
[i
]);
772 gobble_file (argv
[i
], 1, "");
778 gobble_file (".", 1, "");
780 queue_directory (".", 0);
787 extract_dirs_from_files ("", 0);
788 /* `files_index' might be zero now. */
792 print_current_files ();
794 DIRED_PUTCHAR ('\n');
796 else if (pending_dirs
&& pending_dirs
->next
== 0)
801 thispend
= pending_dirs
;
802 pending_dirs
= pending_dirs
->next
;
803 print_dir (thispend
->name
, thispend
->realname
);
804 free (thispend
->name
);
805 if (thispend
->realname
)
806 free (thispend
->realname
);
811 if (dired
&& format
== long_format
)
813 /* No need to free these since we're about to exit. */
814 dired_dump_obstack ("//DIRED//", &dired_obstack
);
815 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
816 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
817 ARGMATCH_TO_ARGUMENT (filename_quoting_options
,
818 quoting_style_args
, quoting_style_vals
));
821 /* Restore default color before exiting */
822 if (print_with_color
)
824 put_indicator (&color_indicator
[C_LEFT
]);
825 put_indicator (&color_indicator
[C_RIGHT
]);
832 /* Set all the option flags according to the switches specified.
833 Return the index of the first non-option argument. */
836 decode_switches (int argc
, char **argv
)
838 register char const *p
;
843 qmark_funny_chars
= 0;
845 /* initialize all switches to default settings */
850 /* This is for the `dir' program. */
851 format
= many_per_line
;
852 set_quoting_style (NULL
, escape_quoting_style
);
856 /* This is for the `vdir' program. */
857 format
= long_format
;
858 set_quoting_style (NULL
, escape_quoting_style
);
862 /* This is for the `ls' program. */
865 format
= many_per_line
;
866 /* See description of qmark_funny_chars, above. */
867 qmark_funny_chars
= 1;
871 format
= one_per_line
;
872 qmark_funny_chars
= 0;
880 time_type
= time_mtime
;
882 sort_type
= sort_name
;
885 print_block_size
= 0;
886 indicator_style
= none
;
892 really_all_files
= 0;
895 /* FIXME: Shouldn't we complain on wrong values? */
896 if ((p
= getenv ("QUOTING_STYLE"))
897 && 0 <= (i
= ARGCASEMATCH (p
, quoting_style_args
, quoting_style_vals
)))
898 set_quoting_style (NULL
, quoting_style_vals
[i
]);
900 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size
);
903 if ((p
= getenv ("COLUMNS")) && *p
)
905 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
906 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
908 line_length
= (int) tmp_long
;
913 _("ignoring invalid width in environment variable COLUMNS: %s"),
922 if (ioctl (1, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
!= 0)
923 line_length
= ws
.ws_col
;
927 /* Using the TABSIZE environment variable is not POSIX-approved.
928 Ignore it when POSIXLY_CORRECT is set. */
930 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
932 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
933 && 0 <= tmp_long
&& tmp_long
<= INT_MAX
)
935 tabsize
= (int) tmp_long
;
940 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
945 while ((c
= getopt_long (argc
, argv
,
946 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
947 long_options
, NULL
)) != -1)
956 really_all_files
= 1;
960 set_quoting_style (NULL
, escape_quoting_style
);
964 time_type
= time_ctime
;
965 sort_type
= sort_time
;
973 /* Same as enabling -a -U and disabling -l -s. */
975 really_all_files
= 1;
976 sort_type
= sort_none
;
978 if (format
== long_format
)
979 format
= (isatty (1) ? many_per_line
: one_per_line
);
980 print_block_size
= 0; /* disable -s */
981 print_with_color
= 0; /* disable --color */
985 /* No effect. For BSD compatibility. */
989 output_block_size
= -1024;
993 output_block_size
= -1000;
1001 output_block_size
= 1024;
1005 format
= long_format
;
1009 format
= with_commas
;
1016 case 'o': /* Just like -l, but don't display group info. */
1017 format
= long_format
;
1022 indicator_style
= file_type
;
1026 qmark_funny_chars
= 1;
1034 print_block_size
= 1;
1038 sort_type
= sort_time
;
1042 sort_type
= sort_time
;
1043 time_type
= time_atime
;
1047 sort_type
= sort_version
;
1051 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1052 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1053 error (EXIT_FAILURE
, 0, _("invalid line width: %s"),
1055 line_length
= (int) tmp_long
;
1059 format
= horizontal
;
1063 really_all_files
= 0;
1068 add_ignore_pattern ("*~");
1069 add_ignore_pattern (".*~");
1073 format
= many_per_line
;
1081 indicator_style
= classify
;
1084 case 'G': /* inhibit display of group info */
1089 add_ignore_pattern (optarg
);
1097 set_quoting_style (NULL
, literal_quoting_style
);
1101 set_quoting_style (NULL
, c_quoting_style
);
1109 sort_type
= sort_size
;
1113 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1114 || tmp_long
< 0 || tmp_long
> INT_MAX
)
1115 error (EXIT_FAILURE
, 0, _("invalid tab size: %s"),
1117 tabsize
= (int) tmp_long
;
1121 sort_type
= sort_none
;
1125 sort_type
= sort_extension
;
1129 format
= one_per_line
;
1132 case 10: /* --sort */
1133 sort_type
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
1136 case 11: /* --time */
1137 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
1140 case 12: /* --format */
1141 format
= XARGMATCH ("--format", optarg
, format_args
, format_types
);
1144 case 13: /* --color */
1146 i
= XARGMATCH ("--color", optarg
, color_args
, color_types
);
1148 /* Using --color with no argument is equivalent to using
1152 print_with_color
= (i
== color_always
1153 || (i
== color_if_tty
1154 && isatty (STDOUT_FILENO
)));
1156 if (print_with_color
)
1158 /* Don't use TAB characters in output. Some terminal
1159 emulators can't handle the combination of tabs and
1160 color codes on the same line. */
1165 case 14: /* --indicator-style */
1166 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
1167 indicator_style_args
,
1168 indicator_style_types
);
1171 case 15: /* --quoting-style */
1172 set_quoting_style (NULL
,
1173 XARGMATCH ("--quoting-style", optarg
,
1175 quoting_style_vals
));
1179 qmark_funny_chars
= 0;
1183 human_block_size (optarg
, 1, &output_block_size
);
1187 usage (EXIT_FAILURE
);
1191 filename_quoting_options
= clone_quoting_options (NULL
);
1192 if (get_quoting_style (filename_quoting_options
) == escape_quoting_style
)
1193 set_char_quoting (filename_quoting_options
, ' ', 1);
1194 if (indicator_style
!= none
)
1195 for (p
= "*=@|" + (int) indicator_style
- 1; *p
; p
++)
1196 set_char_quoting (filename_quoting_options
, *p
, 1);
1198 dirname_quoting_options
= clone_quoting_options (NULL
);
1199 set_char_quoting (dirname_quoting_options
, ':', 1);
1204 /* Parse a string as part of the LS_COLORS variable; this may involve
1205 decoding all kinds of escape characters. If equals_end is set an
1206 unescaped equal sign ends the string, otherwise only a : or \0
1207 does. Returns the number of characters output, or -1 on failure.
1209 The resulting string is *not* null-terminated, but may contain
1212 Note that both dest and src are char **; on return they point to
1213 the first free byte after the array and the character that ended
1214 the input string, respectively. */
1217 get_funky_string (char **dest
, const char **src
, int equals_end
)
1219 int num
; /* For numerical codes */
1220 int count
; /* Something to count with */
1222 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1227 p
= *src
; /* We don't want to double-indirect */
1228 q
= *dest
; /* the whole darn time. */
1230 count
= 0; /* No characters counted in yet. */
1233 state
= ST_GND
; /* Start in ground state. */
1234 while (state
< ST_END
)
1238 case ST_GND
: /* Ground state (no escapes) */
1243 state
= ST_END
; /* End of string */
1246 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1250 state
= ST_CARET
; /* Caret escape */
1256 state
= ST_END
; /* End */
1259 /* else fall through */
1267 case ST_BACKSLASH
: /* Backslash escaped character */
1278 state
= ST_OCTAL
; /* Octal sequence */
1283 state
= ST_HEX
; /* Hex sequence */
1286 case 'a': /* Bell */
1287 num
= 7; /* Not all C compilers know what \a means */
1289 case 'b': /* Backspace */
1292 case 'e': /* Escape */
1295 case 'f': /* Form feed */
1298 case 'n': /* Newline */
1301 case 'r': /* Carriage return */
1307 case 'v': /* Vtab */
1310 case '?': /* Delete */
1313 case '_': /* Space */
1316 case '\0': /* End of string */
1317 state
= ST_ERROR
; /* Error! */
1319 default: /* Escaped character like \ ^ : = */
1323 if (state
== ST_BACKSLASH
)
1332 case ST_OCTAL
: /* Octal sequence */
1333 if (*p
< '0' || *p
> '7')
1340 num
= (num
<< 3) + (*(p
++) - '0');
1343 case ST_HEX
: /* Hex sequence */
1356 num
= (num
<< 4) + (*(p
++) - '0');
1364 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1372 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1382 case ST_CARET
: /* Caret escape */
1383 state
= ST_GND
; /* Should be the next state... */
1384 if (*p
>= '@' && *p
<= '~')
1386 *(q
++) = *(p
++) & 037;
1406 return state
== ST_ERROR
? -1 : count
;
1410 parse_ls_color (void)
1412 const char *p
; /* Pointer to character being parsed */
1413 char *buf
; /* color_buf buffer pointer */
1414 int state
; /* State of parser */
1415 int ind_no
; /* Indicator number */
1416 char label
[3]; /* Indicator label */
1417 struct color_ext_type
*ext
; /* Extension we are working on */
1419 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1423 strcpy (label
, "??");
1425 /* This is an overly conservative estimate, but any possible
1426 LS_COLORS string will *not* generate a color_buf longer than
1427 itself, so it is a safe way of allocating a buffer in
1429 buf
= color_buf
= xstrdup (p
);
1436 case 1: /* First label character */
1444 /* Allocate new extension block and add to head of
1445 linked list (this way a later definition will
1446 override an earlier one, which can be useful for
1447 having terminal-specific defs override global). */
1449 ext
= (struct color_ext_type
*)
1450 xmalloc (sizeof (struct color_ext_type
));
1451 ext
->next
= color_ext_list
;
1452 color_ext_list
= ext
;
1455 ext
->ext
.string
= buf
;
1457 state
= (ext
->ext
.len
=
1458 get_funky_string (&buf
, &p
, 1)) < 0 ? -1 : 4;
1462 state
= 0; /* Done! */
1465 default: /* Assume it is file type label */
1472 case 2: /* Second label character */
1479 state
= -1; /* Error */
1482 case 3: /* Equal sign after indicator label */
1483 state
= -1; /* Assume failure... */
1484 if (*(p
++) == '=')/* It *should* be... */
1486 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
1488 if (STREQ (label
, indicator_name
[ind_no
]))
1490 color_indicator
[ind_no
].string
= buf
;
1491 state
= ((color_indicator
[ind_no
].len
=
1492 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1);
1497 error (0, 0, _("unrecognized prefix: %s"), quotearg (label
));
1501 case 4: /* Equal sign after *.ext */
1504 ext
->seq
.string
= buf
;
1505 state
= (ext
->seq
.len
=
1506 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1;
1516 struct color_ext_type
*e
;
1517 struct color_ext_type
*e2
;
1520 _("unparsable value for LS_COLORS environment variable"));
1522 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
1528 print_with_color
= 0;
1532 /* Request that the directory named `name' have its contents listed later.
1533 If `realname' is nonzero, it will be used instead of `name' when the
1534 directory name is printed. This allows symbolic links to directories
1535 to be treated as regular directories but still be listed under their
1539 queue_directory (const char *name
, const char *realname
)
1541 struct pending
*new;
1543 new = (struct pending
*) xmalloc (sizeof (struct pending
));
1544 new->next
= pending_dirs
;
1546 new->name
= xstrdup (name
);
1548 new->realname
= xstrdup (realname
);
1553 /* Read directory `name', and list the files in it.
1554 If `realname' is nonzero, print its name instead of `name';
1555 this is used for symbolic links to directories. */
1558 print_dir (const char *name
, const char *realname
)
1560 register DIR *reading
;
1561 register struct dirent
*next
;
1562 register uintmax_t total_blocks
= 0;
1565 reading
= opendir (name
);
1568 error (0, errno
, "%s", quotearg_colon (name
));
1573 /* Read the directory entries, and insert the subfiles into the `files'
1578 while ((next
= readdir (reading
)) != NULL
)
1579 if (file_interesting (next
))
1580 total_blocks
+= gobble_file (next
->d_name
, 0, name
);
1582 if (CLOSEDIR (reading
))
1584 error (0, errno
, "%s", quotearg_colon (name
));
1586 /* Don't return; print whatever we got. */
1589 /* Sort the directory contents. */
1592 /* If any member files are subdirectories, perhaps they should have their
1593 contents listed rather than being mentioned here as files. */
1596 extract_dirs_from_files (name
, 1);
1598 if (trace_dirs
|| print_dir_name
)
1601 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1602 dired_pos
+= quote_name (stdout
, realname
? realname
: name
,
1603 dirname_quoting_options
);
1604 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1605 DIRED_FPUTS_LITERAL (":\n", stdout
);
1608 if (format
== long_format
|| print_block_size
)
1611 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1615 DIRED_FPUTS (p
, stdout
, strlen (p
));
1616 DIRED_PUTCHAR (' ');
1617 p
= human_readable (total_blocks
, buf
, ST_NBLOCKSIZE
, output_block_size
);
1618 DIRED_FPUTS (p
, stdout
, strlen (p
));
1619 DIRED_PUTCHAR ('\n');
1623 print_current_files ();
1626 DIRED_PUTCHAR ('\n');
1629 /* Add `pattern' to the list of patterns for which files that match are
1633 add_ignore_pattern (const char *pattern
)
1635 register struct ignore_pattern
*ignore
;
1637 ignore
= (struct ignore_pattern
*) xmalloc (sizeof (struct ignore_pattern
));
1638 ignore
->pattern
= pattern
;
1639 /* Add it to the head of the linked list. */
1640 ignore
->next
= ignore_patterns
;
1641 ignore_patterns
= ignore
;
1644 /* Return nonzero if the file in `next' should be listed. */
1647 file_interesting (const struct dirent
*next
)
1649 register struct ignore_pattern
*ignore
;
1651 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
1652 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
1655 if (really_all_files
1656 || next
->d_name
[0] != '.'
1658 && next
->d_name
[1] != '\0'
1659 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
1665 /* Enter and remove entries in the table `files'. */
1667 /* Empty the table of files. */
1674 for (i
= 0; i
< files_index
; i
++)
1676 free (files
[i
].name
);
1677 if (files
[i
].linkname
)
1678 free (files
[i
].linkname
);
1682 block_size_size
= 4;
1685 /* Add a file to the current table of files.
1686 Verify that the file exists, and print an error message if it does not.
1687 Return the number of blocks that the file occupies. */
1690 gobble_file (const char *name
, int explicit_arg
, const char *dirname
)
1692 register uintmax_t blocks
;
1694 register char *path
;
1696 if (files_index
== nfiles
)
1699 files
= (struct fileinfo
*) xrealloc ((char *) files
,
1700 sizeof (*files
) * nfiles
);
1703 files
[files_index
].linkname
= 0;
1704 files
[files_index
].linkmode
= 0;
1705 files
[files_index
].linkok
= 0;
1707 if (explicit_arg
|| format_needs_stat
)
1709 /* `path' is the absolute pathname of this file. */
1711 if (name
[0] == '/' || dirname
[0] == 0)
1712 path
= (char *) name
;
1715 path
= (char *) alloca (strlen (name
) + strlen (dirname
) + 2);
1716 attach (path
, dirname
, name
);
1721 val
= stat (path
, &files
[files_index
].stat
);
1723 /* Perhaps a symbolically-linked to file doesn't exist; stat
1724 the link instead. */
1725 val
= lstat (path
, &files
[files_index
].stat
);
1729 val
= lstat (path
, &files
[files_index
].stat
);
1734 error (0, errno
, "%s", quotearg_colon (path
));
1739 if (S_ISLNK (files
[files_index
].stat
.st_mode
)
1740 && (explicit_arg
|| format
== long_format
|| print_with_color
))
1743 struct stat linkstats
;
1745 get_link_name (path
, &files
[files_index
]);
1746 linkpath
= make_link_path (path
, files
[files_index
].linkname
);
1748 /* Avoid following symbolic links when possible, ie, when
1749 they won't be traced and when no indicator is needed. */
1751 && ((explicit_arg
&& format
!= long_format
)
1752 || indicator_style
!= none
1753 || print_with_color
)
1754 && stat (linkpath
, &linkstats
) == 0)
1756 files
[files_index
].linkok
= 1;
1758 /* Symbolic links to directories that are mentioned on the
1759 command line are automatically traced if not being
1761 if (explicit_arg
&& format
!= long_format
1762 && S_ISDIR (linkstats
.st_mode
))
1764 /* Substitute the linked-to directory's name, but
1765 save the real name in `linkname' for printing. */
1766 if (!immediate_dirs
)
1768 const char *tempname
= name
;
1770 linkpath
= files
[files_index
].linkname
;
1771 files
[files_index
].linkname
= (char *) tempname
;
1773 files
[files_index
].stat
= linkstats
;
1777 /* Get the linked-to file's mode for the filetype indicator
1778 in long listings. */
1779 files
[files_index
].linkmode
= linkstats
.st_mode
;
1780 files
[files_index
].linkok
= 1;
1787 if (S_ISLNK (files
[files_index
].stat
.st_mode
))
1788 files
[files_index
].filetype
= symbolic_link
;
1789 else if (S_ISDIR (files
[files_index
].stat
.st_mode
))
1791 if (explicit_arg
&& !immediate_dirs
)
1792 files
[files_index
].filetype
= arg_directory
;
1794 files
[files_index
].filetype
= directory
;
1797 files
[files_index
].filetype
= normal
;
1799 blocks
= ST_NBLOCKS (files
[files_index
].stat
);
1801 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1802 int len
= strlen (human_readable (blocks
, buf
, ST_NBLOCKSIZE
,
1803 output_block_size
));
1804 if (block_size_size
< len
)
1805 block_size_size
= len
< 7 ? len
: 7;
1811 files
[files_index
].name
= xstrdup (name
);
1819 /* Put the name of the file that `filename' is a symbolic link to
1820 into the `linkname' field of `f'. */
1823 get_link_name (const char *filename
, struct fileinfo
*f
)
1826 register int linksize
;
1828 linkbuf
= (char *) alloca (PATH_MAX
+ 2);
1829 /* Some automounters give incorrect st_size for mount points.
1830 I can't think of a good workaround for it, though. */
1831 linksize
= readlink (filename
, linkbuf
, PATH_MAX
+ 1);
1834 error (0, errno
, "%s", quotearg_colon (filename
));
1839 linkbuf
[linksize
] = '\0';
1840 f
->linkname
= xstrdup (linkbuf
);
1844 /* If `linkname' is a relative path and `path' contains one or more
1845 leading directories, return `linkname' with those directories
1846 prepended; otherwise, return a copy of `linkname'.
1847 If `linkname' is zero, return zero. */
1850 make_link_path (const char *path
, const char *linkname
)
1858 if (*linkname
== '/')
1859 return xstrdup (linkname
);
1861 /* The link is to a relative path. Prepend any leading path
1862 in `path' to the link name. */
1863 linkbuf
= strrchr (path
, '/');
1865 return xstrdup (linkname
);
1867 bufsiz
= linkbuf
- path
+ 1;
1868 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
1869 strncpy (linkbuf
, path
, bufsiz
);
1870 strcpy (linkbuf
+ bufsiz
, linkname
);
1875 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1876 This is so we don't try to recurse on `././././. ...' */
1879 basename_is_dot_or_dotdot (const char *name
)
1881 char *base
= base_name (name
);
1882 return DOT_OR_DOTDOT (base
);
1885 /* Remove any entries from `files' that are for directories,
1886 and queue them to be listed as directories instead.
1887 `dirname' is the prefix to prepend to each dirname
1888 to make it correct relative to ls's working dir.
1889 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1890 This is desirable when processing directories recursively. */
1893 extract_dirs_from_files (const char *dirname
, int recursive
)
1898 dirlen
= strlen (dirname
) + 2;
1899 /* Queue the directories last one first, because queueing reverses the
1901 for (i
= files_index
- 1; i
>= 0; i
--)
1902 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
1903 && (!recursive
|| !basename_is_dot_or_dotdot (files
[i
].name
)))
1905 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
1907 queue_directory (files
[i
].name
, files
[i
].linkname
);
1911 char *path
= path_concat (dirname
, files
[i
].name
, NULL
);
1912 queue_directory (path
, files
[i
].linkname
);
1915 if (files
[i
].filetype
== arg_directory
)
1916 free (files
[i
].name
);
1919 /* Now delete the directories from the table, compacting all the remaining
1922 for (i
= 0, j
= 0; i
< files_index
; i
++)
1923 if (files
[i
].filetype
!= arg_directory
)
1924 files
[j
++] = files
[i
];
1928 /* Sort the files now in the table. */
1943 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
1946 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
1949 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
1956 func
= sort_reverse
? rev_cmp_name
: compare_name
;
1958 case sort_extension
:
1959 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
1962 func
= sort_reverse
? rev_cmp_size
: compare_size
;
1965 func
= sort_reverse
? rev_cmp_version
: compare_version
;
1971 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
1974 /* Comparison routines for sorting the files. */
1977 compare_ctime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1979 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
1981 diff
= strcmp (file1
->name
, file2
->name
);
1986 rev_cmp_ctime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1988 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
1990 diff
= strcmp (file1
->name
, file2
->name
);
1995 compare_mtime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1997 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
1999 diff
= strcmp (file1
->name
, file2
->name
);
2004 rev_cmp_mtime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2006 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
2008 diff
= strcmp (file1
->name
, file2
->name
);
2013 compare_atime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2015 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2017 diff
= strcmp (file1
->name
, file2
->name
);
2022 rev_cmp_atime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2024 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2026 diff
= strcmp (file1
->name
, file2
->name
);
2031 compare_size (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2033 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2035 diff
= strcmp (file1
->name
, file2
->name
);
2040 rev_cmp_size (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2042 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2044 diff
= strcmp (file1
->name
, file2
->name
);
2049 compare_version (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2051 return strverscmp (file1
->name
, file2
->name
);
2055 rev_cmp_version (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2057 return strverscmp (file1
->name
, file2
->name
);
2061 compare_name (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2063 return strcmp (file1
->name
, file2
->name
);
2067 rev_cmp_name (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2069 return strcmp (file1
->name
, file2
->name
);
2072 /* Compare file extensions. Files with no extension are `smallest'.
2073 If extensions are the same, compare by filenames instead. */
2076 compare_extension (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2078 register char *base1
, *base2
;
2081 base1
= strrchr (file1
->name
, '.');
2082 base2
= strrchr (file2
->name
, '.');
2083 if (base1
== 0 && base2
== 0)
2084 return strcmp (file1
->name
, file2
->name
);
2089 cmp
= strcmp (base1
, base2
);
2091 return strcmp (file1
->name
, file2
->name
);
2096 rev_cmp_extension (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2098 register char *base1
, *base2
;
2101 base1
= strrchr (file1
->name
, '.');
2102 base2
= strrchr (file2
->name
, '.');
2103 if (base1
== 0 && base2
== 0)
2104 return strcmp (file1
->name
, file2
->name
);
2109 cmp
= strcmp (base1
, base2
);
2111 return strcmp (file1
->name
, file2
->name
);
2115 /* List all the files now in the table. */
2118 print_current_files (void)
2125 for (i
= 0; i
< files_index
; i
++)
2127 print_file_name_and_frills (files
+ i
);
2133 init_column_info ();
2134 print_many_per_line ();
2138 init_column_info ();
2139 print_horizontal ();
2143 print_with_commas ();
2147 for (i
= 0; i
< files_index
; i
++)
2149 print_long_format (files
+ i
);
2150 DIRED_PUTCHAR ('\n');
2157 print_long_format (const struct fileinfo
*f
)
2161 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2162 1 10-byte mode string,
2163 1 24-byte time string (may be longer in some locales -- see below)
2164 or LONGEST_HUMAN_READABLE integer,
2165 9 spaces, one following each of these fields, and
2166 1 trailing NUL byte. */
2167 char init_bigbuf
[7 * LONGEST_HUMAN_READABLE
+ 10
2168 + (LONGEST_HUMAN_READABLE
< 24 ? 24 : LONGEST_HUMAN_READABLE
)
2170 char *buf
= init_bigbuf
;
2171 size_t bufsize
= sizeof (init_bigbuf
);
2175 struct tm
*when_local
;
2180 /* Cray DMF: look at the file's migrated, not real, status */
2181 mode_string (f
->stat
.st_dm_mode
, modebuf
);
2183 mode_string (f
->stat
.st_mode
, modebuf
);
2191 when
= f
->stat
.st_ctime
;
2194 when
= f
->stat
.st_mtime
;
2197 when
= f
->stat
.st_atime
;
2203 fmt
= "%a %b %d %H:%M:%S %Y";
2207 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
2208 || current_time
< when
- 60L * 60L) /* In the future. */
2210 /* The file is fairly old or in the future.
2211 POSIX says the cutoff is 6 months old;
2212 approximate this by 6*30 days.
2213 Allow a 1 hour slop factor for what is considered "the future",
2214 to allow for NFS server/client clock disagreement.
2215 Show the year instead of the time of day. */
2220 fmt
= "%b %e %H:%M";
2228 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2229 sprintf (p
, "%*s ", INODE_DIGITS
,
2230 human_readable ((uintmax_t) f
->stat
.st_ino
, hbuf
, 1, 1));
2234 if (print_block_size
)
2236 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2237 sprintf (p
, "%*s ", block_size_size
,
2238 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), hbuf
,
2239 ST_NBLOCKSIZE
, output_block_size
));
2243 /* The space between the mode and the number of links is the POSIX
2244 "optional alternate access method flag". */
2245 sprintf (p
, "%s %3u ", modebuf
, (unsigned int) f
->stat
.st_nlink
);
2248 user_name
= (numeric_ids
? NULL
: getuser (f
->stat
.st_uid
));
2250 sprintf (p
, "%-8.8s ", user_name
);
2252 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_uid
);
2257 char *group_name
= (numeric_ids
? NULL
: getgroup (f
->stat
.st_gid
));
2259 sprintf (p
, "%-8.8s ", group_name
);
2261 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_gid
);
2265 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2266 sprintf (p
, "%3u, %3u ", (unsigned) major (f
->stat
.st_rdev
),
2267 (unsigned) minor (f
->stat
.st_rdev
));
2270 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2272 human_readable ((uintmax_t) f
->stat
.st_size
, hbuf
, 1,
2273 output_block_size
< 0 ? output_block_size
: 1));
2278 /* Use strftime rather than ctime, because the former can produce
2279 locale-dependent names for the weekday (%a) and month (%b). */
2281 if ((when_local
= localtime (&when
)))
2283 while (! (s
= strftime (p
, buf
+ bufsize
- p
- 1, fmt
, when_local
)))
2285 char *newbuf
= (char *) alloca (bufsize
*= 2);
2286 memcpy (newbuf
, buf
, p
- buf
);
2287 p
= newbuf
+ (p
- buf
);
2294 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2299 /* The time cannot be represented as a local time;
2300 print it as a huge integer number of seconds. */
2301 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2302 int width
= full_time
? 24 : 12;
2306 const char *num
= human_readable (- (uintmax_t) when
, hbuf
, 1, 1);
2307 int sign_width
= width
- strlen (num
);
2308 sprintf (p
, "%*s%s ", sign_width
< 0 ? 0 : sign_width
, "-", num
);
2311 sprintf (p
, "%*s ", width
,
2312 human_readable ((uintmax_t) when
, hbuf
, 1, 1));
2318 DIRED_FPUTS (buf
, stdout
, p
- buf
);
2319 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
,
2322 if (f
->filetype
== symbolic_link
)
2326 DIRED_FPUTS_LITERAL (" -> ", stdout
);
2327 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
- 1,
2329 if (indicator_style
!= none
)
2330 print_type_indicator (f
->linkmode
);
2333 else if (indicator_style
!= none
)
2334 print_type_indicator (f
->stat
.st_mode
);
2337 /* Output to OUT a quoted representation of the file name P,
2338 using OPTIONS to control quoting.
2339 Return the number of characters in P's quoted representation. */
2342 quote_name (FILE *out
, const char *p
, struct quoting_options
const *options
)
2344 char smallbuf
[BUFSIZ
];
2345 size_t len
= quotearg_buffer (smallbuf
, sizeof smallbuf
, p
, -1, options
);
2348 if (len
< sizeof smallbuf
)
2352 buf
= (char *) alloca (len
+ 1);
2353 quotearg_buffer (buf
, len
+ 1, p
, -1, options
);
2356 if (qmark_funny_chars
)
2359 for (i
= 0; i
< len
; i
++)
2360 if (! ISPRINT ((unsigned char) buf
[i
]))
2364 fwrite (buf
, 1, len
, out
);
2369 print_name_with_quoting (const char *p
, unsigned int mode
, int linkok
,
2370 struct obstack
*stack
)
2372 if (print_with_color
)
2373 print_color_indicator (p
, mode
, linkok
);
2376 PUSH_CURRENT_DIRED_POS (stack
);
2378 dired_pos
+= quote_name (stdout
, p
, filename_quoting_options
);
2381 PUSH_CURRENT_DIRED_POS (stack
);
2383 if (print_with_color
)
2384 prep_non_filename_text ();
2388 prep_non_filename_text (void)
2390 if (color_indicator
[C_END
].string
!= NULL
)
2391 put_indicator (&color_indicator
[C_END
]);
2394 put_indicator (&color_indicator
[C_LEFT
]);
2395 put_indicator (&color_indicator
[C_NORM
]);
2396 put_indicator (&color_indicator
[C_RIGHT
]);
2400 /* Print the file name of `f' with appropriate quoting.
2401 Also print file size, inode number, and filetype indicator character,
2402 as requested by switches. */
2405 print_file_name_and_frills (const struct fileinfo
*f
)
2407 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2410 printf ("%*s ", INODE_DIGITS
,
2411 human_readable ((uintmax_t) f
->stat
.st_ino
, buf
, 1, 1));
2413 if (print_block_size
)
2414 printf ("%*s ", block_size_size
,
2415 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), buf
,
2416 ST_NBLOCKSIZE
, output_block_size
));
2418 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
, NULL
);
2420 if (indicator_style
!= none
)
2421 print_type_indicator (f
->stat
.st_mode
);
2425 print_type_indicator (unsigned int mode
)
2431 if (indicator_style
== classify
&& (mode
& S_IXUGO
))
2440 else if (S_ISLNK (mode
))
2442 else if (S_ISFIFO (mode
))
2444 else if (S_ISSOCK (mode
))
2446 else if (S_ISDOOR (mode
))
2457 print_color_indicator (const char *name
, unsigned int mode
, int linkok
)
2460 struct color_ext_type
*ext
; /* Color extension */
2461 size_t len
; /* Length of name */
2463 /* Is this a nonexistent file? If so, linkok == -1. */
2465 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
2474 else if (S_ISLNK (mode
))
2475 type
= ((!linkok
&& color_indicator
[C_ORPHAN
].string
)
2476 ? C_ORPHAN
: C_LINK
);
2477 else if (S_ISFIFO (mode
))
2479 else if (S_ISSOCK (mode
))
2481 else if (S_ISBLK (mode
))
2483 else if (S_ISCHR (mode
))
2485 else if (S_ISDOOR (mode
))
2488 if (type
== C_FILE
&& (mode
& S_IXUGO
) != 0)
2491 /* Check the file's suffix only if still classified as C_FILE. */
2495 /* Test if NAME has a recognized suffix. */
2497 len
= strlen (name
);
2498 name
+= len
; /* Pointer to final \0. */
2499 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
2501 if ((size_t) ext
->ext
.len
<= len
2502 && strncmp (name
- ext
->ext
.len
, ext
->ext
.string
,
2509 put_indicator (&color_indicator
[C_LEFT
]);
2510 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
2511 put_indicator (&color_indicator
[C_RIGHT
]);
2514 /* Output a color indicator (which may contain nulls). */
2516 put_indicator (const struct bin_str
*ind
)
2523 for (i
= ind
->len
; i
> 0; --i
)
2528 length_of_file_name_and_frills (const struct fileinfo
*f
)
2530 register int len
= 0;
2533 len
+= INODE_DIGITS
+ 1;
2535 if (print_block_size
)
2536 len
+= 1 + block_size_size
;
2538 len
+= quotearg_buffer (0, 0, f
->name
, -1, filename_quoting_options
);
2540 if (indicator_style
!= none
)
2542 unsigned filetype
= f
->stat
.st_mode
;
2544 if (S_ISREG (filetype
))
2546 if (indicator_style
== classify
2547 && (f
->stat
.st_mode
& S_IXUGO
))
2550 else if (S_ISDIR (filetype
)
2551 || S_ISLNK (filetype
)
2552 || S_ISFIFO (filetype
)
2553 || S_ISSOCK (filetype
)
2554 || S_ISDOOR (filetype
)
2563 print_many_per_line (void)
2565 struct column_info
*line_fmt
;
2566 int filesno
; /* Index into files. */
2567 int row
; /* Current row. */
2568 int max_name_length
; /* Length of longest file name + frills. */
2569 int name_length
; /* Length of each file name + frills. */
2570 int pos
; /* Current character column. */
2571 int cols
; /* Number of files across. */
2572 int rows
; /* Maximum number of files down. */
2575 /* Normally the maximum number of columns is determined by the
2576 screen width. But if few files are available this might limit it
2578 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2580 /* Compute the maximum number of possible columns. */
2581 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2585 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2587 for (i
= 0; i
< max_cols
; ++i
)
2589 if (column_info
[i
].valid_len
)
2591 int idx
= filesno
/ ((files_index
+ i
) / (i
+ 1));
2592 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2594 if (real_length
> column_info
[i
].col_arr
[idx
])
2596 column_info
[i
].line_len
+= (real_length
2597 - column_info
[i
].col_arr
[idx
]);
2598 column_info
[i
].col_arr
[idx
] = real_length
;
2599 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2605 /* Find maximum allowed columns. */
2606 for (cols
= max_cols
; cols
> 1; --cols
)
2608 if (column_info
[cols
- 1].valid_len
)
2612 line_fmt
= &column_info
[cols
- 1];
2614 /* Calculate the number of rows that will be in each column except possibly
2615 for a short column on the right. */
2616 rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
2618 for (row
= 0; row
< rows
; row
++)
2623 /* Print the next row. */
2626 print_file_name_and_frills (files
+ filesno
);
2627 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2628 max_name_length
= line_fmt
->col_arr
[col
++];
2631 if (filesno
>= files_index
)
2634 indent (pos
+ name_length
, pos
+ max_name_length
);
2635 pos
+= max_name_length
;
2642 print_horizontal (void)
2644 struct column_info
*line_fmt
;
2646 int max_name_length
;
2652 /* Normally the maximum number of columns is determined by the
2653 screen width. But if few files are available this might limit it
2655 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2657 /* Compute the maximum file name length. */
2658 max_name_length
= 0;
2659 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2663 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2665 for (i
= 0; i
< max_cols
; ++i
)
2667 if (column_info
[i
].valid_len
)
2669 int idx
= filesno
% (i
+ 1);
2670 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2672 if (real_length
> column_info
[i
].col_arr
[idx
])
2674 column_info
[i
].line_len
+= (real_length
2675 - column_info
[i
].col_arr
[idx
]);
2676 column_info
[i
].col_arr
[idx
] = real_length
;
2677 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2683 /* Find maximum allowed columns. */
2684 for (cols
= max_cols
; cols
> 1; --cols
)
2686 if (column_info
[cols
- 1].valid_len
)
2690 line_fmt
= &column_info
[cols
- 1];
2694 /* Print first entry. */
2695 print_file_name_and_frills (files
);
2696 name_length
= length_of_file_name_and_frills (files
);
2697 max_name_length
= line_fmt
->col_arr
[0];
2700 for (filesno
= 1; filesno
< files_index
; ++filesno
)
2702 int col
= filesno
% cols
;
2711 indent (pos
+ name_length
, pos
+ max_name_length
);
2712 pos
+= max_name_length
;
2715 print_file_name_and_frills (files
+ filesno
);
2717 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2718 max_name_length
= line_fmt
->col_arr
[col
];
2724 print_with_commas (void)
2731 for (filesno
= 0; filesno
< files_index
; filesno
++)
2735 pos
+= length_of_file_name_and_frills (files
+ filesno
);
2736 if (filesno
+ 1 < files_index
)
2737 pos
+= 2; /* For the comma and space */
2739 if (old_pos
!= 0 && pos
>= line_length
)
2745 print_file_name_and_frills (files
+ filesno
);
2746 if (filesno
+ 1 < files_index
)
2755 /* Assuming cursor is at position FROM, indent up to position TO.
2756 Use a TAB character instead of two or more spaces whenever possible. */
2759 indent (int from
, int to
)
2763 if (tabsize
> 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
2766 from
+= tabsize
- from
% tabsize
;
2776 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2777 /* FIXME: maybe remove this function someday. See about using a
2778 non-malloc'ing version of path_concat. */
2781 attach (char *dest
, const char *dirname
, const char *name
)
2783 const char *dirnamep
= dirname
;
2785 /* Copy dirname if it is not ".". */
2786 if (dirname
[0] != '.' || dirname
[1] != 0)
2789 *dest
++ = *dirnamep
++;
2790 /* Add '/' if `dirname' doesn't already end with it. */
2791 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
2800 init_column_info (void)
2805 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2809 if (column_info
== NULL
)
2811 column_info
= (struct column_info
*) xmalloc (max_idx
2812 * sizeof (struct column_info
));
2816 for (i
= 0; i
< max_idx
; ++i
)
2820 column_info
[i
].valid_len
= 1;
2821 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
2824 column_info
[i
].col_arr
= (int *) xmalloc ((i
+ 1) * sizeof (int));
2826 for (j
= 0; j
<= i
; ++j
)
2827 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
2835 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2839 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
2841 List information about the FILEs (the current directory by default).\n\
2842 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2844 -a, --all do not hide entries starting with .\n\
2845 -A, --almost-all do not list implied . and ..\n\
2846 -b, --escape print octal escapes for nongraphic characters\n\
2847 --block-size=SIZE use SIZE-byte blocks\n\
2848 -B, --ignore-backups do not list implied entries ending with ~\n\
2849 -c sort by change time; with -l: show ctime\n\
2850 -C list entries by columns\n\
2851 --color[=WHEN] control whether color is used to distinguish file\n\
2852 types. WHEN may be `never', `always', or `auto'\n\
2853 -d, --directory list directory entries instead of contents\n\
2854 -D, --dired generate output designed for Emacs' dired mode\n\
2855 -f do not sort, enable -aU, disable -lst\n\
2856 -F, --classify append indicator (one of */=@|) to entries\n\
2857 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2858 single-column -1, verbose -l, vertical -C\n\
2859 --full-time list both full date and full time\n"));
2863 -G, --no-group inhibit display of group information\n\
2864 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2865 -H, --si likewise, but use powers of 1000 not 1024\n\
2866 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2867 none (default), classify (-F), file-type (-p)\n\
2868 -i, --inode print index number of each file\n\
2869 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2870 -k, --kilobytes like --block-size=1024\n\
2871 -l use a long listing format\n\
2872 -L, --dereference list entries pointed to by symbolic links\n\
2873 -m fill width with a comma separated list of entries\n\
2874 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2875 -N, --literal print raw entry names (don't treat e.g. control\n\
2876 characters specially)\n\
2877 -o use long listing format without group info\n\
2878 -p, --file-type append indicator (one of /=@|) to entries\n\
2879 -q, --hide-control-chars print ? instead of non graphic characters\n\
2880 --show-control-chars show non graphic characters as-is (default)\n\
2881 -Q, --quote-name enclose entry names in double quotes\n\
2882 --quoting-style=WORD use quoting style WORD for entry names:\n\
2883 literal, shell, shell-always, c, escape\n\
2884 -r, --reverse reverse order while sorting\n\
2885 -R, --recursive list subdirectories recursively\n\
2886 -s, --size print size of each file, in blocks\n"));
2889 -S sort by file size\n\
2890 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2892 status -c, time -t, atime -u, access -u, use -u\n\
2893 --time=WORD show time as WORD instead of modification time:\n\
2894 atime, access, use, ctime or status; use\n\
2895 specified time as sort key if --sort=time\n\
2896 -t sort by modification time\n\
2897 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2898 -u sort by last access time; with -l: show atime\n\
2899 -U do not sort; list entries in directory order\n\
2900 -v sort by version\n\
2901 -w, --width=COLS assume screen width instead of current value\n\
2902 -x list entries by lines instead of by columns\n\
2903 -X sort alphabetically by entry extension\n\
2904 -1 list one file per line\n\
2905 --help display this help and exit\n\
2906 --version output version information and exit\n\
2908 By default, color is not used to distinguish types of files. That is\n\
2909 equivalent to using --color=none. Using the --color option without the\n\
2910 optional WHEN argument is equivalent to using --color=always. With\n\
2911 --color=auto, color codes are output only if standard output is connected\n\
2912 to a terminal (tty).\n\
2914 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));