home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 8 / FreshFishVol8-CD2.bin / bbs / gnu / fileutils-3.12-src.lha / fileutils-3.12 / src / ls.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-12  |  49.7 KB  |  2,186 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988, 1990, 1991 Free Software Foundation, Inc.
  3.  
  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)
  7.    any later version.
  8.  
  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.
  13.  
  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
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* If the macro MULTI_COL is defined,
  19.    the multi-column format is the default regardless
  20.    of the type of output device.
  21.    This is for the `dir' program.
  22.  
  23.    If the macro LONG_FORMAT is defined,
  24.    the long format is the default regardless of the
  25.    type of output device.
  26.    This is for the `vdir' program.
  27.  
  28.    If neither is defined,
  29.    the output format depends on whether the output
  30.    device is a terminal.
  31.    This is for the `ls' program. */
  32.  
  33. /* Written by Richard Stallman and David MacKenzie. */
  34.  
  35. #ifdef _AIX
  36.  #pragma alloca
  37. #endif
  38.  
  39. #include <config.h>
  40. #include <sys/types.h>
  41. #if !defined(_POSIX_SOURCE) || defined(_AIX)
  42. #include <sys/ioctl.h>
  43. #endif
  44. #include <stdio.h>
  45. #include <grp.h>
  46. #include <pwd.h>
  47. #include <getopt.h>
  48. #if HAVE_LIMITS_H
  49. /* limits.h must come before system.h because limits.h on some systems
  50.    undefs PATH_MAX, whereas system.h includes pathmax.h which sets
  51.    PATH_MAX.  */
  52. #include <limits.h>
  53. #endif
  54. #include "system.h"
  55. #include <fnmatch.h>
  56.  
  57. #include "obstack.h"
  58. #include "ls.h"
  59. #include "version.h"
  60. #include "safe-stat.h"
  61. #include "safe-lstat.h"
  62.  
  63. #define obstack_chunk_alloc xmalloc
  64. #define obstack_chunk_free free
  65.  
  66. #ifndef INT_MAX
  67. #define INT_MAX 2147483647
  68. #endif
  69.  
  70. /* Don't hardcode which characters are 'funny',
  71.  * to allow national characters in file names.
  72.  * I think this might be appripriate for other 
  73.  * systems too, not only on the amiga.
  74.  *                      - nisse@lysator.liu.se
  75.  */
  76. #ifdef amigados
  77. #include <ctype.h>
  78. /* The isfunny() macro regards a space as a funny character,
  79.  * the isfunny2() macro doesn't. */
  80. #define isfunny2(c) (iscntrl(c))
  81. #define isfunny(c) (isfunny2(c) || (c) == ' ')
  82. #else
  83. /* Original test */
  84. #define isfunny(c) (!(c > 040 && c < 0177))
  85. #define isfunny2(c) (!(c >= 040 && c < 0177)
  86. #endif
  87.  
  88. /* Return an int indicating the result of comparing two longs. */
  89. #if (INT_MAX <= 65535)
  90. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  91. #else
  92. #define longdiff(a, b) ((a) - (b))
  93. #endif
  94.  
  95. /* The maximum number of digits required to print an inode number
  96.    in an unsigned format.  */
  97. #ifndef INODE_DIGITS
  98. #define INODE_DIGITS 7
  99. #endif
  100.  
  101. #ifndef STDC_HEADERS
  102. char *ctime ();
  103. time_t time ();
  104. void free ();
  105. #endif
  106.  
  107. void mode_string ();
  108.  
  109. char *stpcpy ();
  110. char *xstrdup ();
  111. char *getgroup ();
  112. char *getuser ();
  113. char *xmalloc ();
  114. char *xrealloc ();
  115. int argmatch ();
  116. void error ();
  117. void invalid_arg ();
  118.  
  119. static char *make_link_path ();
  120. static int compare_atime ();
  121. static int rev_cmp_atime ();
  122. static int compare_ctime ();
  123. static int rev_cmp_ctime ();
  124. static int compare_mtime ();
  125. static int rev_cmp_mtime ();
  126. static int compare_size ();
  127. static int rev_cmp_size ();
  128. static int compare_name ();
  129. static int rev_cmp_name ();
  130. static int compare_extension ();
  131. static int rev_cmp_extension ();
  132. static int decode_switches ();
  133. static int file_interesting ();
  134. static int gobble_file ();
  135. static int is_not_dot_or_dotdot ();
  136. static int length_of_file_name_and_frills ();
  137. static void add_ignore_pattern ();
  138. static void attach ();
  139. static void clear_files ();
  140. static void extract_dirs_from_files ();
  141. static void get_link_name ();
  142. static void indent ();
  143. static void print_current_files ();
  144. static void print_dir ();
  145. static void print_file_name_and_frills ();
  146. static void print_horizontal ();
  147. static void print_long_format ();
  148. static void print_many_per_line ();
  149. static void print_name_with_quoting ();
  150. static void print_type_indicator ();
  151. static void print_with_commas ();
  152. static void queue_directory ();
  153. static void sort_files ();
  154. static void usage ();
  155.  
  156.  
  157. /* The name the program was run with, stripped of any leading path. */
  158. char *program_name;
  159.  
  160. enum filetype
  161. {
  162.   symbolic_link,
  163.   directory,
  164.   arg_directory,        /* Directory given as command line arg. */
  165.   normal            /* All others. */
  166. };
  167.  
  168. struct fileinfo
  169. {
  170.   /* The file name. */
  171.   char *name;
  172.  
  173.   struct stat stat;
  174.  
  175.   /* For symbolic link, name of the file linked to, otherwise zero. */
  176.   char *linkname;
  177.  
  178.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  179.      zero. */
  180.   unsigned int linkmode;
  181.  
  182.   enum filetype filetype;
  183. };
  184.  
  185. /* The table of files in the current directory:
  186.  
  187.    `files' points to a vector of `struct fileinfo', one per file.
  188.    `nfiles' is the number of elements space has been allocated for.
  189.    `files_index' is the number actually in use.  */
  190.  
  191. /* Address of block containing the files that are described.  */
  192.  
  193. static struct fileinfo *files;
  194.  
  195. /* Length of block that `files' points to, measured in files.  */
  196.  
  197. static int nfiles;
  198.  
  199. /* Index of first unused in `files'.  */
  200.  
  201. static int files_index;
  202.  
  203. /* Record of one pending directory waiting to be listed.  */
  204.  
  205. struct pending
  206. {
  207.   char *name;
  208.   /* If the directory is actually the file pointed to by a symbolic link we
  209.      were told to list, `realname' will contain the name of the symbolic
  210.      link, otherwise zero. */
  211.   char *realname;
  212.   struct pending *next;
  213. };
  214.  
  215. static struct pending *pending_dirs;
  216.  
  217. /* Current time (seconds since 1970).  When we are printing a file's time,
  218.    include the year if it is more than 6 months before this time.  */
  219.  
  220. static time_t current_time;
  221.  
  222. /* The number of digits to use for block sizes.
  223.    4, or more if needed for bigger numbers.  */
  224.  
  225. static int block_size_size;
  226.  
  227. /* Option flags */
  228.  
  229. /* long_format for lots of info, one per line.
  230.    one_per_line for just names, one per line.
  231.    many_per_line for just names, many per line, sorted vertically.
  232.    horizontal for just names, many per line, sorted horizontally.
  233.    with_commas for just names, many per line, separated by commas.
  234.  
  235.    -l, -1, -C, -x and -m control this parameter.  */
  236.  
  237. enum format
  238. {
  239.   long_format,            /* -l */
  240.   one_per_line,            /* -1 */
  241.   many_per_line,        /* -C */
  242.   horizontal,            /* -x */
  243.   with_commas            /* -m */
  244. };
  245.  
  246. static enum format format;
  247.  
  248. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  249.  
  250. enum time_type
  251. {
  252.   time_mtime,            /* default */
  253.   time_ctime,            /* -c */
  254.   time_atime            /* -u */
  255. };
  256.  
  257. static enum time_type time_type;
  258.  
  259. /* print the full time, otherwise the standard unix heuristics. */
  260.  
  261. int full_time;
  262.  
  263. /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X. */
  264.  
  265. enum sort_type
  266. {
  267.   sort_none,            /* -U */
  268.   sort_name,            /* default */
  269.   sort_extension,        /* -X */
  270.   sort_time,            /* -t */
  271.   sort_size            /* -S */
  272. };
  273.  
  274. static enum sort_type sort_type;
  275.  
  276. /* Direction of sort.
  277.    0 means highest first if numeric,
  278.    lowest first if alphabetic;
  279.    these are the defaults.
  280.    1 means the opposite order in each case.  -r  */
  281.  
  282. static int sort_reverse;
  283.  
  284. /* Nonzero means to NOT display group information.  -G  */
  285.  
  286. int inhibit_group;
  287.  
  288. /* Nonzero means print the user and group id's as numbers rather
  289.    than as names.  -n  */
  290.  
  291. static int numeric_users;
  292.  
  293. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  294.  
  295. static int print_block_size;
  296.  
  297. /* Nonzero means show file sizes in kilobytes instead of blocks
  298.    (the size of which is system-dependent).  -k */
  299.  
  300. static int kilobyte_blocks;
  301.  
  302. /* Precede each line of long output (per file) with a string like `m,n:'
  303.    where M is the number of characters after the `:' and before the
  304.    filename and N is the length of the filename.  Using this format,
  305.    Emacs' dired mode starts up twice as fast, and can handle all
  306.    strange characters in file names.  */
  307. static int dired;
  308.  
  309. /* none means don't mention the type of files.
  310.    all means mention the types of all files.
  311.    not_programs means do so except for executables.
  312.  
  313.    Controlled by -F and -p.  */
  314.  
  315. enum indicator_style
  316. {
  317.   none,                /* default */
  318.   all,                /* -F */
  319.   not_programs            /* -p */
  320. };
  321.  
  322. static enum indicator_style indicator_style;
  323.  
  324. /* Nonzero means mention the inode number of each file.  -i  */
  325.  
  326. static int print_inode;
  327.  
  328. /* Nonzero means when a symbolic link is found, display info on
  329.    the file linked to.  -L  */
  330.  
  331. static int trace_links;
  332.  
  333. /* Nonzero means when a directory is found, display info on its
  334.    contents.  -R  */
  335.  
  336. static int trace_dirs;
  337.  
  338. /* Nonzero means when an argument is a directory name, display info
  339.    on it itself.  -d  */
  340.  
  341. static int immediate_dirs;
  342.  
  343. /* Nonzero means don't omit files whose names start with `.'.  -A */
  344.  
  345. static int all_files;
  346.  
  347. /* Nonzero means don't omit files `.' and `..'
  348.    This flag implies `all_files'.  -a  */
  349.  
  350. static int really_all_files;
  351.  
  352. /* A linked list of shell-style globbing patterns.  If a non-argument
  353.    file name matches any of these patterns, it is omitted.
  354.    Controlled by -I.  Multiple -I options accumulate.
  355.    The -B option adds `*~' and `.*~' to this list.  */
  356.  
  357. struct ignore_pattern
  358. {
  359.   char *pattern;
  360.   struct ignore_pattern *next;
  361. };
  362.  
  363. static struct ignore_pattern *ignore_patterns;
  364.  
  365. /* Nonzero means quote nongraphic chars in file names.  -b  */
  366.  
  367. static int quote_funny_chars;
  368.  
  369. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  370.  
  371. static int qmark_funny_chars;
  372.  
  373. /* Nonzero means output each file name using C syntax for a string.
  374.    Always accompanied by `quote_funny_chars'.
  375.    This mode, together with -x or -C or -m,
  376.    and without such frills as -F or -s,
  377.    is guaranteed to make it possible for a program receiving
  378.    the output to tell exactly what file names are present.  -Q  */
  379.  
  380. static int quote_as_string;
  381.  
  382. /* The number of chars per hardware tab stop.  -T */
  383. static int tabsize;
  384.  
  385. /* Nonzero means we are listing the working directory because no
  386.    non-option arguments were given. */
  387.  
  388. static int dir_defaulted;
  389.  
  390. /* Nonzero means print each directory name before listing it. */
  391.  
  392. static int print_dir_name;
  393.  
  394. /* The line length to use for breaking lines in many-per-line format.
  395.    Can be set with -w.  */
  396.  
  397. static int line_length;
  398.  
  399. /* If nonzero, the file listing format requires that stat be called on
  400.    each file. */
  401.  
  402. static int format_needs_stat;
  403.  
  404. /* The exit status to use if we don't get any fatal errors. */
  405.  
  406. static int exit_status;
  407.  
  408. /* If non-zero, display usage information and exit.  */
  409. static int show_help;
  410.  
  411. /* If non-zero, print the version on standard output and exit.  */
  412. static int show_version;
  413.  
  414. static struct option const long_options[] =
  415. {
  416.   {"all", no_argument, 0, 'a'},
  417.   {"escape", no_argument, 0, 'b'},
  418.   {"directory", no_argument, 0, 'd'},
  419.   {"dired", no_argument, 0, 'D'},
  420.   {"full-time", no_argument, &full_time, 1},
  421.   {"inode", no_argument, 0, 'i'},
  422.   {"kilobytes", no_argument, 0, 'k'},
  423.   {"numeric-uid-gid", no_argument, 0, 'n'},
  424.   {"no-group", no_argument, 0, 'G'},
  425.   {"hide-control-chars", no_argument, 0, 'q'},
  426.   {"reverse", no_argument, 0, 'r'},
  427.   {"size", no_argument, 0, 's'},
  428.   {"width", required_argument, 0, 'w'},
  429.   {"almost-all", no_argument, 0, 'A'},
  430.   {"ignore-backups", no_argument, 0, 'B'},
  431.   {"classify", no_argument, 0, 'F'},
  432.   {"file-type", no_argument, 0, 'F'},
  433.   {"ignore", required_argument, 0, 'I'},
  434.   {"dereference", no_argument, 0, 'L'},
  435.   {"literal", no_argument, 0, 'N'},
  436.   {"quote-name", no_argument, 0, 'Q'},
  437.   {"recursive", no_argument, 0, 'R'},
  438.   {"format", required_argument, 0, 12},
  439.   {"sort", required_argument, 0, 10},
  440.   {"tabsize", required_argument, 0, 'T'},
  441.   {"time", required_argument, 0, 11},
  442.   {"help", no_argument, &show_help, 1},
  443.   {"version", no_argument, &show_version, 1},
  444.   {0, 0, 0, 0}
  445. };
  446.  
  447. static char const* const format_args[] =
  448. {
  449.   "verbose", "long", "commas", "horizontal", "across",
  450.   "vertical", "single-column", 0
  451. };
  452.  
  453. static enum format const formats[] =
  454. {
  455.   long_format, long_format, with_commas, horizontal, horizontal,
  456.   many_per_line, one_per_line
  457. };
  458.  
  459. static char const* const sort_args[] =
  460. {
  461.   "none", "time", "size", "extension", 0
  462. };
  463.  
  464. static enum sort_type const sort_types[] =
  465. {
  466.   sort_none, sort_time, sort_size, sort_extension
  467. };
  468.  
  469. static char const* const time_args[] =
  470. {
  471.   "atime", "access", "use", "ctime", "status", 0
  472. };
  473.  
  474. /* This zero-based index is used solely with the --dired option.
  475.    When that option is in effect, this counter is incremented for each
  476.    character of output generated by this program so that the beginning
  477.    and ending indices (in that output) of every file name can be recorded
  478.    and later output themselves.  */
  479. static size_t dired_pos;
  480.  
  481. #define PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
  482.  
  483. /* Write S to STREAM and increment DIRED_POS by S_LEN.  */
  484. #define FPUTS(s, stream, s_len) \
  485.     do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
  486.  
  487. /* Like FPUTS, but for use when S is a literal string.  */
  488. #define FPUTS_LITERAL(s, stream) \
  489.     do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
  490.  
  491. #define DIRED_INDENT()                            \
  492.     do                                    \
  493.       {                                    \
  494.     /* FIXME: remove the `&& format == long_format' clause.  */    \
  495.     if (dired && format == long_format)                \
  496.       FPUTS_LITERAL ("  ", stdout);                    \
  497.       }                                    \
  498.     while (0)
  499.  
  500. /* With --dired, store pairs of beginning and ending indices of filenames.  */
  501. static struct obstack dired_obstack;
  502.  
  503. /* With --dired and --recursive, store pairs of beginning and ending
  504.    indices of directory names.  */
  505. static struct obstack subdired_obstack;
  506.  
  507. /* Save the current index on the specified obstack, OBS.  */
  508. #define PUSH_CURRENT_DIRED_POS(obs)                    \
  509.   do                                    \
  510.     {                                    \
  511.       /* FIXME: remove the `&& format == long_format' clause.  */    \
  512.       if (dired && format == long_format)                \
  513.     obstack_grow ((obs), &dired_pos, sizeof (dired_pos));        \
  514.     }                                    \
  515.   while (0)
  516.  
  517. static enum time_type const time_types[] =
  518. {
  519.   time_atime, time_atime, time_atime, time_ctime, time_ctime
  520. };
  521.  
  522.  
  523. /* Write to standard output the string PREFIX followed by a space-separated
  524.    list of the integers stored in OS all on one line.  */
  525.  
  526. static void
  527. dired_dump_obstack (prefix, os)
  528.      const char *prefix;
  529.      struct obstack *os;
  530. {
  531.   int i, n_pos;
  532.   size_t *pos;
  533.  
  534.   fputs (prefix, stdout);
  535.   n_pos = obstack_object_size (os) / sizeof (size_t);
  536.   pos = (size_t *) obstack_finish (os);
  537.   for (i = 0; i < n_pos; i++)
  538.     printf (" %d", (int) pos[i]);
  539.   fputs ("\n", stdout);
  540. }
  541.  
  542. main (argc, argv)
  543.      int argc;
  544.      char **argv;
  545. {
  546.   register int i;
  547.   register struct pending *thispend;
  548.  
  549.   exit_status = 0;
  550.   dir_defaulted = 1;
  551.   print_dir_name = 1;
  552.   pending_dirs = 0;
  553.   current_time = time ((time_t *) 0);
  554.  
  555.   program_name = argv[0];
  556.   i = decode_switches (argc, argv);
  557.  
  558.   if (show_version)
  559.     {
  560.       printf ("%s\n", version_string);
  561.       exit (0);
  562.     }
  563.  
  564.   if (show_help)
  565.     usage (0);
  566.  
  567.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  568.     || format == long_format
  569.     || trace_links || trace_dirs || indicator_style != none
  570.     || print_block_size || print_inode;
  571.  
  572.   if (dired && format == long_format)
  573.     {
  574.       obstack_init (&dired_obstack);
  575.       if (trace_dirs)
  576.     obstack_init (&subdired_obstack);
  577.     }
  578.  
  579.   nfiles = 100;
  580.   files = (struct fileinfo *) xmalloc (sizeof (struct fileinfo) * nfiles);
  581.   files_index = 0;
  582.  
  583.   clear_files ();
  584.  
  585.   if (i < argc)
  586.     dir_defaulted = 0;
  587.   for (; i < argc; i++)
  588.     gobble_file (argv[i], 1, "");
  589.  
  590.   if (dir_defaulted)
  591.     {
  592.       if (immediate_dirs)
  593.     gobble_file (".", 1, "");
  594.       else
  595.     queue_directory (".", 0);
  596.     }
  597.  
  598.   if (files_index)
  599.     {
  600.       sort_files ();
  601.       if (!immediate_dirs)
  602.     extract_dirs_from_files ("", 0);
  603.       /* `files_index' might be zero now.  */
  604.     }
  605.   if (files_index)
  606.     {
  607.       print_current_files ();
  608.       if (pending_dirs)
  609.     PUTCHAR ('\n');
  610.     }
  611.   else if (pending_dirs && pending_dirs->next == 0)
  612.     print_dir_name = 0;
  613.  
  614.   while (pending_dirs)
  615.     {
  616.       thispend = pending_dirs;
  617.       pending_dirs = pending_dirs->next;
  618.       print_dir (thispend->name, thispend->realname);
  619.       free (thispend->name);
  620.       if (thispend->realname)
  621.     free (thispend->realname);
  622.       free (thispend);
  623.       print_dir_name = 1;
  624.     }
  625.  
  626.   if (dired && format == long_format)
  627.     {
  628.       /* No need to free these since we're about to exit.  */
  629.       dired_dump_obstack ("//DIRED//", &dired_obstack);
  630.       if (trace_dirs)
  631.     dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
  632.     }
  633.  
  634.   exit (exit_status);
  635. }
  636.  
  637. /* Set all the option flags according to the switches specified.
  638.    Return the index of the first non-option argument.  */
  639.  
  640. static int
  641. decode_switches (argc, argv)
  642.      int argc;
  643.      char **argv;
  644. {
  645.   register char *p;
  646.   int c;
  647.   int i;
  648.  
  649.   qmark_funny_chars = 0;
  650.   quote_funny_chars = 0;
  651.  
  652.   /* initialize all switches to default settings */
  653.  
  654.   switch (ls_mode)
  655.     {
  656.     case LS_MULTI_COL:
  657.       /* This is for the `dir' program.  */
  658.       format = many_per_line;
  659.       quote_funny_chars = 1;
  660.       break;
  661.  
  662.     case LS_LONG_FORMAT:
  663.       /* This is for the `vdir' program.  */
  664.       format = long_format;
  665.       quote_funny_chars = 1;
  666.       break;
  667.  
  668.     case LS_LS:
  669.       /* This is for the `ls' program.  */
  670.       if (isatty (1))
  671.     {
  672.       format = many_per_line;
  673.       qmark_funny_chars = 1;
  674.     }
  675.       else
  676.     {
  677.       format = one_per_line;
  678.       qmark_funny_chars = 0;
  679.     }
  680.       break;
  681.  
  682.     default:
  683.       abort ();
  684.     }
  685.  
  686.   time_type = time_mtime;
  687.   full_time = 0;
  688.   sort_type = sort_name;
  689.   sort_reverse = 0;
  690.   numeric_users = 0;
  691.   print_block_size = 0;
  692.   kilobyte_blocks = getenv ("POSIXLY_CORRECT") == 0;
  693.   indicator_style = none;
  694.   print_inode = 0;
  695.   trace_links = 0;
  696.   trace_dirs = 0;
  697.   immediate_dirs = 0;
  698.   all_files = 0;
  699.   really_all_files = 0;
  700.   ignore_patterns = 0;
  701.   quote_as_string = 0;
  702.  
  703.   p = getenv ("COLUMNS");
  704.   line_length = p ? atoi (p) : 80;
  705.  
  706. #ifdef TIOCGWINSZ
  707.   {
  708.     struct winsize ws;
  709.  
  710.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  711.       line_length = ws.ws_col;
  712.   }
  713. #endif
  714.  
  715.   p = getenv ("TABSIZE");
  716.   tabsize = p ? atoi (p) : 8;
  717.  
  718.   while ((c = getopt_long (argc, argv, "abcdfgiklmnpqrstuw:xABCDFGI:LNQRST:UX1",
  719.                long_options, (int *) 0)) != EOF)
  720.     {
  721.       switch (c)
  722.     {
  723.     case 0:
  724.       break;
  725.  
  726.     case 'a':
  727.       all_files = 1;
  728.       really_all_files = 1;
  729.       break;
  730.  
  731.     case 'b':
  732.       quote_funny_chars = 1;
  733.       qmark_funny_chars = 0;
  734.       break;
  735.  
  736.     case 'c':
  737.       time_type = time_ctime;
  738.       break;
  739.  
  740.     case 'd':
  741.       immediate_dirs = 1;
  742.       break;
  743.  
  744.     case 'f':
  745.       /* Same as enabling -a -U and disabling -l -s.  */
  746.       all_files = 1;
  747.       really_all_files = 1;
  748.       sort_type = sort_none;
  749.       /* disable -l */
  750.       if (format == long_format)
  751.         format = (isatty (1) ? many_per_line : one_per_line);
  752.       print_block_size = 0;  /* disable -s */
  753.       break;
  754.  
  755.     case 'g':
  756.       /* No effect.  For BSD compatibility. */
  757.       break;
  758.  
  759.     case 'i':
  760.       print_inode = 1;
  761.       break;
  762.  
  763.     case 'k':
  764.       kilobyte_blocks = 1;
  765.       break;
  766.  
  767.     case 'l':
  768.       format = long_format;
  769.       break;
  770.  
  771.     case 'm':
  772.       format = with_commas;
  773.       break;
  774.  
  775.     case 'n':
  776.       numeric_users = 1;
  777.       break;
  778.  
  779.     case 'p':
  780.       indicator_style = not_programs;
  781.       break;
  782.  
  783.     case 'q':
  784.       qmark_funny_chars = 1;
  785.       quote_funny_chars = 0;
  786.       break;
  787.  
  788.     case 'r':
  789.       sort_reverse = 1;
  790.       break;
  791.  
  792.     case 's':
  793.       print_block_size = 1;
  794.       break;
  795.  
  796.     case 't':
  797.       sort_type = sort_time;
  798.       break;
  799.  
  800.     case 'u':
  801.       time_type = time_atime;
  802.       break;
  803.  
  804.     case 'w':
  805.       line_length = atoi (optarg);
  806.       if (line_length < 1)
  807.         error (1, 0, "invalid line width: %s", optarg);
  808.       break;
  809.  
  810.     case 'x':
  811.       format = horizontal;
  812.       break;
  813.  
  814.     case 'A':
  815.       all_files = 1;
  816.       break;
  817.  
  818.     case 'B':
  819. #ifdef AMIGA
  820.       add_ignore_pattern ("*!");
  821.       add_ignore_pattern (".*!");
  822. #else
  823.       add_ignore_pattern ("*~");
  824.       add_ignore_pattern (".*~");
  825. #endif
  826.       break;
  827.  
  828.     case 'C':
  829.       format = many_per_line;
  830.       break;
  831.  
  832.     case 'D':
  833.       dired = 1;
  834.       break;
  835.  
  836.     case 'F':
  837.       indicator_style = all;
  838.       break;
  839.  
  840.     case 'G':        /* inhibit display of group info */
  841.       inhibit_group = 1;
  842.       break;
  843.  
  844.     case 'I':
  845.       add_ignore_pattern (optarg);
  846.       break;
  847.  
  848.     case 'L':
  849.       trace_links = 1;
  850.       break;
  851.  
  852.     case 'N':
  853.       quote_funny_chars = 0;
  854.       qmark_funny_chars = 0;
  855.       break;
  856.  
  857.     case 'Q':
  858.       quote_as_string = 1;
  859.       quote_funny_chars = 1;
  860.       qmark_funny_chars = 0;
  861.       break;
  862.  
  863.     case 'R':
  864.       trace_dirs = 1;
  865.       break;
  866.  
  867.     case 'S':
  868.       sort_type = sort_size;
  869.       break;
  870.  
  871.     case 'T':
  872.       tabsize = atoi (optarg);
  873.       if (tabsize < 1)
  874.         error (1, 0, "invalid tab size: %s", optarg);
  875.       break;
  876.  
  877.     case 'U':
  878.       sort_type = sort_none;
  879.       break;
  880.  
  881.     case 'X':
  882.       sort_type = sort_extension;
  883.       break;
  884.  
  885.     case '1':
  886.       format = one_per_line;
  887.       break;
  888.  
  889.     case 10:        /* +sort */
  890.       i = argmatch (optarg, sort_args);
  891.       if (i < 0)
  892.         {
  893.           invalid_arg ("sort type", optarg, i);
  894.           usage (1);
  895.         }
  896.       sort_type = sort_types[i];
  897.       break;
  898.  
  899.     case 11:        /* +time */
  900.       i = argmatch (optarg, time_args);
  901.       if (i < 0)
  902.         {
  903.           invalid_arg ("time type", optarg, i);
  904.           usage (1);
  905.         }
  906.       time_type = time_types[i];
  907.       break;
  908.  
  909.     case 12:        /* +format */
  910.       i = argmatch (optarg, format_args);
  911.       if (i < 0)
  912.         {
  913.           invalid_arg ("format type", optarg, i);
  914.           usage (1);
  915.         }
  916.       format = formats[i];
  917.       break;
  918.  
  919.     default:
  920.       usage (1);
  921.     }
  922.     }
  923.  
  924.   return optind;
  925. }
  926.  
  927. /* Request that the directory named `name' have its contents listed later.
  928.    If `realname' is nonzero, it will be used instead of `name' when the
  929.    directory name is printed.  This allows symbolic links to directories
  930.    to be treated as regular directories but still be listed under their
  931.    real names. */
  932.  
  933. static void
  934. queue_directory (name, realname)
  935.      char *name;
  936.      char *realname;
  937. {
  938.   struct pending *new;
  939.  
  940.   new = (struct pending *) xmalloc (sizeof (struct pending));
  941.   new->next = pending_dirs;
  942.   pending_dirs = new;
  943.   new->name = xstrdup (name);
  944.   if (realname)
  945.     new->realname = xstrdup (realname);
  946.   else
  947.     new->realname = 0;
  948. }
  949.  
  950. /* Read directory `name', and list the files in it.
  951.    If `realname' is nonzero, print its name instead of `name';
  952.    this is used for symbolic links to directories. */
  953.  
  954. static void
  955. print_dir (name, realname)
  956.      const char *name;
  957.      const char *realname;
  958. {
  959.   register DIR *reading;
  960.   register struct dirent *next;
  961.   register int total_blocks = 0;
  962.  
  963.   errno = 0;
  964.   reading = opendir (name);
  965.   if (!reading)
  966.     {
  967.       error (0, errno, "%s", name);
  968.       exit_status = 1;
  969.       return;
  970.     }
  971.  
  972.   /* Read the directory entries, and insert the subfiles into the `files'
  973.      table.  */
  974.  
  975.   clear_files ();
  976.  
  977.   while ((next = readdir (reading)) != NULL)
  978.     if (file_interesting (next))
  979.       total_blocks += gobble_file (next->d_name, 0, name);
  980.  
  981.   if (CLOSEDIR (reading))
  982.     {
  983.       error (0, errno, "%s", name);
  984.       exit_status = 1;
  985.       /* Don't return; print whatever we got. */
  986.     }
  987.  
  988.   /* Sort the directory contents.  */
  989.   sort_files ();
  990.  
  991.   /* If any member files are subdirectories, perhaps they should have their
  992.      contents listed rather than being mentioned here as files.  */
  993.  
  994.   if (trace_dirs)
  995.     extract_dirs_from_files (name, 1);
  996.  
  997.   if (print_dir_name)
  998.     {
  999.       const char *dir;
  1000.  
  1001.       DIRED_INDENT ();
  1002.       dir = (realname ? realname : name);
  1003.       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
  1004.       FPUTS (dir, stdout, strlen (dir));
  1005.       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
  1006.       FPUTS_LITERAL (":\n", stdout);
  1007.     }
  1008.  
  1009.   if (format == long_format || print_block_size)
  1010.     {
  1011.       char buf[6 + 20 + 1 + 1];
  1012.  
  1013.       DIRED_INDENT ();
  1014.       sprintf (buf, "total %u\n", total_blocks);
  1015.       FPUTS (buf, stdout, strlen (buf));
  1016.     }
  1017.  
  1018.   if (files_index)
  1019.     print_current_files ();
  1020.  
  1021.   if (pending_dirs)
  1022.     PUTCHAR ('\n');
  1023. }
  1024.  
  1025. /* Add `pattern' to the list of patterns for which files that match are
  1026.    not listed.  */
  1027.  
  1028. static void
  1029. add_ignore_pattern (pattern)
  1030.      char *pattern;
  1031. {
  1032.   register struct ignore_pattern *ignore;
  1033.  
  1034.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  1035.   ignore->pattern = pattern;
  1036.   /* Add it to the head of the linked list. */
  1037.   ignore->next = ignore_patterns;
  1038.   ignore_patterns = ignore;
  1039. }
  1040.  
  1041. /* Return nonzero if the file in `next' should be listed. */
  1042.  
  1043. static int
  1044. file_interesting (next)
  1045.      register struct dirent *next;
  1046. {
  1047.   register struct ignore_pattern *ignore;
  1048.  
  1049.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  1050.     if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
  1051.       return 0;
  1052.  
  1053.   if (really_all_files
  1054.       || next->d_name[0] != '.'
  1055.       || (all_files
  1056.       && next->d_name[1] != '\0'
  1057.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  1058.     return 1;
  1059.  
  1060.   return 0;
  1061. }
  1062.  
  1063. /* Enter and remove entries in the table `files'.  */
  1064.  
  1065. /* Empty the table of files. */
  1066.  
  1067. static void
  1068. clear_files ()
  1069. {
  1070.   register int i;
  1071.  
  1072.   for (i = 0; i < files_index; i++)
  1073.     {
  1074.       free (files[i].name);
  1075.       if (files[i].linkname)
  1076.     free (files[i].linkname);
  1077.     }
  1078.  
  1079.   files_index = 0;
  1080.   block_size_size = 4;
  1081. }
  1082.  
  1083. /* Add a file to the current table of files.
  1084.    Verify that the file exists, and print an error message if it does not.
  1085.    Return the number of blocks that the file occupies.  */
  1086.  
  1087. static int
  1088. gobble_file (name, explicit_arg, dirname)
  1089.      char *name;
  1090.      int explicit_arg;
  1091.      char *dirname;
  1092. {
  1093.   register int blocks;
  1094.   register int val;
  1095.   register char *path;
  1096.  
  1097.   if (files_index == nfiles)
  1098.     {
  1099.       nfiles *= 2;
  1100.       files = (struct fileinfo *) xrealloc (files, sizeof (*files) * nfiles);
  1101.     }
  1102.  
  1103.   files[files_index].linkname = 0;
  1104.   files[files_index].linkmode = 0;
  1105.  
  1106.   if (explicit_arg || format_needs_stat)
  1107.     {
  1108.       /* `path' is the absolute pathname of this file. */
  1109.  
  1110.       if (name[0] == '/' || dirname[0] == 0)
  1111.     path = name;
  1112.       else
  1113.     {
  1114.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  1115.       attach (path, dirname, name);
  1116.     }
  1117.  
  1118.       if (trace_links)
  1119.     {
  1120.       val = SAFE_STAT (path, &files[files_index].stat);
  1121.       if (val < 0)
  1122.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  1123.            the link instead. */
  1124.         val = SAFE_LSTAT (path, &files[files_index].stat);
  1125.     }
  1126.       else
  1127.     val = SAFE_LSTAT (path, &files[files_index].stat);
  1128.       if (val < 0)
  1129.     {
  1130.       error (0, errno, "%s", path);
  1131.       exit_status = 1;
  1132.       return 0;
  1133.     }
  1134.  
  1135. #ifdef S_ISLNK
  1136.       if (S_ISLNK (files[files_index].stat.st_mode)
  1137.       && (explicit_arg || format == long_format))
  1138.     {
  1139.       char *linkpath;
  1140.       struct stat linkstats;
  1141.  
  1142.       get_link_name (path, &files[files_index]);
  1143.       linkpath = make_link_path (path, files[files_index].linkname);
  1144.  
  1145.       /* Avoid following symbolic links when possible, ie, when
  1146.          they won't be traced and when no indicator is needed. */
  1147.       if (linkpath
  1148.           && ((explicit_arg && format != long_format)
  1149.            || indicator_style != none)
  1150.           && SAFE_STAT (linkpath, &linkstats) == 0)
  1151.         {
  1152.           /* Symbolic links to directories that are mentioned on the
  1153.          command line are automatically traced if not being
  1154.          listed as files.  */
  1155.           if (explicit_arg && format != long_format
  1156.           && S_ISDIR (linkstats.st_mode))
  1157.         {
  1158.           /* Substitute the linked-to directory's name, but
  1159.              save the real name in `linkname' for printing.  */
  1160.           if (!immediate_dirs)
  1161.             {
  1162.               char *tempname = name;
  1163.               name = linkpath;
  1164.               linkpath = files[files_index].linkname;
  1165.               files[files_index].linkname = tempname;
  1166.             }
  1167.           files[files_index].stat = linkstats;
  1168.         }
  1169.           else
  1170.         /* Get the linked-to file's mode for the filetype indicator
  1171.            in long listings.  */
  1172.         files[files_index].linkmode = linkstats.st_mode;
  1173.         }
  1174.       if (linkpath)
  1175.         free (linkpath);
  1176.     }
  1177. #endif
  1178.  
  1179. #ifdef S_ISLNK
  1180.       if (S_ISLNK (files[files_index].stat.st_mode))
  1181.     files[files_index].filetype = symbolic_link;
  1182.       else
  1183. #endif
  1184.     if (S_ISDIR (files[files_index].stat.st_mode))
  1185.       {
  1186.         if (explicit_arg && !immediate_dirs)
  1187.           files[files_index].filetype = arg_directory;
  1188.         else
  1189.           files[files_index].filetype = directory;
  1190.       }
  1191.     else
  1192.       files[files_index].filetype = normal;
  1193.  
  1194.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  1195.                    kilobyte_blocks);
  1196.       if (blocks >= 10000 && block_size_size < 5)
  1197.     block_size_size = 5;
  1198.       if (blocks >= 100000 && block_size_size < 6)
  1199.     block_size_size = 6;
  1200.       if (blocks >= 1000000 && block_size_size < 7)
  1201.     block_size_size = 7;
  1202.     }
  1203.   else
  1204.     blocks = 0;
  1205.  
  1206.   files[files_index].name = xstrdup (name);
  1207.   files_index++;
  1208.  
  1209.   return blocks;
  1210. }
  1211.  
  1212. #ifdef S_ISLNK
  1213.  
  1214. /* Put the name of the file that `filename' is a symbolic link to
  1215.    into the `linkname' field of `f'. */
  1216.  
  1217. static void
  1218. get_link_name (filename, f)
  1219.      char *filename;
  1220.      struct fileinfo *f;
  1221. {
  1222.   char *linkbuf;
  1223.   register int linksize;
  1224.  
  1225.   linkbuf = (char *) alloca (PATH_MAX + 2);
  1226.   /* Some automounters give incorrect st_size for mount points.
  1227.      I can't think of a good workaround for it, though.  */
  1228.   linksize = readlink (filename, linkbuf, PATH_MAX + 1);
  1229.   if (linksize < 0)
  1230.     {
  1231.       error (0, errno, "%s", filename);
  1232.       exit_status = 1;
  1233.     }
  1234.   else
  1235.     {
  1236.       linkbuf[linksize] = '\0';
  1237.       f->linkname = xstrdup (linkbuf);
  1238.     }
  1239. }
  1240.  
  1241. /* If `linkname' is a relative path and `path' contains one or more
  1242.    leading directories, return `linkname' with those directories
  1243.    prepended; otherwise, return a copy of `linkname'.
  1244.    If `linkname' is zero, return zero. */
  1245.  
  1246. static char *
  1247. make_link_path (path, linkname)
  1248.      char *path;
  1249.      char *linkname;
  1250. {
  1251.   char *linkbuf;
  1252.   int bufsiz;
  1253.  
  1254.   if (linkname == 0)
  1255.     return 0;
  1256.  
  1257.   if (*linkname == '/')
  1258.     return xstrdup (linkname);
  1259.  
  1260.   /* The link is to a relative path.  Prepend any leading path
  1261.      in `path' to the link name. */
  1262.   linkbuf = rindex (path, '/');
  1263.   if (linkbuf == 0)
  1264.     return xstrdup (linkname);
  1265.  
  1266.   bufsiz = linkbuf - path + 1;
  1267.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1268.   strncpy (linkbuf, path, bufsiz);
  1269.   strcpy (linkbuf + bufsiz, linkname);
  1270.   return linkbuf;
  1271. }
  1272. #endif
  1273.  
  1274. /* Remove any entries from `files' that are for directories,
  1275.    and queue them to be listed as directories instead.
  1276.    `dirname' is the prefix to prepend to each dirname
  1277.    to make it correct relative to ls's working dir.
  1278.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1279.    This is desirable when processing directories recursively.  */
  1280.  
  1281. static void
  1282. extract_dirs_from_files (dirname, recursive)
  1283.      char *dirname;
  1284.      int recursive;
  1285. {
  1286.   register int i, j;
  1287.   register char *path;
  1288.   int dirlen;
  1289.  
  1290.   dirlen = strlen (dirname) + 2;
  1291.   /* Queue the directories last one first, because queueing reverses the
  1292.      order.  */
  1293.   for (i = files_index - 1; i >= 0; i--)
  1294.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1295.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1296.       {
  1297.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1298.       {
  1299.         queue_directory (files[i].name, files[i].linkname);
  1300.       }
  1301.     else
  1302.       {
  1303.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1304.         attach (path, dirname, files[i].name);
  1305.         queue_directory (path, files[i].linkname);
  1306.         free (path);
  1307.       }
  1308.     if (files[i].filetype == arg_directory)
  1309.       free (files[i].name);
  1310.       }
  1311.  
  1312.   /* Now delete the directories from the table, compacting all the remaining
  1313.      entries.  */
  1314.  
  1315.   for (i = 0, j = 0; i < files_index; i++)
  1316.     if (files[i].filetype != arg_directory)
  1317.       files[j++] = files[i];
  1318.   files_index = j;
  1319. }
  1320.  
  1321. /* Return non-zero if `name' doesn't end in `.' or `..'
  1322.    This is so we don't try to recurse on `././././. ...' */
  1323.  
  1324. static int
  1325. is_not_dot_or_dotdot (name)
  1326.      char *name;
  1327. {
  1328.   char *t;
  1329.  
  1330.   t = rindex (name, '/');
  1331.   if (t)
  1332.     name = t + 1;
  1333.  
  1334.   if (name[0] == '.'
  1335.       && (name[1] == '\0'
  1336.       || (name[1] == '.' && name[2] == '\0')))
  1337.     return 0;
  1338.  
  1339.   return 1;
  1340. }
  1341.  
  1342. /* Sort the files now in the table.  */
  1343.  
  1344. static void
  1345. sort_files ()
  1346. {
  1347.   int (*func) ();
  1348.  
  1349.   switch (sort_type)
  1350.     {
  1351.     case sort_none:
  1352.       return;
  1353.     case sort_time:
  1354.       switch (time_type)
  1355.     {
  1356.     case time_ctime:
  1357.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1358.       break;
  1359.     case time_mtime:
  1360.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1361.       break;
  1362.     case time_atime:
  1363.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1364.       break;
  1365.     default:
  1366.       abort ();
  1367.     }
  1368.       break;
  1369.     case sort_name:
  1370.       func = sort_reverse ? rev_cmp_name : compare_name;
  1371.       break;
  1372.     case sort_extension:
  1373.       func = sort_reverse ? rev_cmp_extension : compare_extension;
  1374.       break;
  1375.     case sort_size:
  1376.       func = sort_reverse ? rev_cmp_size : compare_size;
  1377.       break;
  1378.     default:
  1379.       abort ();
  1380.     }
  1381.  
  1382.   qsort (files, files_index, sizeof (struct fileinfo), func);
  1383. }
  1384.  
  1385. /* Comparison routines for sorting the files. */
  1386.  
  1387. static int
  1388. compare_ctime (file1, file2)
  1389.      struct fileinfo *file1, *file2;
  1390. {
  1391.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1392. }
  1393.  
  1394. static int
  1395. rev_cmp_ctime (file2, file1)
  1396.      struct fileinfo *file1, *file2;
  1397. {
  1398.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1399. }
  1400.  
  1401. static int
  1402. compare_mtime (file1, file2)
  1403.      struct fileinfo *file1, *file2;
  1404. {
  1405.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1406. }
  1407.  
  1408. static int
  1409. rev_cmp_mtime (file2, file1)
  1410.      struct fileinfo *file1, *file2;
  1411. {
  1412.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1413. }
  1414.  
  1415. static int
  1416. compare_atime (file1, file2)
  1417.      struct fileinfo *file1, *file2;
  1418. {
  1419.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1420. }
  1421.  
  1422. static int
  1423. rev_cmp_atime (file2, file1)
  1424.      struct fileinfo *file1, *file2;
  1425. {
  1426.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1427. }
  1428.  
  1429. static int
  1430. compare_size (file1, file2)
  1431.      struct fileinfo *file1, *file2;
  1432. {
  1433.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1434. }
  1435.  
  1436. static int
  1437. rev_cmp_size (file2, file1)
  1438.      struct fileinfo *file1, *file2;
  1439. {
  1440.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1441. }
  1442.  
  1443. static int
  1444. compare_name (file1, file2)
  1445.      struct fileinfo *file1, *file2;
  1446. {
  1447.   return strcmp (file1->name, file2->name);
  1448. }
  1449.  
  1450. static int
  1451. rev_cmp_name (file2, file1)
  1452.      struct fileinfo *file1, *file2;
  1453. {
  1454.   return strcmp (file1->name, file2->name);
  1455. }
  1456.  
  1457. /* Compare file extensions.  Files with no extension are `smallest'.
  1458.    If extensions are the same, compare by filenames instead. */
  1459.  
  1460. static int
  1461. compare_extension (file1, file2)
  1462.      struct fileinfo *file1, *file2;
  1463. {
  1464.   register char *base1, *base2;
  1465.   register int cmp;
  1466.  
  1467.   base1 = rindex (file1->name, '.');
  1468.   base2 = rindex (file2->name, '.');
  1469.   if (base1 == 0 && base2 == 0)
  1470.     return strcmp (file1->name, file2->name);
  1471.   if (base1 == 0)
  1472.     return -1;
  1473.   if (base2 == 0)
  1474.     return 1;
  1475.   cmp = strcmp (base1, base2);
  1476.   if (cmp == 0)
  1477.     return strcmp (file1->name, file2->name);
  1478.   return cmp;
  1479. }
  1480.  
  1481. static int
  1482. rev_cmp_extension (file2, file1)
  1483.      struct fileinfo *file1, *file2;
  1484. {
  1485.   register char *base1, *base2;
  1486.   register int cmp;
  1487.  
  1488.   base1 = rindex (file1->name, '.');
  1489.   base2 = rindex (file2->name, '.');
  1490.   if (base1 == 0 && base2 == 0)
  1491.     return strcmp (file1->name, file2->name);
  1492.   if (base1 == 0)
  1493.     return -1;
  1494.   if (base2 == 0)
  1495.     return 1;
  1496.   cmp = strcmp (base1, base2);
  1497.   if (cmp == 0)
  1498.     return strcmp (file1->name, file2->name);
  1499.   return cmp;
  1500. }
  1501.  
  1502. /* List all the files now in the table.  */
  1503.  
  1504. static void
  1505. print_current_files ()
  1506. {
  1507.   register int i;
  1508.  
  1509.   switch (format)
  1510.     {
  1511.     case one_per_line:
  1512.       for (i = 0; i < files_index; i++)
  1513.     {
  1514.       print_file_name_and_frills (files + i);
  1515.       putchar ('\n');
  1516.     }
  1517.       break;
  1518.  
  1519.     case many_per_line:
  1520.       print_many_per_line ();
  1521.       break;
  1522.  
  1523.     case horizontal:
  1524.       print_horizontal ();
  1525.       break;
  1526.  
  1527.     case with_commas:
  1528.       print_with_commas ();
  1529.       break;
  1530.  
  1531.     case long_format:
  1532.       for (i = 0; i < files_index; i++)
  1533.     {
  1534.       print_long_format (files + i);
  1535.       PUTCHAR ('\n');
  1536.     }
  1537.       break;
  1538.     }
  1539. }
  1540.  
  1541. static void
  1542. print_long_format (f)
  1543.      struct fileinfo *f;
  1544. {
  1545.   char modebuf[20];
  1546.   char timebuf[40];
  1547.  
  1548.   /* 7 fields that may (worst case be 64-bit integral values) require 20 bytes,
  1549.      10 character mode field,
  1550.      24 characters for the time,
  1551.      9 spaces following each of these fields,
  1552.      and 1 trailing NUL byte.  */
  1553.   char bigbuf[7 * 20 + 10 + 24 + 9 + 1];
  1554.   char *p;
  1555.   time_t when;
  1556.  
  1557.   mode_string (f->stat.st_mode, modebuf);
  1558.   modebuf[10] = '\0';
  1559.  
  1560.   switch (time_type)
  1561.     {
  1562.     case time_ctime:
  1563.       when = f->stat.st_ctime;
  1564.       break;
  1565.     case time_mtime:
  1566.       when = f->stat.st_mtime;
  1567.       break;
  1568.     case time_atime:
  1569.       when = f->stat.st_atime;
  1570.       break;
  1571.     }
  1572.  
  1573.   strcpy (timebuf, ctime (&when));
  1574.  
  1575.   if (full_time)
  1576.     timebuf[24] = '\0';
  1577.   else
  1578.     {
  1579.       if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
  1580.       || current_time < when - 60L * 60L) /* In the future. */
  1581.     {
  1582.       /* The file is fairly old or in the future.
  1583.          POSIX says the cutoff is 6 months old;
  1584.          approximate this by 6*30 days.
  1585.          Allow a 1 hour slop factor for what is considered "the future",
  1586.          to allow for NFS server/client clock disagreement.
  1587.          Show the year instead of the time of day.  */
  1588.       strcpy (timebuf + 11, timebuf + 19);
  1589.     }
  1590.       timebuf[16] = 0;
  1591.     }
  1592.  
  1593.   p = bigbuf;
  1594.  
  1595.   if (print_inode)
  1596.     {
  1597.       sprintf (p, "%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
  1598.       p += strlen (p);
  1599.     }
  1600.  
  1601.   if (print_block_size)
  1602.     {
  1603.       sprintf (p, "%*u ", block_size_size,
  1604.            (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
  1605.                       kilobyte_blocks));
  1606.       p += strlen (p);
  1607.     }
  1608.  
  1609.   /* The space between the mode and the number of links is the POSIX
  1610.      "optional alternate access method flag". */
  1611.   sprintf (p, "%s %3u ", modebuf, (unsigned int) f->stat.st_nlink);
  1612.   p += strlen (p);
  1613.  
  1614.   if (numeric_users)
  1615.     sprintf (p, "%-8u ", (unsigned int) f->stat.st_uid);
  1616.   else
  1617.     sprintf (p, "%-8.8s ", getuser (f->stat.st_uid));
  1618.   p += strlen (p);
  1619.  
  1620.   if (!inhibit_group)
  1621.     {
  1622.       if (numeric_users)
  1623.     sprintf (p, "%-8u ", (unsigned int) f->stat.st_gid);
  1624.       else
  1625.     sprintf (p, "%-8.8s ", getgroup (f->stat.st_gid));
  1626.       p += strlen (p);
  1627.     }
  1628.  
  1629.   if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
  1630.     sprintf (p, "%3u, %3u ", (unsigned) major (f->stat.st_rdev),
  1631.          (unsigned) minor (f->stat.st_rdev));
  1632.   else
  1633.     sprintf (p, "%8lu ", (unsigned long) f->stat.st_size);
  1634.   p += strlen (p);
  1635.  
  1636.   sprintf (p, "%s ", full_time ? timebuf : timebuf + 4);
  1637.   p += strlen (p);
  1638.  
  1639.   DIRED_INDENT ();
  1640.   FPUTS (bigbuf, stdout, p - bigbuf);
  1641.   PUSH_CURRENT_DIRED_POS (&dired_obstack);
  1642.   print_name_with_quoting (f->name);
  1643.   PUSH_CURRENT_DIRED_POS (&dired_obstack);
  1644.  
  1645.   if (f->filetype == symbolic_link)
  1646.     {
  1647.       if (f->linkname)
  1648.     {
  1649.       FPUTS_LITERAL (" -> ", stdout);
  1650.       print_name_with_quoting (f->linkname);
  1651.       if (indicator_style != none)
  1652.         print_type_indicator (f->linkmode);
  1653.     }
  1654.     }
  1655.   else if (indicator_style != none)
  1656.     print_type_indicator (f->stat.st_mode);
  1657. }
  1658.  
  1659.  
  1660. /* Set QUOTED_LENGTH to strlen(P) and return NULL if P == quoted(P).
  1661.    Otherwise, return xmalloc'd storage containing the quoted version
  1662.    of P and set QUOTED_LENGTH to the length of the quoted P.  */
  1663.  
  1664. static char *
  1665. quote_filename (p, quoted_length)
  1666.      register const char *p;
  1667.      size_t *quoted_length;
  1668. {
  1669.   register unsigned char c;
  1670.   const char *p0 = p;
  1671.   char *quoted, *q;
  1672.   int found_quotable;
  1673.  
  1674.   if (!quote_as_string && !quote_funny_chars && !qmark_funny_chars)
  1675.     {
  1676.       *quoted_length = strlen (p);
  1677.       return NULL;
  1678.     }
  1679.  
  1680.   found_quotable = 0;
  1681.   for (c = *p; c; c = *++p)
  1682.     {
  1683.       if (quote_funny_chars)
  1684.     {
  1685.       switch (c)
  1686.         {
  1687.         case '\\':
  1688.         case '\n':
  1689.         case '\b':
  1690.         case '\r':
  1691.         case '\t':
  1692.         case '\f':
  1693.         case ' ':
  1694.         case '"':
  1695.           found_quotable = 1;
  1696.           break;
  1697.  
  1698.         default:
  1699.           /* FIXME: why not just use the ISPRINT macro here?  */
  1700.           if (isfunny(c))
  1701.         found_quotable = 1;
  1702.           break;
  1703.         }
  1704.     }
  1705.       else
  1706.     {
  1707.       if (isfunny2(c) && qmark_funny_chars)
  1708.         found_quotable = 1;
  1709.     }
  1710.       if (found_quotable)
  1711.     break;
  1712.     }
  1713.  
  1714.   if (!found_quotable)
  1715.     {
  1716.       *quoted_length = p - p0;
  1717.       return NULL;
  1718.     }
  1719.  
  1720.   p = p0;
  1721.   quoted = xmalloc (4 * strlen (p) + 1);
  1722.   q = quoted;
  1723.  
  1724. #define SAVECHAR(c) *q++ = (c)
  1725. #define SAVE_2_CHARS(c12) \
  1726.     do { *q++ = ((c12)[0]); \
  1727.      *q++ = ((c12)[1]); } while (0)
  1728.  
  1729.   if (quote_as_string)
  1730.     SAVECHAR ('"');
  1731.  
  1732.   while ((c = *p++))
  1733.     {
  1734.       if (quote_funny_chars)
  1735.     {
  1736.       switch (c)
  1737.         {
  1738.         case '\\':
  1739.           SAVE_2_CHARS ("\\\\");
  1740.           break;
  1741.  
  1742.         case '\n':
  1743.           SAVE_2_CHARS ("\\n");
  1744.           break;
  1745.  
  1746.         case '\b':
  1747.           SAVE_2_CHARS ("\\b");
  1748.           break;
  1749.  
  1750.         case '\r':
  1751.           SAVE_2_CHARS ("\\r");
  1752.           break;
  1753.  
  1754.         case '\t':
  1755.           SAVE_2_CHARS ("\\t");
  1756.           break;
  1757.  
  1758.         case '\f':
  1759.           SAVE_2_CHARS ("\\f");
  1760.           break;
  1761.  
  1762.         case ' ':
  1763.           SAVE_2_CHARS ("\\ ");
  1764.           break;
  1765.  
  1766.         case '"':
  1767.           SAVE_2_CHARS ("\\\"");
  1768.           break;
  1769.  
  1770.         default:
  1771.           if (!isfunny(c))
  1772.         SAVECHAR (c);
  1773.           else
  1774.         {
  1775.           char buf[5];
  1776.           sprintf (buf, "\\%03o", (unsigned int) c);
  1777.           q = stpcpy (q, buf);
  1778.         }
  1779.         }
  1780.     }
  1781.       else
  1782.     {
  1783.       if (!isfunny2(c))
  1784.         SAVECHAR (c);
  1785.       else if (!qmark_funny_chars)
  1786.         SAVECHAR (c);
  1787.       else
  1788.         SAVECHAR ('?');
  1789.     }
  1790.     }
  1791.  
  1792.   if (quote_as_string)
  1793.     SAVECHAR ('"');
  1794.  
  1795.   *quoted_length = q - quoted;
  1796.  
  1797.   SAVECHAR ('\0');
  1798.  
  1799.   return quoted;
  1800. }
  1801.  
  1802. static void
  1803. print_name_with_quoting (p)
  1804.      register char *p;
  1805. {
  1806.   char *quoted;
  1807.   size_t quoted_length;
  1808.  
  1809.   quoted = quote_filename (p, "ed_length);
  1810.   FPUTS (quoted != NULL ? quoted : p, stdout, quoted_length);
  1811.   if (quoted)
  1812.     free (quoted);
  1813. }
  1814.  
  1815. /* Print the file name of `f' with appropriate quoting.
  1816.    Also print file size, inode number, and filetype indicator character,
  1817.    as requested by switches.  */
  1818.  
  1819. static void
  1820. print_file_name_and_frills (f)
  1821.      struct fileinfo *f;
  1822. {
  1823.   if (print_inode)
  1824.     printf ("%*lu ", INODE_DIGITS, (unsigned long) f->stat.st_ino);
  1825.  
  1826.   if (print_block_size)
  1827.     printf ("%*u ", block_size_size,
  1828.         (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
  1829.                        kilobyte_blocks));
  1830.  
  1831.   print_name_with_quoting (f->name);
  1832.  
  1833.   if (indicator_style != none)
  1834.     print_type_indicator (f->stat.st_mode);
  1835. }
  1836.  
  1837. static void
  1838. print_type_indicator (mode)
  1839.      unsigned int mode;
  1840. {
  1841.   if (S_ISDIR (mode))
  1842.     PUTCHAR ('/');
  1843.  
  1844. #ifdef S_ISLNK
  1845.   if (S_ISLNK (mode))
  1846.     PUTCHAR ('@');
  1847. #endif
  1848.  
  1849. #ifdef S_ISFIFO
  1850.   if (S_ISFIFO (mode))
  1851.     PUTCHAR ('|');
  1852. #endif
  1853.  
  1854. #ifdef S_ISSOCK
  1855.   if (S_ISSOCK (mode))
  1856.     PUTCHAR ('=');
  1857. #endif
  1858.  
  1859.   if (S_ISREG (mode) && indicator_style == all
  1860.       && (mode & (S_IEXEC | S_IXGRP | S_IXOTH)))
  1861.     PUTCHAR ('*');
  1862. }
  1863.  
  1864. static int
  1865. length_of_file_name_and_frills (f)
  1866.      struct fileinfo *f;
  1867. {
  1868.   register char *p = f->name;
  1869.   register char c;
  1870.   register int len = 0;
  1871.  
  1872.   if (print_inode)
  1873.     len += INODE_DIGITS + 1;
  1874.  
  1875.   if (print_block_size)
  1876.     len += 1 + block_size_size;
  1877.  
  1878.   if (quote_as_string)
  1879.     len += 2;
  1880.  
  1881.   while ((c = *p++))
  1882.     {
  1883.       if (quote_funny_chars)
  1884.     {
  1885.       switch (c)
  1886.         {
  1887.         case '\\':
  1888.         case '\n':
  1889.         case '\b':
  1890.         case '\r':
  1891.         case '\t':
  1892.         case '\f':
  1893.         case ' ':
  1894.           len += 2;
  1895.           break;
  1896.  
  1897.         case '"':
  1898.           if (quote_as_string)
  1899.         len += 2;
  1900.           else
  1901.         len += 1;
  1902.           break;
  1903.  
  1904.         default:
  1905.           if (!isfunny2(c))
  1906.         len += 1;
  1907.           else
  1908.         len += 4;
  1909.         }
  1910.     }
  1911.       else
  1912.     len += 1;
  1913.     }
  1914.  
  1915.   if (indicator_style != none)
  1916.     {
  1917.       unsigned filetype = f->stat.st_mode;
  1918.  
  1919.       if (S_ISREG (filetype))
  1920.     {
  1921.       if (indicator_style == all
  1922.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1923.         len += 1;
  1924.     }
  1925.       else if (S_ISDIR (filetype)
  1926. #ifdef S_ISLNK
  1927.            || S_ISLNK (filetype)
  1928. #endif
  1929. #ifdef S_ISFIFO
  1930.            || S_ISFIFO (filetype)
  1931. #endif
  1932. #ifdef S_ISSOCK
  1933.            || S_ISSOCK (filetype)
  1934. #endif
  1935.            )
  1936.     len += 1;
  1937.     }
  1938.  
  1939.   return len;
  1940. }
  1941.  
  1942. static void
  1943. print_many_per_line ()
  1944. {
  1945.   int filesno;            /* Index into files. */
  1946.   int row;            /* Current row. */
  1947.   int max_name_length;        /* Length of longest file name + frills. */
  1948.   int name_length;        /* Length of each file name + frills. */
  1949.   int pos;            /* Current character column. */
  1950.   int cols;            /* Number of files across. */
  1951.   int rows;            /* Maximum number of files down. */
  1952.  
  1953.   /* Compute the maximum file name length.  */
  1954.   max_name_length = 0;
  1955.   for (filesno = 0; filesno < files_index; filesno++)
  1956.     {
  1957.       name_length = length_of_file_name_and_frills (files + filesno);
  1958.       if (name_length > max_name_length)
  1959.     max_name_length = name_length;
  1960.     }
  1961.  
  1962.   /* Allow at least two spaces between names.  */
  1963.   max_name_length += 2;
  1964.  
  1965.   /* Calculate the maximum number of columns that will fit. */
  1966.   cols = line_length / max_name_length;
  1967.   if (cols == 0)
  1968.     cols = 1;
  1969.   /* Calculate the number of rows that will be in each column except possibly
  1970.      for a short column on the right. */
  1971.   rows = files_index / cols + (files_index % cols != 0);
  1972.   /* Recalculate columns based on rows. */
  1973.   cols = files_index / rows + (files_index % rows != 0);
  1974.  
  1975.   for (row = 0; row < rows; row++)
  1976.     {
  1977.       filesno = row;
  1978.       pos = 0;
  1979.       /* Print the next row.  */
  1980.       while (1)
  1981.     {
  1982.       print_file_name_and_frills (files + filesno);
  1983.       name_length = length_of_file_name_and_frills (files + filesno);
  1984.  
  1985.       filesno += rows;
  1986.       if (filesno >= files_index)
  1987.         break;
  1988.  
  1989.       indent (pos + name_length, pos + max_name_length);
  1990.       pos += max_name_length;
  1991.     }
  1992.       putchar ('\n');
  1993.     }
  1994. }
  1995.  
  1996. static void
  1997. print_horizontal ()
  1998. {
  1999.   int filesno;
  2000.   int max_name_length;
  2001.   int name_length;
  2002.   int cols;
  2003.   int pos;
  2004.  
  2005.   /* Compute the maximum file name length.  */
  2006.   max_name_length = 0;
  2007.   for (filesno = 0; filesno < files_index; filesno++)
  2008.     {
  2009.       name_length = length_of_file_name_and_frills (files + filesno);
  2010.       if (name_length > max_name_length)
  2011.     max_name_length = name_length;
  2012.     }
  2013.  
  2014.   /* Allow two spaces between names.  */
  2015.   max_name_length += 2;
  2016.  
  2017.   cols = line_length / max_name_length;
  2018.   if (cols == 0)
  2019.     cols = 1;
  2020.  
  2021.   pos = 0;
  2022.   name_length = 0;
  2023.  
  2024.   for (filesno = 0; filesno < files_index; filesno++)
  2025.     {
  2026.       if (filesno != 0)
  2027.     {
  2028.       if (filesno % cols == 0)
  2029.         {
  2030.           putchar ('\n');
  2031.           pos = 0;
  2032.         }
  2033.       else
  2034.         {
  2035.           indent (pos + name_length, pos + max_name_length);
  2036.           pos += max_name_length;
  2037.         }
  2038.     }
  2039.  
  2040.       print_file_name_and_frills (files + filesno);
  2041.  
  2042.       name_length = length_of_file_name_and_frills (files + filesno);
  2043.     }
  2044.   putchar ('\n');
  2045. }
  2046.  
  2047. static void
  2048. print_with_commas ()
  2049. {
  2050.   int filesno;
  2051.   int pos, old_pos;
  2052.  
  2053.   pos = 0;
  2054.  
  2055.   for (filesno = 0; filesno < files_index; filesno++)
  2056.     {
  2057.       old_pos = pos;
  2058.  
  2059.       pos += length_of_file_name_and_frills (files + filesno);
  2060.       if (filesno + 1 < files_index)
  2061.     pos += 2;        /* For the comma and space */
  2062.  
  2063.       if (old_pos != 0 && pos >= line_length)
  2064.     {
  2065.       putchar ('\n');
  2066.       pos -= old_pos;
  2067.     }
  2068.  
  2069.       print_file_name_and_frills (files + filesno);
  2070.       if (filesno + 1 < files_index)
  2071.     {
  2072.       putchar (',');
  2073.       putchar (' ');
  2074.     }
  2075.     }
  2076.   putchar ('\n');
  2077. }
  2078.  
  2079. /* Assuming cursor is at position FROM, indent up to position TO.  */
  2080.  
  2081. static void
  2082. indent (from, to)
  2083.      int from, to;
  2084. {
  2085.   while (from < to)
  2086.     {
  2087.       if (to / tabsize > from / tabsize)
  2088.     {
  2089.       putchar ('\t');
  2090.       from += tabsize - from % tabsize;
  2091.     }
  2092.       else
  2093.     {
  2094.       putchar (' ');
  2095.       from++;
  2096.     }
  2097.     }
  2098. }
  2099.  
  2100. /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
  2101.  
  2102. static void
  2103. attach (dest, dirname, name)
  2104.      char *dest, *dirname, *name;
  2105. {
  2106.   char *dirnamep = dirname;
  2107.  
  2108.   /* Copy dirname if it is not ".". */
  2109.   if (dirname[0] != '.' || dirname[1] != 0)
  2110.     {
  2111.       while (*dirnamep)
  2112.     *dest++ = *dirnamep++;
  2113.       /* Add '/' if `dirname' doesn't already end with it. */
  2114.       if (dirnamep > dirname && dirnamep[-1] != '/')
  2115.     *dest++ = '/';
  2116.     }
  2117.   while (*name)
  2118.     *dest++ = *name++;
  2119.   *dest = 0;
  2120. }
  2121.  
  2122. static void
  2123. usage (status)
  2124.      int status;
  2125. {
  2126.   if (status != 0)
  2127.     fprintf (stderr, "Try `%s --help' for more information.\n",
  2128.          program_name);
  2129.   else
  2130.     {
  2131.       printf ("Usage: %s [OPTION]... [PATH]...\n", program_name);
  2132.       printf ("\
  2133. \n\
  2134.   -A, --almost-all           do not list implied . and ..\n\
  2135.   -a, --all                  do not hide entries starting with .\n\
  2136.   -B, --ignore-backups       do not list implied entries ending with ~\n\
  2137.   -b, --escape               print octal escapes for nongraphic characters\n\
  2138.   -C                         list entries by columns\n\
  2139.   -c                         sort by change time; with -l: show ctime\n\
  2140.   -D, --dired                generate output well suited to Emacs' dired mode\n\
  2141.   -d, --directory            list directory entries instead of contents\n\
  2142.   -F, --classify             append a character for typing each entry\n\
  2143.   -f                         do not sort, enable -aU, disable -lst\n\
  2144.       --format=WORD          across -x, commas -m, horizontal -x, long -l,\n\
  2145.                                single-column -1, verbose -l, vertical -C\n\
  2146.       --full-time            list both full date and full time\n");
  2147.  
  2148.       printf ("\
  2149.   -G, --no-group             inhibit display of group information\n\
  2150.   -g                         (ignored)\n\
  2151.   -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN\n\
  2152.   -i, --inode                print index number of each file\n\
  2153.   -k, --kilobytes            use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
  2154.   -L, --dereference          list entries pointed to by symbolic links\n\
  2155.   -l                         use a long listing format\n\
  2156.   -m                         fill width with a comma separated list of entries\n\
  2157.   -N, --literal              do not quote entry names\n\
  2158.   -n, --numeric-uid-gid      list numeric UIDs and GIDs instead of names\n\
  2159.   -p                         append a character for typing each entry\n\
  2160.   -Q, --quote-name           enclose entry names in double quotes\n\
  2161.   -q, --hide-control-chars   print ? instead of non graphic characters\n\
  2162.   -R, --recursive            list subdirectories recursively\n\
  2163.   -r, --reverse              reverse order while sorting\n\
  2164.   -S                         sort by file size\n");
  2165.  
  2166.       printf ("\
  2167.   -s, --size                 print block size of each file\n\
  2168.       --sort=WORD            ctime -c, extension -X, none -U, size -S,\n\
  2169.                                status -c, time -t\n\
  2170.       --time=WORD            atime -u, access -u, use -u\n\
  2171.   -T, --tabsize=COLS         assume tab stops at each COLS instead of 8\n\
  2172.   -t                         sort by modification time; with -l: show mtime\n\
  2173.   -U                         do not sort; list entries in directory order\n\
  2174.   -u                         sort by last access time; with -l: show atime\n\
  2175.   -w, --width=COLS           assume screen width instead of current value\n\
  2176.   -x                         list entries by lines instead of by columns\n\
  2177.   -X                         sort alphabetically by entry extension\n\
  2178.   -1                         list one file per line\n\
  2179.       --help                 display this help and exit\n\
  2180.       --version              output version information and exit\n\
  2181. \n\
  2182. Sort entries alphabetically if none of -cftuSUX nor --sort.\n");
  2183.     }
  2184.   exit (status);
  2185. }
  2186.