home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / unexpand.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  10.4 KB  |  468 lines

  1. /* unexpand - convert spaces to tabs
  2.    Copyright (C) 1989, 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. /* By default, convert only maximal strings of initial blanks and tabs
  19.    into tabs.
  20.    Preserves backspace characters in the output; they decrement the
  21.    column count for tab calculations.
  22.    The default action is equivalent to -8.
  23.  
  24.    Options:
  25.    --tabs=tab1[,tab2[,...]]
  26.    -t tab1[,tab2[,...]]
  27.    -tab1[,tab2[,...]]    If only one tab stop is given, set the tabs tab1
  28.             spaces apart instead of the default 8.  Otherwise,
  29.             set the tabs at columns tab1, tab2, etc. (numbered from
  30.             0); replace any tabs beyond the tabstops given with
  31.             single spaces.
  32.    --all
  33.    -a            Use tabs wherever they would replace 2 or more spaces,
  34.             not just at the beginnings of lines.
  35.  
  36.    David MacKenzie <djm@gnu.ai.mit.edu> */
  37.  
  38. #include <config.h>
  39.  
  40. /* Get isblank from GNU libc.  */
  41. #define _GNU_SOURCE
  42.  
  43. #include <stdio.h>
  44. #include <getopt.h>
  45. #include <sys/types.h>
  46. #include "system.h"
  47. #include "version.h"
  48.  
  49. /* The number of bytes added at a time to the amount of memory
  50.    allocated for the output line. */
  51. #define OUTPUT_BLOCK 256
  52.  
  53. /* The number of bytes added at a time to the amount of memory
  54.    allocated for the list of tabstops. */
  55. #define TABLIST_BLOCK 256
  56.  
  57. char *xmalloc ();
  58. char *xrealloc ();
  59. void error ();
  60.  
  61. static FILE *next_file ();
  62. static void add_tabstop ();
  63. static void parse_tabstops ();
  64. static void unexpand ();
  65. static void usage ();
  66. static void validate_tabstops ();
  67.  
  68. /* The name this program was run with. */
  69. char *program_name;
  70.  
  71. /* If nonzero, convert blanks even after nonblank characters have been
  72.    read on the line. */
  73. static int convert_entire_line;
  74.  
  75. /* If nonzero, the size of all tab stops.  If zero, use `tab_list' instead. */
  76. static int tab_size;
  77.  
  78. /* Array of the explicit column numbers of the tab stops;
  79.    after `tab_list' is exhausted, the rest of the line is printed
  80.    unchanged.  The first column is column 0. */
  81. static int *tab_list;
  82.  
  83. /* The index of the first invalid element of `tab_list',
  84.    where the next element can be added. */
  85. static int first_free_tab;
  86.  
  87. /* Null-terminated array of input filenames. */
  88. static char **file_list;
  89.  
  90. /* Default for `file_list' if no files are given on the command line. */
  91. static char *stdin_argv[] =
  92. {
  93.   "-", NULL
  94. };
  95.  
  96. /* Nonzero if we have ever read standard input. */
  97. static int have_read_stdin;
  98.  
  99. /* Status to return to the system. */
  100. static int exit_status;
  101.  
  102. /* If non-zero, display usage information and exit.  */
  103. static int show_help;
  104.  
  105. /* If non-zero, print the version on standard output then exit.  */
  106. static int show_version;
  107.  
  108. static struct option const longopts[] =
  109. {
  110.   {"tabs", required_argument, NULL, 't'},
  111.   {"all", no_argument, NULL, 'a'},
  112.   {"help", no_argument, &show_help, 1},
  113.   {"version", no_argument, &show_version, 1},
  114.   {NULL, 0, NULL, 0}
  115. };
  116.  
  117. main (argc, argv)
  118.      int argc;
  119.      char **argv;
  120. {
  121.   int tabval = -1;        /* Value of tabstop being read, or -1. */
  122.   int c;            /* Option character. */
  123.  
  124.   have_read_stdin = 0;
  125.   exit_status = 0;
  126.   convert_entire_line = 0;
  127.   tab_list = NULL;
  128.   first_free_tab = 0;
  129.   program_name = argv[0];
  130.  
  131.   while ((c = getopt_long (argc, argv, "at:,0123456789", longopts, (int *) 0))
  132.      != EOF)
  133.     {
  134.       switch (c)
  135.     {
  136.     case 0:
  137.       break;
  138.  
  139.     case '?':
  140.       usage (1);
  141.     case 'a':
  142.       convert_entire_line = 1;
  143.       break;
  144.     case 't':
  145.       convert_entire_line = 1;
  146.       parse_tabstops (optarg);
  147.       break;
  148.     case ',':
  149.       add_tabstop (tabval);
  150.       tabval = -1;
  151.       break;
  152.     default:
  153.       if (tabval == -1)
  154.         tabval = 0;
  155.       tabval = tabval * 10 + c - '0';
  156.       break;
  157.     }
  158.     }
  159.  
  160.   if (show_version)
  161.     {
  162.       printf ("unexpand - %s\n", version_string);
  163.       exit (0);
  164.     }
  165.  
  166.   if (show_help)
  167.     usage (0);
  168.  
  169.   add_tabstop (tabval);
  170.  
  171.   validate_tabstops (tab_list, first_free_tab);
  172.  
  173.   if (first_free_tab == 0)
  174.     tab_size = 8;
  175.   else if (first_free_tab == 1)
  176.     tab_size = tab_list[0];
  177.   else
  178.     tab_size = 0;
  179.  
  180.   if (optind == argc)
  181.     file_list = stdin_argv;
  182.   else
  183.     file_list = &argv[optind];
  184.  
  185.   unexpand ();
  186.  
  187.   if (have_read_stdin && fclose (stdin) == EOF)
  188.     error (1, errno, "-");
  189.   if (fclose (stdout) == EOF)
  190.     error (1, errno, "write error");
  191.   exit (exit_status);
  192. }
  193.  
  194. /* Add the comma or blank separated list of tabstops STOPS
  195.    to the list of tabstops. */
  196.  
  197. static void
  198. parse_tabstops (stops)
  199.      char *stops;
  200. {
  201.   int tabval = -1;
  202.  
  203.   for (; *stops; stops++)
  204.     {
  205.       if (*stops == ',' || ISBLANK (*stops))
  206.     {
  207.       add_tabstop (tabval);
  208.       tabval = -1;
  209.     }
  210.       else if (ISDIGIT (*stops))
  211.     {
  212.       if (tabval == -1)
  213.         tabval = 0;
  214.       tabval = tabval * 10 + *stops - '0';
  215.     }
  216.       else
  217.     error (1, 0, "tab size contains an invalid character");
  218.     }
  219.  
  220.   add_tabstop (tabval);
  221. }
  222.  
  223. /* Add tab stop TABVAL to the end of `tab_list', except
  224.    if TABVAL is -1, do nothing. */
  225.  
  226. static void
  227. add_tabstop (tabval)
  228.      int tabval;
  229. {
  230.   if (tabval == -1)
  231.     return;
  232.   if (first_free_tab % TABLIST_BLOCK == 0)
  233.     tab_list = (int *) xrealloc (tab_list, first_free_tab + TABLIST_BLOCK);
  234.   tab_list[first_free_tab++] = tabval;
  235. }
  236.  
  237. /* Check that the list of tabstops TABS, with ENTRIES entries,
  238.    contains only nonzero, ascending values. */
  239.  
  240. static void
  241. validate_tabstops (tabs, entries)
  242.      int *tabs;
  243.      int entries;
  244. {
  245.   int prev_tab = 0;
  246.   int i;
  247.  
  248.   for (i = 0; i < entries; i++)
  249.     {
  250.       if (tabs[i] == 0)
  251.     error (1, 0, "tab size cannot be 0");
  252.       if (tabs[i] <= prev_tab)
  253.     error (1, 0, "tab sizes must be ascending");
  254.       prev_tab = tabs[i];
  255.     }
  256. }
  257.  
  258. /* Change spaces to tabs, writing to stdout.
  259.    Read each file in `file_list', in order. */
  260.  
  261. static void
  262. unexpand ()
  263. {
  264.   FILE *fp;            /* Input stream. */
  265.   int c;            /* Each input character. */
  266.   /* Index in `tab_list' of next tabstop: */
  267.   int tab_index = 0;        /* For calculating width of pending tabs. */
  268.   int print_tab_index = 0;    /* For printing as many tabs as possible. */
  269.   int column = 0;        /* Column on screen of next char. */
  270.   int next_tab_column;         /* Column the next tab stop is on. */
  271.   int convert = 1;        /* If nonzero, perform translations. */
  272.   int pending = 0;        /* Pending columns of blanks. */
  273.  
  274.   fp = next_file ((FILE *) NULL);
  275.   if (fp == NULL)
  276.     return;
  277.  
  278.   for (;;)
  279.     {
  280.       c = getc (fp);
  281.       if (c == EOF)
  282.     {
  283.       fp = next_file (fp);
  284.       if (fp == NULL)
  285.         break;        /* No more files. */
  286.       else
  287.         continue;
  288.     }
  289.  
  290.       if (c == ' ' && convert)
  291.     {
  292.       ++pending;
  293.       ++column;
  294.     }
  295.       else if (c == '\t' && convert)
  296.     {
  297.       if (tab_size == 0)
  298.         {
  299.           /* Do not let tab_index == first_free_tab;
  300.          stop when it is 1 less. */
  301.           while (tab_index < first_free_tab - 1
  302.              && column >= tab_list[tab_index])
  303.         tab_index++;
  304.           next_tab_column = tab_list[tab_index];
  305.           if (tab_index < first_free_tab - 1)
  306.         tab_index++;
  307.           if (column >= next_tab_column)
  308.         {
  309.           convert = 0;    /* Ran out of tab stops. */
  310.           goto flush_pend;
  311.         }
  312.         }
  313.       else
  314.         {
  315.           next_tab_column = column + tab_size - column % tab_size;
  316.         }
  317.       pending += next_tab_column - column;
  318.       column = next_tab_column;
  319.     }
  320.       else
  321.     {
  322.     flush_pend:
  323.       /* Flush pending spaces.  Print as many tabs as possible,
  324.          then print the rest as spaces. */
  325.       if (pending == 1)
  326.         {
  327.           putchar (' ');
  328.           pending = 0;
  329.         }
  330.       column -= pending;
  331.       while (pending != 0)
  332.         {
  333.           if (tab_size == 0)
  334.         {
  335.           /* Do not let tab_index == first_free_tab;
  336.              stop when it is 1 less. */
  337.           while (tab_index < first_free_tab - 1
  338.              && column >= tab_list[tab_index])
  339.             print_tab_index++;
  340.           next_tab_column = tab_list[print_tab_index];
  341.           if (print_tab_index < first_free_tab - 1)
  342.             print_tab_index++;
  343.         }
  344.           else
  345.         {
  346.           next_tab_column = column + tab_size - column % tab_size;
  347.         }
  348.           if (next_tab_column - column <= pending)
  349.         {
  350.           putchar ('\t');
  351.           pending -= next_tab_column - column;
  352.           column = next_tab_column;
  353.         }
  354.           else
  355.         {
  356.           --print_tab_index;
  357.           column += pending;
  358.           while (pending != 0)
  359.             {
  360.               putchar (' ');
  361.               pending--;
  362.             }
  363.         }
  364.         }
  365.  
  366.       if (convert)
  367.         {
  368.           if (c == '\b')
  369.         {
  370.           if (column > 0)
  371.             --column;
  372.         }
  373.           else
  374.         {
  375.           ++column;
  376.           if (convert_entire_line == 0)
  377.             convert = 0;
  378.         }
  379.         }
  380.  
  381.       putchar (c);
  382.  
  383.       if (c == '\n')
  384.         {
  385.           tab_index = print_tab_index = 0;
  386.           column = pending = 0;
  387.           convert = 1;
  388.         }
  389.     }
  390.     }
  391. }
  392.  
  393. /* Close the old stream pointer FP if it is non-NULL,
  394.    and return a new one opened to read the next input file.
  395.    Open a filename of `-' as the standard input.
  396.    Return NULL if there are no more input files.  */
  397.  
  398. static FILE *
  399. next_file (fp)
  400.      FILE *fp;
  401. {
  402.   static char *prev_file;
  403.   char *file;
  404.  
  405.   if (fp)
  406.     {
  407.       if (ferror (fp))
  408.     {
  409.       error (0, errno, "%s", prev_file);
  410.       exit_status = 1;
  411.     }
  412.       if (fp == stdin)
  413.     clearerr (fp);        /* Also clear EOF. */
  414.       else if (fclose (fp) == EOF)
  415.     {
  416.       error (0, errno, "%s", prev_file);
  417.       exit_status = 1;
  418.     }
  419.     }
  420.  
  421.   while ((file = *file_list++) != NULL)
  422.     {
  423.       if (file[0] == '-' && file[1] == '\0')
  424.     {
  425.       have_read_stdin = 1;
  426.       prev_file = file;
  427.       return stdin;
  428.     }
  429.       fp = fopen (file, "r");
  430.       if (fp)
  431.     {
  432.       prev_file = file;
  433.       return fp;
  434.     }
  435.       error (0, errno, "%s", file);
  436.       exit_status = 1;
  437.     }
  438.   return NULL;
  439. }
  440.  
  441. static void
  442. usage (status)
  443.      int status;
  444. {
  445.   if (status != 0)
  446.     fprintf (stderr, "Try `%s --help' for more information.\n",
  447.          program_name);
  448.   else
  449.     {
  450.       printf ("\
  451. Usage: %s [OPTION]... [FILE]...\n\
  452. ",
  453.           program_name);
  454.       printf ("\
  455. \n\
  456.   -a, --all           convert all whitespace, instead of initial whitespace\n\
  457.   -t, --tabs=NUMBER   have tabs NUMBER characters apart instead of 8\n\
  458.   -t, --tabs=LIST     use comma separated list of explicit tab positions\n\
  459.       --help          display this help and exit\n\
  460.       --version       output version information and exit\n\
  461. \n\
  462. Instead of -t NUMBER or -t LIST, -NUMBER or -LIST may be used.  With\n\
  463. no FILE, or when FILE is -, read standard input.\n\
  464. ");
  465.     }
  466.   exit (status);
  467. }
  468.