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>
82 #include "path-concat.h"
84 #include "strverscmp.h"
87 /* Use access control lists only under all the following conditions.
88 Some systems (OSF4, Irix5, Irix6) have the acl function, but not
89 sys/acl.h or don't define the GETACLCNT macro. */
90 #if HAVE_SYS_ACL_H && HAVE_ACL && defined GETACLCNT
94 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
95 : (ls_mode == LS_MULTI_COL \
98 #define AUTHORS "Richard Stallman and David MacKenzie"
100 #define obstack_chunk_alloc malloc
101 #define obstack_chunk_free free
103 /* Return an int indicating the result of comparing two integers.
104 Subtracting doesn't always work, due to overflow. */
105 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
107 /* The field width for inode numbers. On some hosts inode numbers are
108 64 bits, so columns won't line up exactly when a huge inode number
109 is encountered, but in practice 7 digits is usually enough. */
111 # define INODE_DIGITS 7
115 # define HAVE_SYMLINKS 1
117 # define HAVE_SYMLINKS 0
120 /* If any of the S_* macros are undefined, define them here so each
121 use doesn't have to be guarded with e.g., #ifdef S_ISLNK. */
123 # define S_ISLNK(Mode) 0
127 # define S_ISFIFO(Mode) 0
131 # define S_ISSOCK(Mode) 0
135 # define S_ISCHR(Mode) 0
139 # define S_ISBLK(Mode) 0
143 # define S_ISDOOR(Mode) 0
150 arg_directory
, /* Directory given as command line arg. */
151 normal
/* All others. */
161 /* For symbolic link, name of the file linked to, otherwise zero. */
164 /* For symbolic link and long listing, st_mode of file linked to, otherwise
166 unsigned int linkmode
;
168 /* For symbolic link and color printing, 1 if linked-to file
169 exists, otherwise 0. */
172 enum filetype filetype
;
175 /* For long listings, nonzero if the file has an access control list,
182 # define FILE_HAS_ACL(F) ((F)->have_acl)
184 # define FILE_HAS_ACL(F) 0
187 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
189 /* Null is a valid character in a color indicator (think about Epson
190 printers, for example) so we have to use a length/buffer string
195 int len
; /* Number of bytes */
196 char *string
; /* Pointer to the same */
205 void strip_trailing_slashes ();
208 static size_t quote_name
PARAMS ((FILE *out
, const char *name
,
209 struct quoting_options
const *options
));
210 static char *make_link_path
PARAMS ((const char *path
, const char *linkname
));
211 static int compare_atime
PARAMS ((const struct fileinfo
*file1
,
212 const struct fileinfo
*file2
));
213 static int rev_cmp_atime
PARAMS ((const struct fileinfo
*file2
,
214 const struct fileinfo
*file1
));
215 static int compare_ctime
PARAMS ((const struct fileinfo
*file1
,
216 const struct fileinfo
*file2
));
217 static int rev_cmp_ctime
PARAMS ((const struct fileinfo
*file2
,
218 const struct fileinfo
*file1
));
219 static int compare_mtime
PARAMS ((const struct fileinfo
*file1
,
220 const struct fileinfo
*file2
));
221 static int rev_cmp_mtime
PARAMS ((const struct fileinfo
*file2
,
222 const struct fileinfo
*file1
));
223 static int compare_size
PARAMS ((const struct fileinfo
*file1
,
224 const struct fileinfo
*file2
));
225 static int rev_cmp_size
PARAMS ((const struct fileinfo
*file2
,
226 const struct fileinfo
*file1
));
227 static int compare_name
PARAMS ((const struct fileinfo
*file1
,
228 const struct fileinfo
*file2
));
229 static int rev_cmp_name
PARAMS ((const struct fileinfo
*file2
,
230 const struct fileinfo
*file1
));
231 static int compare_extension
PARAMS ((const struct fileinfo
*file1
,
232 const struct fileinfo
*file2
));
233 static int rev_cmp_extension
PARAMS ((const struct fileinfo
*file2
,
234 const struct fileinfo
*file1
));
235 static int compare_version
PARAMS ((const struct fileinfo
*file1
,
236 const struct fileinfo
*file2
));
237 static int rev_cmp_version
PARAMS ((const struct fileinfo
*file2
,
238 const struct fileinfo
*file1
));
239 static int decode_switches
PARAMS ((int argc
, char **argv
));
240 static int file_interesting
PARAMS ((const struct dirent
*next
));
241 static uintmax_t gobble_file
PARAMS ((const char *name
, int explicit_arg
,
242 const char *dirname
));
243 static void print_color_indicator
PARAMS ((const char *name
, unsigned int mode
,
245 static void put_indicator
PARAMS ((const struct bin_str
*ind
));
246 static int length_of_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
247 static void add_ignore_pattern
PARAMS ((const char *pattern
));
248 static void attach
PARAMS ((char *dest
, const char *dirname
, const char *name
));
249 static void clear_files
PARAMS ((void));
250 static void extract_dirs_from_files
PARAMS ((const char *dirname
,
252 static void get_link_name
PARAMS ((const char *filename
, struct fileinfo
*f
));
253 static void indent
PARAMS ((int from
, int to
));
254 static void init_column_info
PARAMS ((void));
255 static void print_current_files
PARAMS ((void));
256 static void print_dir
PARAMS ((const char *name
, const char *realname
));
257 static void print_file_name_and_frills
PARAMS ((const struct fileinfo
*f
));
258 static void print_horizontal
PARAMS ((void));
259 static void print_long_format
PARAMS ((const struct fileinfo
*f
));
260 static void print_many_per_line
PARAMS ((void));
261 static void print_name_with_quoting
PARAMS ((const char *p
, unsigned int mode
,
263 struct obstack
*stack
));
264 static void prep_non_filename_text
PARAMS ((void));
265 static void print_type_indicator
PARAMS ((unsigned int mode
));
266 static void print_with_commas
PARAMS ((void));
267 static void queue_directory
PARAMS ((const char *name
, const char *realname
));
268 static void sort_files
PARAMS ((void));
269 static void parse_ls_color
PARAMS ((void));
270 void usage
PARAMS ((int status
));
272 /* The name the program was run with, stripped of any leading path. */
275 /* The table of files in the current directory:
277 `files' points to a vector of `struct fileinfo', one per file.
278 `nfiles' is the number of elements space has been allocated for.
279 `files_index' is the number actually in use. */
281 /* Address of block containing the files that are described. */
283 static struct fileinfo
*files
;
285 /* Length of block that `files' points to, measured in files. */
289 /* Index of first unused in `files'. */
291 static int files_index
;
293 /* Record of one pending directory waiting to be listed. */
298 /* If the directory is actually the file pointed to by a symbolic link we
299 were told to list, `realname' will contain the name of the symbolic
300 link, otherwise zero. */
302 struct pending
*next
;
305 static struct pending
*pending_dirs
;
307 /* Current time (seconds since 1970). When we are printing a file's time,
308 include the year if it is more than 6 months before this time. */
310 static time_t current_time
;
312 /* The number of digits to use for block sizes.
313 4, or more if needed for bigger numbers. */
315 static int block_size_size
;
319 /* long_format for lots of info, one per line.
320 one_per_line for just names, one per line.
321 many_per_line for just names, many per line, sorted vertically.
322 horizontal for just names, many per line, sorted horizontally.
323 with_commas for just names, many per line, separated by commas.
325 -l, -1, -C, -x and -m control this parameter. */
329 long_format
, /* -l */
330 one_per_line
, /* -1 */
331 many_per_line
, /* -C */
336 static enum format format
;
338 /* Type of time to print or sort by. Controlled by -c and -u. */
342 time_mtime
, /* default */
347 static enum time_type time_type
;
349 /* print the full time, otherwise the standard unix heuristics. */
351 static int full_time
;
353 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
358 sort_name
, /* default */
359 sort_extension
, /* -X */
362 sort_version
/* -v */
365 static enum sort_type sort_type
;
367 /* Direction of sort.
368 0 means highest first if numeric,
369 lowest first if alphabetic;
370 these are the defaults.
371 1 means the opposite order in each case. -r */
373 static int sort_reverse
;
375 /* Nonzero means to NOT display group information. -G */
377 static int inhibit_group
;
379 /* Nonzero means print the user and group id's as numbers rather
382 static int numeric_ids
;
384 /* Nonzero means mention the size in blocks of each file. -s */
386 static int print_block_size
;
388 /* If positive, the units to use when printing sizes;
389 if negative, the human-readable base. */
390 static int output_block_size
;
392 /* Precede each line of long output (per file) with a string like `m,n:'
393 where M is the number of characters after the `:' and before the
394 filename and N is the length of the filename. Using this format,
395 Emacs' dired mode starts up twice as fast, and can handle all
396 strange characters in file names. */
399 /* `none' means don't mention the type of files.
400 `classify' means mention file types and mark executables.
401 `file_type' means mention only file types.
403 Controlled by -F, -p, and --indicator-style. */
407 none
, /* --indicator-style=none */
408 classify
, /* -F, --indicator-style=classify */
409 file_type
/* -p, --indicator-style=file-type */
412 static enum indicator_style indicator_style
;
414 /* Names of indicator styles. */
415 static char const *const indicator_style_args
[] =
417 "none", "classify", "file-type", 0
420 static enum indicator_style
const indicator_style_types
[]=
422 none
, classify
, file_type
425 /* Nonzero means use colors to mark types. Also define the different
426 colors as well as the stuff for the LS_COLORS environment variable.
427 The LS_COLORS variable is now in a termcap-like format. */
429 static int print_with_color
;
433 color_never
, /* 0: default or --color=never */
434 color_always
, /* 1: --color=always */
435 color_if_tty
/* 2: --color=tty */
440 C_LEFT
, C_RIGHT
, C_END
, C_NORM
, C_FILE
, C_DIR
, C_LINK
, C_FIFO
, C_SOCK
,
441 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
444 static const char *const indicator_name
[]=
446 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
447 "bd", "cd", "mi", "or", "ex", "do", NULL
450 struct color_ext_type
452 struct bin_str ext
; /* The extension we're looking for */
453 struct bin_str seq
; /* The sequence to output when we do */
454 struct color_ext_type
*next
; /* Next in list */
457 static struct bin_str color_indicator
[] =
459 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
460 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
461 { 0, NULL
}, /* ec: End color (replaces lc+no+rc) */
462 { LEN_STR_PAIR ("0") }, /* no: Normal */
463 { LEN_STR_PAIR ("0") }, /* fi: File: default */
464 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
465 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
466 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
467 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
468 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
469 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
470 { 0, NULL
}, /* mi: Missing file: undefined */
471 { 0, NULL
}, /* or: Orphanned symlink: undefined */
472 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
473 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
477 static struct color_ext_type
*color_ext_list
= NULL
;
479 /* Buffer for color sequences */
480 static char *color_buf
;
482 /* Nonzero means mention the inode number of each file. -i */
484 static int print_inode
;
486 /* Nonzero means when a symbolic link is found, display info on
487 the file linked to. -L */
489 static int trace_links
;
491 /* Nonzero means when a directory is found, display info on its
494 static int trace_dirs
;
496 /* Nonzero means when an argument is a directory name, display info
499 static int immediate_dirs
;
501 /* Nonzero means don't omit files whose names start with `.'. -A */
503 static int all_files
;
505 /* Nonzero means don't omit files `.' and `..'
506 This flag implies `all_files'. -a */
508 static int really_all_files
;
510 /* A linked list of shell-style globbing patterns. If a non-argument
511 file name matches any of these patterns, it is omitted.
512 Controlled by -I. Multiple -I options accumulate.
513 The -B option adds `*~' and `.*~' to this list. */
515 struct ignore_pattern
518 struct ignore_pattern
*next
;
521 static struct ignore_pattern
*ignore_patterns
;
523 /* Nonzero means output nongraphic chars in file names as `?'.
524 (-q, --hide-control-chars)
525 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
526 independent. The algorithm is: first, obey the quoting style to get a
527 string representing the file name; then, if qmark_funny_chars is set,
528 replace all nonprintable chars in that string with `?'. It's necessary
529 to replace nonprintable chars even in quoted strings, because we don't
530 want to mess up the terminal if control chars get sent to it, and some
531 quoting methods pass through control chars as-is. */
532 static int qmark_funny_chars
;
534 /* Quoting options for file and dir name output. */
536 static struct quoting_options
*filename_quoting_options
;
537 static struct quoting_options
*dirname_quoting_options
;
539 /* The number of chars per hardware tab stop. Setting this to zero
540 inhibits the use of TAB characters for separating columns. -T */
543 /* Nonzero means we are listing the working directory because no
544 non-option arguments were given. */
546 static int dir_defaulted
;
548 /* Nonzero means print each directory name before listing it. */
550 static int print_dir_name
;
552 /* The line length to use for breaking lines in many-per-line format.
553 Can be set with -w. */
555 static int line_length
;
557 /* If nonzero, the file listing format requires that stat be called on
560 static int format_needs_stat
;
562 /* The exit status to use if we don't get any fatal errors. */
564 static int exit_status
;
566 static struct option
const long_options
[] =
568 {"all", no_argument
, 0, 'a'},
569 {"escape", no_argument
, 0, 'b'},
570 {"directory", no_argument
, 0, 'd'},
571 {"dired", no_argument
, 0, 'D'},
572 {"full-time", no_argument
, &full_time
, 1},
573 {"human-readable", no_argument
, 0, 'h'},
574 {"inode", no_argument
, 0, 'i'},
575 {"kilobytes", no_argument
, 0, 'k'},
576 {"numeric-uid-gid", no_argument
, 0, 'n'},
577 {"no-group", no_argument
, 0, 'G'},
578 {"hide-control-chars", no_argument
, 0, 'q'},
579 {"reverse", no_argument
, 0, 'r'},
580 {"size", no_argument
, 0, 's'},
581 {"width", required_argument
, 0, 'w'},
582 {"almost-all", no_argument
, 0, 'A'},
583 {"ignore-backups", no_argument
, 0, 'B'},
584 {"classify", no_argument
, 0, 'F'},
585 {"file-type", no_argument
, 0, 'F'},
586 {"si", no_argument
, 0, 'H'},
587 {"ignore", required_argument
, 0, 'I'},
588 {"indicator-style", required_argument
, 0, 14},
589 {"dereference", no_argument
, 0, 'L'},
590 {"literal", no_argument
, 0, 'N'},
591 {"quote-name", no_argument
, 0, 'Q'},
592 {"quoting-style", required_argument
, 0, 15},
593 {"recursive", no_argument
, 0, 'R'},
594 {"format", required_argument
, 0, 12},
595 {"show-control-chars", no_argument
, 0, 16},
596 {"sort", required_argument
, 0, 10},
597 {"tabsize", required_argument
, 0, 'T'},
598 {"time", required_argument
, 0, 11},
599 {"color", optional_argument
, 0, 13},
600 {"block-size", required_argument
, 0, 17},
601 {GETOPT_HELP_OPTION_DECL
},
602 {GETOPT_VERSION_OPTION_DECL
},
606 static char const *const format_args
[] =
608 "verbose", "long", "commas", "horizontal", "across",
609 "vertical", "single-column", 0
612 static enum format
const format_types
[] =
614 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
615 many_per_line
, one_per_line
618 static char const *const sort_args
[] =
620 "none", "time", "size", "extension", "version", 0
623 static enum sort_type
const sort_types
[] =
625 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
628 static char const *const time_args
[] =
630 "atime", "access", "use", "ctime", "status", 0
633 static enum time_type
const time_types
[] =
635 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
638 static char const *const color_args
[] =
640 /* force and none are for compatibility with another color-ls version */
641 "always", "yes", "force",
642 "never", "no", "none",
643 "auto", "tty", "if-tty", 0
646 static enum color_type
const color_types
[] =
648 color_always
, color_always
, color_always
,
649 color_never
, color_never
, color_never
,
650 color_if_tty
, color_if_tty
, color_if_tty
653 /* Information about filling a column. */
661 /* Array with information about column filledness. */
662 static struct column_info
*column_info
;
664 /* Maximum number of columns ever possible for this display. */
667 /* The minimum width of a colum is 3: 1 character for the name and 2
668 for the separating white space. */
669 #define MIN_COLUMN_WIDTH 3
672 /* This zero-based index is used solely with the --dired option.
673 When that option is in effect, this counter is incremented for each
674 character of output generated by this program so that the beginning
675 and ending indices (in that output) of every file name can be recorded
676 and later output themselves. */
677 static size_t dired_pos
;
679 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
681 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
682 #define DIRED_FPUTS(s, stream, s_len) \
683 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
685 /* Like DIRED_FPUTS, but for use when S is a literal string. */
686 #define DIRED_FPUTS_LITERAL(s, stream) \
687 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
689 #define DIRED_INDENT() \
692 /* FIXME: remove the `&& format == long_format' clause. */ \
693 if (dired && format == long_format) \
694 DIRED_FPUTS_LITERAL (" ", stdout); \
698 /* With --dired, store pairs of beginning and ending indices of filenames. */
699 static struct obstack dired_obstack
;
701 /* With --dired, store pairs of beginning and ending indices of any
702 directory names that appear as headers (just before `total' line)
703 for lists of directory entries. Such directory names are seen when
704 listing hierarchies using -R and when a directory is listed with at
705 least one other command line argument. */
706 static struct obstack subdired_obstack
;
708 /* Save the current index on the specified obstack, OBS. */
709 #define PUSH_CURRENT_DIRED_POS(obs) \
712 /* FIXME: remove the `&& format == long_format' clause. */ \
713 if (dired && format == long_format) \
714 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
719 /* Write to standard output PREFIX, followed by the quoting style and
720 a space-separated list of the integers stored in OS all on one line. */
723 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
727 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
733 pos
= (size_t *) obstack_finish (os
);
734 fputs (prefix
, stdout
);
735 for (i
= 0; i
< n_pos
; i
++)
736 printf (" %d", (int) pos
[i
]);
737 fputs ("\n", stdout
);
742 main (int argc
, char **argv
)
745 register struct pending
*thispend
;
747 program_name
= argv
[0];
748 setlocale (LC_ALL
, "");
749 bindtextdomain (PACKAGE
, LOCALEDIR
);
750 textdomain (PACKAGE
);
752 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
753 assert (N_ENTRIES (color_indicator
) + 1 == N_ENTRIES (indicator_name
));
759 current_time
= time ((time_t *) 0);
761 i
= decode_switches (argc
, argv
);
763 if (print_with_color
)
766 prep_non_filename_text ();
769 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
770 || format
== long_format
771 || trace_links
|| trace_dirs
|| indicator_style
!= none
772 || print_block_size
|| print_inode
|| print_with_color
;
774 if (dired
&& format
== long_format
)
776 obstack_init (&dired_obstack
);
777 obstack_init (&subdired_obstack
);
781 files
= (struct fileinfo
*) xmalloc (sizeof (struct fileinfo
) * nfiles
);
788 for (; i
< argc
; i
++)
790 strip_trailing_slashes (argv
[i
]);
791 gobble_file (argv
[i
], 1, "");
797 gobble_file (".", 1, "");
799 queue_directory (".", 0);
806 extract_dirs_from_files ("", 0);
807 /* `files_index' might be zero now. */
811 print_current_files ();
813 DIRED_PUTCHAR ('\n');
815 else if (pending_dirs
&& pending_dirs
->next
== 0)
820 thispend
= pending_dirs
;
821 pending_dirs
= pending_dirs
->next
;
822 print_dir (thispend
->name
, thispend
->realname
);
823 free (thispend
->name
);
824 if (thispend
->realname
)
825 free (thispend
->realname
);
830 if (dired
&& format
== long_format
)
832 /* No need to free these since we're about to exit. */
833 dired_dump_obstack ("//DIRED//", &dired_obstack
);
834 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
835 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
836 ARGMATCH_TO_ARGUMENT (filename_quoting_options
,
837 quoting_style_args
, quoting_style_vals
));
840 /* Restore default color before exiting */
841 if (print_with_color
)
843 put_indicator (&color_indicator
[C_LEFT
]);
844 put_indicator (&color_indicator
[C_RIGHT
]);
851 /* Set all the option flags according to the switches specified.
852 Return the index of the first non-option argument. */
855 decode_switches (int argc
, char **argv
)
857 register char const *p
;
862 qmark_funny_chars
= 0;
864 /* initialize all switches to default settings */
869 /* This is for the `dir' program. */
870 format
= many_per_line
;
871 set_quoting_style (NULL
, escape_quoting_style
);
875 /* This is for the `vdir' program. */
876 format
= long_format
;
877 set_quoting_style (NULL
, escape_quoting_style
);
881 /* This is for the `ls' program. */
882 if (isatty (STDOUT_FILENO
))
884 format
= many_per_line
;
885 /* See description of qmark_funny_chars, above. */
886 qmark_funny_chars
= 1;
890 format
= one_per_line
;
891 qmark_funny_chars
= 0;
899 time_type
= time_mtime
;
901 sort_type
= sort_name
;
904 print_block_size
= 0;
905 indicator_style
= none
;
911 really_all_files
= 0;
914 /* FIXME: Shouldn't we complain on wrong values? */
915 if ((p
= getenv ("QUOTING_STYLE"))
916 && 0 <= (i
= ARGCASEMATCH (p
, quoting_style_args
, quoting_style_vals
)))
917 set_quoting_style (NULL
, quoting_style_vals
[i
]);
919 human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size
);
922 if ((p
= getenv ("COLUMNS")) && *p
)
924 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
925 && 0 < tmp_long
&& tmp_long
<= INT_MAX
)
927 line_length
= (int) tmp_long
;
932 _("ignoring invalid width in environment variable COLUMNS: %s"),
941 if (ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
!= 0)
942 line_length
= ws
.ws_col
;
946 /* Using the TABSIZE environment variable is not POSIX-approved.
947 Ignore it when POSIXLY_CORRECT is set. */
949 if (!getenv ("POSIXLY_CORRECT") && (p
= getenv ("TABSIZE")))
951 if (xstrtol (p
, NULL
, 0, &tmp_long
, NULL
) == LONGINT_OK
952 && 0 <= tmp_long
&& tmp_long
<= INT_MAX
)
954 tabsize
= (int) tmp_long
;
959 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
964 while ((c
= getopt_long (argc
, argv
,
965 "abcdefghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
966 long_options
, NULL
)) != -1)
975 really_all_files
= 1;
979 set_quoting_style (NULL
, escape_quoting_style
);
983 time_type
= time_ctime
;
984 sort_type
= sort_time
;
992 /* Same as enabling -a -U and disabling -l -s. */
994 really_all_files
= 1;
995 sort_type
= sort_none
;
997 if (format
== long_format
)
998 format
= (isatty (STDOUT_FILENO
) ? many_per_line
: one_per_line
);
999 print_block_size
= 0; /* disable -s */
1000 print_with_color
= 0; /* disable --color */
1004 /* No effect. For BSD compatibility. */
1008 output_block_size
= -1024;
1012 output_block_size
= -1000;
1020 output_block_size
= 1024;
1024 format
= long_format
;
1028 format
= with_commas
;
1035 case 'o': /* Just like -l, but don't display group info. */
1036 format
= long_format
;
1041 indicator_style
= file_type
;
1045 qmark_funny_chars
= 1;
1053 print_block_size
= 1;
1057 sort_type
= sort_time
;
1061 sort_type
= sort_time
;
1062 time_type
= time_atime
;
1066 sort_type
= sort_version
;
1070 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1071 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1072 error (EXIT_FAILURE
, 0, _("invalid line width: %s"),
1074 line_length
= (int) tmp_long
;
1078 format
= horizontal
;
1082 really_all_files
= 0;
1087 add_ignore_pattern ("*~");
1088 add_ignore_pattern (".*~");
1092 format
= many_per_line
;
1100 indicator_style
= classify
;
1103 case 'G': /* inhibit display of group info */
1108 add_ignore_pattern (optarg
);
1116 set_quoting_style (NULL
, literal_quoting_style
);
1120 set_quoting_style (NULL
, c_quoting_style
);
1128 sort_type
= sort_size
;
1132 if (xstrtol (optarg
, NULL
, 0, &tmp_long
, NULL
) != LONGINT_OK
1133 || tmp_long
< 0 || tmp_long
> INT_MAX
)
1134 error (EXIT_FAILURE
, 0, _("invalid tab size: %s"),
1136 tabsize
= (int) tmp_long
;
1140 sort_type
= sort_none
;
1144 sort_type
= sort_extension
;
1148 format
= one_per_line
;
1151 case 10: /* --sort */
1152 sort_type
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
1155 case 11: /* --time */
1156 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
1159 case 12: /* --format */
1160 format
= XARGMATCH ("--format", optarg
, format_args
, format_types
);
1163 case 13: /* --color */
1165 i
= XARGMATCH ("--color", optarg
, color_args
, color_types
);
1167 /* Using --color with no argument is equivalent to using
1171 print_with_color
= (i
== color_always
1172 || (i
== color_if_tty
1173 && isatty (STDOUT_FILENO
)));
1175 if (print_with_color
)
1177 /* Don't use TAB characters in output. Some terminal
1178 emulators can't handle the combination of tabs and
1179 color codes on the same line. */
1184 case 14: /* --indicator-style */
1185 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
1186 indicator_style_args
,
1187 indicator_style_types
);
1190 case 15: /* --quoting-style */
1191 set_quoting_style (NULL
,
1192 XARGMATCH ("--quoting-style", optarg
,
1194 quoting_style_vals
));
1198 qmark_funny_chars
= 0;
1202 human_block_size (optarg
, 1, &output_block_size
);
1205 case_GETOPT_HELP_CHAR
;
1207 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1210 usage (EXIT_FAILURE
);
1214 filename_quoting_options
= clone_quoting_options (NULL
);
1215 if (get_quoting_style (filename_quoting_options
) == escape_quoting_style
)
1216 set_char_quoting (filename_quoting_options
, ' ', 1);
1217 if (indicator_style
!= none
)
1218 for (p
= "*=@|" + (int) indicator_style
- 1; *p
; p
++)
1219 set_char_quoting (filename_quoting_options
, *p
, 1);
1221 dirname_quoting_options
= clone_quoting_options (NULL
);
1222 set_char_quoting (dirname_quoting_options
, ':', 1);
1227 /* Parse a string as part of the LS_COLORS variable; this may involve
1228 decoding all kinds of escape characters. If equals_end is set an
1229 unescaped equal sign ends the string, otherwise only a : or \0
1230 does. Returns the number of characters output, or -1 on failure.
1232 The resulting string is *not* null-terminated, but may contain
1235 Note that both dest and src are char **; on return they point to
1236 the first free byte after the array and the character that ended
1237 the input string, respectively. */
1240 get_funky_string (char **dest
, const char **src
, int equals_end
)
1242 int num
; /* For numerical codes */
1243 int count
; /* Something to count with */
1245 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
1250 p
= *src
; /* We don't want to double-indirect */
1251 q
= *dest
; /* the whole darn time. */
1253 count
= 0; /* No characters counted in yet. */
1256 state
= ST_GND
; /* Start in ground state. */
1257 while (state
< ST_END
)
1261 case ST_GND
: /* Ground state (no escapes) */
1266 state
= ST_END
; /* End of string */
1269 state
= ST_BACKSLASH
; /* Backslash scape sequence */
1273 state
= ST_CARET
; /* Caret escape */
1279 state
= ST_END
; /* End */
1282 /* else fall through */
1290 case ST_BACKSLASH
: /* Backslash escaped character */
1301 state
= ST_OCTAL
; /* Octal sequence */
1306 state
= ST_HEX
; /* Hex sequence */
1309 case 'a': /* Bell */
1310 num
= 7; /* Not all C compilers know what \a means */
1312 case 'b': /* Backspace */
1315 case 'e': /* Escape */
1318 case 'f': /* Form feed */
1321 case 'n': /* Newline */
1324 case 'r': /* Carriage return */
1330 case 'v': /* Vtab */
1333 case '?': /* Delete */
1336 case '_': /* Space */
1339 case '\0': /* End of string */
1340 state
= ST_ERROR
; /* Error! */
1342 default: /* Escaped character like \ ^ : = */
1346 if (state
== ST_BACKSLASH
)
1355 case ST_OCTAL
: /* Octal sequence */
1356 if (*p
< '0' || *p
> '7')
1363 num
= (num
<< 3) + (*(p
++) - '0');
1366 case ST_HEX
: /* Hex sequence */
1379 num
= (num
<< 4) + (*(p
++) - '0');
1387 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
1395 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
1405 case ST_CARET
: /* Caret escape */
1406 state
= ST_GND
; /* Should be the next state... */
1407 if (*p
>= '@' && *p
<= '~')
1409 *(q
++) = *(p
++) & 037;
1429 return state
== ST_ERROR
? -1 : count
;
1433 parse_ls_color (void)
1435 const char *p
; /* Pointer to character being parsed */
1436 char *buf
; /* color_buf buffer pointer */
1437 int state
; /* State of parser */
1438 int ind_no
; /* Indicator number */
1439 char label
[3]; /* Indicator label */
1440 struct color_ext_type
*ext
; /* Extension we are working on */
1442 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
1446 strcpy (label
, "??");
1448 /* This is an overly conservative estimate, but any possible
1449 LS_COLORS string will *not* generate a color_buf longer than
1450 itself, so it is a safe way of allocating a buffer in
1452 buf
= color_buf
= xstrdup (p
);
1459 case 1: /* First label character */
1467 /* Allocate new extension block and add to head of
1468 linked list (this way a later definition will
1469 override an earlier one, which can be useful for
1470 having terminal-specific defs override global). */
1472 ext
= (struct color_ext_type
*)
1473 xmalloc (sizeof (struct color_ext_type
));
1474 ext
->next
= color_ext_list
;
1475 color_ext_list
= ext
;
1478 ext
->ext
.string
= buf
;
1480 state
= (ext
->ext
.len
=
1481 get_funky_string (&buf
, &p
, 1)) < 0 ? -1 : 4;
1485 state
= 0; /* Done! */
1488 default: /* Assume it is file type label */
1495 case 2: /* Second label character */
1502 state
= -1; /* Error */
1505 case 3: /* Equal sign after indicator label */
1506 state
= -1; /* Assume failure... */
1507 if (*(p
++) == '=')/* It *should* be... */
1509 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
1511 if (STREQ (label
, indicator_name
[ind_no
]))
1513 color_indicator
[ind_no
].string
= buf
;
1514 state
= ((color_indicator
[ind_no
].len
=
1515 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1);
1520 error (0, 0, _("unrecognized prefix: %s"), quotearg (label
));
1524 case 4: /* Equal sign after *.ext */
1527 ext
->seq
.string
= buf
;
1528 state
= (ext
->seq
.len
=
1529 get_funky_string (&buf
, &p
, 0)) < 0 ? -1 : 1;
1539 struct color_ext_type
*e
;
1540 struct color_ext_type
*e2
;
1543 _("unparsable value for LS_COLORS environment variable"));
1545 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
1551 print_with_color
= 0;
1555 /* Request that the directory named `name' have its contents listed later.
1556 If `realname' is nonzero, it will be used instead of `name' when the
1557 directory name is printed. This allows symbolic links to directories
1558 to be treated as regular directories but still be listed under their
1562 queue_directory (const char *name
, const char *realname
)
1564 struct pending
*new;
1566 new = (struct pending
*) xmalloc (sizeof (struct pending
));
1567 new->next
= pending_dirs
;
1569 new->name
= xstrdup (name
);
1571 new->realname
= xstrdup (realname
);
1576 /* Read directory `name', and list the files in it.
1577 If `realname' is nonzero, print its name instead of `name';
1578 this is used for symbolic links to directories. */
1581 print_dir (const char *name
, const char *realname
)
1583 register DIR *reading
;
1584 register struct dirent
*next
;
1585 register uintmax_t total_blocks
= 0;
1588 reading
= opendir (name
);
1591 error (0, errno
, "%s", quotearg_colon (name
));
1596 /* Read the directory entries, and insert the subfiles into the `files'
1601 while ((next
= readdir (reading
)) != NULL
)
1602 if (file_interesting (next
))
1603 total_blocks
+= gobble_file (next
->d_name
, 0, name
);
1605 if (CLOSEDIR (reading
))
1607 error (0, errno
, "%s", quotearg_colon (name
));
1609 /* Don't return; print whatever we got. */
1612 /* Sort the directory contents. */
1615 /* If any member files are subdirectories, perhaps they should have their
1616 contents listed rather than being mentioned here as files. */
1619 extract_dirs_from_files (name
, 1);
1621 if (trace_dirs
|| print_dir_name
)
1624 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1625 dired_pos
+= quote_name (stdout
, realname
? realname
: name
,
1626 dirname_quoting_options
);
1627 PUSH_CURRENT_DIRED_POS (&subdired_obstack
);
1628 DIRED_FPUTS_LITERAL (":\n", stdout
);
1631 if (format
== long_format
|| print_block_size
)
1634 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1638 DIRED_FPUTS (p
, stdout
, strlen (p
));
1639 DIRED_PUTCHAR (' ');
1640 p
= human_readable (total_blocks
, buf
, ST_NBLOCKSIZE
, output_block_size
);
1641 DIRED_FPUTS (p
, stdout
, strlen (p
));
1642 DIRED_PUTCHAR ('\n');
1646 print_current_files ();
1649 DIRED_PUTCHAR ('\n');
1652 /* Add `pattern' to the list of patterns for which files that match are
1656 add_ignore_pattern (const char *pattern
)
1658 register struct ignore_pattern
*ignore
;
1660 ignore
= (struct ignore_pattern
*) xmalloc (sizeof (struct ignore_pattern
));
1661 ignore
->pattern
= pattern
;
1662 /* Add it to the head of the linked list. */
1663 ignore
->next
= ignore_patterns
;
1664 ignore_patterns
= ignore
;
1667 /* Return nonzero if the file in `next' should be listed. */
1670 file_interesting (const struct dirent
*next
)
1672 register struct ignore_pattern
*ignore
;
1674 for (ignore
= ignore_patterns
; ignore
; ignore
= ignore
->next
)
1675 if (fnmatch (ignore
->pattern
, next
->d_name
, FNM_PERIOD
) == 0)
1678 if (really_all_files
1679 || next
->d_name
[0] != '.'
1681 && next
->d_name
[1] != '\0'
1682 && (next
->d_name
[1] != '.' || next
->d_name
[2] != '\0')))
1688 /* Enter and remove entries in the table `files'. */
1690 /* Empty the table of files. */
1697 for (i
= 0; i
< files_index
; i
++)
1699 free (files
[i
].name
);
1700 if (files
[i
].linkname
)
1701 free (files
[i
].linkname
);
1705 block_size_size
= 4;
1708 /* Add a file to the current table of files.
1709 Verify that the file exists, and print an error message if it does not.
1710 Return the number of blocks that the file occupies. */
1713 gobble_file (const char *name
, int explicit_arg
, const char *dirname
)
1715 register uintmax_t blocks
;
1717 register char *path
;
1719 if (files_index
== nfiles
)
1722 files
= (struct fileinfo
*) xrealloc ((char *) files
,
1723 sizeof (*files
) * nfiles
);
1726 files
[files_index
].linkname
= 0;
1727 files
[files_index
].linkmode
= 0;
1728 files
[files_index
].linkok
= 0;
1730 if (explicit_arg
|| format_needs_stat
)
1732 /* `path' is the absolute pathname of this file. */
1734 if (name
[0] == '/' || dirname
[0] == 0)
1735 path
= (char *) name
;
1738 path
= (char *) alloca (strlen (name
) + strlen (dirname
) + 2);
1739 attach (path
, dirname
, name
);
1744 val
= stat (path
, &files
[files_index
].stat
);
1747 /* Perhaps a symbolically-linked to file doesn't exist; stat
1748 the link instead. */
1749 val
= lstat (path
, &files
[files_index
].stat
);
1754 val
= lstat (path
, &files
[files_index
].stat
);
1756 files
[files_index
].have_acl
= (acl (path
, GETACLCNT
, 0, NULL
) > 4);
1762 error (0, errno
, "%s", quotearg_colon (path
));
1767 if (S_ISLNK (files
[files_index
].stat
.st_mode
)
1768 && (explicit_arg
|| format
== long_format
|| print_with_color
))
1771 struct stat linkstats
;
1773 get_link_name (path
, &files
[files_index
]);
1774 linkpath
= make_link_path (path
, files
[files_index
].linkname
);
1776 /* Avoid following symbolic links when possible, ie, when
1777 they won't be traced and when no indicator is needed. */
1779 && ((explicit_arg
&& format
!= long_format
)
1780 || indicator_style
!= none
1781 || print_with_color
)
1782 && stat (linkpath
, &linkstats
) == 0)
1784 files
[files_index
].linkok
= 1;
1786 /* Symbolic links to directories that are mentioned on the
1787 command line are automatically traced if not being
1789 if (explicit_arg
&& format
!= long_format
1790 && S_ISDIR (linkstats
.st_mode
))
1792 /* Substitute the linked-to directory's name, but
1793 save the real name in `linkname' for printing. */
1794 if (!immediate_dirs
)
1796 const char *tempname
= name
;
1798 linkpath
= files
[files_index
].linkname
;
1799 files
[files_index
].linkname
= (char *) tempname
;
1801 files
[files_index
].stat
= linkstats
;
1805 /* Get the linked-to file's mode for the filetype indicator
1806 in long listings. */
1807 files
[files_index
].linkmode
= linkstats
.st_mode
;
1808 files
[files_index
].linkok
= 1;
1815 if (S_ISLNK (files
[files_index
].stat
.st_mode
))
1816 files
[files_index
].filetype
= symbolic_link
;
1817 else if (S_ISDIR (files
[files_index
].stat
.st_mode
))
1819 if (explicit_arg
&& !immediate_dirs
)
1820 files
[files_index
].filetype
= arg_directory
;
1822 files
[files_index
].filetype
= directory
;
1825 files
[files_index
].filetype
= normal
;
1827 blocks
= ST_NBLOCKS (files
[files_index
].stat
);
1829 char buf
[LONGEST_HUMAN_READABLE
+ 1];
1830 int len
= strlen (human_readable (blocks
, buf
, ST_NBLOCKSIZE
,
1831 output_block_size
));
1832 if (block_size_size
< len
)
1833 block_size_size
= len
< 7 ? len
: 7;
1839 files
[files_index
].name
= xstrdup (name
);
1847 /* Put the name of the file that `filename' is a symbolic link to
1848 into the `linkname' field of `f'. */
1851 get_link_name (const char *filename
, struct fileinfo
*f
)
1854 register int linksize
;
1856 linkbuf
= (char *) alloca (PATH_MAX
+ 2);
1857 /* Some automounters give incorrect st_size for mount points.
1858 I can't think of a good workaround for it, though. */
1859 linksize
= readlink (filename
, linkbuf
, PATH_MAX
+ 1);
1862 error (0, errno
, "%s", quotearg_colon (filename
));
1867 linkbuf
[linksize
] = '\0';
1868 f
->linkname
= xstrdup (linkbuf
);
1872 /* If `linkname' is a relative path and `path' contains one or more
1873 leading directories, return `linkname' with those directories
1874 prepended; otherwise, return a copy of `linkname'.
1875 If `linkname' is zero, return zero. */
1878 make_link_path (const char *path
, const char *linkname
)
1886 if (*linkname
== '/')
1887 return xstrdup (linkname
);
1889 /* The link is to a relative path. Prepend any leading path
1890 in `path' to the link name. */
1891 linkbuf
= strrchr (path
, '/');
1893 return xstrdup (linkname
);
1895 bufsiz
= linkbuf
- path
+ 1;
1896 linkbuf
= xmalloc (bufsiz
+ strlen (linkname
) + 1);
1897 strncpy (linkbuf
, path
, bufsiz
);
1898 strcpy (linkbuf
+ bufsiz
, linkname
);
1903 /* Return nonzero if base_name (NAME) ends in `.' or `..'
1904 This is so we don't try to recurse on `././././. ...' */
1907 basename_is_dot_or_dotdot (const char *name
)
1909 char *base
= base_name (name
);
1910 return DOT_OR_DOTDOT (base
);
1913 /* Remove any entries from `files' that are for directories,
1914 and queue them to be listed as directories instead.
1915 `dirname' is the prefix to prepend to each dirname
1916 to make it correct relative to ls's working dir.
1917 `recursive' is nonzero if we should not treat `.' and `..' as dirs.
1918 This is desirable when processing directories recursively. */
1921 extract_dirs_from_files (const char *dirname
, int recursive
)
1926 dirlen
= strlen (dirname
) + 2;
1927 /* Queue the directories last one first, because queueing reverses the
1929 for (i
= files_index
- 1; i
>= 0; i
--)
1930 if ((files
[i
].filetype
== directory
|| files
[i
].filetype
== arg_directory
)
1931 && (!recursive
|| !basename_is_dot_or_dotdot (files
[i
].name
)))
1933 if (files
[i
].name
[0] == '/' || dirname
[0] == 0)
1935 queue_directory (files
[i
].name
, files
[i
].linkname
);
1939 char *path
= path_concat (dirname
, files
[i
].name
, NULL
);
1940 queue_directory (path
, files
[i
].linkname
);
1943 if (files
[i
].filetype
== arg_directory
)
1944 free (files
[i
].name
);
1947 /* Now delete the directories from the table, compacting all the remaining
1950 for (i
= 0, j
= 0; i
< files_index
; i
++)
1951 if (files
[i
].filetype
!= arg_directory
)
1952 files
[j
++] = files
[i
];
1956 /* Sort the files now in the table. */
1971 func
= sort_reverse
? rev_cmp_ctime
: compare_ctime
;
1974 func
= sort_reverse
? rev_cmp_mtime
: compare_mtime
;
1977 func
= sort_reverse
? rev_cmp_atime
: compare_atime
;
1984 func
= sort_reverse
? rev_cmp_name
: compare_name
;
1986 case sort_extension
:
1987 func
= sort_reverse
? rev_cmp_extension
: compare_extension
;
1990 func
= sort_reverse
? rev_cmp_size
: compare_size
;
1993 func
= sort_reverse
? rev_cmp_version
: compare_version
;
1999 qsort (files
, files_index
, sizeof (struct fileinfo
), func
);
2002 /* Comparison routines for sorting the files. */
2005 compare_ctime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2007 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
2009 diff
= strcmp (file1
->name
, file2
->name
);
2014 rev_cmp_ctime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2016 int diff
= CTIME_CMP (file2
->stat
, file1
->stat
);
2018 diff
= strcmp (file1
->name
, file2
->name
);
2023 compare_mtime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2025 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
2027 diff
= strcmp (file1
->name
, file2
->name
);
2032 rev_cmp_mtime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2034 int diff
= MTIME_CMP (file2
->stat
, file1
->stat
);
2036 diff
= strcmp (file1
->name
, file2
->name
);
2041 compare_atime (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2043 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2045 diff
= strcmp (file1
->name
, file2
->name
);
2050 rev_cmp_atime (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2052 int diff
= ATIME_CMP (file2
->stat
, file1
->stat
);
2054 diff
= strcmp (file1
->name
, file2
->name
);
2059 compare_size (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2061 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2063 diff
= strcmp (file1
->name
, file2
->name
);
2068 rev_cmp_size (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2070 int diff
= longdiff (file2
->stat
.st_size
, file1
->stat
.st_size
);
2072 diff
= strcmp (file1
->name
, file2
->name
);
2077 compare_version (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2079 return strverscmp (file1
->name
, file2
->name
);
2083 rev_cmp_version (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2085 return strverscmp (file1
->name
, file2
->name
);
2089 compare_name (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2091 return strcmp (file1
->name
, file2
->name
);
2095 rev_cmp_name (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2097 return strcmp (file1
->name
, file2
->name
);
2100 /* Compare file extensions. Files with no extension are `smallest'.
2101 If extensions are the same, compare by filenames instead. */
2104 compare_extension (const struct fileinfo
*file1
, const struct fileinfo
*file2
)
2106 register char *base1
, *base2
;
2109 base1
= strrchr (file1
->name
, '.');
2110 base2
= strrchr (file2
->name
, '.');
2111 if (base1
== 0 && base2
== 0)
2112 return strcmp (file1
->name
, file2
->name
);
2117 cmp
= strcmp (base1
, base2
);
2119 return strcmp (file1
->name
, file2
->name
);
2124 rev_cmp_extension (const struct fileinfo
*file2
, const struct fileinfo
*file1
)
2126 register char *base1
, *base2
;
2129 base1
= strrchr (file1
->name
, '.');
2130 base2
= strrchr (file2
->name
, '.');
2131 if (base1
== 0 && base2
== 0)
2132 return strcmp (file1
->name
, file2
->name
);
2137 cmp
= strcmp (base1
, base2
);
2139 return strcmp (file1
->name
, file2
->name
);
2143 /* List all the files now in the table. */
2146 print_current_files (void)
2153 for (i
= 0; i
< files_index
; i
++)
2155 print_file_name_and_frills (files
+ i
);
2161 init_column_info ();
2162 print_many_per_line ();
2166 init_column_info ();
2167 print_horizontal ();
2171 print_with_commas ();
2175 for (i
= 0; i
< files_index
; i
++)
2177 print_long_format (files
+ i
);
2178 DIRED_PUTCHAR ('\n');
2185 print_long_format (const struct fileinfo
*f
)
2189 /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2190 1 10-byte mode string,
2191 1 24-byte time string (may be longer in some locales -- see below)
2192 or LONGEST_HUMAN_READABLE integer,
2193 9 spaces, one following each of these fields, and
2194 1 trailing NUL byte. */
2195 char init_bigbuf
[7 * LONGEST_HUMAN_READABLE
+ 10
2196 + (LONGEST_HUMAN_READABLE
< 24 ? 24 : LONGEST_HUMAN_READABLE
)
2198 char *buf
= init_bigbuf
;
2199 size_t bufsize
= sizeof (init_bigbuf
);
2203 struct tm
*when_local
;
2208 /* Cray DMF: look at the file's migrated, not real, status */
2209 mode_string (f
->stat
.st_dm_mode
, modebuf
);
2211 mode_string (f
->stat
.st_mode
, modebuf
);
2214 modebuf
[10] = (FILE_HAS_ACL (f
) ? '+' : ' ');
2220 when
= f
->stat
.st_ctime
;
2223 when
= f
->stat
.st_mtime
;
2226 when
= f
->stat
.st_atime
;
2232 fmt
= "%a %b %d %H:%M:%S %Y";
2236 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
2237 || current_time
< when
- 60L * 60L) /* In the future. */
2239 /* The file is fairly old or in the future.
2240 POSIX says the cutoff is 6 months old;
2241 approximate this by 6*30 days.
2242 Allow a 1 hour slop factor for what is considered "the future",
2243 to allow for NFS server/client clock disagreement.
2244 Show the year instead of the time of day. */
2249 fmt
= "%b %e %H:%M";
2257 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2258 sprintf (p
, "%*s ", INODE_DIGITS
,
2259 human_readable ((uintmax_t) f
->stat
.st_ino
, hbuf
, 1, 1));
2263 if (print_block_size
)
2265 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2266 sprintf (p
, "%*s ", block_size_size
,
2267 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), hbuf
,
2268 ST_NBLOCKSIZE
, output_block_size
));
2272 /* The last byte of the mode string is the POSIX
2273 "optional alternate access method flag". */
2274 sprintf (p
, "%s %3u ", modebuf
, (unsigned int) f
->stat
.st_nlink
);
2277 user_name
= (numeric_ids
? NULL
: getuser (f
->stat
.st_uid
));
2279 sprintf (p
, "%-8.8s ", user_name
);
2281 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_uid
);
2286 char *group_name
= (numeric_ids
? NULL
: getgroup (f
->stat
.st_gid
));
2288 sprintf (p
, "%-8.8s ", group_name
);
2290 sprintf (p
, "%-8u ", (unsigned int) f
->stat
.st_gid
);
2294 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
2295 sprintf (p
, "%3u, %3u ", (unsigned) major (f
->stat
.st_rdev
),
2296 (unsigned) minor (f
->stat
.st_rdev
));
2299 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2301 human_readable ((uintmax_t) f
->stat
.st_size
, hbuf
, 1,
2302 output_block_size
< 0 ? output_block_size
: 1));
2307 /* Use strftime rather than ctime, because the former can produce
2308 locale-dependent names for the weekday (%a) and month (%b). */
2310 if ((when_local
= localtime (&when
)))
2312 while (! (s
= strftime (p
, buf
+ bufsize
- p
- 1, fmt
, when_local
)))
2314 char *newbuf
= (char *) alloca (bufsize
*= 2);
2315 memcpy (newbuf
, buf
, p
- buf
);
2316 p
= newbuf
+ (p
- buf
);
2323 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
2328 /* The time cannot be represented as a local time;
2329 print it as a huge integer number of seconds. */
2330 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
2331 int width
= full_time
? 24 : 12;
2335 const char *num
= human_readable (- (uintmax_t) when
, hbuf
, 1, 1);
2336 int sign_width
= width
- strlen (num
);
2337 sprintf (p
, "%*s%s ", sign_width
< 0 ? 0 : sign_width
, "-", num
);
2340 sprintf (p
, "%*s ", width
,
2341 human_readable ((uintmax_t) when
, hbuf
, 1, 1));
2347 DIRED_FPUTS (buf
, stdout
, p
- buf
);
2348 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
,
2351 if (f
->filetype
== symbolic_link
)
2355 DIRED_FPUTS_LITERAL (" -> ", stdout
);
2356 print_name_with_quoting (f
->linkname
, f
->linkmode
, f
->linkok
- 1,
2358 if (indicator_style
!= none
)
2359 print_type_indicator (f
->linkmode
);
2362 else if (indicator_style
!= none
)
2363 print_type_indicator (f
->stat
.st_mode
);
2366 /* Output to OUT a quoted representation of the file name P,
2367 using OPTIONS to control quoting.
2368 Return the number of characters in P's quoted representation. */
2371 quote_name (FILE *out
, const char *p
, struct quoting_options
const *options
)
2373 char smallbuf
[BUFSIZ
];
2374 size_t len
= quotearg_buffer (smallbuf
, sizeof smallbuf
, p
, -1, options
);
2377 if (len
< sizeof smallbuf
)
2381 buf
= (char *) alloca (len
+ 1);
2382 quotearg_buffer (buf
, len
+ 1, p
, -1, options
);
2385 if (qmark_funny_chars
)
2388 for (i
= 0; i
< len
; i
++)
2389 if (! ISPRINT ((unsigned char) buf
[i
]))
2393 fwrite (buf
, 1, len
, out
);
2398 print_name_with_quoting (const char *p
, unsigned int mode
, int linkok
,
2399 struct obstack
*stack
)
2401 if (print_with_color
)
2402 print_color_indicator (p
, mode
, linkok
);
2405 PUSH_CURRENT_DIRED_POS (stack
);
2407 dired_pos
+= quote_name (stdout
, p
, filename_quoting_options
);
2410 PUSH_CURRENT_DIRED_POS (stack
);
2412 if (print_with_color
)
2413 prep_non_filename_text ();
2417 prep_non_filename_text (void)
2419 if (color_indicator
[C_END
].string
!= NULL
)
2420 put_indicator (&color_indicator
[C_END
]);
2423 put_indicator (&color_indicator
[C_LEFT
]);
2424 put_indicator (&color_indicator
[C_NORM
]);
2425 put_indicator (&color_indicator
[C_RIGHT
]);
2429 /* Print the file name of `f' with appropriate quoting.
2430 Also print file size, inode number, and filetype indicator character,
2431 as requested by switches. */
2434 print_file_name_and_frills (const struct fileinfo
*f
)
2436 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2439 printf ("%*s ", INODE_DIGITS
,
2440 human_readable ((uintmax_t) f
->stat
.st_ino
, buf
, 1, 1));
2442 if (print_block_size
)
2443 printf ("%*s ", block_size_size
,
2444 human_readable ((uintmax_t) ST_NBLOCKS (f
->stat
), buf
,
2445 ST_NBLOCKSIZE
, output_block_size
));
2447 print_name_with_quoting (f
->name
, f
->stat
.st_mode
, f
->linkok
, NULL
);
2449 if (indicator_style
!= none
)
2450 print_type_indicator (f
->stat
.st_mode
);
2454 print_type_indicator (unsigned int mode
)
2460 if (indicator_style
== classify
&& (mode
& S_IXUGO
))
2469 else if (S_ISLNK (mode
))
2471 else if (S_ISFIFO (mode
))
2473 else if (S_ISSOCK (mode
))
2475 else if (S_ISDOOR (mode
))
2486 print_color_indicator (const char *name
, unsigned int mode
, int linkok
)
2489 struct color_ext_type
*ext
; /* Color extension */
2490 size_t len
; /* Length of name */
2492 /* Is this a nonexistent file? If so, linkok == -1. */
2494 if (linkok
== -1 && color_indicator
[C_MISSING
].string
!= NULL
)
2503 else if (S_ISLNK (mode
))
2504 type
= ((!linkok
&& color_indicator
[C_ORPHAN
].string
)
2505 ? C_ORPHAN
: C_LINK
);
2506 else if (S_ISFIFO (mode
))
2508 else if (S_ISSOCK (mode
))
2510 else if (S_ISBLK (mode
))
2512 else if (S_ISCHR (mode
))
2514 else if (S_ISDOOR (mode
))
2517 if (type
== C_FILE
&& (mode
& S_IXUGO
) != 0)
2520 /* Check the file's suffix only if still classified as C_FILE. */
2524 /* Test if NAME has a recognized suffix. */
2526 len
= strlen (name
);
2527 name
+= len
; /* Pointer to final \0. */
2528 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
2530 if ((size_t) ext
->ext
.len
<= len
2531 && strncmp (name
- ext
->ext
.len
, ext
->ext
.string
,
2538 put_indicator (&color_indicator
[C_LEFT
]);
2539 put_indicator (ext
? &(ext
->seq
) : &color_indicator
[type
]);
2540 put_indicator (&color_indicator
[C_RIGHT
]);
2543 /* Output a color indicator (which may contain nulls). */
2545 put_indicator (const struct bin_str
*ind
)
2552 for (i
= ind
->len
; i
> 0; --i
)
2557 length_of_file_name_and_frills (const struct fileinfo
*f
)
2559 register int len
= 0;
2562 len
+= INODE_DIGITS
+ 1;
2564 if (print_block_size
)
2565 len
+= 1 + block_size_size
;
2567 len
+= quotearg_buffer (0, 0, f
->name
, -1, filename_quoting_options
);
2569 if (indicator_style
!= none
)
2571 unsigned filetype
= f
->stat
.st_mode
;
2573 if (S_ISREG (filetype
))
2575 if (indicator_style
== classify
2576 && (f
->stat
.st_mode
& S_IXUGO
))
2579 else if (S_ISDIR (filetype
)
2580 || S_ISLNK (filetype
)
2581 || S_ISFIFO (filetype
)
2582 || S_ISSOCK (filetype
)
2583 || S_ISDOOR (filetype
)
2592 print_many_per_line (void)
2594 struct column_info
*line_fmt
;
2595 int filesno
; /* Index into files. */
2596 int row
; /* Current row. */
2597 int max_name_length
; /* Length of longest file name + frills. */
2598 int name_length
; /* Length of each file name + frills. */
2599 int pos
; /* Current character column. */
2600 int cols
; /* Number of files across. */
2601 int rows
; /* Maximum number of files down. */
2604 /* Normally the maximum number of columns is determined by the
2605 screen width. But if few files are available this might limit it
2607 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2609 /* Compute the maximum number of possible columns. */
2610 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2614 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2616 for (i
= 0; i
< max_cols
; ++i
)
2618 if (column_info
[i
].valid_len
)
2620 int idx
= filesno
/ ((files_index
+ i
) / (i
+ 1));
2621 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2623 if (real_length
> column_info
[i
].col_arr
[idx
])
2625 column_info
[i
].line_len
+= (real_length
2626 - column_info
[i
].col_arr
[idx
]);
2627 column_info
[i
].col_arr
[idx
] = real_length
;
2628 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2634 /* Find maximum allowed columns. */
2635 for (cols
= max_cols
; cols
> 1; --cols
)
2637 if (column_info
[cols
- 1].valid_len
)
2641 line_fmt
= &column_info
[cols
- 1];
2643 /* Calculate the number of rows that will be in each column except possibly
2644 for a short column on the right. */
2645 rows
= files_index
/ cols
+ (files_index
% cols
!= 0);
2647 for (row
= 0; row
< rows
; row
++)
2652 /* Print the next row. */
2655 print_file_name_and_frills (files
+ filesno
);
2656 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2657 max_name_length
= line_fmt
->col_arr
[col
++];
2660 if (filesno
>= files_index
)
2663 indent (pos
+ name_length
, pos
+ max_name_length
);
2664 pos
+= max_name_length
;
2671 print_horizontal (void)
2673 struct column_info
*line_fmt
;
2675 int max_name_length
;
2681 /* Normally the maximum number of columns is determined by the
2682 screen width. But if few files are available this might limit it
2684 max_cols
= max_idx
> files_index
? files_index
: max_idx
;
2686 /* Compute the maximum file name length. */
2687 max_name_length
= 0;
2688 for (filesno
= 0; filesno
< files_index
; ++filesno
)
2692 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2694 for (i
= 0; i
< max_cols
; ++i
)
2696 if (column_info
[i
].valid_len
)
2698 int idx
= filesno
% (i
+ 1);
2699 int real_length
= name_length
+ (idx
== i
? 0 : 2);
2701 if (real_length
> column_info
[i
].col_arr
[idx
])
2703 column_info
[i
].line_len
+= (real_length
2704 - column_info
[i
].col_arr
[idx
]);
2705 column_info
[i
].col_arr
[idx
] = real_length
;
2706 column_info
[i
].valid_len
= column_info
[i
].line_len
< line_length
;
2712 /* Find maximum allowed columns. */
2713 for (cols
= max_cols
; cols
> 1; --cols
)
2715 if (column_info
[cols
- 1].valid_len
)
2719 line_fmt
= &column_info
[cols
- 1];
2723 /* Print first entry. */
2724 print_file_name_and_frills (files
);
2725 name_length
= length_of_file_name_and_frills (files
);
2726 max_name_length
= line_fmt
->col_arr
[0];
2729 for (filesno
= 1; filesno
< files_index
; ++filesno
)
2731 int col
= filesno
% cols
;
2740 indent (pos
+ name_length
, pos
+ max_name_length
);
2741 pos
+= max_name_length
;
2744 print_file_name_and_frills (files
+ filesno
);
2746 name_length
= length_of_file_name_and_frills (files
+ filesno
);
2747 max_name_length
= line_fmt
->col_arr
[col
];
2753 print_with_commas (void)
2760 for (filesno
= 0; filesno
< files_index
; filesno
++)
2764 pos
+= length_of_file_name_and_frills (files
+ filesno
);
2765 if (filesno
+ 1 < files_index
)
2766 pos
+= 2; /* For the comma and space */
2768 if (old_pos
!= 0 && pos
>= line_length
)
2774 print_file_name_and_frills (files
+ filesno
);
2775 if (filesno
+ 1 < files_index
)
2784 /* Assuming cursor is at position FROM, indent up to position TO.
2785 Use a TAB character instead of two or more spaces whenever possible. */
2788 indent (int from
, int to
)
2792 if (tabsize
> 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
2795 from
+= tabsize
- from
% tabsize
;
2805 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
2806 /* FIXME: maybe remove this function someday. See about using a
2807 non-malloc'ing version of path_concat. */
2810 attach (char *dest
, const char *dirname
, const char *name
)
2812 const char *dirnamep
= dirname
;
2814 /* Copy dirname if it is not ".". */
2815 if (dirname
[0] != '.' || dirname
[1] != 0)
2818 *dest
++ = *dirnamep
++;
2819 /* Add '/' if `dirname' doesn't already end with it. */
2820 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
2829 init_column_info (void)
2834 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2838 if (column_info
== NULL
)
2840 column_info
= (struct column_info
*) xmalloc (max_idx
2841 * sizeof (struct column_info
));
2845 for (i
= 0; i
< max_idx
; ++i
)
2849 column_info
[i
].valid_len
= 1;
2850 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
2853 column_info
[i
].col_arr
= (int *) xmalloc ((i
+ 1) * sizeof (int));
2855 for (j
= 0; j
<= i
; ++j
)
2856 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
2864 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2868 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
2870 List information about the FILEs (the current directory by default).\n\
2871 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
2873 -a, --all do not hide entries starting with .\n\
2874 -A, --almost-all do not list implied . and ..\n\
2875 -b, --escape print octal escapes for nongraphic characters\n\
2876 --block-size=SIZE use SIZE-byte blocks\n\
2877 -B, --ignore-backups do not list implied entries ending with ~\n\
2878 -c sort by change time; with -l: show ctime\n\
2879 -C list entries by columns\n\
2880 --color[=WHEN] control whether color is used to distinguish file\n\
2881 types. WHEN may be `never', `always', or `auto'\n\
2882 -d, --directory list directory entries instead of contents\n\
2883 -D, --dired generate output designed for Emacs' dired mode\n\
2884 -f do not sort, enable -aU, disable -lst\n\
2885 -F, --classify append indicator (one of */=@|) to entries\n\
2886 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
2887 single-column -1, verbose -l, vertical -C\n\
2888 --full-time list both full date and full time\n"));
2892 -G, --no-group inhibit display of group information\n\
2893 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
2894 -H, --si likewise, but use powers of 1000 not 1024\n\
2895 --indicator-style=WORD append indicator with style WORD to entry names:\n\
2896 none (default), classify (-F), file-type (-p)\n\
2897 -i, --inode print index number of each file\n\
2898 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
2899 -k, --kilobytes like --block-size=1024\n\
2900 -l use a long listing format\n\
2901 -L, --dereference list entries pointed to by symbolic links\n\
2902 -m fill width with a comma separated list of entries\n\
2903 -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names\n\
2904 -N, --literal print raw entry names (don't treat e.g. control\n\
2905 characters specially)\n\
2906 -o use long listing format without group info\n\
2907 -p, --file-type append indicator (one of /=@|) to entries\n\
2908 -q, --hide-control-chars print ? instead of non graphic characters\n\
2909 (This is the default unless the output is a\n\
2910 terminal and the program is `ls'; otherwise,\n\
2911 the default is --show-control-chars)\n\
2912 --show-control-chars show non graphic characters as-is (default)\n\
2913 -Q, --quote-name enclose entry names in double quotes\n\
2914 --quoting-style=WORD use quoting style WORD for entry names:\n\
2915 literal, shell, shell-always, c, escape\n\
2916 -r, --reverse reverse order while sorting\n\
2917 -R, --recursive list subdirectories recursively\n\
2918 -s, --size print size of each file, in blocks\n"));
2921 -S sort by file size\n\
2922 --sort=WORD extension -X, none -U, size -S, time -t,\n\
2924 status -c, time -t, atime -u, access -u, use -u\n\
2925 --time=WORD show time as WORD instead of modification time:\n\
2926 atime, access, use, ctime or status; use\n\
2927 specified time as sort key if --sort=time\n\
2928 -t sort by modification time\n\
2929 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
2930 -u sort by last access time; with -l: show atime\n\
2931 -U do not sort; list entries in directory order\n\
2932 -v sort by version\n\
2933 -w, --width=COLS assume screen width instead of current value\n\
2934 -x list entries by lines instead of by columns\n\
2935 -X sort alphabetically by entry extension\n\
2936 -1 list one file per line\n\
2937 --help display this help and exit\n\
2938 --version output version information and exit\n\
2940 By default, color is not used to distinguish types of files. That is\n\
2941 equivalent to using --color=none. Using the --color option without the\n\
2942 optional WHEN argument is equivalent to using --color=always. With\n\
2943 --color=auto, color codes are output only if standard output is connected\n\
2944 to a terminal (tty).\n\
2946 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));