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