v23i023: The SC Spreadsheet, release 6.8, Part03/06

Rich Salz rsalz at bbn.com
Wed Sep 5 05:21:34 AEST 1990


Submitted-by: Jeff Buhrt <sawmill!buhrt>
Posting-number: Volume 23, Issue 23
Archive-name: sc6.8/part03

#! /bin/sh
# This is a shell archive.  Remove anything before this line, then feed it
# into a shell via "sh file" or similar.  To overwrite existing files,
# type "sh file -c".
# The tool that generated this appeared in the comp.sources.unix newsgroup;
# send mail to comp-sources-unix at uunet.uu.net if you want that tool.
# Contents:  help.c sc.c
# Wrapped by rsalz at litchi.bbn.com on Fri Jul 13 15:24:19 1990
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
echo If this archive is complete, you will see the following message:
echo '          "shar: End of archive 3 (of 6)."'
if test -f 'help.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'help.c'\"
else
  echo shar: Extracting \"'help.c'\" \(16990 characters\)
  sed "s/^X//" >'help.c' <<'END_OF_FILE'
X/*
X * Help functions for sc 
X * R. Bond, 1988
X * $Revision: 6.8 $
X */
X
X#include <curses.h>
X#include "sc.h"
X
Xchar *intro[] = {
X" ",
X" Overview:",
X" ",
X" A:   This overview",
X" B:   Options",
X" C:   Cursor movement commands",
X" D:   Cell entry and editing commands",
X" E:   Line Editing",
X" F:   File commands",
X" G:   Row and column commands",
X" H:   Range commands",
X" I:   Miscellaneous commands",
X" J:   Variable names/Expressions",
X" K:   Range functions",
X" L:   Numeric functions",
X" M:   String functions",
X" N:   Financial functions",
X" O:   Time and date functions",
X" ",
X" Q:   Return to main spreadsheet",
X(char *)0
X};
X
Xchar *options[] = {
X" ",
X" B: Options",
X" ",
X"     ^To  Toggle options. Toggle one option selected by o:",
X" ",
X"          a    Recalculate automatically or on ``@'' commands.",
X"          c    Current cell highlighting enable/disable.",  
X"          e    External function execution enable/disable.",
X"          n    If enabled, a digit starts a numeric value.",
X"          t    Top line display enable/disable.",
X"          x    Encrypt/decrypt database and listing files.",
X"          $    Dollar prescale.  If enabled, all numeric constants.",
X"               (not expressions) entered are multipled by 0.01.",
X" ",
X"     S    Set options.  Options include:",
X" ",
X"          byrows        Recalculate in row order. (default)",
X"          bycols        Recalculate in column order.",
X"          iterations=n  Set the number of iterations allowed. (10)",
X"          tblstyle=xx   Set ``T'' output style to:",
X"                        0 (none), tex, latex, or tbl.",
X(char *)0
X};
X
Xchar *cursor[] = {
X" ",
X" C: Cell cursor movement (always OK):",
X" ",
X"     ^N ^P ^B ^F Down, up, back, forward",
X"     ^Ed         Go to end of range.  Follow ^E by a direction indicator",
X"                 such as ^P or j.",
X"     Arrow keys (if the terminal and termcap support them.)",
X" ",
X" Cell cursor movement if no prompt active:",
X"     j,k,l,h    Down, up, right, left",
X"     SPACE      Forward",
X"     ^H         Back",
X"     TAB        Forward, otherwise starts/ends a range",
X"     ^          Up to row 0 of the current column.",
X"     #          Down to the last valid row of the current column.",
X"     0          Back to column A.  Preface with ^U if numeric mode.",
X"     $          Forward to the last valid column of the current row.",
X"     b          Back then up to the previous valid cell.",
X"     w          Forward then down to the next valid cell.",
X"     g          Go to a cell.  Cell name, range name, quoted string,",
X"                or a number specify which cell.",
X(char *)0
X};
X
X
Xchar *cell[] = {
X" ",
X" D: Cell entry and editing commands:",
X" ",
X"     =    Enter a numeric constant or expression.",
X"     <    Enter a left justified string or string expression.",
X"     \",>  Enter a right justified string or string expression.",
X"     e    Edit the current cell's numeric value.",
X"     E    Edit the current cell's string part.",
X"     x    Clear the current cell.",
X"     c    Copy the last marked cell to the current cell.",
X"     m    Mark a cell to be used as the source for ``c''",
X"     +    Increment numeric part",
X"     -    Decrement numeric part",
X" ",
X"     In numeric mode, a decimal digit, ``+'', ``-'', and ``.'' all start",
X"     a new numeric constant or expression.",
X(char *)0
X};
X
X
Xchar *vi[] = {
X" ",
X" E: Line Editor",
X" ",
X"     Hitting the ESC key while entering any command on the top line",
X"     will start a one-line vi-style editor.  Supported commands:",
X" ",
X"     ESC q        Abort command entry.",
X"     h l          Move cursor forward, backward.",
X"     0 $          Move cursor to the beginning, end of the line.",
X"     b w          Move cursor forward/back one word.",
X"     fc           Move cursor to character c.",
X"     tc           Move the cursor the the character before c.",
X"     i a          Enter insert mode before/after the cursor.",
X"     I            Move to cursor column 0 and enter insert mode.",
X"     x X          Delete the character under/before the cursor.",
X"     rc           Replace the character under the cursor with c.",
X"     cm           Change - m = b,f,h,l,t or w.",
X"     dm           Delete - m = b,f,h,l,t or w.",
X"     R            Enter replace (overstrike) mode.",
X"     + j - k /    Forward/backward/search the command history.",
X"     n            Repeat last history search.",
X"     . u          Repeat/undo the last command.",
X(char *)0
X};
X
Xchar *file[] = {
X" ",
X" F: File commands:",
X" ",
X"     G    Get a new database from a file. ",
X"     M    Merge a new file into the current database.",
X"     P    Put the current database into a file.",
X"     W    Write a listing of the current database into a file in",
X"          a form that matches its appearance on the screen.",
X"     T    Write a listing of the current database to a file, but",
X"          put delimiters between each pair of fields.",
X"          Optionally brackets output with control lines for ``tbl'',",
X"          ``LaTeX'', or ``TeX''.",
X" ",
X"     If encryption mode is set, file I/O will be encrypted/decrypted.",
X"     ``\"| program\"'' for a file name will pipe (unencrypted) output to",
X"     a program for Put, Write and Table.  If a cell name is used",
X"     as the file name, the cell's string part will be used as the",
X"     file name.",
X(char *)0
X};
X
X
Xchar *row[] = {
X" ",
X" G: Row and column commands:",
X" ",
X"     ir, ic      Insert a new, empty row (column)",
X"     ar, ac      Append a new copy of the current row (column)",
X"     dr, dc      Delete the current row (column)",
X"     pr, pc, pm  Pull deleted cells back into the spreadsheet",
X"                 Insert rows, columns or merge the cells.",
X"     vr, vc      Remove expressions from the affected rows (columns),",
X"                 leaving only the values.",
X"     zr, zc      Hide (``zap'') the current row (column)",
X"     sr, sc      Show hidden rows (columns)",
X"     f           Set the output format to be used with the values of",
X"                 each cell in this column.  Enter field width and",
X"                 number of fractional digits.  A preceding count can be",
X"                 used to change more than one column.",
X" ",
X"     Commands which move or copy cells also modify the row and column ",
X"     references in the new cell expressions.  Use ``fixed'' or the",
X"     ``$'' style cell reference to supress the change.",
X(char *)0
X};
X
X
Xchar *range[] = {
X" ",
X" H: Range commands:",
X" ",
X"     /x   Clear a range. ",
X"     /v   Remove the expressions from a range of cells, leaving ",
X"          just the values.",
X"     /c   Copy a source range to a destination range.",
X"     /f   Fill a range with constant values starting with a given",
X"          value and increasing by a given increment.",
X"     /d   Assign a name to a cell or a range of cells.  Give the",
X"          the name, surrounded by quotes, and either a cell name such",
X"          as ``A10'' or a range such as ``a1:b20''.",
X"     /s   Shows the currently defined range names.  Pipe output to",
X"          sort, then to less.",
X"     /u   Use this command to undefine a previously defined range",
X"          name.",
X" ",
X"     Range operations affect a rectangular region on the screen",
X"     defined by the upper left and lower right cells in the region.",
X"     A range is specified by giving the cell names separated by ``:'',",
X"     such as ``a20:k52''.  Another way to refer to a range is to use",
X"     a name previously defined using ``/d''.",
X(char *)0
X};
X
X
Xchar *misc[] = {
X" ",
X" I: Miscellaneous commands:",
X" ",
X"     Q q ^C   Exit from the program.",
X"     ^G ESC   Abort entry of the current command.",
X"     ?        Help",
X"     !        Shell escape.  Enter a command to run.  ``!!'' repeats",
X"              the last command.  Just ``!'' starts an interactive shell.",
X"     ^L       Redraw the screen.",
X"     ^R       Redraw the screen.  Highlight cells with values but no",
X"              expressions.",
X"     ^X       Redraw the screen.  Show formulas, not values.",
X"     @        Recalculate the spreadsheet.",
X"     ^V       Type, in the command line, the name of the current cell.",
X"     ^W       Type, in the command line, the current cell's expression.",
X"     ^A       Type, in the command line, the current cell's numeric value.",
X"     TAB      When the character cursor is on the top line TAB can be used",
X"              to start or stop the display of the default range.",
X(char *)0
X};
X
Xchar *var[] = {
X" ",
X" J: Variable names:",
X" ",
X"     K20    Row and column can vary on copies.",
X"     $K$20  Row and column stay fixed on copies.",
X"     $K20   Row can vary; column stays fixed on copies.",
X"     K$20   Row stays fixed; column can vary on copies.",
X"     fixed  holds following expession fixed on copies.",
X"     Cells and ranges can be given a symbolic name via ``/d''.",
X" ",
X" Expressions:",
X"     -e      Negation                e<=e  Less than or equal",
X"     e+e     Addition                e=e   Equal",
X"     e-e     Subtraction             e!=e  Not Equal",
X"     e*e     Multiplication          e>=e  Greater than or equal",
X"     e/e     Division                e>e  Greater than",
X"     e%e     Modulo                  e<e  Less than",
X"     e^e     Exponentiation          e&e  Boolean operator AND.",
X"     ~e      Boolean operator NOT    e|e  Boolean operator OR",
X"     e?e1:e2  or @if(e,e1,e2)",
X"             Conditional: If e is non zero then then e1, else e2.",
X"     Terms may be constants, variables, and parenthesized expressions.",
X(char *)0
X};
X
Xchar *rangef[] = {
X" ",
X" K: Range functions:",
X" ",
X"     @sum(r)           Sum all valid cells in the range.",
X"     @prod(r)          Multiply together all valid cells in the range.",
X"     @avg(r)           Average all valid cells in the range.",
X"     @count(r)         Count all valid cells in the range.",
X"     @max(r)           Return the maximum value in the range.",
X"     @min(r)           Return the minimum value in the range.",
X"     @stddev(r)        Return the sample standard deviation of ",
X"                       the cells in the range.",
X"     @index(e,r) @stindex(e,r)",
X"                       Return the numeric (string) value of the cell at",
X"                       index e into range r.",
X"     @lookup(e,r) @hlookup(e,r,n) @vlookup(e,r,n)",
X"                       Search through the range r for a value that",
X"                       matches e.  If e is numeric, the last value <= e",
X"                       matches; if string, an exact match is required.",
X"                       @lookup searches a single row (column) and returns",
X"                       the value from the next column (row); @hlookup",
X"                       (@vlookup) searches the first row (column) in r and",
X"                       returns the value n columns (rows) from the match.",
X(char *)0
X};
X
Xchar *numericf[] = {
X" ",
X" L: Numeric functions:",
X" ",
X"     @atan2(e1,e2)     Arc tangent of e1/e2.",
X"     @ceil(e)          Smallest integer not less than e.",
X"     @eqs(se1,se2)     1 if string expr se1 has the same value as se2.",
X"     @exp(e)           Exponential function of e.",
X"     @abs(e) @fabs(e)  Absolute value of e.",
X"     @floor(e)         The largest integer not greater than e.",
X"     @hypot(x,y)       Sqrt(x*x+y*y).",
X"     @max(e1,e2,...)   The maximum of the values of the e's.",
X"     @min(e1,e2,...)   The minimum of the values of the e's",
X"     @nval(se,e)       The numeric value of a named cell.",
X"     pi                A constant quite close to pi.",
X"     @pow(e1,e2)       e1 raised to the power of e2.",
X"     @rnd(e)           Round e to the nearest integer.",
X"     @round(e,n)       Round e to n decimal places.",
X"     @sqrt(e)          Square root of e.",
X"     @ston(se)         Convert string expr se to a numeric",
X"     @ln(e)   @log(e)           Natural/base 10 logarithm of e.",
X"     @dtr(e)  @rtd(e)           Convert degrees to/from radians.",
X"     @cos(e)  @sin(e)  @tan(e)  Trig functions of radian arguments.",
X"     @asin(e) @acos(e) @atan(e) Inverse trig function.",
X(char *)0
X};
X
Xchar *stringf[] = {
X" ",
X" M: String functions:",
X" ",
X"     #                 Concatenate strings.  For example, the",
X"                       string expression ``A0 # \"zy dog\"'' yields",
X"                       ``the lazy dog'' if A0 is ``the la''.",
X"     @substr(se,e1,e2) Extract characters e1 through e2 from the",
X"                       string expression se.  For example,",
X"                       ``@substr(\"Nice jacket\" 4, 7)'' yields ",
X"                       ``e jac''.",
X"     @fmt(se,e)        Convert a number to a string using sprintf(3).",
X"                       For example,  ``@fmt(\"*%6.3f*\",10.5)'' yields",
X"                       ``*10.500*''.  Use formats are e, E, f, g, and G.", 
X"     @sval(se,e)       Return the string value of a cell selected by name.",
X"     @ext(se,e)        Call an external function (program or",
X"                       script).  Convert e to a string and append it",
X"                       to the command line as an argument.  @ext yields",
X"                       a string: the first line printed to standard",
X"                       output by the command.",
X"     String expressions are made up of constant strings (characters",
X"     surrounded by quotes), variables, and string functions.",
X(char *)0
X};
X
X
Xchar *finf[] = {
X" ",
X" N: Financial functions:",
X" ",
X"     @pmt(e1,e2,e3)    @pmt(60000,.01,360) computes the monthly",
X"                       payments for a $60000 mortgage at 12%",
X"                       annual interest (.01 per month) for 30",
X"                       years (360 months).",
X" ",
X"     @fv(e1,e2,e3)     @fv(100,.005,36) computes the future value",
X"                       of 36 monthly payments of $100 at 6%",
X"                       interest (.005 per month).  It answers the",
X"                       question:  ``How much will I have in 36",
X"                       months if I deposit $100 per month in a",
X"                       savings account paying 6% interest com-",
X"                       pounded monthly?''",
X" ",
X"     @pv(e1,e2,e3)     @pv(1000,.015,36) computes the present",
X"                       value of an ordinary annuity of 36",
X"                       monthly payments of $1000 at 18% annual",
X"                       interest.  It answers the question: ``How",
X"                       much can I borrow at 18% for 30 years if I",
X"                       pay $1000 per month?''",
X(char *)0
X};
X
X
Xchar *timef[] = {
X" ",
X" O: Time and date functions:",
X" ",
X"     @now              Return the time encoded in seconds since 1970.",
X"     @dts(m,d,y)       Return m/d/y encoded in seconds since 1970.",
X"     @tts(h,m,s)       Return h:m:s encoded in seconds since midnight.",
X" ",
X"     All of the following take an argument expressed in seconds:",
X" ",
X"     @date(e)          Convert the time in seconds to a date",
X"                       string 24 characters long in the following",
X"                       form: ``Sun Sep 16 01:03:52 1973''.  Note",
X"                       that you can extract pieces of this fixed format",
X"                       string with @substr.",
X"     @year(e)          Return the year.  Valid years begin with 1970.",
X"     @month(e)         Return the month: 1 (Jan) to 12 (Dec).",
X"     @day(e)           Return the day of the month: 1 to 31.",
X"     @hour(e)          Return the number of hours since midnight: 0 to 23.",
X"     @minute(e)        Return the number of minutes since the",
X"                       last full hour: 0 to 59.",
X"     @second(e)        Return the number of seconds since the",
X"                       last full minute: 0 to 59.",
X(char *)0
X};
Xvoid
Xhelp()
X{
X    int option;
X    char **ns = intro;
X
X    while((option = pscreen(ns)) != 'q' && option != 'Q') {
X    	switch (option) {
X	case 'a': case 'A': ns = intro; break;
X	case 'b': case 'B': ns = options; break;
X	case 'c': case 'C': ns = cursor; break;
X	case 'd': case 'D': ns = cell; break;
X	case 'e': case 'E': ns = vi; break;
X	case 'f': case 'F': ns = file; break;
X	case 'g': case 'G': ns = row; break;
X	case 'h': case 'H': ns = range; break;
X	case 'i': case 'I': ns = misc; break;
X	case 'j': case 'J': ns = var; break;
X	case 'k': case 'K': ns = rangef; break;
X	case 'l': case 'L': ns = numericf; break;
X	case 'm': case 'M': ns = stringf; break;
X	case 'n': case 'N': ns = finf; break;
X	case 'o': case 'O': ns = timef; break;
X	default: ns = intro; break;
X	}
X    }
X    FullUpdate++;
X    (void) move(1,0);
X    (void) clrtobot();
X}
X
Xpscreen(screen)
Xchar *screen[];
X{
X    int line;
X    int dbline;
X
X    (void) move(1,0);
X    (void) clrtobot();
X    dbline = 1;
X    for (line = 0; screen[line]; line++) {
X	(void) move(dbline++, 4);
X	(void) addstr (screen[line]);
X	(void) clrtoeol();
X    }
X    (void) move(0,0);
X    (void) printw("Which Screen? [a-n, q]");
X    (void) clrtoeol();
X    (void) refresh();
X    return(nmgetch());
X}
END_OF_FILE
  if test 16990 -ne `wc -c <'help.c'`; then
    echo shar: \"'help.c'\" unpacked with wrong size!
  fi
  # end of 'help.c'
fi
if test -f 'sc.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'sc.c'\"
else
  echo shar: Extracting \"'sc.c'\" \(33828 characters\)
  sed "s/^X//" >'sc.c' <<'END_OF_FILE'
X/*	SC	A Spreadsheet Calculator
X *		Main driver
X *
X *		original by James Gosling, September 1982
X *		modifications by Mark Weiser and Bruce Israel,
X *			University of Maryland
X *
X *              More mods Robert Bond, 12/86
X *		More mods by Alan Silverstein, 3-4/88, see list of changes.
X *		Currently supported by pur-phy!sawmill!buhrt (Jeff Buhrt)
X *		$Revision: 6.8 $
X *
X */
X
X
X#include <signal.h>
X#include <curses.h>
X#include <ctype.h>
X
X#ifdef BSD42
X#include <strings.h>
X#else
X#ifndef SYSIII
X#include <string.h>
X#endif
X#endif
X
X#include <stdio.h>
X#include "sc.h"
X
Xchar *getenv();
X
X#ifdef SYSV3
Xvoid exit();
X#endif
X
X#ifndef DFLT_PAGER
X#define	DFLT_PAGER "more"	/* more is probably more widespread than less */
X#endif /* DFLT_PAGER */
X
X#define MAXCMD 160	/* for ! command below */
X
Xextern	char	*rev;
X
X/* Globals defined in sc.h */
X
Xstruct ent ***tbl;
Xint strow, stcol;
Xint currow, curcol;
Xint savedrow, savedcol;
Xint FullUpdate;
Xint maxrow, maxcol;
Xint maxrows, maxcols;
Xint *fwidth;
Xint *precision;
Xchar *col_hidden;
Xchar *row_hidden;
Xchar line[FBUFLEN];
Xint changed;
Xstruct ent *to_fix;
Xint modflg;
Xint numeric;
Xchar *mdir;
Xint showsc, showsr;	/* Starting cell for highlighted range */
Xchar mode_ind = '.';
X
Xchar curfile[PATHLEN];
Xchar    revmsg[80];
X
Xint  linelim = -1;
X
Xint  showtop   = 1;	/* Causes current cell value display in top line  */
Xint  showcell  = 1;	/* Causes current cell to be highlighted	  */
Xint  showrange = 0;	/* Causes ranges to be highlighted		  */
Xint  showneed  = 0;	/* Causes cells needing values to be highlighted  */
Xint  showexpr  = 0;	/* Causes cell exprs to be displayed, highlighted */
X
Xint  autocalc = 1 ;	/* 1 to calculate after each update */
Xint  calc_order = BYROWS;
Xint  tbl_style = 0;	/* headers for T command output */
X
Xint  lastmx, lastmy;	/* Screen address of the cursor */
Xint  lastcol;		/* Spreadsheet Column the cursor was in last */
Xchar under_cursor[] = " "; /* Data under the < cursor */
X
X#ifdef VMS
Xint VMS_read_raw = 0;
X#endif
X
Xint seenerr;
X
Xvoid
Xyyerror(err)
Xchar *err; {
X    if (seenerr) return;
X    seenerr++;
X    (void) move(1,0);
X    (void) clrtoeol();
X    (void) printw("%s: %.*s<=%s",err,linelim,line,line+linelim);
X}
X
Xstruct ent *
Xlookat(row,col)
Xint	row, col;
X{
X    register struct ent **pp;
X
X    checkbounds(&row, &col);
X    pp = ATBL(tbl, row, col);
X    if (*pp == (struct ent *)0) {
X	*pp = (struct ent *) xmalloc((unsigned)sizeof(struct ent));
X	if (row>maxrow) maxrow = row;
X	if (col>maxcol) maxcol = col;
X	(*pp)->label = (char *)0;
X	(*pp)->row = row;
X	(*pp)->col = col;
X	(*pp)->flags = 0;
X	(*pp)->expr = (struct enode *)0;
X	(*pp)->v = (double) 0.0;
X	(*pp)->evnext = (struct ent *)0;
X    }
X    return *pp;
X}
X
X/*
X * This structure is used to keep ent structs around before they
X * are deleted to allow the sync_refs routine a chance to fix the
X * variable references.
X * We also use it as a last-deleted buffer for the 'p' command.
X */
X
Xvoid
Xfree_ent(p)
Xregister struct ent *p;
X{
X    p->next = to_fix;
X    to_fix = p;
X    p->flags |= is_deleted;
X}
X
Xvoid
Xflush_saved()
X{
X    register struct ent *p;
X    register struct ent *q;
X
X    if (!(p = to_fix))
X	return;
X    while (p) {
X	(void) clearent(p);
X	q = p->next;
X	xfree((char *)p);
X	p = q;
X    }
X    to_fix = 0;
X}
X
X/*
X * standout last time in update()?
X *	At this point we will let curses do work
X */
Xint	standlast	= FALSE;
X
Xvoid
Xupdate (anychanged)
Xint	anychanged;	/* did any cell really change in value? */
X{
X    register    row,
X                col;
X    register struct ent **pp;
X    int     mxcol;
X    int     mxrow;
X    int     rows;
X    int     cols;
X    int     minsr, minsc, maxsr, maxsc;
X    register r;
X    register i;
X
X    while (row_hidden[currow])   /* You can't hide the last row or col */
X	currow++;
X    while (col_hidden[curcol])
X	curcol++;
X    /* First see if the last display still covers curcol */
X    if (stcol <= curcol) { 
X	for (i = stcol, cols = 0, col = RESCOL;
X			(col + fwidth[i]) < COLS-1 && i < maxcols; i++) {
X	    cols++;
X	    if (col_hidden[i])
X		continue;
X	    col += fwidth[i];
X	}
X    }
X    while (stcol + cols - 1 < curcol || curcol < stcol) {
X	FullUpdate++;
X	if (stcol - 1 == curcol) {    /* How about back one? */
X	    stcol--;
X	} else if (stcol + cols == curcol) {   /* Forward one? */
X	    stcol++;
X	} else {
X	    /* Try to put the cursor in the center of the screen */
X	    col = (COLS - RESCOL - fwidth[curcol]) / 2 + RESCOL; 
X	    stcol = curcol;
X	    for (i=curcol-1; i >= 0 && col-fwidth[i] > RESCOL; i--) {
X		stcol--;
X		if (col_hidden[i])
X		    continue;
X		col -= fwidth[i];
X	    }
X	}
X	/* Now pick up the counts again */
X	for (i = stcol, cols = 0, col = RESCOL;
X			(col + fwidth[i]) < COLS-1 && i < maxcols; i++) {
X	    cols++;
X	    if (col_hidden[i])
X		continue;
X	    col += fwidth[i];
X	}
X    }
X    /* Now - same process on the rows */
X    if (strow <= currow) { 
X	for (i = strow, rows = 0, row=RESROW; row<LINES && i<maxrows; i++) {
X	    rows++;
X	    if (row_hidden[i])
X		continue;
X	    row++;
X	}
X    }
X    while (strow + rows - 1 < currow || currow < strow) {
X	FullUpdate++;
X	if (strow - 1 == currow) {    /* How about up one? */
X	    strow--;
X	} else if (strow + rows == currow) {   /* Down one? */
X	    strow++;
X	} else {
X	    /* Try to put the cursor in the center of the screen */
X	    row = (LINES - RESROW) / 2 + RESROW; 
X	    strow = currow;
X	    for (i=currow-1; i >= 0 && row-1 > RESROW; i--) {
X		strow--;
X		if (row_hidden[i])
X		    continue;
X		row--;
X	    }
X	}
X	/* Now pick up the counts again */
X	for (i = strow, rows = 0, row=RESROW; row<LINES && i<maxrows; i++) {
X	    rows++;
X	    if (row_hidden[i])
X		continue;
X	    row++;
X	}
X    }
X    mxcol = stcol + cols - 1;
X    mxrow = strow + rows - 1;
X    if (FullUpdate || standlast) {
X	(void) move(2, 0);
X	(void) clrtobot();
X	(void) standout();
X	for (row=RESROW, i=strow; i <= mxrow; i++) {
X	    if (row_hidden[i]) 
X		continue;
X	    (void) move(row,0);
X	    if (maxrows < 1000)
X		(void) printw("%-*d", RESCOL-1, i);
X	    else
X		(void) printw("%-*d", RESCOL, i);
X	    row++;
X	}
X	(void) move(2,0);
X	(void) printw("%*s", RESCOL, " ");
X
X	for (col=RESCOL, i = stcol; i <= mxcol; i++) {
X	    register int k;
X	    if (col_hidden[i])
X		continue;
X	    (void) move(2, col);
X	    k = fwidth[i]/2;
X	    if (k == 0)
X		(void) printw("%1s", coltoa(i));
X	    else
X	        (void) printw("%*s%-*s", k, " ", fwidth[i]-k, coltoa(i));
X	    col += fwidth[i];
X	}
X	(void) standend();
X    }
X
X    /* Get rid of cursor standout on the cell at previous cursor position */
X    if (showcell)
X    {	(void) move(lastmx, lastmy);
X        repaint(lastmx, lastmy, fwidth[lastcol]);
X    }
X
X    if (showrange) {
X	minsr = showsr < currow ? showsr : currow;
X	minsc = showsc < curcol ? showsc : curcol;
X	maxsr = showsr > currow ? showsr : currow;
X	maxsc = showsc > curcol ? showsc : curcol;
X
X	if (showtop) {
X	    (void) move(1,0);
X	    (void) clrtoeol();
X	    (void) printw("Default range:  %s",
X			    r_name(minsr, minsc, maxsr, maxsc));
X	}
X    }
X
X    /* Repaint the visible screen */
X    if (showrange || anychanged || FullUpdate || standlast)
X    {
X	/* may be reset in loop, if not next time we will do a FullUpdate */
X      if (standlast)
X      {	FullUpdate = TRUE;
X	standlast = FALSE;
X      }
X      for (row = strow, r = RESROW; row <= mxrow; row++) {
X	register c = RESCOL;
X	int do_stand = 0;
X	int fieldlen;
X	int nextcol;
X
X	if (row_hidden[row])
X	    continue;
X	for (pp = ATBL(tbl, row, col = stcol); col <= mxcol;
X	         pp += nextcol - col,  col = nextcol, c += fieldlen) {
X
X	    nextcol = col+1;
X	    if (col_hidden[col]) {
X		fieldlen = 0;
X		continue;
X	    }
X
X	    fieldlen = fwidth[col];
X
X	    /*
X	     * Set standout if:
X	     *
X	     * - showing ranges, and not showing cells which need to be filled
X	     *	 in, and not showing cell expressions, and in a range, OR
X	     *
X	     * - if showing cells which need to be filled in and this one is
X	     *	 of that type (has a value and doesn't have an expression,
X	     *	 or it is a string expression), OR
X	     *
X	     * - if showing cells which have expressions and this one does.
X	     */
X
X	    if ((showrange && (! showneed) && (! showexpr)
X			   && (row >= minsr) && (row <= maxsr)
X			   && (col >= minsc) && (col <= maxsc))
X		    || (showneed && (*pp) && ((*pp) -> flags & is_valid)
X			&& (((*pp) -> flags & is_strexpr) || !((*pp) -> expr)))
X		    || (showexpr && (*pp) && ((*pp) -> expr)))
X	    {
X		(void) move(r, c);
X		(void) standout();
X		standlast++;
X		if (!*pp)	/* no cell, but standing out */
X		{	(void) printw("%*s", fwidth[col], " ");
X			(void) standend();
X			continue;
X		}
X		else
X			do_stand = 1;
X	    }
X	    else
X		do_stand = 0;
X
X	    if ((*pp) && ((*pp) -> flags & is_changed || FullUpdate) || do_stand) {
X		if (do_stand) {
X		    (*pp) -> flags |= is_changed; 
X		} else {
X		    (void) move(r, c);
X		    (*pp) -> flags &= ~is_changed;
X		}
X
X		/*
X		 * Show expression; takes priority over other displays:
X		 */
X
X		if (showexpr && ((*pp) -> expr)) {
X		    linelim = 0;
X		    editexp(row, col);		/* set line to expr */
X		    linelim = -1;
X		    showstring(line, /* leftflush = */ 1, /* hasvalue = */ 0,
X				row, col, & nextcol, mxcol, & fieldlen, r, c);
X		}
X		else {
X
X		    /*
X		     * Show cell's numeric value:
X		     */
X
X		    if ((*pp) -> flags & is_valid) {
X			char field[FBUFLEN];
X			(void)sprintf(field,"%*.*f", fwidth[col], precision[col], (*pp)->v);
X			if(strlen(field) > fwidth[col]) {
X			    for(i = 0; i<fwidth[col]; i++)
X				(void)addch('*');
X			} else {
X			    (void)addstr(field);
X			}
X		    }
X
X		    /*
X		     * Show cell's label string:
X		     */
X
X		    if ((*pp) -> label) {
X			showstring((*pp) -> label,
X				    (*pp) -> flags & is_leftflush,
X				    (*pp) -> flags & is_valid,
X				    row, col, & nextcol, mxcol,
X				    & fieldlen, r, c);
X		    }
X		    else	/* repaint a blank cell: */
X		    if ((do_stand || !FullUpdate) &&
X				((*pp)->flags & is_changed) &&
X				!((*pp)->flags & is_valid) && !(*pp)->label) {
X			(void) printw("%*s", fwidth[col], " ");
X		    }
X		} /* else */
X
X		if (do_stand) {
X		    (void) standend();
X		    do_stand = 0;
X		}
X	    }
X	}
X	r++;
X      }
X    }
X	    
X    (void) move(lastmy, lastmx+fwidth[lastcol]);
X    if((inch() & A_CHARTEXT ) == '<')
X        (void) addstr(under_cursor);
X
X    lastmy =  RESROW;
X    for (row = strow; row < currow; row++)
X	if (!row_hidden[row])
X		lastmy += 1;
X    lastmx = RESCOL;
X    for (col = stcol; col < curcol; col++)
X	if (!col_hidden[col])
X		lastmx += fwidth[col];
X    lastcol = curcol;
X    if (showcell && (! showneed) && (! showexpr)) {
X	(void) move(lastmy, lastmx);
X        (void) standout();
X        repaint(lastmx, lastmy, fwidth[lastcol]);
X        (void) standend();
X    }
X    (void) move(lastmy, lastmx+fwidth[lastcol]);
X    *under_cursor = (inch() & A_CHARTEXT );
X    (void) addstr("<");
X
X    (void) move(0, 0);
X    (void) clrtoeol();
X    if (linelim >= 0) {
X	(void) addch(mode_ind);
X	(void) addstr("> ");
X	(void) addstr(line);
X	(void) move(0, linelim+3);
X    } else {
X	if (showtop) {			/* show top line */
X	    register struct ent *p1;
X	    int printed = 0;		/* printed something? */
X
X            (void) printw("%s%d ", coltoa(curcol), currow);
X
X	    if (p1 = *ATBL(tbl, currow, curcol)) {
X		if (p1 -> expr) {
X		    /* has expr of some type */
X		    linelim = 0;
X		    editexp(currow, curcol);	/* set line to expr */
X		    linelim = -1;
X		}
X
X		/*
X		 * Display string part of cell:
X		 */
X
X		if ((p1 -> expr) && (p1 -> flags & is_strexpr)) {
X		    (void) addstr((p1 -> flags & is_leftflush) ? "<{" : ">{");
X		    (void) addstr(line);
X		    (void) addstr("} ");	/* and this '}' is for vi % */
X		    printed = 1;
X
X		} else if (p1 -> label) {
X		    /* has constant label only */
X		    (void) addstr ((p1 -> flags & is_leftflush) ? "<\"" : ">\"");
X		    (void) addstr (p1 -> label);
X		    (void) addstr ("\" ");
X		    printed = 1;
X		}
X
X		/*
X		 * Display value part of cell:
X		 */
X
X		if (p1 -> flags & is_valid) {
X		    /* has value or num expr */
X		    if ((! (p1 -> expr)) || (p1 -> flags & is_strexpr))
X			(void) sprintf (line, "%.15g", p1 -> v);
X
X		    (void) addstr ("[");
X		    (void) addstr (line);
X		    (void) addstr ("]");
X		    printed = 1;
X		}
X	    }
X	    if (! printed)
X		(void) addstr ("[]");
X	}
X	(void) move (lastmy, lastmx + fwidth[lastcol]);
X    }
X    if (revmsg[0]) {
X	(void) move(0, 0);
X	(void) clrtoeol ();	/* get rid of topline display */
X	(void) printw(revmsg);
X	revmsg[0] = '\0';	/* don't show it again */
X	(void) move (lastmy, lastmx + fwidth[lastcol]);
X    }
X    FullUpdate = FALSE;
X}
X
Xvoid
Xrepaint(x, y, len)
Xint x, y, len;
X{
X    int c;
X
X    while(len-- > 0) {
X	(void) move(y,x);
X	c = inch() & A_CHARTEXT;
X	(void) addch(c);
X	x++;
X    }
X}
X
Xchar    *progname;
X
Xint
Xmain (argc, argv)
Xint argc;
Xchar  **argv;
X{
X    int     inloop = 1;
X    register int   c;
X    int     edistate = -1;
X    int     arg = 1;
X    int     narg;
X    int     nedistate;
X    int	    running;
X    char    *revi;
X    int	    anychanged = FALSE;
X
X    /*
X     * Keep command line options around until the file is read so the
X     * command line overrides file options
X     */
X
X    int Mopt = 0;
X    int Nopt = 0;
X    int Copt = 0; 
X    int Ropt = 0;
X
X    int tempx, tempy; 	/* Temp versions of curx, cury */
X
X    if ((revi = strrchr(argv[0], '/')) != NULL)
X	progname = revi+1;
X    else
X	progname = argv[0];
X
X    while (argc > 1 && argv[1][0] == '-') {
X	argv++;
X	argc--;
X    	switch (argv[0][1]) {
X	    case 'x':
X#ifdef VMS
X		    (void) fprintf(stderr, "Crypt not available for VMS\n");
X		    exit(1);
X#else 
X		    Crypt = 1;
X#endif
X		    break;
X	    case 'm':
X		    Mopt = 1;
X		    break;
X	    case 'n':
X		    Nopt = 1;
X		    break;
X	    case 'c':
X		    Copt = 1;
X		    break;
X	    case 'r':
X		    Ropt = 1;
X		    break;
X	    default:
X		    (void) fprintf(stderr,"%s: unrecognized option: \"%c\"\n",
X			progname,argv[0][1]);
X		    exit(1);
X	}
X    }
X
X    *curfile ='\0';
X
X    signals();
X    (void) initscr();
X
X	/* setup the spreadsheet arrays, initscr() will get the screen size */
X    if (!growtbl(GROWNEW, 0, 0))
X    {	endwin();
X	exit(1);
X    }
X
X    (void) clear();
X#ifdef VMS
X    VMS_read_raw = 1;
X#else
X    nonl();
X    noecho ();
X    cbreak();
X#endif
X    initkbd();
X    scrollok(stdscr, 1);
X
X    /*
X     * Build revision message for later use:
X     */
X
X    (void) strcpy (revmsg, progname);
X    for (revi = rev; (*revi++) != ':'; );	/* copy after colon */
X    (void) strcat (revmsg, revi);
X    revmsg [strlen (revmsg) - 2] = 0;		/* erase last character */
X    (void) strcat (revmsg, ":  Type '?' for help.");
X
X    if (argc > 1) {
X	(void) strcpy(curfile,argv[1]);
X	readfile (argv[1], 0);
X    }
X
X    if (Mopt)
X	autocalc = 0;
X    if (Nopt)
X	numeric = 1;
X    if (Copt)
X	calc_order = BYCOLS;
X    if (Ropt)
X	calc_order = BYROWS;
X
X    modflg = 0;
X#ifdef VENIX
X    setbuf (stdin, NULL);
X#endif
X    FullUpdate++;
X    while (inloop) { running = 1;
X    while (running) {
X	nedistate = -1;
X	narg = 1;
X	if (edistate < 0 && linelim < 0 && autocalc && (changed || FullUpdate))
X	{    EvalAll ();
X	     if (changed)		/* if EvalAll changed or was before */
X		anychanged = TRUE;
X	     changed = 0;
X	}
X	else		/* any cells change? */
X	if (changed)
X	     anychanged = TRUE;
X
X	update(anychanged);
X	anychanged = FALSE;
X#ifndef SYSV3
X	(void) refresh(); /* 5.3 does a refresh in getch */ 
X#endif
X	c = nmgetch();
X	getyx(stdscr, tempy, tempx);
X	(void) move (1, 0);
X	(void) clrtoeol ();
X	(void) move(tempy, tempx);
X	(void) fflush (stdout);
X	seenerr = 0;
X	showneed = 0;	/* reset after each update */
X	showexpr = 0;
X
X	/* if ((c < ' ') || ( c == DEL ))   how about international here ? PB */
X	   if ( iscntrl(c) )
X	    switch (c) {
X#ifdef SIGTSTP
X		case ctl('z'):
X		    (void) deraw();
X		    (void) kill(0, SIGTSTP); /* Nail process group */
X
X		    /* the pc stops here */
X
X		    (void) goraw();
X		    break;
X#endif
X		case ctl('r'):
X		    showneed = 1;
X		case ctl('l'):
X		    FullUpdate++;
X		    (void) clearok(stdscr,1);
X		    break;
X		case ctl('x'):
X		    FullUpdate++;
X		    showexpr = 1;
X		    (void) clearok(stdscr,1);
X		    break;
X		default:
X		    error ("No such command (^%c)", c + 0100);
X		    break;
X		case ctl('b'):
X		    backcol(arg);
X		    break;
X		case ctl('c'):
X		    running = 0;
X		    break;
X
X		case ctl('e'):
X
X		    switch (nmgetch()) {
X		    case ctl('p'): case 'k':	doend (-1, 0);	break;
X		    case ctl('n'): case 'j':	doend ( 1, 0);	break;
X		    case ctl('b'): case 'h':
X		    case ctl('h'):		doend ( 0,-1);	break;
X		    case ctl('f'): case 'l':
X		    case ctl('i'): case ' ':	doend ( 0, 1);	break;
X
X		    case ESC:
X		    case ctl('g'):
X			break;
X
X		    default:
X			error("Invalid ^E command");
X			break;
X		    }
X
X		    break;
X
X		case ctl('f'):
X		    forwcol(arg);
X		    break;
X
X		case ctl('g'):
X		    showrange = 0;
X		    linelim = -1;
X		    (void) move (1, 0);
X		    (void) clrtoeol ();
X		    break;
X
X		case ESC:	/* ctl('[') */
X		    write_line(ESC);
X		    break;
X
X		case ctl('d'):
X		    write_line(ctl('d'));
X		    break;
X
X		case DEL:
X		case ctl('h'):
X		    if (linelim < 0) {	/* not editing line */
X			backcol(arg);	/* treat like ^B    */
X			break;
X		    }
X		    write_line(ctl('h'));
X		    break;
X
X		case ctl('i'): 		/* tab */
X		    if (linelim < 0) {	/* not editing line */
X			forwcol(arg);
X			break;
X		    }
X		    if (!showrange) {
X			startshow();
X		    } else {
X			showdr();
X			linelim = strlen(line);
X			line[linelim++] = ' ';
X			line[linelim] = 0;
X			showrange = 0;
X		    }
X		    linelim = strlen (line);
X		    break;
X
X		case ctl('m'):
X		case ctl('j'):
X		    write_line(ctl('m'));
X		    break;
X
X		case ctl('n'):
X		    forwrow(arg);
X		    break;
X
X		case ctl('p'):
X		    backrow(arg);
X		    break;
X
X		case ctl('q'):
X		    break;	/* ignore flow control */
X
X		case ctl('s'):
X		    break;	/* ignore flow control */
X
X		case ctl('t'):
X		    error(
X"Toggle:  a:auto  c:cell  e:ext funcs  n:numeric  t:top  x:encrypt  $:pre-scale");
X		    (void) refresh();
X
X		    switch (nmgetch()) {
X			case 'a': case 'A':
X			case 'm': case 'M':
X			    autocalc ^= 1;
X			    error("Automatic recalculation %sabled.",
X				autocalc ? "en":"dis");
X			    break;
X			case 'n': case 'N':
X			    numeric = (! numeric);
X			    error ("Numeric input %sabled.",
X				    numeric ? "en" : "dis");
X			    break;
X			case 't': case 'T':
X			    showtop = (! showtop);
X			    repaint(lastmx, lastmy, fwidth[lastcol]);
X			    error ("Top line %sabled.", showtop ? "en" : "dis");
X			    break;
X			case 'c': case 'C':
X			    showcell = (! showcell);
X			    repaint(lastmx, lastmy, fwidth[lastcol]);
X			    error ("Cell highlighting %sabled.",
X				    showcell ? "en" : "dis");
X			    break;
X			case 'x': case 'X':
X			    Crypt = (! Crypt);
X			    error ("Encryption %sabled.", Crypt? "en" : "dis");
X			    break;
X			case '$':
X			    if (prescale == 1.0) {
X				error ("Prescale enabled.");
X				prescale = 0.01;
X			    } else {
X				prescale = 1.0;
X				error ("Prescale disabled.");
X			    }
X			    break;
X			case 'e': case 'E':
X			    extfunc = (! extfunc);
X			    error ("External functions %sabled.",
X				    extfunc? "en" : "dis");
X			    break;
X			case ESC:
X			case ctl('g'):
X			    --modflg;	/* negate the modflg++ */
X			    break;
X			default:
X			    error ("Invalid toggle command");
X			    --modflg;	/* negate the modflg++ */
X		    }
X		    FullUpdate++;
X		    modflg++;
X		    break;
X
X		case ctl('u'):
X		    narg = arg * 4;
X		    nedistate = 1;
X		    break;
X
X		case ctl('v'):	/* insert variable name */
X		    if (linelim > 0)
X		        ins_string(v_name(currow, curcol));
X		    break;
X
X		case ctl('w'):	/* insert variable expression */
X		    if (linelim > 0)  {
X			char *temp, *temp1;
X			int templim;
X
X			temp = strcpy(xmalloc((unsigned)(strlen(line)+1)),line);
X			templim = linelim;
X			editexp(currow,curcol);
X			temp1= strcpy(xmalloc((unsigned)(strlen(line)+1)),line);
X			strcpy(line, temp);
X			linelim = templim;
X			ins_string(temp1);
X			xfree(temp);
X			xfree(temp1);
X		    }
X		    break;
X
X		case ctl('a'):	/* insert variable value */
X		    if (linelim > 0) {
X			struct ent *p = *ATBL(tbl, currow, curcol);
X			char temp[100];
X
X			if (p && p -> flags & is_valid) {
X			    (void) sprintf (temp, "%.*f",
X					precision[curcol],p -> v);
X			    ins_string(temp);
X			}
X		    }
X		    break;
X
X	    } /* End of the control char switch stmt */
X	else if (isdigit(c) && ((numeric && edistate >= 0) ||
X			(!numeric && (linelim < 0 || edistate >= 0)))) {
X	    /* we got a leading number */
X	    if (edistate != 0) {
X		/* First char of the count */
X		if (c == '0')      /* just a '0' goes to left col */
X		    curcol = 0;
X		else {
X		    nedistate = 0;
X		    narg = c - '0';
X		}
X	    } else {
X		/* Succeeding count chars */
X		nedistate = 0;
X		narg = arg * 10 + (c - '0');
X	    }
X	} else if (linelim >= 0) {
X	    /* Editing line */
X	    switch(c) {
X	    case ')':
X		if (showrange) {
X		    showdr();
X		    showrange = 0;
X		    linelim = strlen (line);
X		}
X		break;
X	    default:
X		break;
X	    }
X	    write_line(c);
X
X	} else if (!numeric && ( c == '+' || c == '-' ) ) {
X	    /* increment/decrement ops */
X	    register struct ent *p = *ATBL(tbl, currow, curcol);
X	    if (!p)
X		continue;
X	    if (p->expr && !(p->flags & is_strexpr)) {
X		error("Can't increment/decrement a formula\n");
X		continue;
X	    }
X	    FullUpdate++;
X	    modflg++;
X	    if( c == '+' )
X	    	p -> v += (double) arg;
X	    else
X		p -> v -= (double) arg;
X	} else
X	    /* switch on a normal command character */
X	    switch (c) {
X		case ':':
X		    break;	/* Be nice to vi users */
X
X		case '@':
X		    EvalAll ();
X		    changed = 0;
X		    anychanged = TRUE;
X		    break;
X
X		case '0': case '1': case '2': case '3': case '4':
X		case '5': case '6': case '7': case '8': case '9':
X		case '-': case '.': case '+':
X		    (void) sprintf(line,"let %s = %c",
X				v_name(currow, curcol), c);
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X
X		case '=':
X		    (void) sprintf(line,"let %s = ",
X					v_name(currow, curcol));
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X
X		case '!':
X		    {
X		    /*
X		     *  "! command"  executes command
X		     *  "!"	forks a shell
X		     *  "!!" repeats last command
X		     */
X#ifdef VMS
X		    error("Not implemented on VMS");
X#else /* VMS */
X		    char *shl;
X		    int pid, temp;
X		    char cmd[MAXCMD];
X		    static char lastcmd[MAXCMD];
X
X		    if (!(shl = getenv("SHELL")))
X			shl = "/bin/sh";
X
X		    deraw();
X		    (void) fputs("! ", stdout);
X		    (void) fflush(stdout);
X		    (void) fgets(cmd, MAXCMD, stdin);
X		    cmd[strlen(cmd) - 1] = '\0';	/* clobber \n */
X		    if(strcmp(cmd,"!") == 0)		/* repeat? */
X			    (void) strcpy(cmd, lastcmd);
X		    else
X			    (void) strcpy(lastcmd, cmd);
X
X		    if (modflg)
X		    {
X			(void) puts ("[No write since last change]");
X			(void) fflush (stdout);
X		    }
X
X		    if (!(pid = fork()))
X		    {
X			(void) signal (SIGINT, SIG_DFL);  /* reset */
X			if(strlen(cmd))
X				(void)execl(shl,shl,"-c",cmd,(char *)0);
X			else
X				(void) execl(shl, shl, (char *)0);
X			exit(-127);
X		    }
X
X		    while (pid != wait(&temp));
X
X		    (void) printf("Press RETURN to continue ");
X		    (void)nmgetch();
X		    goraw();
X#endif /* VMS */
X		    break;
X		    }
X
X		/*
X		 * Range commands:
X		 */
X
X		case '/':
X		    error (
X"Range:  x:erase  v:value  c:copy  f:fill  d:define  s:show  u:undefine");
X		    (void) refresh();
X
X		    switch (nmgetch()) {
X		    case 'c':
X			(void) sprintf(line,"copy [dest_range src_range] ");
X			linelim = strlen(line);
X			startshow();
X			insert_mode();
X			break;
X		    case 'x':
X			(void) sprintf(line,"erase [range] ");
X			linelim = strlen(line);
X			startshow();
X			insert_mode();
X			break;
X		    case 'v':
X			(void) sprintf(line, "value [range] ");
X			linelim = strlen(line);
X			startshow();
X			insert_mode();
X			break;
X		    case 'f':
X			(void) sprintf(line,"fill [range start inc] ");
X			linelim = strlen(line);
X			startshow();
X			insert_mode();
X			break;
X		    case 'd':
X			(void) sprintf(line,"define [string range] \"");
X			linelim = strlen(line);
X			startshow();
X			insert_mode();
X			modflg++;
X			break;
X		    case 'u':
X			(void) sprintf(line,"undefine [range] ");
X			linelim = strlen(line);
X			insert_mode();
X			modflg++;
X			break;
X		    case 's':
X			if(are_ranges())
X			{
X			FILE *f;
X			int pid;
X			char px[MAXCMD] ;
X			char *pager;
X
X			(void) strcpy(px, "| sort | ");
X			if(!(pager = getenv("PAGER")))
X				pager = DFLT_PAGER;
X			(void) strcat(px,pager);
X			f = openout(px, &pid);
X			if (!f) {
X			    error("Can't open pipe to sort");
X			    break;
X			}
X			list_range(f);
X			closeout(f, pid);
X			}
X			else error("No ranges defined");
X			break;
X			
X		    case ESC:
X		    case ctl('g'):
X			break;
X		   default:
X			error("Invalid region command");
X			break;
X		   }
X		   break;
X
X		/*
X		 * Row/column commands:
X		 */
X
X		case 'i':
X		case 'a':
X		case 'd':
X		case 'p':
X		case 'v':
X		case 'z':
X		case 's':
X		    {
X			register rcqual;
X
X			if (! (rcqual = get_rcqual (c))) {
X			    error ("Invalid row/column command");
X			    break;
X			}
X
X			error ("");	/* clear line */
X
X			if ( rcqual == ESC || rcqual == ctl('g'))
X			    break;
X
X			switch (c) {
X
X			case 'i':
X			    if (rcqual == 'r')	insertrow(arg);
X			    else		opencol(curcol, arg);
X			    break;
X
X			case 'a':
X			    if (rcqual == 'r')	while (arg--) duprow();
X			    else		while (arg--) dupcol();
X			    break;
X
X			case 'd':
X			    if (rcqual == 'r')	deleterow(arg);
X			    else		closecol(curcol, arg);
X			    break;
X
X			case 'p':
X			    while (arg--)	pullcells(rcqual);
X			    break;
X
X			case 'v':
X			    if (rcqual == 'r')	rowvalueize(arg);
X			    else		colvalueize(arg);
X			    modflg = 1;
X			    break;
X
X			case 'z':
X			    if (rcqual == 'r')	hiderow(arg);
X			    else		hidecol(arg);
X			    break;
X
X			case 's':
X			    /* special case; no repeat count */
X
X			    if (rcqual == 'r')	rowshow_op();
X			    else		colshow_op();
X			    break;
X			}
X			break;
X		    }
X
X		case '$':
X		    {
X		    register struct ent *p;
X
X		    curcol = maxcols - 1;
X		    while (!VALID_CELL(p, currow, curcol) && curcol > 0)
X			curcol--;
X		    break;
X		    }
X		case '#':
X		    {
X		    register struct ent *p;
X
X		    currow = maxrows - 1;
X		    while (!VALID_CELL(p, currow, curcol) && currow > 0)
X			currow--;
X		    break;
X		    }
X		case 'w':
X		    {
X		    register struct ent *p;
X
X		    while (--arg>=0) {
X			do {
X			    if (curcol < maxcols - 1)
X				curcol++;
X			    else {
X				if (currow < maxrows - 1) {
X				    while(++currow < maxrows - 1 &&
X					    row_hidden[currow]) /* */;
X				    curcol = 0;
X				} else {
X				    error("At end of table");
X				    break;
X				}
X			    }
X			} while(col_hidden[curcol] ||
X				!VALID_CELL(p, currow, curcol));
X		    }
X		    break;
X		    }
X		case 'b':
X		    {
X		    register struct ent *p;
X
X		    while (--arg>=0) {
X			do {
X			    if (curcol) 
X				curcol--;
X			    else {
X				if (currow) {
X				    while(--currow &&
X					row_hidden[currow]) /* */;
X				    curcol = maxcols - 1;
X				} else {
X				    error ("At start of table");
X				    break;
X				}
X			    }
X			} while(col_hidden[curcol] ||
X				!VALID_CELL(p, currow, curcol));
X		    }
X		    break;
X		    }
X		case '^':
X		    currow = 0;
X		    break;
X		case '?':
X		    help();
X		    break;
X		case '"':
X		    (void) sprintf (line, "label %s = \"",
X					v_name(currow, curcol));
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case '<':
X		    (void) sprintf (line, "leftstring %s = \"",
X			    v_name(currow, curcol));
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case '>':
X		    (void) sprintf (line, "rightstring %s = \"",
X			   v_name(currow, curcol));
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'e':
X		    editv (currow, curcol);
X		    edit_mode();
X		    break;
X		case 'E':
X		    edits (currow, curcol);
X		    edit_mode();
X		    break;
X		case 'f':
X		    if (arg == 1)
X			(void) sprintf (line, "format [for column] %s ",
X				coltoa(curcol));
X		    else {
X			(void) sprintf(line, "format [for columns] %s:",
X				coltoa(curcol));
X			(void) sprintf(line+strlen(line), "%s ",
X				coltoa(curcol+arg-1));
X		    }
X		    error("Current format is %d %d",
X				fwidth[curcol],precision[curcol]);
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'g':
X		    (void) sprintf (line, "goto [v] ");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'P':
X		    (void) sprintf (line, "put [\"dest\" range] \"");
X		    if (*curfile)
X			error ("Default path is \"%s\"",curfile);
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'M':
X		    (void) sprintf (line, "merge [\"source\"] \"");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'R':
X		    if (mdir)
X			(void) sprintf (line,"merge [\"macro_file\"] \"%s/", mdir);
X		    else
X			(void) sprintf (line,"merge [\"macro_file\"] \"");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'D':
X		    (void) sprintf (line, "mdir [\"macro_directory\"] \"");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'G':
X		    (void) sprintf (line, "get [\"source\"] \"");
X		    if (*curfile)
X			error ("Default file is \"%s\"",curfile);
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'W':
X		    (void) sprintf (line, "write [\"dest\" range] \"");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'S':	/* set options */
X		    (void) sprintf (line, "set ");
X		    error("Options: byrows, bycols, iterations=n, tblstyle=(0|tbl|latex|tex)");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'T':	/* tbl output */
X		    (void) sprintf (line, "tbl [\"dest\" range] \"");
X		    linelim = strlen (line);
X		    insert_mode();
X		    break;
X		case 'x':
X		    {
X		    register struct ent **pp;
X		    register int c1;
X
X		    flush_saved();
X		    if(calc_order == BYROWS) {
X		    for (c1 = curcol; arg-- && c1 < maxcols; c1++) {
X			pp = ATBL(tbl, currow, c1);
X			if (*pp) {
X			    free_ent(*pp);
X			    *pp = (struct ent *)0;
X			}
X		    }
X		    }
X		    else {
X		    for (c1 = currow; arg-- && c1 < maxrows; c1++) {
X			pp = ATBL(tbl, c1, curcol);
X			if (*pp) {
X			    free_ent(*pp);
X			    *pp = (struct ent *)0;
X			}
X		    }
X		    }
X		    sync_refs();
X		    modflg++;
X		    FullUpdate++;
X		    }
X		    break;
X		case 'Q':
X		case 'q':
X		    running = 0;
X		    break;
X		case 'h':
X		    backcol(arg);
X		    break;
X		case 'j':
X		    forwrow(arg);
X		    break;
X		case 'k':
X		    backrow(arg);
X		    break;
X		case ' ':
X		case 'l':
X		    forwcol(arg);
X		    break;
X		case 'm':
X		    savedrow = currow;
X		    savedcol = curcol;
X		    break;
X		case 'c': {
X		    register struct ent *p = *ATBL(tbl, savedrow, savedcol);
X		    register c1;
X		    register struct ent *n;
X		    if (!p)
X			break;
X		    FullUpdate++;
X		    modflg++;
X		    for (c1 = curcol; arg-- && c1 < maxcols; c1++) {
X			n = lookat (currow, c1);
X			(void) clearent(n);
X			copyent( n, p, currow - savedrow, c1 - savedcol);
X		    }
X		    break;
X		}
X		default:
X		    if ((toascii(c)) != c)
X			error ("Weird character, decimal %d\n",
X				(int) c);
X		    else
X			    error ("No such command (%c)", c);
X		    break;
X	    }
X	edistate = nedistate;
X	arg = narg;
X    }				/* while (running) */
X    inloop = modcheck(" before exiting");
X    }				/*  while (inloop) */
X    deraw();
X    endwin();
X#ifdef VMS	/* Unit VMS "fixes" exit we should say 1 here */
X    exit(1);
X#else
X    exit(0);
X#endif
X    /*NOTREACHED*/
X}
X
Xvoid
Xstartshow()
X{
X    showrange = 1;
X    showsr = currow;
X    showsc = curcol;
X}
X
Xvoid
Xshowdr()
X{
X    int     minsr, minsc, maxsr, maxsc;
X
X    minsr = showsr < currow ? showsr : currow;
X    minsc = showsc < curcol ? showsc : curcol;
X    maxsr = showsr > currow ? showsr : currow;
X    maxsc = showsc > curcol ? showsc : curcol;
X    (void) sprintf (line+linelim,"%s", r_name(minsr, minsc, maxsr, maxsc));
X}
X
Xvoid
Xsetorder(i)
Xint i;
X{
X	if((i == BYROWS)||(i == BYCOLS))
X	    calc_order = i;
X	else
X	    error("Not yet implemented");
X}
X
Xvoid
Xsetauto(i)
Xint i;
X{
X	autocalc = i;
X}
X
X
X#ifdef VMS
X
Xgoraw()
X{
X    VMS_read_raw = 1;
X    FullUpdate++;
X}
X
Xderaw()
X{
X    (void) move (LINES - 1, 0);
X    (void) clrtoeol();
X    (void) refresh();
X    VMS_read_raw = 0;
X}
X
X#else /* VMS */
Xvoid
Xgoraw()
X{
X#if SYSV2 || SYSV3
X    fixterm();
X#else /* SYSV2 || SYSV3 */
X    cbreak();
X    nonl();
X    noecho ();
X#endif /* SYSV2 || SYSV3 */
X    kbd_again();
X    (void) clear();
X    FullUpdate++;
X}
X
Xvoid
Xderaw()
X{
X    (void) move (LINES - 1, 0);
X    (void) clrtoeol();
X    (void) refresh();
X#if SYSV2 || SYSV3
X    resetterm();
X#else
X    nocbreak();
X    nl();
X    echo();
X#endif
X    resetkbd();
X}
X
X#endif /* VMS */
X
Xvoid
Xsignals()
X{
X#ifdef SIGVOID
X    void quit();
X    void time_out();
X    void dump_me();
X#else
X    int quit();
X    int time_out();
X    int dump_me();
X#endif
X
X    (void) signal(SIGINT, SIG_IGN);
X    (void) signal(SIGQUIT, dump_me);
X    (void) signal(SIGPIPE, quit);
X    (void) signal(SIGTERM, quit);
X    (void) signal(SIGALRM, time_out);
X    (void) signal(SIGFPE, quit);
X    (void) signal(SIGBUS, quit);
X}
X
X#ifdef SIGVOID
Xvoid
X#endif
Xquit()
X{
X    diesave();
X    deraw();
X    resetkbd();
X    endwin();
X    exit(1);
X}
X
X#ifdef SIGVOID
Xvoid
X#endif
Xdump_me()
X{
X    diesave();
X    deraw();
X    abort();
X}
X
X/* try to save the current spreadsheet if we can */
Xdiesave()
X{   char	path[PATHLEN];
X    if (modcheck(" before Spreadsheet dies") == 1)
X    {	sprintf(path, "~/SC.SAVE");
X	if (writefile(path, 0, 0, maxrow, maxcol) < 0)
X	    if (writefile("/tmp/SC.SAVE", 0, 0, maxrow, maxcol) < 0)
X		error("Couldn't save current spreadsheet, Sorry");
X    }
X}
X
Xint
Xmodcheck(endstr)
Xchar *endstr;
X{
X    if (modflg && curfile[0]) {
X	int	yn_ans;
X	char	lin[100];
X
X	(void) sprintf (lin,"File \"%s\" is modified, save%s? ",curfile,endstr);
X	if ((yn_ans = yn_ask(lin)) < 0)
X		return(1);
X	else
X	if (yn_ans == 1)
X	{    if (writefile(curfile, 0, 0, maxrow, maxcol) < 0)
X 		return (1);
X	}
X    } else if (modflg) {
X	int	yn_ans;
X
X	if ((yn_ans = yn_ask("Do you want a chance to save the data? ")) < 0)
X		return(1);
X	else
X		return(yn_ans);
X    }
X    return(0);
X}
END_OF_FILE
  if test 33828 -ne `wc -c <'sc.c'`; then
    echo shar: \"'sc.c'\" unpacked with wrong size!
  fi
  # end of 'sc.c'
fi
echo shar: End of archive 3 \(of 6\).
cp /dev/null ark3isdone
MISSING=""
for I in 1 2 3 4 5 6 ; do
    if test ! -f ark${I}isdone ; then
	MISSING="${MISSING} ${I}"
    fi
done
if test "${MISSING}" = "" ; then
    echo You have unpacked all 6 archives.
    rm -f ark[1-9]isdone
else
    echo You still must unpack the following archives:
    echo "        " ${MISSING}
fi
exit 0
exit 0 # Just in case...
-- 
Please send comp.sources.unix-related mail to rsalz at uunet.uu.net.
Use a domain-based address or give alternate paths, or you may lose out.



More information about the Comp.sources.unix mailing list