Yet Another Shell (part 3 of 11)

Dave Clemans dclemans.falcon at mntgfx.mentor.com
Thu Mar 16 08:18:51 AEST 1989


With all the talk about shells that has been going on recently...

Here's an early pre-release of a "Korn"-like shell for anyone
who might want to experiment.  It is definitely NOT complete,
but it starting to be usable.  It does use some GNU code (for
expression evaluation), so it presumably comes under their
"copyleft".

It basically runs on BSD/USG Unix systems, and on the Atari ST.
I'm currently working on a port to the Amiga.

dgc

#! /bin/sh
# This is a shell archive.  Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file".  To overwrite existing
# files, type "sh file -c".  You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g..  If this archive is complete, you
# will see the following message at the end:
#		"End of archive 3 (of 11)."
# Contents:  cexp.y reader/tenex.c wild.c
# Wrapped by dclemans at dclemans on Wed Mar 15 14:03:54 1989
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'cexp.y' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'cexp.y'\"
else
echo shar: Extracting \"'cexp.y'\" \(16516 characters\)
sed "s/^X//" >'cexp.y' <<'END_OF_FILE'
X/*
X * Command Input Shell
X * Dave Clemans
X * (below code modified for use in shell 2/89)
X *
X * "spiritually" based on Bourne, Korn shells
X *
X * Expression evaluation
X *
X * $Id: cexp.y,v 1.3 89/02/20 20:14:09 dclemans Exp $
X *
X * $Log:	cexp.y,v $
X * Revision 1.3  89/02/20  20:14:09  dclemans
X * Add RCS identifiers
X * 
X */
X/* Parse C expressions for CCCP.
X   Copyright (C) 1987 Free Software Foundation.
X
X		       NO WARRANTY
X
X  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
XAND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
XCORRECTION.
X
X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
X
X		GENERAL PUBLIC LICENSE TO COPY
X
X  1. You may copy and distribute verbatim copies of this source file
Xas you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy a valid copyright notice "Copyright
X(C) 1987 Free Software Foundation"; and include following the
Xcopyright notice a verbatim copy of the above disclaimer of warranty
Xand of this License.  You may charge a distribution fee for the
Xphysical act of transferring a copy.
X
X  2. You may modify your copy or copies of this source file or
Xany portion of it, and copy and distribute such modifications under
Xthe terms of Paragraph 1 above, provided that you also do the following:
X
X    a) cause the modified files to carry prominent notices stating
X    that you changed the files and the date of any change; and
X
X    b) cause the whole of any work that you distribute or publish,
X    that in whole or in part contains or is a derivative of this
X    program or any part thereof, to be licensed at no charge to all
X    third parties on terms identical to those contained in this
X    License Agreement (except that you may choose to grant more extensive
X    warranty protection to some or all third parties, at your option).
X
X    c) You may charge a distribution fee for the physical act of
X    transferring a copy, and you may at your option offer warranty
X    protection in exchange for a fee.
X
XMere aggregation of another unrelated program with this program (or its
Xderivative) on a volume of a storage or distribution medium does not bring
Xthe other program under the scope of these terms.
X
X  3. You may copy and distribute this program (or a portion or derivative
Xof it, under Paragraph 2) in object code or executable form under the terms
Xof Paragraphs 1 and 2 above provided that you also do one of the following:
X
X    a) accompany it with the complete corresponding machine-readable
X    source code, which must be distributed under the terms of
X    Paragraphs 1 and 2 above; or,
X
X    b) accompany it with a written offer, valid for at least three
X    years, to give any third party free (except for a nominal
X    shipping charge) a complete machine-readable copy of the
X    corresponding source code, to be distributed under the terms of
X    Paragraphs 1 and 2 above; or,
X
X    c) accompany it with the information you received as to where the
X    corresponding source code may be obtained.  (This alternative is
X    allowed only for noncommercial distribution and only if you
X    received the program in object code or executable form alone.)
X
XFor an executable file, complete source code means all the source code for
Xall modules it contains; but, as a special exception, it need not include
Xsource code for modules which are standard libraries that accompany the
Xoperating system on which the executable file runs.
X
X  4. You may not copy, sublicense, distribute or transfer this program
Xexcept as expressly provided under this License Agreement.  Any attempt
Xotherwise to copy, sublicense, distribute or transfer this program is void and
Xyour rights to use the program under this License agreement shall be
Xautomatically terminated.  However, parties who have received computer
Xsoftware programs from you with this License Agreement will not have
Xtheir licenses terminated so long as such parties remain in full compliance.
X
X  5. If you wish to incorporate parts of this program into other free
Xprograms whose distribution conditions are different, write to the Free
XSoftware Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
Xworked out a simple rule that can be stated here, but we will often permit
Xthis.  We will be guided by the two goals of preserving the free status of
Xall derivatives of our free software and of promoting the sharing and reuse of
Xsoftware.
X
X
X In other words, you are welcome to use, share and improve this program.
X You are forbidden to forbid anyone else to use, share and improve
X what you give them.   Help stamp out software-hoarding!
X
X Adapted from expread.y of GDB by Paul Rubin, July 1986.
X
X/* Parse a C expression from text in a string  */
X   
X%{
X#include "shell.h"
X#include <setjmp.h>
X/* #define YYDEBUG 1 */
X
X  int yylex ();
X  void yyerror ();
X  int expression_value;
X
X  static jmp_buf parse_return_error;
X
X  /* some external tables of character types */
X  extern unsigned char is_idstart[], is_idchar[];
X
X  static int allow_side_effects = 0;
X
X%}
X
X%union {
X  long lval;
X  int voidval;
X  char *sval;
X}
X
X%type <lval> exp exp1 start
X%token <lval> INT CHAR
X%token <sval> NAME
X%token <lval> ERROR
X
X%right '?' ':'
X%left ','
X%left OR
X%left AND
X%left '|'
X%left '^'
X%left '&'
X%left EQUAL NOTEQUAL
X%left '<' '>' LEQ GEQ
X%left LSH RSH
X%left '+' '-'
X%left '*' '/' '%'
X%right UNARY
X
X/* %expect 40 */
X
X%%
X
Xstart   :	exp1
X		{ expression_value = $1; }
X	;
X
X/* Expressions, including the comma operator.  */
Xexp1	:	exp
X	|	exp1 ',' exp
X			{ $$ = $3; }
X	;
X
X/* Expressions, not including the comma operator.  */
Xexp	:	'-' exp    %prec UNARY
X			{ $$ = - $2; }
X	|	'!' exp    %prec UNARY
X			{ $$ = ! $2; }
X	|	'~' exp    %prec UNARY
X			{ $$ = ~ $2; }
X	|	'(' exp1 ')'
X			{ $$ = $2; }
X    |   NAME '=' exp1
X			{
X              if ($1 == (char *)NULL)
X                $$ = 0;
X              else { char buffer[16];
X                sprintf(buffer,"%d",$3);
X                if (allow_side_effects)
X                  var_define0(&$1[1],buffer,0);
X                free($1);
X                $$ = $3;
X              }
X            }
X	;
X
X/* Binary operators in order of decreasing precedence.  */
Xexp	:	exp '*' exp
X			{ $$ = $1 * $3; }
X	|	exp '/' exp
X			{ if ($3 == 0)
X			    {
X			      errmsg (0,LOC("yyparse"),"division by zero");
X			      $3 = 1;
X			    }
X			  $$ = $1 / $3; }
X	|	exp '%' exp
X			{ if ($3 == 0)
X			    {
X			      errmsg (0,LOC("yparse"),"division by zero");
X			      $3 = 1;
X			    }
X			  $$ = $1 % $3; }
X	|	exp '+' exp
X			{ $$ = $1 + $3; }
X	|	exp '-' exp
X			{ $$ = $1 - $3; }
X	|	exp LSH exp
X			{ $$ = $1 << $3; }
X	|	exp RSH exp
X			{ $$ = $1 >> $3; }
X	|	exp EQUAL exp
X			{ $$ = ($1 == $3); }
X	|	exp NOTEQUAL exp
X			{ $$ = ($1 != $3); }
X	|	exp LEQ exp
X			{ $$ = ($1 <= $3); }
X	|	exp GEQ exp
X			{ $$ = ($1 >= $3); }
X	|	exp '<' exp
X			{ $$ = ($1 < $3); }
X	|	exp '>' exp
X			{ $$ = ($1 > $3); }
X	|	exp '&' exp
X			{ $$ = ($1 & $3); }
X	|	exp '^' exp
X			{ $$ = ($1 ^ $3); }
X	|	exp '|' exp
X			{ $$ = ($1 | $3); }
X	|	exp AND exp
X			{ $$ = ($1 && $3); }
X	|	exp OR exp
X			{ $$ = ($1 || $3); }
X	|	exp '?' exp ':' exp
X			{ $$ = $1 ? $3 : $5; }
X	|	INT
X			{ $$ = yylval.lval; }
X	|	CHAR
X			{ $$ = yylval.lval; }
X	|	NAME
X			{
X              if (yylval.sval == (char *)NULL)
X                $$ = 0;
X              else { char *ptr;
X                ptr = var_normal(yylval.sval);
X                if (ptr != (char *)NULL) {
X                  $$ = atoi(ptr);
X                  free(ptr);
X                }
X                else $$ = 0;
X                free(yylval.sval);
X              }
X            }
X	;
X%%
X
X/* During parsing of a C expression, the pointer to the next character
X   is in this variable.  */
X
Xstatic char *lexptr;
X
X/* Take care of parsing a number (anything that starts with a digit).
X   Set yylval and return the token type; update lexptr.
X   LEN is the number of characters in it.  */
X
X/* maybe needs to actually deal with floating point numbers */
X
Xint
Xparse_number (olen)
X     int olen;
X{
X  register char *p = lexptr;
X  register long n = 0;
X  register int c;
X  register int base = 10;
X  register len = olen;
X
X  extern double atof ();
X
X  for (c = 0; c < len; c++)
X    if (p[c] == '.') {
X      /* It's a float since it contains a point.  */
X      yyerror ("floating point numbers not allowed in expressions");
X      return ERROR;
X      
X/* ****************
X	 yylval.dval = atof (p);
X	 lexptr += len;
X	 return FLOAT;
X		 ****************  */
X    }
X  
X  if (len >= 3 && (!strncmp (p, "0x", 2) || !strncmp (p, "0X", 2))) {
X    p += 2;
X    base = 16;
X    len -= 2;
X  }
X  else if (*p == '0')
X    base = 8;
X  
X  while (len-- > 0) {
X    c = *p++;
X    n *= base;
X    if (c >= '0' && c <= '9')
X      n += c - '0';
X    else {
X      if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
X      if (base == 16 && c >= 'a' && c <= 'f')
X	n += c - 'a' + 10;
X      else if (len == 0 && c == 'l')
X	;
X      else {
X	yyerror ("Invalid number in expression");
X	return ERROR;
X      }
X    }
X  }
X
X  lexptr = p;
X  yylval.lval = n;
X  return INT;
X}
X
Xstruct etoken {
X  char *operator;
X  int token;
X};
X
X#ifndef	NULL
X#define NULL 0
X#endif
X
Xstatic struct etoken tokentab2[] = {
X  {"&&", AND},
X  {"||", OR},
X  {"<<", LSH},
X  {">>", RSH},
X  {"==", EQUAL},
X  {"!=", NOTEQUAL},
X  {"<=", LEQ},
X  {">=", GEQ},
X  {NULL, ERROR}
X};
X
X/* Read one token, getting characters through lexptr.  */
X
Xint
Xyylex ()
X{
X  register int c;
X  register int namelen;
X  register char *tokstart;
X  register struct etoken *toktab;
X  char *name;
X
X retry:
X
X  tokstart = lexptr;
X  c = *tokstart;
X  /* See if it is a special token of length 2.  */
X  for (toktab = tokentab2; toktab->operator != NULL; toktab++)
X    if (c == *toktab->operator && tokstart[1] == toktab->operator[1]) {
X      lexptr += 2;
X      return toktab->token;
X    }
X
X  switch (c) {
X  case 0:
X    return 0;
X    
X  case ' ':
X  case '\t':
X  case '\n':
X    lexptr++;
X    goto retry;
X    
X  case '\'':
X    lexptr++;
X    c = *lexptr++;
X    if (c == '\\')
X      c = parse_escape (&lexptr);
X    yylval.lval = c;
X    c = *lexptr++;
X    if (c != '\'') {
X      yyerror ("Invalid character constant");
X      return ERROR;
X    }
X    
X    return CHAR;
X
X    /* some of these chars are invalid in constant expressions;
X       maybe do something about them later */
X  case '/':
X  case '+':
X  case '-':
X  case '*':
X  case '%':
X  case '|':
X  case '&':
X  case '^':
X  case '~':
X  case '!':
X  case '@':
X  case '<':
X  case '>':
X  case '(':
X  case ')':
X  case '[':
X  case ']':
X  case '.':
X  case '?':
X  case ':':
X  case '=':
X  case '{':
X  case '}':
X  case ',':
X    lexptr++;
X    return c;
X    
X  case '"':
X    yyerror ("double quoted strings not allowed in expressions");
X    return ERROR;
X  }
X  if (c >= '0' && c <= '9') {
X    /* It's a number */
X    for (namelen = 0;
X	 c = tokstart[namelen], is_idchar[c] || c == '.'; 
X	 namelen++)
X      ;
X    return parse_number (namelen);
X  }
X  
X  if (!is_idstart[c]) {
X    yyerror ("Invalid token in expression");
X    return ERROR;
X  }
X  
X  /* It is a name.  See how long it is.  */
X
X  for (namelen = 0; is_idchar[tokstart[namelen]]; namelen++)
X    ;
X  name = new_string(namelen+2);
X  if (name == (char *)NULL)
X    errmsg(SHERR_NOMEM,LOC("yylex"));
X  yylval.sval = name;
X  if (name != (char *)NULL) {
X    name[0] = '$';
X    strncpy(&name[1],tokstart,namelen);
X    name[namelen+1] = '\0';
X  }
X  
X  lexptr += namelen;
X  return NAME;
X}
X
X
X/* Parse a C escape sequence.  STRING_PTR points to a variable
X   containing a pointer to the string to parse.  That pointer
X   is updated past the characters we use.  The value of the
X   escape sequence is returned.
X
X   A negative value means the sequence \ newline was seen,
X   which is supposed to be equivalent to nothing at all.
X
X   If \ is followed by a null character, we return a negative
X   value and leave the string pointer pointing at the null character.
X
X   If \ is followed by 000, we return 0 and leave the string pointer
X   after the zeros.  A value of 0 does not mean end of string.  */
X
Xint
Xparse_escape (string_ptr)
X     char **string_ptr;
X{
X  register int c = *(*string_ptr)++;
X  switch (c)
X    {
X    case 'a':
X      return '\a';
X    case 'b':
X      return '\b';
X    case 'e':
X      return 033;
X    case 'f':
X      return '\f';
X    case 'n':
X      return '\n';
X    case 'r':
X      return '\r';
X    case 't':
X      return '\t';
X    case 'v':
X      return '\v';
X    case '\n':
X      return -2;
X    case 0:
X      (*string_ptr)--;
X      return 0;
X    case '^':
X      c = *(*string_ptr)++;
X      if (c == '\\')
X	c = parse_escape (string_ptr);
X      if (c == '?')
X	return 0177;
X      return (c & 0200) | (c & 037);
X      
X    case '0':
X    case '1':
X    case '2':
X    case '3':
X    case '4':
X    case '5':
X    case '6':
X    case '7':
X      {
X	register int i = c - '0';
X	register int count = 0;
X	while (++count < 3)
X	  {
X	    if ((c = *(*string_ptr)++) >= '0' && c <= '7')
X	      {
X		i *= 8;
X		i += c - '0';
X	      }
X	    else
X	      {
X		(*string_ptr)--;
X		break;
X	      }
X	  }
X	return i;
X      }
X    default:
X      return c;
X    }
X}
X
Xvoid
Xyyerror (s)
X     char *s;
X{
X  errmsg (0,LOC("yyerror"),s);
X  longjmp (parse_return_error, 1);
X}
X
X/* This page contains the entry point to this file.  */
X
X/* Parse STRING as an expression, and complain if this fails
X   to use up all of the contents of STRING.  */
X/* We do not support C comments.  They should be removed before
X   this function is called.  */
X
Xint
Xparse_c_expression (string,side_effects)
X     char *string;
X     int side_effects;
X{
X  static int initialized;
X
X  if (!initialized) {
X    initialize_random_junk();
X    initialized++;
X  }
X
X  lexptr = string;
X  allow_side_effects = side_effects;
X  
X  if (lexptr == 0 || *lexptr == 0) {
X    return 0;
X  }
X
X  /* if there is some sort of scanning error, just return 0 and assume
X     the parsing routine has printed an error message somewhere.
X     there is surely a better thing to do than this.     */
X  if (setjmp(parse_return_error))
X    return 0;
X
X  if (yyparse ())
X    return 0;			/* actually this is never reached
X				   the way things stand. */
X  if (*lexptr)
X    errmsg (0,LOC("parse_c_expression"),"Junk after end of expression.");
X
X  return expression_value;	/* set by yyparse() */
X}
X
X/* table to tell if char can be part of a C identifier. */
Xunsigned char is_idchar[256];
X/* table to tell if char can be first char of a c identifier. */
Xunsigned char is_idstart[256];
X
X/*
X * initialize random junk in the hash table and maybe other places
X */
Xinitialize_random_junk()
X{
X  register int i;
X
X  /*
X   * Set up is_idchar and is_idstart tables.  These should be
X   * faster than saying (is_alpha(c) || c == '_'), etc.
X   * Must do set up these things before calling any routines tthat
X   * refer to them.
X   */
X  for (i = 'a'; i <= 'z'; i++) {
X    ++is_idchar[i - 'a' + 'A'];
X    ++is_idchar[i];
X    ++is_idstart[i - 'a' + 'A'];
X    ++is_idstart[i];
X  }
X  for (i = '0'; i <= '9'; i++)
X    ++is_idchar[i];
X  ++is_idchar['_'];
X  ++is_idstart['_'];
X#ifdef DOLLARS_IN_IDENTIFIERS
X  ++is_idchar['$'];
X  ++is_idstart['$'];
X#endif
X}
X
X
X#ifdef TEST_EXP_READER
X/* main program, for testing purposes. */
Xmain()
X{
X  int n;
X  char buf[1024];
X  extern int yydebug;
X/*
X  yydebug = 1;
X*/
X  initialize_random_junk ();
X
X  for (;;) {
X    printf("enter expression: ");
X    n = 0;
X    while ((buf[n] = getchar()) != '\n')
X      n++;
X    buf[n] = '\0';
X    printf("parser returned %d\n", parse_c_expression(buf));
X  }
X}
X
Xerrmsg (code,f,r,l,msg)
Xint code;
Xchar *f;
Xchar *r;
Xint l;
X{
X  printf("error: %s\n", msg);
X}
X#endif
END_OF_FILE
if test 16516 -ne `wc -c <'cexp.y'`; then
    echo shar: \"'cexp.y'\" unpacked with wrong size!
fi
# end of 'cexp.y'
fi
if test -f 'reader/tenex.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'reader/tenex.c'\"
else
echo shar: Extracting \"'reader/tenex.c'\" \(16108 characters\)
sed "s/^X//" >'reader/tenex.c' <<'END_OF_FILE'
X/*
X * tenex -		file name or command expansion for "reader"
X *
X * Dave Clemans, 4/84 (initial version); 1/89 (more generality)
X *
X * Modeled from, (or taken from), the equivalent routines from
X * Ken Greer's "Tenex" C-shell.
X *
X * Main entry point:
X *	ExpandAName	given a line, expands last word in it
X *
X * $Id: tenex.c,v 1.3 89/02/20 20:20:26 dclemans Exp $
X *
X * $Log:	tenex.c,v $
X * Revision 1.3  89/02/20  20:20:26  dclemans
X * Add RCS identifiers
X * 
X */
X#ifndef GEMDOS
X#include <sys/types.h>
X#include <sys/stat.h>
X#include <sys/dir.h>
X#include <pwd.h>
X#include <signal.h>
X#else
X#include <types.h>
X#include <stat.h>
X#include "ndir.h"
X#include <strings.h>
X#include <ctype.h>
X#define index  strchr
X#define rindex strrchr
X#ifndef NULL
X#define	NULL	((char *)0)
X#endif  NULL
X#endif  GEMDOS
X#ifndef LOC
X#define LOC(r)  __FILE__,r,__LINE__
X#endif  LOC
X
Xtypedef enum {LIST, RECOGNIZE} COMMAND;
X
X#define	TRUE	1
X#define	FALSE	0
X#define	FILSIZ	512		/* Max reasonable file name length */
X
X#ifndef DIR_SEPARATOR
X#ifndef GEMDOS
X#define DIR_SEPARATOR '/'
X#else
X#define DIR_SEPARATOR '\\'
X#endif  GEMDOS
X#endif  DIR_SEPARATOR
X
X/*
X * Interesting function definitions
X */
Xextern char *index();
Xextern char *var_normal();
Xextern int _writechar();
Xstatic char filetype();
X
X/*
X * max of a,b
X */
Xstatic
Xmax (a, b)
X{
X    if (a > b)
X	return (a);
X    return (b);
X};	/* end of max */
X
X/*
X * For qsort()
X */
Xstatic
Xfcompare (file1, file2)
Xchar  **file1, **file2;
X{
X    return (strcmp (*file1, *file2));
X};	/* end of fcompare */
X
X/*
X * Append characters to end of global place
X */
Xstatic char *CharPtr;
Xstatic
XCharAppend (c)
Xchar c;
X{
X    *CharPtr++ = c;
X    *CharPtr   = 0;
X};	/* end of CharAppend */
X
X/*
X * Set up to search for names
X */
XExpandAName (inputline, inputline_size, num_read, doRecognize)
Xchar   *inputline;		/* match string prefix */
Xint     inputline_size;		/* max size of string */
Xint	num_read;		/* # actually in inputline */
X{
X    static char 
X	    delims[] = " '\"\t;&<>()|^%";
X    char word [FILSIZ + 1];
X    register char *str_end, *word_start, *cmd_start, *wp;
X    int space_left;
X    int is_a_cmd;		/* UNIX command rather than filename */
X    int rc;
X
X    CharPtr = str_end = &inputline[num_read];
X
X   /*
X    * Find LAST occurence of a delimiter in the inputline.
X    * The word start is one character past it.
X    */
X    for (word_start = str_end; word_start > inputline; --word_start)
X	if (index (delims, word_start[-1]))
X	    break;
X
X    space_left = inputline_size - (word_start - inputline) - 1;
X
X    is_a_cmd = starting_a_command (word_start, inputline);
X
X    for (cmd_start = word_start, wp = word; cmd_start < str_end;
X    	 *wp++ = *cmd_start++);
X    *wp = 0;
X
X    if (doRecognize)
X	return search (word, wp, space_left, is_a_cmd, RECOGNIZE, CharAppend);
X    else
X    {	/* do LIST command */
X#ifdef  GEMDOS
X        _writechar('\r');
X#endif  GEMDOS
X	_writechar('\n');
X	rc = search (word, wp, space_left, is_a_cmd, LIST, _writechar);
X	_doStandardRetype('\0');
X	return rc;
X    }
X};	/* end of ExpandAName */
X
X/*
X * Are we starting a command (i.e., still in the first word on the line?
X */
Xstatic starting_a_command (wordstart, inputline)
Xregister char *wordstart, *inputline;
X{
X    static char
X	    cmdstart[] = ";&(|`",
X	    cmdalive[] = " \t'\"";
X    while (--wordstart >= inputline)
X    {
X	if (index (cmdstart, *wordstart))
X	    break;
X	if (!index (cmdalive, *wordstart))
X	    return (FALSE);
X    }
X    if (wordstart > inputline && *wordstart == '&')	/* Look for >& */
X    {
X	while (wordstart > inputline &&
X			(*--wordstart == ' ' || *wordstart == '\t'));
X	if (*wordstart == '>')
X		return (FALSE);
X    }
X    return (TRUE);
X};	/* end of starting_a_command */
X
X/*
X * expand "old" file name with possible tilde usage
X *		~person/mumble
X * expands to
X *		home_directory_of_person/mumble
X * into string "new".
X */
X
Xstatic char *
Xtilde (new, old)
Xchar *new, *old;
X{
X#ifndef GEMDOS
X    extern struct passwd *getpwuid (), *getpwnam ();
X
X    register char *o, *p;
X    register struct passwd *pw;
X    static char person[40] = {0};
X
X    if (old[0] != '~')
X    {
X	strcpy (new, old);
X	return (new);
X    }
X
X    for (p = person, o = &old[1]; *o && *o != DIR_SEPARATOR; *p++ = *o++);
X    *p = '\0';
X
X    if (person[0] == '\0')			/* then use current uid */
X	pw = getpwuid (getuid ());
X    else
X	pw = getpwnam (person);
X
X    if (pw == NULL)
X	return (NULL);
X
X    strcpy (new, pw -> pw_dir);
X    (void) strcat (new, o);
X    return (new);
X#else
X    strcpy (new, old);
X    return (new);
X#endif  GEMDOS
X};	/* end of tilde */
X
X/*
X * parse full path in file into 2 parts: directory and file names
X * Should leave final slash (/) at end of dir.
X */
Xstatic
Xextract_dir_and_name (path, dir, name)
Xchar   *path, *dir, *name;
X{
X    extern char *rindex ();
X    register char  *p;
X
X    p = rindex (path, DIR_SEPARATOR);
X    if (p == NULL)
X    {
X	copyn (name, path, MAXNAMLEN);
X	dir[0] = '\0';
X    }
X    else
X    {
X	p++;
X	copyn (name, p, MAXNAMLEN);
X	copyn (dir, path, p - path);
X    }
X};	/* end of extract_dir_and_name */
X
X
X/*
X * Get a directory entry
X */
Xstatic char *
Xgetentry (dir_fd, looking_for_lognames)
XDIR *dir_fd;
X{
X#ifndef GEMDOS
X    if (looking_for_lognames)			/* Is it login names we want? */
X    {
X	extern struct passwd *getpwent ();
X	register struct passwd *pw;
X	if ((pw = getpwent ()) == NULL)
X	    return (NULL);
X	return (pw -> pw_name);
X    }
X    else					/* It's a dir entry we want */
X    {
X#endif  GEMDOS
X	register struct direct *dirp;
X        register char *p;
X
X	if (dirp = readdir (dir_fd))
X	{
X#ifdef  GEMDOS
X            for (p = dirp->d_name; *p; p++)
X                if (isupper(*p))
X                    *p = _tolower(*p);
X#endif  GEMDOS
X	    return (dirp -> d_name);
X        }
X	return (NULL);
X#ifndef GEMDOS
X    }
X#endif  GEMDOS
X};	/* end of getentry */
X
X/*
X * Free a list of strings
X */
Xstatic
Xfree_items (items)
Xregister char **items;
X{
X    register int i;
X    for (i = 0; items[i]; i++)
X	free (items[i]);
X    free (items);
X};	/* end of free_items */
X
X#define FREE_ITEMS(items)\
X{\
X    free_items (items);\
X    items = NULL;\
X}
X#define FREE_DIR(fd)\
X{\
X    closedir (fd);\
X    fd = NULL;\
X}
X
X/*
X * Strip next directory from path; return ptr to next unstripped directory.
X */
X 
Xstatic char *extract_dir_from_path (path, dir)
Xchar *path, dir[];
X{
X    register char *d = dir;
X    char sep;
X
X#ifndef GEMDOS
X    sep = ':';
X#else
X    sep = ',';
X#endif  GEMDOS
X    while (*path && (*path == ' ' || *path == sep)) path++;
X    while (*path && (*path != ' ' && *path != sep)) *(d++) = *(path++);
X    while (*path && (*path == ' ' || *path == sep)) path++;
X
X    *(d++) = DIR_SEPARATOR;
X    *d = 0;
X
X    return path;
X};	/* end of extract_dir_from_path */
X
X/*
X * Perform a RECOGNIZE or LIST command on string "word".
X */
Xstatic
Xsearch (word, wp, max_word_length, looking_for_command, command, routine)
Xchar   *word,
X       *wp;			/* original end-of-word */
Xint max_word_length,
X	looking_for_command;
XCOMMAND command;
Xint (*routine) ();
X{
X#define	MAXITEMS	2048
X    register numitems,
X	    name_length,		/* Length of prefix (file name) */
X	    looking_for_lognames;	/* True if looking for login names */
X    struct stat
X	    dot_statb,			/* Stat buffer for "." */
X	    curdir_statb;		/* Stat buffer for current directory */
X    int	    dot_scan,			/* True if scanning "." */
X	    dot_got;			/* True if have scanned dot already */
X    char    tilded_dir[FILSIZ + 1],	/* dir after ~ expansion */
X	    dir[FILSIZ + 1],		/* /x/y/z/ part in /x/y/z/f */
X            name[MAXNAMLEN + 1],	/* f part in /d/d/d/f */
X            extended_name[MAXNAMLEN+1],	/* the recognized (extended) name */
X            *entry,			/* single directory entry or logname */
X	    *path,			/* hacked PATH environment variable */
X            *savepath;
X    static DIR 
X	    *dir_fd = NULL;
X    static char
X            **items = NULL;		/* file names when doing a LIST */
X
X    savepath = (char *)NULL;
X    tilded_dir[0] = '\0';
X    if (items != NULL)
X	FREE_ITEMS (items);
X    if (dir_fd != NULL)
X	FREE_DIR (dir_fd);
X
X#ifndef GEMDOS
X    looking_for_lognames = (*word == '~') && (index (word, DIR_SEPARATOR) == NULL);
X#else
X    looking_for_lognames = 0;
X#endif  GEMDOS
X    looking_for_command &= (*word != '~') && (index (word, DIR_SEPARATOR) == NULL);
X
X    if (looking_for_command)
X    {
X        copyn (name, word, MAXNAMLEN);
X        if ((savepath = path = var_normal ("$PATH")) == NULL)
X	    path = ".";
X    	path = extract_dir_from_path (path, dir);
X    }
X    numitems = 0;
X
X    dot_got = FALSE;
X    stat (".", &dot_statb);
X
Xcmdloop:	/* One loop per directory in PATH, if looking_for_command */
X
X    if (looking_for_lognames)			/* Looking for login names? */
X    {
X#ifndef GEMDOS
X	setpwent ();				/* Open passwd file */
X#endif  GEMDOS
X	copyn (name, &word[1], MAXNAMLEN);	/* name sans ~ */
X    }
X    else
X    {						/* Open directory */
X        if (!looking_for_command)
X	    extract_dir_and_name (word, dir, name);
X	if ((tilde (tilded_dir, dir) == 0) ||	/* expand ~user/... stuff */
X	    
X	   ((dir_fd = opendir (*tilded_dir ? tilded_dir : ".")) == NULL))
X	{
X	    if (looking_for_command)
X	        goto try_next_path;
X	    else
X            {
X                if (savepath != (char *)NULL)
X                    free(savepath);
X		return (0);
X            }
X	}
X	dot_scan = FALSE;
X#ifndef GEMDOS
X	if (looking_for_command)
X	{
X	    /*
X	     * Are we searching "."?
X	     */
X	    fstat (dir_fd->dd_fd, &curdir_statb);
X	    if (curdir_statb.st_dev == dot_statb.st_dev &&
X	        curdir_statb.st_ino == dot_statb.st_ino)
X	    {
X	        if (dot_got)			/* Second time in PATH? */
X			goto try_next_path;
X		dot_scan = TRUE;
X		dot_got = TRUE;
X	    }
X        }
X#endif  GEMDOS
X    }
X
X    name_length = strlen (name);
X
X    while (entry = getentry (dir_fd, looking_for_lognames))
X    {
X	if (!is_prefix (name, entry))
X	    continue;
X
X	/*
X	 * Don't match . files on null prefix match
X	 */
X	if (name_length == 0 && entry[0] == '.' && !looking_for_lognames)
X	    continue;
X
X	/*
X	 * Skip non-executables if looking for commands:
X	 * Only done for directory "." for speed.
X	 * (Benchmarked with and without:
X	 * With filetype check, a full search took 10 seconds.
X	 * Without filetype check, a full search took 1 second.)
X	 *                                   -Ken Greer
X         */
X	if (looking_for_command && dot_scan && filetype (dir, entry) != '*')
X	    continue;
X
X	if (command == LIST)		/* LIST command */
X	{
X	    extern char *malloc ();
X	    register int length;
X	    if (numitems >= MAXITEMS)
X	    {
X#ifndef GEMDOS
X                errmsg(0,LOC("search"),"\nYikes!! Too many %s !!",
X                    looking_for_lognames?"names in password file":"files");
X#else
X                errmsg(0,LOC("search"),"\r\nYikes!! Too many files !!");
X#endif  GEMDOS
X		break;
X	    }
X	    if (items == NULL)
X	    {
X		items = (char **) malloc (sizeof (items[1]) * (MAXITEMS + 1));
X		if (items == NULL)
X		    break;
X		for (length = 1; length < MAXITEMS + 1; length++)
X		    items[length] = (char *)NULL;
X	    }
X	    length = strlen(entry) + 1;
X	    if ((items[numitems] = malloc (length)) == NULL)
X	    {
X                errmsg(0,LOC("search"),"out of memory");
X		break;
X	    }
X	    copyn (items[numitems], entry, MAXNAMLEN);
X	    numitems++;
X	}
X	else					/* RECOGNIZE command */
X	    if (recognize (extended_name, entry, name_length, ++numitems))
X		break;
X    }
X
X    if (looking_for_lognames)
X#ifndef GEMDOS
X	endpwent ();
X#else
X        ;
X#endif  GEMDOS
X    else
X	FREE_DIR (dir_fd);
X
Xtry_next_path:
X    if (looking_for_command && *path &&
X    	(path = extract_dir_from_path (path, dir), dir)) 
X    	goto cmdloop;
X    
X    if (command == RECOGNIZE && numitems > 0)
X    {
X	if (looking_for_lognames)
X	    copyn (word, "~", 1);
X	else if (looking_for_command)
X	    word[0] = 0;
X	else
X	    copyn (word, dir, max_word_length);		/* put back dir part */
X	catn (word, extended_name, max_word_length);	/* add extended name */
X	while (*wp) (*routine) (*wp++);
X        if (savepath != (char *)NULL)
X            free(savepath);
X	return (numitems);
X    }
X
X    if (command == LIST)
X    {
X	qsort (items, numitems, sizeof (items[1]), fcompare);
X	print_by_column (looking_for_lognames ? NULL:tilded_dir, items,
X			 numitems, looking_for_command);
X	if (items != NULL)
X	    FREE_ITEMS (items);
X    }
X    if (savepath != (char *)NULL)
X        free(savepath);
X    return (0);
X};	/* end of search */
X
X/*
X * Object: extend what user typed up to an ambiguity.
X * Algorithm:
X * On first match, copy full entry (assume it'll be the only match) 
X * On subsequent matches, shorten extended_name to the first
X * character mismatch between extended_name and entry.
X * If we shorten it back to the prefix length, stop searching.
X */
Xstatic recognize (extended_name, entry, name_length, numitems)
Xchar *extended_name, *entry;
X{
X    if (numitems == 1)				/* 1st match */
X	copyn (extended_name, entry, MAXNAMLEN);
X    else					/* 2nd and subsequent matches */
X    {
X	register char *x, *ent;
X	register int len = 0;
X	for (x = extended_name, ent = entry; *x && *x == *ent++; x++, len++);
X	*x = '\0';				/* Shorten at 1st char diff */
X	if (len == name_length)			/* Ambiguous to prefix? */
X	    return (-1);			/* So stop now and save time */
X    }
X    return (0);
X};	/* end of recognize */
X
X/*
X * return true if check items initial chars in template
X * This differs from PWB imatch in that if check is null
X * it items anything
X */
Xstatic
Xis_prefix (check, template)
Xchar   *check,
X       *template;
X{
X    register char  *check_char,
X                   *template_char;
X
X    check_char = check;
X    template_char = template;
X    do
X	if (*check_char == 0)
X	    return (TRUE);
X    while (*check_char++ == *template_char++);
X    return (FALSE);
X};	/* end of is_prefix */
X
X/*
X * like strncpy but always leave room for trailing \0
X * and always null terminate.
X */
Xstatic copyn (des, src, count)
Xregister char *des, *src;
Xregister count;
X{
X    while (--count >= 0)
X	if ((*des++ = *src++) == 0)
X	    return;
X    *des = '\0';
X};	/* end of copyn */
X
X/*
X * Concatonate src onto tail of des.
X * Des is a string whose maximum length is count.
X * Always null terminate.
X */
Xstatic catn (des, src, count)
Xregister char *des, *src;
Xregister count;
X{
X    while (--count >= 0 && *des)
X	des++;
X    while (--count >= 0)
X	if ((*des++ = *src++) == 0)
X	    return;
X    *des = '\0';
X};	/* end of catn */
X
X/*
X * Return a character denoting the type of a file:
X *	* if executable
X *	/ if directory
X *	space otherwise
X */
Xstatic char
Xfiletype (dir, file)
Xchar *dir, *file;
X{
X    if (dir)
X    {
X	char path[512];
X	struct stat statb;
X	strcpy (path, dir);
X	catn (path, file, sizeof path);
X#ifndef GEMDOS
X	if (lstat (path, &statb) >= 0)
X	{
X	    if ((statb.st_mode & S_IFMT) == S_IFDIR)
X		return (DIR_SEPARATOR);
X	    if ((statb.st_mode & S_IFMT) == S_IFLNK)
X		return ('@');
X	    if (statb.st_mode & (S_IEXEC |
X	       (S_IEXEC>>3) | (S_IEXEC>>6)))
X		return ('*');
X	}
X#else
X        if (stat (path, &statb) >= 0)
X        {
X            if (statb.st_mode & S_IJDIR)
X                return (DIR_SEPARATOR);
X        }
X#endif  GEMDOS
X    }
X    return (' ');
X};	/* end of filetype */
X
X/*
X * Print sorted down columns
X */
Xstatic
Xprint_by_column (dir, items, count, looking_for_command)
Xregister char *dir, *items[];
X{
X    register int i, rows, r, c, maxwidth = 0, columns;
X    for (i = 0; i < count; i++)
X	maxwidth = max (maxwidth, strlen (items[i]));
X    maxwidth += looking_for_command ? 1:2;	/* for the file tag and space */
X    columns = 80 / maxwidth;
X    rows = (count + (columns - 1)) / columns;
X    for (r = 0; r < rows; r++)
X    {
X	for (c = 0; c < columns; c++)
X	{
X	    i = c * rows + r;
X	    if (i < count)
X	    {
X		register int w;
X		prstring (items[i]);
X		w = strlen (items[i]);
X		/* Print filename followed by '/' or '*' or ' ' */
X		if (!looking_for_command)
X			_writechar (filetype (dir, items[i])), w++;
X		if (c < (columns - 1))			/* Not last column? */
X		    for (; w < maxwidth; w++)
X			_writechar (' ');
X	    }
X	}
X#ifdef  GEMDOS
X        _writechar ('\r');
X#endif
X	_writechar ('\n');
X    }
X};	/* end of print_by_column */
X
Xstatic prstring(s)
Xregister char *s;
X{
X	while (*s)
X	{	/* dump the string */
X		_writechar(*s);
X		s++;
X	}
X};	/* end of prstring */
END_OF_FILE
if test 16108 -ne `wc -c <'reader/tenex.c'`; then
    echo shar: \"'reader/tenex.c'\" unpacked with wrong size!
fi
# end of 'reader/tenex.c'
fi
if test -f 'wild.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'wild.c'\"
else
echo shar: Extracting \"'wild.c'\" \(16451 characters\)
sed "s/^X//" >'wild.c' <<'END_OF_FILE'
X/*
X * Command Input Shell
X * Dave Clemans
X * 12/88-1/89
X *
X * "spiritually" based on Bourne, Korn shells
X *
X * Wild card expansion
X *
X * $Id: wild.c,v 1.4 89/02/20 20:03:40 dclemans Exp $
X *
X * $Log:	wild.c,v $
X * Revision 1.4  89/02/20  20:03:40  dclemans
X * Add RCS identifiers
X * 
X */
X#include <stdio.h>
X#include "shell.h"
X#ifdef  GEMDOS
X#include "ndir.h"
X#else
X#include <sys/types.h>
X#ifndef USG
X#include <sys/dir.h>
X#else
X#include <dirent.h>
X#endif  /* USG */
X#endif  /* GEMDOS */
X
X#define WILDCARDS       "*?["
X
X/**** Start of "glob" package ****/
X/* This software is copyright (c) 1986 by Stichting Mathematisch Centrum.
X * You may use, modify and copy it, provided this notice is present in all
X * copies, modified or unmodified, and provided you don't make money for it.
X *
X * Written 86-jun-28 by Guido van Rossum, CWI, Amsterdam <guido at mcvax.uucp>
X * Stripped down for local use, more portability by Dave Clemans
X */
X
X/* Pattern matching function for filenames */
X/* Each occurrence of the * pattern causes a recursion level */
X
X#define EOS '\0'
X
X#define BOOL int
X#define NO 0
X#define YES 1
X
X#define M_ALL '\001'        /* * */
X#define M_ONE '\002'        /* ? */
X#define M_SET '\003'        /* [ */
X#define M_CMP '\004'        /* ^ */
X#define M_RNG '\005'        /* - */
X#define M_END '\006'        /* ] */
X
Xstatic BOOL match(name, pat)
X    char *name;
X    char *pat;
X{
X    register char c, k;
X    BOOL ok,cmp;
X
X    for (c = *pat++; c != EOS; c = *pat++) {
X        switch (c) {
X
X        case M_ONE:
X            if (*name++ == EOS)
X                return NO;
X            break;
X
X        case M_ALL:
X            if (*pat == EOS)
X                return YES;
X            for (; *name != EOS; ++name) {
X                if (match(name, pat))
X                    return YES;
X            }
X            return NO;
X
X        case M_SET:
X            cmp= NO;
X            ok= NO;
X            k= *name++;
X            while ((c= *pat++) != M_END) {
X                if (c == M_CMP)
X                    cmp= YES;
X                else if (*pat == M_RNG) {
X                    if (c <= k && k <= pat[1])
X                        ok= YES;
X                    pat += 2;
X                }
X                else if (c == k)
X                    ok= YES;
X            }
X            if (!cmp && !ok)
X                return NO;
X            if (cmp && ok)
X                return NO;
X            break;
X
X        default:
X            if (*name++ != c)
X                return NO;
X            break;
X
X        }
X    }
X    return *name == EOS;
X}
X/**** End of "glob" package ****/
X
Xchar *wild_compile(pattern,upcase)
Xchar *pattern;
Xint upcase;
X{
X    register char *compiled;
X    register char *in,*out;
X
X    compiled = new_string(strlen(pattern)+1);
X    if (compiled == (char *)NULL)
X    {   /* enough memory? */
X        errmsg(SHERR_NOMEM,LOC("wild_compile"));
X        return (char *)NULL;
X    }
X    out = compiled;
X    for (in = pattern; *in; in++)
X    {   /* copy, "compiling" the pattern */
X        switch (*in)
X        {   /* a "special" character? */
X            case '\'':
X                in++;
X                while (*in && *in != '\'')
X                    *out++ = *in++;
X                if (*in != '\'')
X                    break;
X                break;
X            case '"':
X                in++;
X                while (*in && *in != '"')
X                {   /* scan the string */
X                    if (*in == ESCAPE_CHAR)
X                    {   /* embedded escape char? */
X                        in++;
X                        if (*in == '\0')
X                            break;
X                    }
X                    *out++ = *in++;
X                }
X                if (*in != '"')
X                    break;
X                break;
X            case ESCAPE_CHAR:
X                in++;
X                if (*in == '\0')
X                    break;
X                *out++ = *in;
X                break;
X            case '*':
X                *out++ = M_ALL;
X                break;
X            case '?':
X                *out++ = M_ONE;
X                break;
X            case '[':
X                *out++ = M_SET;
X                in++;
X                while (*in && *in != ']')
X                {   /* scan the set */
X                    if (*in == '-' &&
X                       (in[-1] == '[' || (in[-1] == '^' && in[-2] == '[')))
X                        *out++ = '-';
X                    else if (*in == '-')
X                        *out++ = M_RNG;
X                    else if (*in == '^' && in[-1] == '[')
X                        *out++ = M_CMP;
X                    else if (*in == '^')
X                        *out++ = '^';
X                    else if (*in == ESCAPE_CHAR && in[1] != '\0')
X                        *out++ = *++in;
X                    else if (*in == ESCAPE_CHAR)
X                        *out++ = ESCAPE_CHAR;
X                    else *out++ = *in;
X                    in++;
X                }
X                if (*in != ']')
X                {   /* if error found */
X                    errmsg(0,LOC("wild_compile"),"incomplete character class: missing ']'");
X                    free(compiled);
X                    return (char *)NULL;
X                }
X                *out++ = M_END;
X                break;
X            default:
X                *out++ = *in;
X                break;
X        }
X        if (*in == '\0')
X            break;
X    }
X#ifdef  GEMDOS
X    *out = '\0';
X    for (out = compiled; *out; out++)
X    {   /* fixups for mono-case matching */
X        if (!upcase)
X            continue;
X        if (islower(*out))
X            *out = _toupper(*out);
X    }
X#endif  /* GEMDOS */
X    *out = '\0';
X
X    /* finally done, return compiled string */
X    return compiled;
X}   /* end of wild_compile */
X
Xint wild_match(string,pattern)
Xchar *string;
Xchar *pattern;
X{
X    register char *compiled;
X    int rc;
X
X    compiled = wild_compile(pattern,0);
X    if (compiled == (char *)NULL)
X    {   /* any errors? message already printed */
X        return 0;
X    }
X    rc = match(string,compiled);
X    free(compiled);
X    return rc;
X}   /* end of wild_match */
X
Xvoid wild_save(path,tokens,exp)
Xchar *path;
Xstruct token **tokens;
Xint exp;
X{
X    register struct token *new,*tp,*ltp;
X    int rc;
X    char buffer[6],*dir,*npath;
X#ifdef  GEMDOS
X    char *p;
X#endif  /* GEMDOS */
X
X    dir = (char *)NULL;
X    if (path[0] == '~')
X    {   /* need tilde expansion? */
X        sprintf(buffer,"~%c*",DIR_SEPARATOR);
X        if (wild_match(path,buffer) || strcmp(path,"~") == 0)
X        {   /* paste in home directory? */
X            dir = strcopy(base_env.homedir);
X            npath = &path[1];
X        }
X        sprintf(buffer,"~+%c*",DIR_SEPARATOR);
X        if (wild_match(path,buffer) || strcmp(path,"~+") == 0)
X        {   /* paste in current directory? */
X            dir = strcopy(base_env.dir->current);
X            npath = &path[2];
X        }
X        sprintf(buffer,"~-%c*",DIR_SEPARATOR);
X        if (wild_match(path,buffer) || strcmp(path,"~-") == 0)
X        {   /* paste in old current directory */
X            dir = var_normal("$OLDPWD");
X            npath = &path[2];
X        }
X        if (dir != (char *)NULL)
X        {   /* if something to paste in */
X            path = new_string(strlen(dir)+strlen(npath)+1);
X            if (path == (char *)NULL)
X            {   /* enough memory? */
X                errmsg(SHERR_NOMEM,LOC("wild_save"));
X                return;
X            }
X            sprintf(path,"%s%s",dir,npath);
X        }
X    }
X    new = new_token(strlen(path));
X    if (new == (struct token *)NULL)
X    {   /* enough memory? */
X        errmsg(SHERR_NOMEM,LOC("wild_save"));
X        return;
X    }
X    new->type = SYM_WORD;
X    strcpy(new->name,path);
X    if (dir != (char *)NULL)
X        free(path);
X#ifdef  GEMDOS
X    if (exp)
X    {   /* mono-case support */
X        for (p = new->name; *p; p++)
X            if (isupper(*p))
X                *p = _tolower(*p);
X    }
X#endif  /* GEMDOS */
X
X    ltp = (struct token *)NULL;
X    for (tp = *tokens; tp != (struct token *)NULL; tp = tp->next)
X    {   /* look for place to put name */
X        rc = strcmp(new->name,tp->name);
X        if (rc < 0)
X            break;
X        ltp = tp;
X    }
X    if (*tokens == (struct token *)NULL)
X        *tokens = new;
X    else if (ltp == (struct token *)NULL)
X    {   /* head of list? */
X        new->next = *tokens;
X        *tokens = new;
X    }
X    else
X    {   /* middle of list */
X        new->next = tp;
X        ltp->next = new;
X    }
X}   /* end of wild_save */
X
Xstruct token *wild_search(path,tokens)
Xchar *path;
Xstruct token **tokens;
X{
X    register char *leadin,*pattern,*trailer;
X    char *p,*pp;
X    int rc,wild,sep,mask;
X    char *compiled;
X    DIR *source;
X#ifndef USG
X    struct direct *name;
X#else
X    struct dirent *name;
X#endif  /* USG */
X    char lead[2];
X    struct token *expansion;
X
X    /* break into 3 pieces: leadin, pattern, everything else */
X    wild = sep = 0;
X    leadin = pattern = path;
X    trailer = (char *)NULL;
X    for (p = path; *p; p++)
X    {   /* scan, looking for special characters */
X        switch (*p)
X        {   /* an interesting char? */
X            case ESCAPE_CHAR:
X                p++;
X                break;
X            case '\'':
X                p++;
X                while (*p && *p != '\'')
X                    p++;
X                break;
X            case '"':
X                while (*p && *p != '"')
X                    p++;
X                break;
X#ifdef  GEMDOS
X            case ':':
X#endif  /* GEMDOS */
X            case DIR_SEPARATOR:
X                sep++;
X                if (wild)
X                {   /* if wild cards in last segment */
X                    if (leadin == pattern)
X                        leadin = ".";
X                    trailer = p;
X                    break;
X                }
X                pattern = p+1;
X                break;
X            case '*':
X                wild++;
X                break;
X            case '?':
X                wild++;
X                break;
X            case ']':
X                wild++;
X                while (*p && *p != ']')
X                    p++;
X                break;
X            default:
X                break;
X        }
X        if (*p == '\0')
X            break;
X        if (trailer != (char *)NULL)
X            break;
X    }
X    if (tokens == (struct token **)NULL)
X        tokens = &expansion;
X    expansion = (struct token *)NULL;
X    if (wild == 0)
X    {   /* then no expansion (except for possible tildes) */
X        if (path[0] != '~')
X            return (struct token *)NULL;
X        wild_save(path,tokens,0);
X        return *tokens;
X    }
X    if (trailer == (char *)NULL)
X    {   /* if pieces not set up yet */
X        if (sep == 0)
X        {   /* just a pattern... */
X            leadin = ".";
X            pattern = path;
X        }
X        else
X        {   /* leadin - pattern */
X            p = strrchr(path,DIR_SEPARATOR);
X            if (p == (char *)NULL)
X                p = strrchr(path,':');
X            leadin = path;
X            pattern = p+1;
X        }
X        for (trailer = pattern; *trailer; trailer++)
X            /* do nothing */;
X    }
X    lead[0] = lead[1] = '\0';
X    if (strcmp(leadin,".") != 0)
X    {   /* make leadin string usable */
X        /* ASSERT that leadin == path */
X        leadin = new_string((int)(pattern-path)+1);
X        if (leadin == (char *)NULL)
X        {   /* enough memory? */
X            errmsg(SHERR_NOMEM,LOC("wild_search"));
X            return (struct token *)NULL;
X        }
X        strncpy(leadin,path,(int)(pattern-path));
X        leadin[(int)(pattern-path)] = '\0';
X        for (p = leadin; *p; p++)
X            /* do nothing */;
X        p--;
X        if (*p == DIR_SEPARATOR && p != leadin
X#ifdef  GEMDOS
X                                               && p[-1] != ':'
X#endif  /* GEMDOS */
X                                                              )
X        {   /* remove trailing sep */
X            *p = '\0';
X            lead[0] = DIR_SEPARATOR;
X        }
X        stripquotes(leadin);
X        if (strcmp(leadin,"~") == 0)
X        {   /* paste in home directory */
X            free(leadin);
X            leadin = strcopy(base_env.homedir);
X            if (leadin == (char *)NULL)
X            {   /* enough memory? */
X                /* message already printed */
X                return (struct token *)NULL;
X            }
X        }
X        else if (strcmp(leadin,"~+") == 0)
X        {   /* paste in current directory */
X            free(leadin);
X            leadin = strcopy(base_env.dir->current);
X            if (leadin == (char *)NULL)
X            {   /* enough memory? */
X                /* message already printed */
X                return (struct token *)NULL;
X            }
X        }
X        else if (strcmp(leadin,"~-") == 0)
X        {   /* paste in old current directory */
X            free(leadin);
X            leadin = var_normal("$OLDPWD");
X            if (leadin == (char *)NULL)
X                leadin = strcopy(base_env.dir->current);
X            if (leadin == (char *)NULL)
X            {   /* enough memory? */
X                /* message already printed */
X                return (struct token *)NULL;
X            }
X        }
X    }
X    else sep = 0;
X    pp = new_string((int)(trailer-pattern)+1);
X    if (pp == (char *)NULL)
X    {   /* enough memory? */
X        errmsg(SHERR_NOMEM,LOC("wild_search"));
X        if (sep)
X            free(leadin);
X        return (struct token *)NULL;
X    }
X    strncpy(pp,pattern,(int)(trailer-pattern));
X    pp[(int)(trailer-pattern)] = '\0';
X    pattern = pp;
X    compiled = wild_compile(pattern,1);
X    if (compiled == (char *)NULL)
X    {   /* any errors? message already printed */
X        free(pattern);
X        if (sep)
X            free(leadin);
X        return (struct token *)NULL;
X    }
X
X#ifdef  GEMDOS
X    if (*trailer == ':')
X    {   /* wild-carded drive name? */
X        lead[1] = '\0';
X        mask = Drvmap();
X        for (rc = 0; rc < 16; rc++)
X        {   /* for each possible drive */
X            if (mask & (1<<rc))
X            {   /* if drive present */
X                lead[0] = 'A' + rc;
X                if (match(lead,compiled))
X                {   /* if this drive is wanted */
X                    pp = new_string(strlen(trailer)+2);
X                    if (pp == (char *)NULL)
X                    {   /* enough memory? */
X                        errmsg(SHERR_NOMEM,LOC("wild_search"));
X                        break;
X                    }
X                    sprintf(pp,"%s%s",lead,trailer);
X                    wild_search(pp,tokens);
X                    free(pp);
X                }
X            }
X        }
X        free(pattern);
X        free(compiled);
X        return *tokens;
X    }
X#endif  /* GEMDOS */
X
X    source = opendir(leadin);
X    if (source == (DIR *)NULL)
X    {   /* did it work? */
X        errmsg(0,LOC("wild_search"),"can't open directory %s",leadin);
X        free(compiled);
X        free(pattern);
X        if (sep)
X            free(leadin);
X        return (struct token *)NULL;
X    }
X    while ((name = readdir(source)) != NULL)
X    {   /* while there are names... */
X        if (strcmp(name->d_name,".") == 0 || strcmp(name->d_name,"..") == 0)
X            continue;
X        rc = match(name->d_name,compiled);
X        if (rc)
X        {   /* if a match was found */
X            if (*trailer == '\0' && sep)
X            {   /* save the path */
X                pp = new_string(strlen(leadin)+strlen(lead)+strlen(name->d_name)+1);
X                if (pp == (char *)NULL)
X                {   /* enough memory? */
X                    errmsg(SHERR_NOMEM,LOC("wild_search"));
X                    break;
X                }
X                sprintf(pp,"%s%s%s",leadin,lead,name->d_name);
X                wild_save(pp,tokens,1);
X                free(pp);
X            }
X            else if (*trailer == '\0')
X                wild_save(name->d_name,tokens,1);
X            else
X            {   /* need to recurse to handle trailer */
X                pp = new_string(strlen(leadin)+strlen(name->d_name)+strlen(trailer)+2);
X                if (pp == (char *)NULL)
X                {   /* enough memory */
X                    errmsg(SHERR_NOMEM,LOC("wild_search"));
X                    break;
X                }
X                sprintf(pp,"%s%s%s%s",leadin,lead,name->d_name,trailer);
X                wild_search(pp,tokens);
X                free(pp);
X            }
X        }
X    }
X    closedir(source);
X    free(compiled);
X    free(pattern);
X    if (sep)
X        free(leadin);
X    return *tokens;
X}   /* end of wild_search */
END_OF_FILE
if test 16451 -ne `wc -c <'wild.c'`; then
    echo shar: \"'wild.c'\" unpacked with wrong size!
fi
# end of 'wild.c'
fi
echo shar: End of archive 3 \(of 11\).
cp /dev/null ark3isdone
MISSING=""
for I in 1 2 3 4 5 6 7 8 9 10 11 ; do
    if test ! -f ark${I}isdone ; then
	MISSING="${MISSING} ${I}"
    fi
done
if test "${MISSING}" = "" ; then
    echo You have unpacked all 11 archives.
    rm -f ark[1-9]isdone ark[1-9][0-9]isdone
else
    echo You still need to unpack the following archives:
    echo "        " ${MISSING}
fi
##  End of shell archive.
exit 0



More information about the Alt.sources mailing list