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>
58 #ifdef WINSIZE_IN_PTEM
59 # include <sys/stream.h>
60 # include <sys/ptem.h>
77 #include "path-concat.h"
79 #include "strverscmp.h"
82 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
83 : (ls_mode == LS_MULTI_COL \
86 #define AUTHORS "Richard Stallman and David MacKenzie"
88 #define obstack_chunk_alloc malloc
89 #define obstack_chunk_free free
91 /* Return an int indicating the result of comparing two integers.
92 Subtracting doesn't always work, due to overflow. */
93 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
95 /* The field width for inode numbers. On some hosts inode numbers are
96 64 bits, so columns won't line up exactly when a huge inode number
97 is encountered, but in practice 7 digits is usually enough. */
99 # define INODE_DIGITS 7
103 # define HAVE_SYMLINKS 1
105 # define HAVE_SYMLINKS 0
108 /* If any of the S_* macros are undefined, define them here so each
109 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
111 # define S_ISLNK(Mode) 0
115 # define S_ISFIFO(Mode) 0
119 # define S_ISSOCK(Mode) 0
123 # define S_ISCHR(Mode) 0
127 # define S_ISBLK(Mode) 0
131 # define S_ISDOOR(Mode) 0
138 arg_directory
, /* Directory given as command line arg. */
139 normal
/* All others. */
149 /* For symbolic link, name of the file linked to, otherwise zero. */
152 /* For symbolic link and long listing, st_mode of file linked to, otherwise
154 unsigned int linkmode
;
156 /* For symbolic link and color printing, 1 if linked-to file
157 exists, otherwise 0. */
160 enum filetype filetype
;
163 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
165 /* Null is a valid character in a color indicator (think about Epson
166 printers, for example) so we have to use a length/buffer string
171 int len
; /* Number of bytes */
172 char *string
; /* Pointer to the same */
181 void strip_trailing_slashes ();
184 static size_t quote_name
PARAMS ((FILE *out
, const char *name
,
185 struct quoting_options
const *options
));
186 static char *make_link_path
PARAMS ((const char *path
, const char *linkname
));
187 static int compare_atime
PARAMS ((const struct fileinfo
*file1
,
188 const struct fileinfo
*file2
));
189 static int rev_cmp_atime
PARAMS ((const struct fileinfo
*file2
,
190 const struct fileinfo
*file1
));
191 static int compare_ctime
PARAMS ((const struct fileinfo
*file1
,
192 const struct fileinfo
*file2
));
193 static int rev_cmp_ctime
PARAMS ((const struct fileinfo
*file2
,
194 const struct fileinfo
*file1
));
195 static int compare_mtime
PARAMS ((const struct fileinfo
*file1
,
196 const struct fileinfo
*file2
));
197 static int rev_cmp_mtime
PARAMS ((const struct fileinfo
*file2
,
198 const struct fileinfo
*file1
));
199 static int compare_size
PARAMS ((const struct fileinfo
*file1
,
200 const struct fileinfo
*file2
));
201 static int rev_cmp_size
PARAMS ((const struct fileinfo
*file2
,
202 const struct fileinfo
*file1
));
203 static int compare_name
PARAMS ((const struct fileinfo
*file1
,
204 const struct fileinfo
*file2
));
205 static int rev_cmp_name
PARAMS ((const struct fileinfo
*file2
,
206 const struct fileinfo
*file1
));
207 static int compare_extension
PARAMS ((const struct fileinfo
*file1
,
208 const struct fileinfo
*file2
));
209 static int rev_cmp_extension
PARAMS ((const struct fileinfo
*file2
,
210 const struct fileinfo
*file1
));
211 static int compare_version
PARAMS ((const struct fileinfo
*file1
,
212 const struct fileinfo
*file2
));
213 static int rev_cmp_version
PARAMS ((const struct fileinfo
*file2
,
214 const struct fileinfo
*file1
));
215 static int decode_switches
PARAMS ((int argc
, char **argv
));
216 static int file_interesting
PARAMS ((const struct dirent
*next
));
217 static uintmax_t gobble_file
PARAMS ((const char *name
, int explicit_arg
,
218 const char *dirname
));
219 static void print_color_indicator
PARAMS ((const char *name
, unsigned int mode
,
221 static void put_indicator
PARAMS ((const struct bin_str
*ind
));
222 static int length_of_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
223 static void add_ignore_pattern
PARAMS ((const char *pattern
));
224 static void attach
PARAMS ((char *dest
, const char *dirname
, const char *name
));
225 static void clear_files
PARAMS ((void));
226 static void extract_dirs_from_files
PARAMS ((const char *dirname
,
228 static void get_link_name
PARAMS ((const char *filename
, struct fileinfo
*f
));
229 static void indent
PARAMS ((int from
, int to
));
230 static void init_column_info
PARAMS ((void));
231 static void print_current_files
PARAMS ((void));
232 static void print_dir
PARAMS ((const char *name
, const char *realname
));
233 static void print_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
234 static void print_horizontal
PARAMS ((void));
235 static void print_long_format
PARAMS ((const struct fileinfo
*f
));
236 static void print_many_per_line
PARAMS ((void));
237 static void print_name_with_quoting
PARAMS ((const char *p
, unsigned int mode
,
239 struct obstack
*stack
));
240 static void prep_non_filename_text
PARAMS ((void));
241 static void print_type_indicator
PARAMS ((unsigned int mode
));
242 static void print_with_commas
PARAMS ((void));
243 static void queue_directory
PARAMS ((const char *name
, const char *realname
));
244 static void sort_files
PARAMS ((void));
245 static void parse_ls_color
PARAMS ((void));
246 void usage
PARAMS ((int status
));
248 /* The name the program was run with, stripped of any leading path. */
251 /* The table of files in the current directory:
253 `files' points to a vector of `struct fileinfo', one per file.
254 `nfiles' is the number of elements space has been allocated for.
255 `files_index' is the number actually in use. */
257 /* Address of block containing the files that are described. */
259 static struct fileinfo
*files
;
261 /* Length of block that `files' points to, measured in files. */
265 /* Index of first unused in `files'. */
267 static int files_index
;
269 /* Record of one pending directory waiting to be listed. */
274 /* If the directory is actually the file pointed to by a symbolic link we
275 were told to list, `realname' will contain the name of the symbolic
276 link, otherwise zero. */
278 struct pending
*next
;
281 static struct pending
*pending_dirs
;
283 /* Current time (seconds since 1970). When we are printing a file's time,
284 include the year if it is more than 6 months before this time. */
286 static time_t current_time
;
288 /* The number of digits to use for block sizes.
289 4, or more if needed for bigger numbers. */
291 static int block_size_size
;
295 /* long_format for lots of info, one per line.
296 one_per_line for just names, one per line.
297 many_per_line for just names, many per line, sorted vertically.
298 horizontal for just names, many per line, sorted horizontally.
299 with_commas for just names, many per line, separated by commas.
301 -l, -1, -C, -x and -m control this parameter. */
305 long_format
, /* -l */
306 one_per_line
, /* -1 */
307 many_per_line
, /* -C */
312 static enum format format
;
314 /* Type of time to print or sort by. Controlled by -c and -u. */
318 time_mtime
, /* default */
323 static enum time_type time_type
;
325 /* print the full time, otherwise the standard unix heuristics. */
327 static int full_time
;
329 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
334 sort_name
, /* default */
335 sort_extension
, /* -X */
338 sort_version
/* -v */
341 static enum sort_type sort_type
;
343 /* Direction of sort.
344 0 means highest first if numeric,
345 lowest first if alphabetic;
346 these are the defaults.
347 1 means the opposite order in each case. -r */
349 static int sort_reverse
;
351 /* Nonzero means to NOT display group information. -G */
353 static int inhibit_group
;
355 /* Nonzero means print the user and group id's as numbers rather
358 static int numeric_ids
;
360 /* Nonzero means mention the size in blocks of each file. -s */
362 static int print_block_size
;
364 /* If positive, the units to use when printing sizes;
365 if negative, the human-readable base. */
366 static int output_block_size
;
368 /* Precede each line of long output (per file) with a string like `m,n:'
369 where M is the number of characters after the `:' and before the
370 filename and N is the length of the filename. Using this format,
371 Emacs' dired mode starts up twice as fast, and can handle all
372 strange characters in file names. */
375 /* `none' means don't mention the type of files.
376 `classify' means mention file types and mark executables.
377 `file_type' means mention only file types.
379 Controlled by -F, -p, and --indicator-style. */
383 none
, /* --indicator-style=none */
384 classify
, /* -F, --indicator-style=classify */
385 file_type
/* -p, --indicator-style=file-type */
388 static enum indicator_style indicator_style
;
390 /* Names of indicator styles. */
391 static char const *const indicator_style_args
[] =
393 "none", "classify", "file-type", 0
396 static enum indicator_style
const indicator_style_types
[]=
398 none
, classify
, file_type
401 /* Nonzero means use colors to mark types. Also define the different
402 colors as well as the stuff for the LS_COLORS environment variable.
403 The LS_COLORS variable is now in a termcap-like format. */
405 static int print_with_color
;
409 color_never
, /* 0: default or --color=never */
410 color_always
, /* 1: --color=always */
411 color_if_tty
/* 2: --color=tty */
416 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
417 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
420 static const char *const indicator_name
[]=
422 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
423 "bd", "cd", "mi", "or", "ex", "do", NULL
426 struct color_ext_type
428 struct bin_str ext
; /* The extension we're looking for */
429 struct bin_str seq
; /* The sequence to output when we do */
430 struct color_ext_type
*next
; /* Next in list */
433 static struct bin_str color_indicator
[] =
435 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
436 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
437 { 0, NULL
}, /* ec: End color (replaces lc+no+rc) */
438 { LEN_STR_PAIR ("0") }, /* no: Normal */
439 { LEN_STR_PAIR ("0") }, /* fi: File: default */
440 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
441 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
442 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
443 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
444 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
445 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
446 { 0, NULL
}, /* mi: Missing file: undefined */
447 { 0, NULL
}, /* or: Orphanned symlink: undefined */
448 { LEN_STR_PAIR ("01;32") } /* ex: Executable: bright green */
452 static struct color_ext_type
*color_ext_list
= NULL
;
454 /* Buffer for color sequences */
455 static char *color_buf
;
457 /* Nonzero means mention the inode number of each file. -i */
459 static int print_inode
;
461 /* Nonzero means when a symbolic link is found, display info on
462 the file linked to. -L */
464 static int trace_links
;
466 /* Nonzero means when a directory is found, display info on its
469 static int trace_dirs
;
471 /* Nonzero means when an argument is a directory name, display info
474 static int immediate_dirs
;
476 /* Nonzero means don't omit files whose names start with `.'. -A */
478 static int all_files
;
480 /* Nonzero means don't omit files `.' and `..'
481 This flag implies `all_files'. -a */
483 static int really_all_files
;
485 /* A linked list of shell-style globbing patterns. If a non-argument
486 file name matches any of these patterns, it is omitted.
487 Controlled by -I. Multiple -I options accumulate.
488 The -B option adds `*~' and `.*~' to this list. */
490 struct ignore_pattern
493 struct ignore_pattern
*next
;
496 static struct ignore_pattern
*ignore_patterns
;
498 /* Nonzero means output nongraphic chars in file names as `?'.
499 (-q, --hide-control-chars)
500 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
501 independent. The algorithm is: first, obey the quoting style to get a
502 string representing the file name; then, if qmark_funny_chars is set,
503 replace all nonprintable chars in that string with `?'. It's necessary
504 to replace nonprintable chars even in quoted strings, because we don't
505 want to mess up the terminal if control chars get sent to it, and some
506 quoting methods pass through control chars as-is. */
507 static int qmark_funny_chars
;
509 /* Quoting options for file and dir name output. */
511 static struct quoting_options
*filename_quoting_options
;
512 static struct quoting_options
*dirname_quoting_options
;
514 /* The number of chars per hardware tab stop. Setting this to zero
515 inhibits the use of TAB characters for separating columns. -T */
518 /* Nonzero means we are listing the working directory because no
519 non-option arguments were given. */
521 static int dir_defaulted
;
523 /* Nonzero means print each directory name before listing it. */
525 static int print_dir_name
;
527 /* The line length to use for breaking lines in many-per-line format.
528 Can be set with -w. */
530 static int line_length
;
532 /* If nonzero, the file listing format requires that stat be called on
535 static int format_needs_stat
;
537 /* The exit status to use if we don't get any fatal errors. */
539 static int exit_status
;
541 static struct option
const long_options
[] =
543 {"all", no_argument
, 0, 'a'},
544 {"escape", no_argument
, 0, 'b'},
545 {"directory", no_argument
, 0, 'd'},
546 {"dired", no_argument
, 0, 'D'},
547 {"full-time", no_argument
, &full_time
, 1},
548 {"human-readable", no_argument
, 0, 'h'},
549 {"inode", no_argument
, 0, 'i'},
550 {"kilobytes", no_argument
, 0, 'k'},
551 {"numeric-uid-gid", no_argument
, 0, 'n'},
552 {"no-group", no_argument
, 0, 'G'},
553 {"hide-control-chars", no_argument
, 0, 'q'},
554 {"reverse", no_argument
, 0, 'r'},
555 {"size", no_argument
, 0, 's'},
556 {"width", required_argument
, 0, 'w'},
557 {"almost-all", no_argument
, 0, 'A'},
558 {"ignore-backups", no_argument
, 0, 'B'},
559 {"classify", no_argument
, 0, 'F'},
560 {"file-type", no_argument
, 0, 'F'},
561 {"si", no_argument
, 0, 'H'},
562 {"ignore", required_argument
, 0, 'I'},
563 {"indicator-style", required_argument
, 0, 14},
564 {"dereference", no_argument
, 0, 'L'},
565 {"literal", no_argument
, 0, 'N'},
566 {"quote-name", no_argument
, 0, 'Q'},
567 {"quoting-style", required_argument
, 0, 15},
568 {"recursive", no_argument
, 0, 'R'},
569 {"format", required_argument
, 0, 12},
570 {"show-control-chars", no_argument
, 0, 16},
571 {"sort", required_argument
, 0, 10},
572 {"tabsize", required_argument
, 0, 'T'},
573 {"time", required_argument
, 0, 11},
574 {"color", optional_argument
, 0, 13},
575 {"block-size", required_argument
, 0, 17},
576 {GETOPT_HELP_OPTION_DECL
},
577 {GETOPT_VERSION_OPTION_DECL
},
581 static char const *const format_args
[] =
583 "verbose", "long", "commas", "horizontal", "across",
584 "vertical", "single-column", 0
587 static enum format
const format_types
[] =
589 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
590 many_per_line
, one_per_line
593 static char const *const sort_args
[] =
595 "none", "time", "size", "extension", "version", 0
598 static enum sort_type
const sort_types
[] =
600 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
603 static char const *const time_args
[] =
605 "atime", "access", "use", "ctime", "status", 0
608 static enum time_type
const time_types
[] =
610 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
613 static char const *const color_args
[] =
615 /* force and none are for compatibility with another color-ls version */
616 "always", "yes", "force",
617 "never", "no", "none",
618 "auto", "tty", "if-tty", 0
621 static enum color_type
const color_types
[] =
623 color_always
, color_always
, color_always
,
624 color_never
, color_never
, color_never
,
625 color_if_tty
, color_if_tty
, color_if_tty
628 /* Information about filling a column. */
636 /* Array with information about column filledness. */
637 static struct column_info
*column_info
;
639 /* Maximum number of columns ever possible for this display. */
642 /* The minimum width of a colum is 3: 1 character for the name and 2
643 for the separating white space. */
644 #define MIN_COLUMN_WIDTH 3
647 /* This zero-based index is used solely with the --dired option.
648 When that option is in effect, this counter is incremented for each
649 character of output generated by this program so that the beginning
650 and ending indices (in that output) of every file name can be recorded
651 and later output themselves. */
652 static size_t dired_pos
;
654 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
656 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
657 #define DIRED_FPUTS(s, stream, s_len) \
658 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
660 /* Like DIRED_FPUTS, but for use when S is a literal string. */
661 #define DIRED_FPUTS_LITERAL(s, stream) \
662 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
664 #define DIRED_INDENT() \
667 /* FIXME: remove the `&& format == long_format' clause. */ \
668 if (dired && format == long_format) \
669 DIRED_FPUTS_LITERAL (" ", stdout); \
673 /* With --dired, store pairs of beginning and ending indices of filenames. */
674 static struct obstack dired_obstack
;
676 /* With --dired, store pairs of beginning and ending indices of any
677 directory names that appear as headers (just before `total' line)
678 for lists of directory entries. Such directory names are seen when
679 listing hierarchies using -R and when a directory is listed with at
680 least one other command line argument. */
681 static struct obstack subdired_obstack
;
683 /* Save the current index on the specified obstack, OBS. */
684 #define PUSH_CURRENT_DIRED_POS(obs) \
687 /* FIXME: remove the `&& format == long_format' clause. */ \
688 if (dired && format == long_format) \
689 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
694 /* Write to standard output PREFIX, followed by the quoting style and
695 a space-separated list of the integers stored in OS all on one line. */
698 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
702 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
708 pos
= (size_t *) obstack_finish (os
);
709 fputs (prefix
, stdout
);
710 for (i
= 0; i
< n_pos
; i
++)
711 printf (" %d", (int) pos
[i
]);
712 fputs ("\n", stdout
);
717 main (int argc
, char **argv
)
720 register struct pending
*thispend
;
722 program_name
= argv
[0];
723 setlocale (LC_ALL
, "");
724 bindtextdomain (PACKAGE
, LOCALEDIR
);
725 textdomain (PACKAGE
);
731 current_time
= time ((time_t *) 0);
733 i
= decode_switches (argc
, argv
);
735 if (print_with_color
)
738 prep_non_filename_text ();
741 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
742 || format
== long_format
743 || trace_links
|| trace_dirs
|| indicator_style
!= none
744 || print_block_size
|| print_inode
|| print_with_color
;
746 if (dired
&& format
== long_format
)
748 obstack_init (&dired_obstack
);
749 obstack_init (&subdired_obstack
);
753 files
= (struct fileinfo
*) xmalloc (sizeof (struct fileinfo
) * nfiles
);
760 for (; i
< argc
; i
++)
762 strip_trailing_slashes (argv
[i
]);
763 gobble_file (argv
[i
], 1, "");
769 gobble_file (".", 1, "");
771 queue_directory (".", 0);
778 extract_dirs_from_files ("", 0);
779 /* `files_index' might be zero now. */
783 print_current_files ();
785 DIRED_PUTCHAR ('\n');
787 else if (pending_dirs
&& pending_dirs
->next
== 0)
792 thispend
= pending_dirs
;
793 pending_dirs
= pending_dirs
->next
;
794 print_dir (thispend
->name
, thispend
->realname
);
795 free (thispend
->name
);
796 if (thispend
->realname
)
797 free (thispend
->realname
);
802 if (dired
&& format
== long_format
)
804 /* No need to free these since we're about to exit. */
805 dired_dump_obstack ("//DIRED//", &dired_obstack
);
806 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
807 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
808 ARGMATCH_TO_ARGUMENT (filename_quoting_options
,
809 quoting_style_args
, quoting_style_vals
));
812 /* Restore default color before exiting */
813 if (print_with_color
)
815 put_indicator (&color_indicator
[C_LEFT
]);
816 put_indicator (&color_indicator
[C_RIGHT
]);
823 /* Set all the option flags according to the switches specified.
824 Return the index of the first non-option argument. */
827 decode_switches (int argc
, char **argv
)
829 register char const *p
;
834 qmark_funny_chars
= 0;
836 /* initialize all switches to default settings */
841 /* This is for the `dir' program. */
842 format
= many_per_line
;
843 set_quoting_style (NULL
, escape_quoting_style
);
847 /* This is for the `vdir' program. */
848 format
= long_format
;
849 set_quoting_style (NULL
, escape_quoting_style
);
853 /* This is for the `ls' program. */
856 format
= many_per_line
;
857 /* See description of qmark_funny_chars, above. */
858 qmark_funny_chars
= 1;
862 format
= one_per_line
;
863 qmark_funny_chars
= 0;
871 time_type
= time_mtime
;
873 sort_type
= sort_name
;
876 print_block_size
= 0;
877 indicator_style
= none
;
883 really_all_files
= 0;
886 /* FIXME: Shouldn't we complain on wrong values? */
887 if ((p
= getenv ("QUOTING_STYLE"))
888 && 0 <= (i
= ARGCASEMATCH (p
, quoting_style_args
, quoting_style_vals
)))
889 set_quoting_style (NULL
, quoting_style_vals
[i
]);
891 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size
);
894 if ((p
= getenv ("COLUMNS")) && *p
)
896 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
897 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
899 line_length
= (int) tmp_long
;
904 _("ignoring invalid width in environment variable COLUMNS: %s"),
913 if (ioctl (1, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
!= 0)
914 line_length
= ws
.ws_col
;
918 /* Using the TABSIZE environment variable is not POSIX-approved.
919 Ignore it when POSIXLY_CORRECT is set. */
921 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
923 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
924 && 0 <= tmp_long
&& tmp_long
<= INT_MAX
)
926 tabsize
= (int) tmp_long
;
931 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
936 while ((c
= getopt_long (argc
, argv
,
937 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
938 long_options
, NULL
)) != -1)
947 really_all_files
= 1;
951 set_quoting_style (NULL
, escape_quoting_style
);
955 time_type
= time_ctime
;
956 sort_type
= sort_time
;
964 /* Same as enabling -a -U and disabling -l -s. */
966 really_all_files
= 1;
967 sort_type
= sort_none
;
969 if (format
== long_format
)
970 format
= (isatty (1) ? many_per_line
: one_per_line
);
971 print_block_size
= 0; /* disable -s */
972 print_with_color
= 0; /* disable --color */
976 /* No effect. For BSD compatibility. */
980 output_block_size
= -1024;
984 output_block_size
= -1000;
992 output_block_size
= 1024;
996 format
= long_format
;
1000 format
= with_commas
;
1007 case 'o': /* Just like -l, but don't display group info. */
1008 format
= long_format
;
1013 indicator_style
= file_type
;
1017 qmark_funny_chars
= 1;
1025 print_block_size
= 1;
1029 sort_type
= sort_time
;
1033 sort_type
= sort_time
;
1034 time_type
= time_atime
;
1038 sort_type
= sort_version
;
1042 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1043 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1044 error (EXIT_FAILURE
, 0, _("invalid line width: %s"),
1046 line_length
= (int) tmp_long
;
1050 format
= horizontal
;
1054 really_all_files
= 0;
1059 add_ignore_pattern ("*~");
1060 add_ignore_pattern (".*~");
1064 format
= many_per_line
;
1072 indicator_style
= classify
;
1075 case 'G': /* inhibit display of group info */
1080 add_ignore_pattern (optarg
);
1088 set_quoting_style (NULL
, literal_quoting_style
);
1092 set_quoting_style (NULL
, c_quoting_style
);
1100 sort_type
= sort_size
;
1104 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1105 || tmp_long
< 0 || tmp_long
> INT_MAX
)
1106 error (EXIT_FAILURE
, 0, _("invalid tab size: %s"),
1108 tabsize
= (int) tmp_long
;
1112 sort_type
= sort_none
;
1116 sort_type
= sort_extension
;
1120 format
= one_per_line
;
1123 case 10: /* --sort */
1124 sort_type
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
1127 case 11: /* --time */
1128 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
1131 case 12: /* --format */
1132 format
= XARGMATCH ("--format", optarg
, format_args
, format_types
);
1135 case 13: /* --color */
1137 i
= XARGMATCH ("--color", optarg
, color_args
, color_types
);
1139 /* Using --color with no argument is equivalent to using
1143 print_with_color
= (i
== color_always
1144 || (i
== color_if_tty
1145 && isatty (STDOUT_FILENO
)));
1147 if (print_with_color
)
1149 /* Don't use TAB characters in output. Some terminal
1150 emulators can't handle the combination of tabs and
1151 color codes on the same line. */
1156 case 14: /* --indicator-style */
1157 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
1158 indicator_style_args
,
1159 indicator_style_types
);
1162 case 15: /* --quoting-style */
1163 set_quoting_style (NULL
,
1164 XARGMATCH ("--quoting-style", optarg
,
1166 quoting_style_vals
));
1170 qmark_funny_chars
= 0;
1174 human_block_size (optarg
, 1, &output_block_size
);
1177 case_GETOPT_HELP_CHAR
;
1179 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1182 usage (EXIT_FAILURE
);
1186 filename_quoting_options
= clone_quoting_options (NULL
);
1187 if (get_quoting_style (filename_quoting_options
) == escape_quoting_style
)
1188 set_char_quoting (filename_quoting_options
, ' ', 1);
1189 if (indicator_style
!= none
)
1190 for (p
= "*=@|" + (int) indicator_style
- 1; *p
; p
++)
1191 set_char_quoting (filename_quoting_options
, *p
, 1);
1193 dirname_quoting_options
= clone_quoting_options (NULL
);
1194 set_char_quoting (dirname_quoting_options
, ':', 1);
1199 /* Parse a string as part of the LS_COLORS variable; this may involve
1200 decoding all kinds of escape characters. If equals_end is set an
1201 unescaped equal sign ends the string, otherwise only a : or \0
1202 does. Returns the number of characters output, or -1 on failure.
1204 The resulting string is *not* null-terminated, but may contain
1207 Note that both dest and src are char **; on return they point to
1208 the first free byte after the array and the character that ended
1209 the input string, respectively. */
1212 get_funky_string (char **dest
, const char **src
, int equals_end
)
1214 int num
; /* For numerical codes */
1215 int count
; /* Something to count with */
1217 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1222 p
= *src
; /* We don't want to double-indirect */
1223 q
= *dest
; /* the whole darn time. */
1225 count
= 0; /* No characters counted in yet. */
1228 state
= ST_GND
; /* Start in ground state. */
1229 while (state
< ST_END
)
1233 case ST_GND
: /* Ground state (no escapes) */
1238 state
= ST_END
; /* End of string */
1241 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1245 state
= ST_CARET
; /* Caret escape */
1251 state
= ST_END
; /* End */
1254 /* else fall through */
1262 case ST_BACKSLASH
: /* Backslash escaped character */
1273 state
= ST_OCTAL
; /* Octal sequence */
1278 state
= ST_HEX
; /* Hex sequence */
1281 case 'a': /* Bell */
1282 num
= 7; /* Not all C compilers know what \a means */
1284 case 'b': /* Backspace */
1287 case 'e': /* Escape */
1290 case 'f': /* Form feed */
1293 case 'n': /* Newline */
1296 case 'r': /* Carriage return */
1302 case 'v': /* Vtab */
1305 case '?': /* Delete */
1308 case '_': /* Space */
1311 case '\0': /* End of string */
1312 state
= ST_ERROR
; /* Error! */
1314 default: /* Escaped character like \ ^ : = */
1318 if (state
== ST_BACKSLASH
)
1327 case ST_OCTAL
: /* Octal sequence */
1328 if (*p
< '0' || *p
> '7')
1335 num
= (num
<< 3) + (*(p
++) - '0');
1338 case ST_HEX
: /* Hex sequence */
1351 num
= (num
<< 4) + (*(p
++) - '0');
1359 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1367 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1377 case ST_CARET
: /* Caret escape */
1378 state
= ST_GND
; /* Should be the next state... */
1379 if (*p
>= '@' && *p
<= '~')
1381 *(q
++) = *(p
++) & 037;
1401 return state
== ST_ERROR
? -1 : count
;
1405 parse_ls_color (void)
1407 const char *p
; /* Pointer to character being parsed */
1408 char *buf
; /* color_buf buffer pointer */
1409 int state
; /* State of parser */
1410 int ind_no
; /* Indicator number */
1411 char label
[3]; /* Indicator label */
1412 struct color_ext_type
*ext
; /* Extension we are working on */
1414 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1418 strcpy (label
, "??");
1420 /* This is an overly conservative estimate, but any possible
1421 LS_COLORS string will *not* generate a color_buf longer than
1422 itself, so it is a safe way of allocating a buffer in
1424 buf
= color_buf
= xstrdup (p
);
1431 case 1: /* First label character */
1439 /* Allocate new extension block and add to head of
1440 linked list (this way a later definition will
1441 override an earlier one, which can be useful for
1442 having terminal-specific defs override global). */
1444 ext
= (struct color_ext_type
*)
1445 xmalloc (sizeof (struct color_ext_type
));
1446 ext
->next
= color_ext_list
;
1447 color_ext_list
= ext
;
1450 ext
->ext
.string
= buf
;
1452 state
= (ext
->ext
.len
=
1453 get_funky_string (&buf
, &p
, 1)) < 0 ? -1 : 4;
1457 state
= 0; /* Done! */
1460 default: /* Assume it is file type label */
1467 case 2: /* Second label character */
1474 state
= -1; /* Error */
1477 case 3: /* Equal sign after indicator label */
1478 state
= -1; /* Assume failure... */
1479 if (*(p
++) == '=')/* It *should* be... */
1481 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
1483 if (STREQ (label
, indicator_name
[ind_no
]))
1485 color_indicator
[ind_no
].string
= buf
;
1486 state
= ((color_indicator
[ind_no
].len
=
1487 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1);
1492 error (0, 0, _("unrecognized prefix: %s"), quotearg (label
));
1496 case 4: /* Equal sign after *.ext */
1499 ext
->seq
.string
= buf
;
1500 state
= (ext
->seq
.len
=
1501 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1;
1511 struct color_ext_type
*e
;
1512 struct color_ext_type
*e2
;
1515 _("unparsable value for LS_COLORS environment variable"));
1517 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
1523 print_with_color
= 0;
1527 /* Request that the directory named `name' have its contents listed later.
1528 If `realname' is nonzero, it will be used instead of `name' when the
1529 directory name is printed. This allows symbolic links to directories
1530 to be treated as regular directories but still be listed under their
1534 queue_directory (const char *name
, const char *realname
)
1536 struct pending
*new;
1538 new = (struct pending
*) xmalloc (sizeof (struct pending
));
1539 new->next
= pending_dirs
;
1541 new->name
= xstrdup (name
);
1543 new->realname
= xstrdup (realname
);
1548 /* Read directory `name', and list the files in it.
1549 If `realname' is nonzero, print its name instead of `name';
1550 this is used for symbolic links to directories. */
1553 print_dir (const char *name
, const char *realname
)
1555 register DIR *reading
;
1556 register struct dirent
*next
;
1557 register uintmax_t total_blocks
= 0;
1560 reading
= opendir (name
);
1563 error (0, errno
, "%s", quotearg_colon (name
));
1568 /* Read the directory entries, and insert the subfiles into the `files'
1573 while ((next
= readdir (reading
)) != NULL
)
1574 if (file_interesting (next
))
1575 total_blocks
+= gobble_file (next
->d_name
, 0, name
);
1577 if (CLOSEDIR (reading
))
1579 error (0, errno
, "%s", quotearg_colon (name
));
1581 /* Don't return; print whatever we got. */
1584 /* Sort the directory contents. */
1587 /* If any member files are subdirectories, perhaps they should have their
1588 contents listed rather than being mentioned here as files. */
1591 extract_dirs_from_files (name
, 1);
1593 if (trace_dirs
|| print_dir_name
)
1596 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1597 dired_pos
+= quote_name (stdout
, realname
? realname
: name
,
1598 dirname_quoting_options
);
1599 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1600 DIRED_FPUTS_LITERAL (":\n", stdout
);
1603 if (format
== long_format
|| print_block_size
)
1606 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1610 DIRED_FPUTS (p
, stdout
, strlen (p
));
1611 DIRED_PUTCHAR (' ');
1612 p
= human_readable (total_blocks
, buf
, ST_NBLOCKSIZE
, output_block_size
);
1613 DIRED_FPUTS (p
, stdout
, strlen (p
));
1614 DIRED_PUTCHAR ('\n');
1618 print_current_files ();
1621 DIRED_PUTCHAR ('\n');
1624 /* Add `pattern' to the list of patterns for which files that match are
1628 add_ignore_pattern (const char *pattern
)
1630 register struct ignore_pattern
*ignore
;
1632 ignore
= (struct ignore_pattern
*) xmalloc (sizeof (struct ignore_pattern
));
1633 ignore
->pattern
= pattern
;
1634 /* Add it to the head of the linked list. */
1635 ignore
->next
= ignore_patterns
;
1636 ignore_patterns
= ignore
;
1639 /* Return nonzero if the file in `next' should be listed. */
1642 file_interesting (const struct dirent
*next
)
1644 register struct ignore_pattern
*ignore
;
1646 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
1647 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
1650 if (really_all_files
1651 || next
->d_name
[0] != '.'
1653 && next
->d_name
[1] != '\0'
1654 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
1660 /* Enter and remove entries in the table `files'. */
1662 /* Empty the table of files. */
1669 for (i
= 0; i
< files_index
; i
++)
1671 free (files
[i
].name
);
1672 if (files
[i
].linkname
)
1673 free (files
[i
].linkname
);
1677 block_size_size
= 4;
1680 /* Add a file to the current table of files.
1681 Verify that the file exists, and print an error message if it does not.
1682 Return the number of blocks that the file occupies. */
1685 gobble_file (const char *name
, int explicit_arg
, const char *dirname
)
1687 register uintmax_t blocks
;
1689 register char *path
;
1691 if (files_index
== nfiles
)
1694 files
= (struct fileinfo
*) xrealloc ((char *) files
,
1695 sizeof (*files
) * nfiles
);
1698 files
[files_index
].linkname
= 0;
1699 files
[files_index
].linkmode
= 0;
1700 files
[files_index
].linkok
= 0;
1702 if (explicit_arg
|| format_needs_stat
)
1704 /* `path' is the absolute pathname of this file. */
1706 if (name
[0] == '/' || dirname
[0] == 0)
1707 path
= (char *) name
;
1710 path
= (char *) alloca (strlen (name
) + strlen (dirname
) + 2);
1711 attach (path
, dirname
, name
);
1716 val
= stat (path
, &files
[files_index
].stat
);
1718 /* Perhaps a symbolically-linked to file doesn't exist; stat
1719 the link instead. */
1720 val
= lstat (path
, &files
[files_index
].stat
);
1724 val
= lstat (path
, &files
[files_index
].stat
);
1729 error (0, errno
, "%s", quotearg_colon (path
));
1734 if (S_ISLNK (files
[files_index
].stat
.st_mode
)
1735 && (explicit_arg
|| format
== long_format
|| print_with_color
))
1738 struct stat linkstats
;
1740 get_link_name (path
, &files
[files_index
]);
1741 linkpath
= make_link_path (path
, files
[files_index
].linkname
);
1743 /* Avoid following symbolic links when possible, ie, when
1744 they won't be traced and when no indicator is needed. */
1746 && ((explicit_arg
&& format
!= long_format
)
1747 || indicator_style
!= none
1748 || print_with_color
)
1749 && stat (linkpath
, &linkstats
) == 0)
1751 files
[files_index
].linkok
= 1;
1753 /* Symbolic links to directories that are mentioned on the
1754 command line are automatically traced if not being
1756 if (explicit_arg
&& format
!= long_format
1757 && S_ISDIR (linkstats
.st_mode
))
1759 /* Substitute the linked-to directory's name, but
1760 save the real name in `linkname' for printing. */
1761 if (!immediate_dirs
)
1763 const char *tempname
= name
;
1765 linkpath
= files
[files_index
].linkname
;
1766 files
[files_index
].linkname
= (char *) tempname
;
1768 files
[files_index
].stat
= linkstats
;
1772 /* Get the linked-to file's mode for the filetype indicator
1773 in long listings. */
1774 files
[files_index
].linkmode
= linkstats
.st_mode
;
1775 files
[files_index
].linkok
= 1;
1782 if (S_ISLNK (files
[files_index
].stat
.st_mode
))
1783 files
[files_index
].filetype
= symbolic_link
;
1784 else if (S_ISDIR (files
[files_index
].stat
.st_mode
))
1786 if (explicit_arg
&& !immediate_dirs
)
1787 files
[files_index
].filetype
= arg_directory
;
1789 files
[files_index
].filetype
= directory
;
1792 files
[files_index
].filetype
= normal
;
1794 blocks
= ST_NBLOCKS (files
[files_index
].stat
);
1796 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1797 int len
= strlen (human_readable (blocks
, buf
, ST_NBLOCKSIZE
,
1798 output_block_size
));
1799 if (block_size_size
< len
)
1800 block_size_size
= len
< 7 ? len
: 7;
1806 files
[files_index
].name
= xstrdup (name
);
1814 /* Put the name of the file that `filename' is a symbolic link to
1815 into the `linkname' field of `f'. */
1818 get_link_name (const char *filename
, struct fileinfo
*f
)
1821 register int linksize
;
1823 linkbuf
= (char *) alloca (PATH_MAX
+ 2);
1824 /* Some automounters give incorrect st_size for mount points.
1825 I can't think of a good workaround for it, though. */
1826 linksize
= readlink (filename
, linkbuf
, PATH_MAX
+ 1);
1829 error (0, errno
, "%s", quotearg_colon (filename
));
1834 linkbuf
[linksize
] = '\0';
1835 f
->linkname
= xstrdup (linkbuf
);
1839 /* If `linkname' is a relative path and `path' contains one or more
1840 leading directories, return `linkname' with those directories
1841 prepended; otherwise, return a copy of `linkname'.
1842 If `linkname' is zero, return zero. */
1845 make_link_path (const char *path
, const char *linkname
)
1853 if (*linkname
== '/')
1854 return xstrdup (linkname
);
1856 /* The link is to a relative path. Prepend any leading path
1857 in `path' to the link name. */
1858 linkbuf
= strrchr (path
, '/');
1860 return xstrdup (linkname
);
1862 bufsiz
= linkbuf
- path
+ 1;
1863 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
1864 strncpy (linkbuf
, path
, bufsiz
);
1865 strcpy (linkbuf
+ bufsiz
, linkname
);
1870 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1871 This is so we don't try to recurse on `././././. ...' */
1874 basename_is_dot_or_dotdot (const char *name
)
1876 char *base
= base_name (name
);
1877 return DOT_OR_DOTDOT (base
);
1880 /* Remove any entries from `files' that are for directories,
1881 and queue them to be listed as directories instead.
1882 `dirname' is the prefix to prepend to each dirname
1883 to make it correct relative to ls's working dir.
1884 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1885 This is desirable when processing directories recursively. */
1888 extract_dirs_from_files (const char *dirname
, int recursive
)
1893 dirlen
= strlen (dirname
) + 2;
1894 /* Queue the directories last one first, because queueing reverses the
1896 for (i
= files_index
- 1; i
>= 0; i
--)
1897 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
1898 && (!recursive
|| !basename_is_dot_or_dotdot (files
[i
].name
)))
1900 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
1902 queue_directory (files
[i
].name
, files
[i
].linkname
);
1906 char *path
= path_concat (dirname
, files
[i
].name
, NULL
);
1907 queue_directory (path
, files
[i
].linkname
);
1910 if (files
[i
].filetype
== arg_directory
)
1911 free (files
[i
].name
);
1914 /* Now delete the directories from the table, compacting all the remaining
1917 for (i
= 0, j
= 0; i
< files_index
; i
++)
1918 if (files
[i
].filetype
!= arg_directory
)
1919 files
[j
++] = files
[i
];
1923 /* Sort the files now in the table. */
1938 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
1941 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
1944 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
1951 func
= sort_reverse
? rev_cmp_name
: compare_name
;
1953 case sort_extension
:
1954 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
1957 func
= sort_reverse
? rev_cmp_size
: compare_size
;
1960 func
= sort_reverse
? rev_cmp_version
: compare_version
;
1966 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
1969 /* Comparison routines for sorting the files. */
1972 compare_ctime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1974 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
1976 diff
= strcmp (file1
->name
, file2
->name
);
1981 rev_cmp_ctime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
1983 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
1985 diff
= strcmp (file1
->name
, file2
->name
);
1990 compare_mtime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
1992 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
1994 diff
= strcmp (file1
->name
, file2
->name
);
1999 rev_cmp_mtime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2001 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
2003 diff
= strcmp (file1
->name
, file2
->name
);
2008 compare_atime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2010 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2012 diff
= strcmp (file1
->name
, file2
->name
);
2017 rev_cmp_atime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2019 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2021 diff
= strcmp (file1
->name
, file2
->name
);
2026 compare_size (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2028 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2030 diff
= strcmp (file1
->name
, file2
->name
);
2035 rev_cmp_size (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2037 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2039 diff
= strcmp (file1
->name
, file2
->name
);
2044 compare_version (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2046 return strverscmp (file1
->name
, file2
->name
);
2050 rev_cmp_version (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2052 return strverscmp (file1
->name
, file2
->name
);
2056 compare_name (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2058 return strcmp (file1
->name
, file2
->name
);
2062 rev_cmp_name (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2064 return strcmp (file1
->name
, file2
->name
);
2067 /* Compare file extensions. Files with no extension are `smallest'.
2068 If extensions are the same, compare by filenames instead. */
2071 compare_extension (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2073 register char *base1
, *base2
;
2076 base1
= strrchr (file1
->name
, '.');
2077 base2
= strrchr (file2
->name
, '.');
2078 if (base1
== 0 && base2
== 0)
2079 return strcmp (file1
->name
, file2
->name
);
2084 cmp
= strcmp (base1
, base2
);
2086 return strcmp (file1
->name
, file2
->name
);
2091 rev_cmp_extension (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2093 register char *base1
, *base2
;
2096 base1
= strrchr (file1
->name
, '.');
2097 base2
= strrchr (file2
->name
, '.');
2098 if (base1
== 0 && base2
== 0)
2099 return strcmp (file1
->name
, file2
->name
);
2104 cmp
= strcmp (base1
, base2
);
2106 return strcmp (file1
->name
, file2
->name
);
2110 /* List all the files now in the table. */
2113 print_current_files (void)
2120 for (i
= 0; i
< files_index
; i
++)
2122 print_file_name_and_frills (files
+ i
);
2128 init_column_info ();
2129 print_many_per_line ();
2133 init_column_info ();
2134 print_horizontal ();
2138 print_with_commas ();
2142 for (i
= 0; i
< files_index
; i
++)
2144 print_long_format (files
+ i
);
2145 DIRED_PUTCHAR ('\n');
2152 print_long_format (const struct fileinfo
*f
)
2156 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2157 1 10-byte mode string,
2158 1 24-byte time string (may be longer in some locales -- see below)
2159 or LONGEST_HUMAN_READABLE integer,
2160 9 spaces, one following each of these fields, and
2161 1 trailing NUL byte. */
2162 char init_bigbuf
[7 * LONGEST_HUMAN_READABLE
+ 10
2163 + (LONGEST_HUMAN_READABLE
< 24 ? 24 : LONGEST_HUMAN_READABLE
)
2165 char *buf
= init_bigbuf
;
2166 size_t bufsize
= sizeof (init_bigbuf
);
2170 struct tm
*when_local
;
2175 /* Cray DMF: look at the file's migrated, not real, status */
2176 mode_string (f
->stat
.st_dm_mode
, modebuf
);
2178 mode_string (f
->stat
.st_mode
, modebuf
);
2186 when
= f
->stat
.st_ctime
;
2189 when
= f
->stat
.st_mtime
;
2192 when
= f
->stat
.st_atime
;
2198 fmt
= "%a %b %d %H:%M:%S %Y";
2202 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
2203 || current_time
< when
- 60L * 60L) /* In the future. */
2205 /* The file is fairly old or in the future.
2206 POSIX says the cutoff is 6 months old;
2207 approximate this by 6*30 days.
2208 Allow a 1 hour slop factor for what is considered "the future",
2209 to allow for NFS server/client clock disagreement.
2210 Show the year instead of the time of day. */
2215 fmt
= "%b %e %H:%M";
2223 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2224 sprintf (p
, "%*s ", INODE_DIGITS
,
2225 human_readable ((uintmax_t) f
->stat
.st_ino
, hbuf
, 1, 1));
2229 if (print_block_size
)
2231 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2232 sprintf (p
, "%*s ", block_size_size
,
2233 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), hbuf
,
2234 ST_NBLOCKSIZE
, output_block_size
));
2238 /* The space between the mode and the number of links is the POSIX
2239 "optional alternate access method flag". */
2240 sprintf (p
, "%s %3u ", modebuf
, (unsigned int) f
->stat
.st_nlink
);
2243 user_name
= (numeric_ids
? NULL
: getuser (f
->stat
.st_uid
));
2245 sprintf (p
, "%-8.8s ", user_name
);
2247 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_uid
);
2252 char *group_name
= (numeric_ids
? NULL
: getgroup (f
->stat
.st_gid
));
2254 sprintf (p
, "%-8.8s ", group_name
);
2256 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_gid
);
2260 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2261 sprintf (p
, "%3u, %3u ", (unsigned) major (f
->stat
.st_rdev
),
2262 (unsigned) minor (f
->stat
.st_rdev
));
2265 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2267 human_readable ((uintmax_t) f
->stat
.st_size
, hbuf
, 1,
2268 output_block_size
< 0 ? output_block_size
: 1));
2273 /* Use strftime rather than ctime, because the former can produce
2274 locale-dependent names for the weekday (%a) and month (%b). */
2276 if ((when_local
= localtime (&when
)))
2278 while (! (s
= strftime (p
, buf
+ bufsize
- p
- 1, fmt
, when_local
)))
2280 char *newbuf
= (char *) alloca (bufsize
*= 2);
2281 memcpy (newbuf
, buf
, p
- buf
);
2282 p
= newbuf
+ (p
- buf
);
2289 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2294 /* The time cannot be represented as a local time;
2295 print it as a huge integer number of seconds. */
2296 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2297 int width
= full_time
? 24 : 12;
2301 const char *num
= human_readable (- (uintmax_t) when
, hbuf
, 1, 1);
2302 int sign_width
= width
- strlen (num
);
2303 sprintf (p
, "%*s%s ", sign_width
< 0 ? 0 : sign_width
, "-", num
);
2306 sprintf (p
, "%*s ", width
,
2307 human_readable ((uintmax_t) when
, hbuf
, 1, 1));
2313 DIRED_FPUTS (buf
, stdout
, p
- buf
);
2314 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
,
2317 if (f
->filetype
== symbolic_link
)
2321 DIRED_FPUTS_LITERAL (" -> ", stdout
);
2322 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
- 1,
2324 if (indicator_style
!= none
)
2325 print_type_indicator (f
->linkmode
);
2328 else if (indicator_style
!= none
)
2329 print_type_indicator (f
->stat
.st_mode
);
2332 /* Output to OUT a quoted representation of the file name P,
2333 using OPTIONS to control quoting.
2334 Return the number of characters in P's quoted representation. */
2337 quote_name (FILE *out
, const char *p
, struct quoting_options
const *options
)
2339 char smallbuf
[BUFSIZ
];
2340 size_t len
= quotearg_buffer (smallbuf
, sizeof smallbuf
, p
, -1, options
);
2343 if (len
< sizeof smallbuf
)
2347 buf
= (char *) alloca (len
+ 1);
2348 quotearg_buffer (buf
, len
+ 1, p
, -1, options
);
2351 if (qmark_funny_chars
)
2354 for (i
= 0; i
< len
; i
++)
2355 if (! ISPRINT ((unsigned char) buf
[i
]))
2359 fwrite (buf
, 1, len
, out
);
2364 print_name_with_quoting (const char *p
, unsigned int mode
, int linkok
,
2365 struct obstack
*stack
)
2367 if (print_with_color
)
2368 print_color_indicator (p
, mode
, linkok
);
2371 PUSH_CURRENT_DIRED_POS (stack
);
2373 dired_pos
+= quote_name (stdout
, p
, filename_quoting_options
);
2376 PUSH_CURRENT_DIRED_POS (stack
);
2378 if (print_with_color
)
2379 prep_non_filename_text ();
2383 prep_non_filename_text (void)
2385 if (color_indicator
[C_END
].string
!= NULL
)
2386 put_indicator (&color_indicator
[C_END
]);
2389 put_indicator (&color_indicator
[C_LEFT
]);
2390 put_indicator (&color_indicator
[C_NORM
]);
2391 put_indicator (&color_indicator
[C_RIGHT
]);
2395 /* Print the file name of `f' with appropriate quoting.
2396 Also print file size, inode number, and filetype indicator character,
2397 as requested by switches. */
2400 print_file_name_and_frills (const struct fileinfo
*f
)
2402 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2405 printf ("%*s ", INODE_DIGITS
,
2406 human_readable ((uintmax_t) f
->stat
.st_ino
, buf
, 1, 1));
2408 if (print_block_size
)
2409 printf ("%*s ", block_size_size
,
2410 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), buf
,
2411 ST_NBLOCKSIZE
, output_block_size
));
2413 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
, NULL
);
2415 if (indicator_style
!= none
)
2416 print_type_indicator (f
->stat
.st_mode
);
2420 print_type_indicator (unsigned int mode
)
2426 if (indicator_style
== classify
&& (mode
& S_IXUGO
))
2435 else if (S_ISLNK (mode
))
2437 else if (S_ISFIFO (mode
))
2439 else if (S_ISSOCK (mode
))
2441 else if (S_ISDOOR (mode
))
2452 print_color_indicator (const char *name
, unsigned int mode
, int linkok
)
2455 struct color_ext_type
*ext
; /* Color extension */
2456 size_t len
; /* Length of name */
2458 /* Is this a nonexistent file? If so, linkok == -1. */
2460 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
2469 else if (S_ISLNK (mode
))
2470 type
= ((!linkok
&& color_indicator
[C_ORPHAN
].string
)
2471 ? C_ORPHAN
: C_LINK
);
2472 else if (S_ISFIFO (mode
))
2474 else if (S_ISSOCK (mode
))
2476 else if (S_ISBLK (mode
))
2478 else if (S_ISCHR (mode
))
2480 else if (S_ISDOOR (mode
))
2483 if (type
== C_FILE
&& (mode
& S_IXUGO
) != 0)
2486 /* Check the file's suffix only if still classified as C_FILE. */
2490 /* Test if NAME has a recognized suffix. */
2492 len
= strlen (name
);
2493 name
+= len
; /* Pointer to final \0. */
2494 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
2496 if ((size_t) ext
->ext
.len
<= len
2497 && strncmp (name
- ext
->ext
.len
, ext
->ext
.string
,
2504 put_indicator (&color_indicator
[C_LEFT
]);
2505 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
2506 put_indicator (&color_indicator
[C_RIGHT
]);
2509 /* Output a color indicator (which may contain nulls). */
2511 put_indicator (const struct bin_str
*ind
)
2518 for (i
= ind
->len
; i
> 0; --i
)
2523 length_of_file_name_and_frills (const struct fileinfo
*f
)
2525 register int len
= 0;
2528 len
+= INODE_DIGITS
+ 1;
2530 if (print_block_size
)
2531 len
+= 1 + block_size_size
;
2533 len
+= quotearg_buffer (0, 0, f
->name
, -1, filename_quoting_options
);
2535 if (indicator_style
!= none
)
2537 unsigned filetype
= f
->stat
.st_mode
;
2539 if (S_ISREG (filetype
))
2541 if (indicator_style
== classify
2542 && (f
->stat
.st_mode
& S_IXUGO
))
2545 else if (S_ISDIR (filetype
)
2546 || S_ISLNK (filetype
)
2547 || S_ISFIFO (filetype
)
2548 || S_ISSOCK (filetype
)
2549 || S_ISDOOR (filetype
)
2558 print_many_per_line (void)
2560 struct column_info
*line_fmt
;
2561 int filesno
; /* Index into files. */
2562 int row
; /* Current row. */
2563 int max_name_length
; /* Length of longest file name + frills. */
2564 int name_length
; /* Length of each file name + frills. */
2565 int pos
; /* Current character column. */
2566 int cols
; /* Number of files across. */
2567 int rows
; /* Maximum number of files down. */
2570 /* Normally the maximum number of columns is determined by the
2571 screen width. But if few files are available this might limit it
2573 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2575 /* Compute the maximum number of possible columns. */
2576 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2580 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2582 for (i
= 0; i
< max_cols
; ++i
)
2584 if (column_info
[i
].valid_len
)
2586 int idx
= filesno
/ ((files_index
+ i
) / (i
+ 1));
2587 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2589 if (real_length
> column_info
[i
].col_arr
[idx
])
2591 column_info
[i
].line_len
+= (real_length
2592 - column_info
[i
].col_arr
[idx
]);
2593 column_info
[i
].col_arr
[idx
] = real_length
;
2594 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2600 /* Find maximum allowed columns. */
2601 for (cols
= max_cols
; cols
> 1; --cols
)
2603 if (column_info
[cols
- 1].valid_len
)
2607 line_fmt
= &column_info
[cols
- 1];
2609 /* Calculate the number of rows that will be in each column except possibly
2610 for a short column on the right. */
2611 rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
2613 for (row
= 0; row
< rows
; row
++)
2618 /* Print the next row. */
2621 print_file_name_and_frills (files
+ filesno
);
2622 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2623 max_name_length
= line_fmt
->col_arr
[col
++];
2626 if (filesno
>= files_index
)
2629 indent (pos
+ name_length
, pos
+ max_name_length
);
2630 pos
+= max_name_length
;
2637 print_horizontal (void)
2639 struct column_info
*line_fmt
;
2641 int max_name_length
;
2647 /* Normally the maximum number of columns is determined by the
2648 screen width. But if few files are available this might limit it
2650 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2652 /* Compute the maximum file name length. */
2653 max_name_length
= 0;
2654 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2658 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2660 for (i
= 0; i
< max_cols
; ++i
)
2662 if (column_info
[i
].valid_len
)
2664 int idx
= filesno
% (i
+ 1);
2665 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2667 if (real_length
> column_info
[i
].col_arr
[idx
])
2669 column_info
[i
].line_len
+= (real_length
2670 - column_info
[i
].col_arr
[idx
]);
2671 column_info
[i
].col_arr
[idx
] = real_length
;
2672 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2678 /* Find maximum allowed columns. */
2679 for (cols
= max_cols
; cols
> 1; --cols
)
2681 if (column_info
[cols
- 1].valid_len
)
2685 line_fmt
= &column_info
[cols
- 1];
2689 /* Print first entry. */
2690 print_file_name_and_frills (files
);
2691 name_length
= length_of_file_name_and_frills (files
);
2692 max_name_length
= line_fmt
->col_arr
[0];
2695 for (filesno
= 1; filesno
< files_index
; ++filesno
)
2697 int col
= filesno
% cols
;
2706 indent (pos
+ name_length
, pos
+ max_name_length
);
2707 pos
+= max_name_length
;
2710 print_file_name_and_frills (files
+ filesno
);
2712 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2713 max_name_length
= line_fmt
->col_arr
[col
];
2719 print_with_commas (void)
2726 for (filesno
= 0; filesno
< files_index
; filesno
++)
2730 pos
+= length_of_file_name_and_frills (files
+ filesno
);
2731 if (filesno
+ 1 < files_index
)
2732 pos
+= 2; /* For the comma and space */
2734 if (old_pos
!= 0 && pos
>= line_length
)
2740 print_file_name_and_frills (files
+ filesno
);
2741 if (filesno
+ 1 < files_index
)
2750 /* Assuming cursor is at position FROM, indent up to position TO.
2751 Use a TAB character instead of two or more spaces whenever possible. */
2754 indent (int from
, int to
)
2758 if (tabsize
> 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
2761 from
+= tabsize
- from
% tabsize
;
2771 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2772 /* FIXME: maybe remove this function someday. See about using a
2773 non-malloc'ing version of path_concat. */
2776 attach (char *dest
, const char *dirname
, const char *name
)
2778 const char *dirnamep
= dirname
;
2780 /* Copy dirname if it is not ".". */
2781 if (dirname
[0] != '.' || dirname
[1] != 0)
2784 *dest
++ = *dirnamep
++;
2785 /* Add '/' if `dirname' doesn't already end with it. */
2786 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
2795 init_column_info (void)
2800 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2804 if (column_info
== NULL
)
2806 column_info
= (struct column_info
*) xmalloc (max_idx
2807 * sizeof (struct column_info
));
2811 for (i
= 0; i
< max_idx
; ++i
)
2815 column_info
[i
].valid_len
= 1;
2816 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
2819 column_info
[i
].col_arr
= (int *) xmalloc ((i
+ 1) * sizeof (int));
2821 for (j
= 0; j
<= i
; ++j
)
2822 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
2830 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2834 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
2836 List information about the FILEs (the current directory by default).\n\
2837 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2839 -a, --all do not hide entries starting with .\n\
2840 -A, --almost-all do not list implied . and ..\n\
2841 -b, --escape print octal escapes for nongraphic characters\n\
2842 --block-size=SIZE use SIZE-byte blocks\n\
2843 -B, --ignore-backups do not list implied entries ending with ~\n\
2844 -c sort by change time; with -l: show ctime\n\
2845 -C list entries by columns\n\
2846 --color[=WHEN] control whether color is used to distinguish file\n\
2847 types. WHEN may be `never', `always', or `auto'\n\
2848 -d, --directory list directory entries instead of contents\n\
2849 -D, --dired generate output designed for Emacs' dired mode\n\
2850 -f do not sort, enable -aU, disable -lst\n\
2851 -F, --classify append indicator (one of */=@|) to entries\n\
2852 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2853 single-column -1, verbose -l, vertical -C\n\
2854 --full-time list both full date and full time\n"));
2858 -G, --no-group inhibit display of group information\n\
2859 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2860 -H, --si likewise, but use powers of 1000 not 1024\n\
2861 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2862 none (default), classify (-F), file-type (-p)\n\
2863 -i, --inode print index number of each file\n\
2864 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2865 -k, --kilobytes like --block-size=1024\n\
2866 -l use a long listing format\n\
2867 -L, --dereference list entries pointed to by symbolic links\n\
2868 -m fill width with a comma separated list of entries\n\
2869 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2870 -N, --literal print raw entry names (don't treat e.g. control\n\
2871 characters specially)\n\
2872 -o use long listing format without group info\n\
2873 -p, --file-type append indicator (one of /=@|) to entries\n\
2874 -q, --hide-control-chars print ? instead of non graphic characters\n\
2875 --show-control-chars show non graphic characters as-is (default)\n\
2876 -Q, --quote-name enclose entry names in double quotes\n\
2877 --quoting-style=WORD use quoting style WORD for entry names:\n\
2878 literal, shell, shell-always, c, escape\n\
2879 -r, --reverse reverse order while sorting\n\
2880 -R, --recursive list subdirectories recursively\n\
2881 -s, --size print size of each file, in blocks\n"));
2884 -S sort by file size\n\
2885 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2887 status -c, time -t, atime -u, access -u, use -u\n\
2888 --time=WORD show time as WORD instead of modification time:\n\
2889 atime, access, use, ctime or status; use\n\
2890 specified time as sort key if --sort=time\n\
2891 -t sort by modification time\n\
2892 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2893 -u sort by last access time; with -l: show atime\n\
2894 -U do not sort; list entries in directory order\n\
2895 -v sort by version\n\
2896 -w, --width=COLS assume screen width instead of current value\n\
2897 -x list entries by lines instead of by columns\n\
2898 -X sort alphabetically by entry extension\n\
2899 -1 list one file per line\n\
2900 --help display this help and exit\n\
2901 --version output version information and exit\n\
2903 By default, color is not used to distinguish types of files. That is\n\
2904 equivalent to using --color=none. Using the --color option without the\n\
2905 optional WHEN argument is equivalent to using --color=always. With\n\
2906 --color=auto, color codes are output only if standard output is connected\n\
2907 to a terminal (tty).\n\
2909 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));