File: glob.c

package info (click to toggle)
vile 9.8t-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 10,076 kB
  • sloc: ansic: 117,510; lex: 13,877; sh: 3,614; perl: 3,495; cpp: 3,179; makefile: 1,231; awk: 271; sed: 14
file content (1133 lines) | stat: -rw-r--r-- 25,546 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
/*
 *	glob.c
 *
 * Performs wildcard-expansion for UNIX, VMS and MS-DOS systems.
 * Written by T.E.Dickey for vile (april 1993).
 *
 * (MS-DOS code was originally taken from the winc app example of the
 * zortech compiler - pjr)
 *
 * To do:
 *	make the wildcard expansion know about escaped characters (e.g.,
 *	with backslash a la UNIX.
 *
 *	modify (ifdef-style) 'expand_leaf()' to allow ellipsis.
 *
 * $Header: /usr/build/vile/vile/RCS/glob.c,v 1.103 2016/07/16 14:08:37 tom Exp $
 *
 */

#include "estruct.h"		/* global structures and defines */
#include "edef.h"		/* defines 'slash' */

#if SYS_OS2
# define INCL_DOSFILEMGR
# define INCL_ERRORS
# include <os2.h>
#else
# include "dirstuff.h"		/* directory-scanning interface & definitions */
#endif

#define BAKTIK '`'		/* used in UNIX shell for pipe */
#define	isname(c)	(isAlnum(c) || ((c) == '_'))
#define	isdelim(c)	((c) == '(' || ((c) == '{'))

#if SYS_MSDOS || SYS_OS2 || SYS_WINNT
# if UNIX_GLOBBING
#  define DirEntryStr(p)		p->d_name
# else
#  ifdef __ZTC__
#   define DeclareFind(p)		struct FIND *p
#   define DirEntryStr(p)		p->name
#   define DirFindFirst(path,p)		(p = findfirst(path, 0))
#   define DirFindNext(p)		(p = findnext())
#  else
#   define DeclareFind(p)		struct find_t p
#   define DirEntryStr(p)		p.name
#   define DirFindFirst(path,p)		(!_dos_findfirst(path, 0, &p))
#   define DirFindNext(p)		(!_dos_findnext(&p))
#  endif
# endif
# define DirEntryLen(p)			strlen(DirEntryStr(p))
#endif /* SYS_MSDOS */

/*
 * Verify that we don't have both boolean- and string-valued 'glob' modes.
 */
#if defined(GMDGLOB) && defined(GVAL_GLOB)
huh ? ?
#else
# ifdef GMDGLOB			/* boolean */
#  define globbing_active() global_g_val(GMDGLOB)
# endif
# ifdef GVAL_GLOB		/* string */
#  define globbing_active() !is_falsem(global_g_val_ptr(GVAL_GLOB))
# endif
# ifndef globbing_active
#  define globbing_active() TRUE
# endif
#endif

/*
 * Some things simply don't work on VMS: pipes and $variables
 */
#if OPT_VMS_PATH
#
# undef  UNIX_GLOBBING
# define UNIX_GLOBBING 0
#
# undef  OPT_GLOB_ENVIRON
# define OPT_GLOB_ENVIRON 0
#
# undef  OPT_GLOB_PIPE
# define OPT_GLOB_PIPE 0
#
#endif

/*--------------------------------------------------------------------------*/

/* the expanded list is defined outside of the functions because if we
 * handle ellipsis, the generating function must be recursive.
 */
static size_t myMax = 0;	/* length and index of the expanded list */
static size_t myLen = 0;	/* length and index of the expanded list */
static char **myVec = 0;	/* the expanded list */

/*--------------------------------------------------------------------------*/
#if UNIX_GLOBBING
static void
strip_escapes(char *buffer)
{
    int j, k, ch;

    for (j = k = 0; (ch = buffer[j]) != EOS; ++j) {
	if (ch == BACKSLASH)
	    ++j;
	if ((buffer[k++] = buffer[j]) == EOS)
	    break;
    }
    buffer[k] = EOS;
}
#endif

/*
 * Use this function to decide if we should perform wildcard expansion.
 */
static int
string_has_globs(const char *item)
{
#if OPT_VMS_PATH || SYS_UNIX || OPT_MSDOS_PATH
    while (*item != EOS) {
	if (*item == GLOB_SINGLE || *item == GLOB_MULTI)
	    return TRUE;
#if OPT_GLOB_ELLIPSIS || SYS_VMS
	if (vl_glob_opts & vl_GLOB_ELLIPSIS) {
	    if (!strncmp(item, GLOB_ELLIPSIS, sizeof(GLOB_ELLIPSIS) - 1))
		return TRUE;
	}
#endif
#if !OPT_VMS_PATH
#if OPT_GLOB_RANGE
	if (vl_glob_opts & vl_GLOB_RANGE) {
	    if (*item == GLOB_RANGE[0])
		return TRUE;
	}
#endif
#endif
	item++;
    }
#endif
    return FALSE;
}

/*
 * Use this function to decide if we should do wildcard/tilde/variable
 * expansion.
 */
int
string_has_wildcards(const char *item)
{
    const char *base = item;

#if OPT_VMS_PATH || SYS_WINNT	/* either host can support ~/whatever */
    if (*item == CH_TILDE)
	return TRUE;
#endif
#if OPT_VMS_PATH || SYS_UNIX || OPT_MSDOS_PATH
    while (*item != EOS) {
#if UNIX_GLOBBING
	if (iswild(*item))
	    return TRUE;
#endif
#if !OPT_VMS_PATH
#if OPT_GLOB_ENVIRON
	if ((vl_glob_opts & vl_GLOB_ENVIRON)
	    && (*item == GLOB_ENVIRON[0])
	    && (item == base || !isEscaped(item))
	    && (isname(item[1]) || isdelim(item[1]))) {
	    return TRUE;
	}
#endif
#endif
	item++;
    }
#endif
    return string_has_globs(base);
}

/*
 * Record a pattern-match in 'myVec[]', returning false if an error occurs
 */
static int
record_a_match(char *item)
{
    int result = TRUE;
    char **myTmp;

    beginDisplay();
    if (item != 0 && *item != EOS) {
	if ((item = strmalloc(item)) == 0) {
	    result = no_memory("glob-match");
	} else {
	    if (myLen + 2 >= myMax) {
		myMax = myLen + 2;
		if (myVec == 0) {
		    myVec = typeallocn(char *, myMax);
		} else {
		    myTmp = typereallocn(char *, myVec, myMax);
		    if (myTmp == 0) {
			myVec = glob_free(myVec);
		    } else {
			myVec = myTmp;
		    }
		}
	    }
	    if (myVec == 0) {
		free(item);
		result = no_memory("glob-pointers");
	    } else {
		myVec[myLen++] = item;
		myVec[myLen] = 0;
	    }
	}
    }
    endofDisplay();
    return result;
}

#if !SMALLER || UNIX_GLOBBING

static int
cs_char(int ch)
{
    return (global_g_val(GMDFILENAME_IC)
	    ? (isUpper(ch)
	       ? toLower(ch)
	       : ch)
	    : CharOf(ch));
}

static int
only_multi(char *pattern)
{
    int result = TRUE;
    while (*pattern != 0) {
	if (*pattern++ != GLOB_MULTI) {
	    result = FALSE;
	    break;
	}
    }
    return result;
}

/*
 * This is the heart of the wildcard matching.  We are given a directory
 * leaf and a pointer to the leaf that contains wildcards that we must
 * match against the leaf.
 */
int
glob_match_leaf(char *leaf, char *pattern)
{
    while (*leaf != EOS && *pattern != EOS) {
	if (*pattern == GLOB_SINGLE) {
	    leaf++;
	    pattern++;
	} else if (*pattern == GLOB_MULTI) {
	    int multi = FALSE;
	    pattern++;
	    while (*leaf != EOS) {
		if (glob_match_leaf(leaf, pattern)) {
		    multi = TRUE;
		    break;
		}
		leaf++;
	    }
	    if (!multi && *leaf != EOS)
		return FALSE;
#if OPT_GLOB_RANGE
	} else if ((vl_glob_opts & vl_GLOB_RANGE)
		   && (*pattern == GLOB_RANGE[0])) {
	    int found = FALSE;
	    char *first = ++pattern;
	    int negate = 0;

	    if (*first == GLOB_NEGATE[0] ||
		(GLOB_NEGATE[1] && *first == GLOB_NEGATE[1])) {
		negate = 1;
		first = pattern++;
	    }
	    while (*pattern != EOS) {
		if (*pattern == GLOB_RANGE[1]) {
		    pattern++;
		    break;
		}
		if (*pattern == '-' && pattern != first) {
		    int lo = CharOf(pattern[-1]);
		    int hi = CharOf(pattern[1]);
		    if (hi == GLOB_RANGE[1])
			hi = '~';	/* last-printable ASCII */
		    if (((cs_char(lo) <= cs_char(*leaf))
			 && (cs_char(*leaf) <= cs_char(hi))) != negate)
			found = TRUE;
		    pattern++;
		} else if ((cs_char(*pattern++) == cs_char(*leaf)) != negate)
		    found = TRUE;
	    }
	    if (!found)
		return FALSE;
	    leaf++;
#endif
	} else if (cs_char(*pattern++) != cs_char(*leaf++))
	    return FALSE;
    }
    return (*leaf == EOS && only_multi(pattern));
}
#endif /* !SMALLER || UNIX_GLOBBING */

#if UNIX_GLOBBING
/*
 * Point to the leaf following the given string (i.e., skip a slash), returns
 * null if none is found.
 */
static char *
next_leaf(char *path)
{
    if (path != 0) {
	while (*path != EOS) {
	    if (is_slashc(*path))
		return path + 1;
	    path++;
	}
    }
    return 0;
}

/*
 * Point to the beginning (after slash, if present) of the first leaf in
 * the given pattern argument that contains a wildcard.
 */
static char *
wild_leaf(char *pattern)
{
    int j, k, ok;
    char c;

    /* skip leading slashes */
    for (j = 0; pattern[j] != EOS && is_slashc(pattern[j]); j++) ;

    /* skip to the leaf with wildcards */
    while (pattern[j] != EOS) {
	int skip = FALSE;
	for (k = j + 1; (c = pattern[k]) != EOS; k++) {
	    if (is_slashc(c)) {
		pattern[k] = EOS;
		ok = string_has_globs(pattern + j);
		pattern[k] = c;
		if (ok)
		    return pattern + j;
		skip = TRUE;	/* skip this leaf */
		break;
	    }
	}
	if (skip) {
	    j = k + 1;		/* point past slash */
	} else {
	    break;
	}
    }
    return string_has_globs(pattern + j) ? pattern + j : 0;
}

#if !SYS_OS2
/*
 * Recursive procedure that allows any leaf (or all!) leaves in a path to
 * have wildcards.  Except for an ellipsis, each wildcard is completed
 * within a single leaf.
 *
 * Returns false if we ran out of memory (a problem on ms-dos), and true
 * if everything went well (e.g., matches).
 */
static int
expand_leaf(char *path,		/* built-up pathname, top-level */
	    char *pattern)
{
    DIR *dp;
    DIRENT *de;
    int result = TRUE;
    char save = 0;		/* warning suppression */
    size_t len;
    char *leaf;
    char *wild = wild_leaf(pattern);
    char *next = next_leaf(wild);
    char *s;

    /* Fill-in 'path[]' with the non-wild leaves that we skipped to get
     * to 'wild'.
     */
    if (wild == pattern) {	/* top-level, first leaf is wild */
	if (*path == EOS)
	    (void) strcpy(path, ".");
	leaf = skip_string(path) + 1;
    } else {
	len = (size_t) (wild - pattern) - 1;
	if (*(s = path) != EOS) {
	    s += strlen(s);
	    *s++ = SLASHC;
	}
	if (len != 0) {
	    (void) strncpy(s, pattern, len);
	    s[len] = EOS;
	}
	if (*path == EOS) {
	    path[0] = SLASHC;
	    path[1] = EOS;
	    leaf = path + 1;
	}
#if OPT_MSDOS_PATH
	/* Force the strncpy from 'pattern' to pick up a slash just
	 * after the ':' in a drive specification.
	 */
	else if ((s = is_msdos_drive(path)) != 0 && s[0] == EOS) {
	    s[0] = SLASHC;
	    s[1] = EOS;
	    leaf = s + 1;
	}
#endif
	else {
	    leaf = skip_string(path) + 1;
	}
    }

    if (next != 0) {
	save = next[-1];
	next[-1] = EOS;		/* restrict 'wild[]' to one leaf */
    }

    /* Scan the directory, looking for leaves that match the pattern.
     */
    if ((dp = opendir(SL_TO_BSL(path))) != 0) {
	leaf[-1] = SLASHC;	/* connect the path to the leaf */
	while ((de = readdir(dp)) != 0) {
#if OPT_MSDOS_PATH
	    (void) strcpy(leaf, de->d_name);
	    if (!global_g_val(GMDFILENAME_IC))
		(void) mklower(leaf);
	    if (strchr(pattern, '.') && !strchr(leaf, '.'))
		(void) strcat(leaf, ".");
#else
#if USE_D_NAMLEN
	    len = de->d_namlen;
	    (void) strncpy(leaf, de->d_name, len);
	    leaf[len] = EOS;
#else
	    (void) strcpy(leaf, de->d_name);
#endif
#endif
	    if (!strcmp(leaf, ".")
		|| !strcmp(leaf, ".."))
		continue;
	    if (!glob_match_leaf(leaf, wild))
		continue;
	    if (next != 0) {	/* there are more leaves */
		if (!string_has_globs(next)) {
		    s = skip_string(leaf);
		    *s++ = SLASHC;
		    (void) strcpy(s, next);
		    if (ffexists(path)
			&& !record_a_match(path)) {
			result = FALSE;
			break;
		    }
		} else if (is_directory(path)) {
#if SYS_MSDOS
		    s = strrchr(path, '.');
		    if (s[1] == EOS)
			s[0] = EOS;
#endif
		    if (!expand_leaf(path, next)) {
			result = FALSE;
			break;
		    }
		}
	    } else if (!record_a_match(path)) {
		result = FALSE;
		break;
	    }
	}
	(void) closedir(dp);
    } else {
	result = SORTOFTRUE;	/* at least we didn't run out of memory */
    }

    if (next != 0)
	next[-1] = save;

    return result;
}

#else /* SYS_OS2 */

/*
 * Recursive procedure that allows any leaf (or all!) leaves in a path to
 * have wildcards.  Except for an ellipsis, each wildcard is completed
 * within a single leaf.
 *
 * Returns false if we ran out of memory (a problem on ms-dos), and true
 * if everything went well (e.g., matches).
 */
static int
expand_leaf(char *path,		/* built-up pathname, top-level */
	    char *pattern)
{
    FILEFINDBUF3 fb;
    ULONG entries;
    HDIR hdir;
    APIRET rc;

    int result = TRUE;
    char save = 0;		/* warning suppression */
    size_t len;
    char *leaf;
    char *wild = wild_leaf(pattern);
    char *next = next_leaf(wild);
    char *s;

    /* Fill-in 'path[]' with the non-wild leaves that we skipped to get
     * to 'wild'.
     */
    if (wild == pattern) {	/* top-level, first leaf is wild */
	if (*path == EOS)
	    (void) strcpy(path, ".");
    } else {
	len = wild - pattern - 1;
	if (*(s = path) != EOS) {
	    s += strlen(s);
	    *s++ = SLASHC;
	}
	if (len != 0)
	    strncpy(s, pattern, len)[len] = EOS;
    }
    leaf = skip_string(path) + 1;

    if (next != 0) {
	save = next[-1];
	next[-1] = EOS;		/* restrict 'wild[]' to one leaf */
    }

    /* Scan the directory, looking for leaves that match the pattern.
     */
    len = strlen(path);
    if (!is_slashc(path[len - 1]))
	(void) strcat(path, "/*.*");
    else
	(void) strcat(path, "*.*");

    hdir = HDIR_CREATE;
    entries = 1;
    rc = DosFindFirst(SL_TO_BSL(path), &hdir,
		      FILE_DIRECTORY | FILE_READONLY,
		      &fb, sizeof(fb), &entries, FIL_STANDARD);
    if (rc == NO_ERROR) {
	leaf[-1] = SLASHC;

	do {
	    (void) mklower(strcpy(leaf, fb.achName));

	    if (strcmp(leaf, ".") == 0 || strcmp(leaf, "..") == 0)
		continue;
	    if (!glob_match_leaf(leaf, wild))
		continue;

	    if (next != 0) {	/* there are more leaves */
		if (!string_has_globs(next)) {
		    s = skip_string(leaf);
		    *s++ = SLASHC;
		    (void) strcpy(s, next);
		    if (!record_a_match(path)) {
			result = FALSE;
			break;
		    }
		} else if (is_directory(path)) {
		    s = strrchr(path, '.');
		    if (s[1] == EOS)
			s[0] = EOS;
		    if (!expand_leaf(path, next)) {
			result = FALSE;
			break;
		    }
		}
	    } else if (!record_a_match(path)) {
		result = FALSE;
		break;
	    }

	} while (entries = 1,
		 DosFindNext(hdir, &fb, sizeof(fb), &entries) == NO_ERROR
		 && entries == 1);

	DosFindClose(hdir);
    } else {
	result = SORTOFTRUE;	/* at least we didn't run out of memory */
    }

    if (next != 0)
	next[-1] = save;

    return result;
}
#endif /* SYS_OS2 */

static int
compar(const void *a, const void *b)
{
    return cs_strcmp(global_g_val(GMDFILENAME_IC),
		     *(const char *const *) a,
		     *(const char *const *) b);
}
#endif /* UNIX_GLOBBING */

#if OPT_GLOB_PIPE
static int
glob_from_pipe(const char *pattern)
{
    static char only_echo[] = "!echo %s";
#ifdef GVAL_GLOB
    char *cmd = global_g_val_ptr(GVAL_GLOB);
    int single;
#else
    char *cmd = only_echo;
    static int single = TRUE;
#endif
    FILE *cf;
    char tmp[NFILEN];
    int result = FALSE;
    size_t len;
    char *s, *d;

#ifdef GVAL_GLOB

    /*
     * For now, assume that only 'echo' will supply the result all on one
     * line.  Other programs (e.g., 'ls' and 'find' do the sensible thing
     * and break up the output with newlines.
     */
    if (!isShellOrPipe(cmd)) {
	cmd = only_echo;
	single = TRUE;
	d = cmd + 1;
    } else {
	char save = EOS;
	for (d = cmd + 1; *d != EOS && isSpace(*d); d++) ;
	for (s = d; *s != EOS; s++) {
	    if (isSpace(*s)) {
		save = *s;
		*s = EOS;
		break;
	    }
	}
	single = !strcmp(pathleaf(d), "echo");
	if (save != EOS)
	    *s = save;
    }
#else
    d = cmd + 1;
#endif

    (void) lsprintf(tmp, d, pattern);
    if ((cf = npopen(tmp, "r")) != 0) {
	char old[NFILEN + 1];

	*(d = old) = EOS;

	while ((len = fread(tmp, sizeof(*tmp), sizeof(tmp), cf)) > 0) {
	    /*
	     * Split the buffer up.  If 'single', split on all
	     * whitespace, otherwise only on newlines.
	     */
	    for (s = tmp; (size_t) (s - tmp) < len; s++) {
		if ((single && isSpace(*s))
		    || (!single && (*s == '\n' || *s == EOS))) {
		    *d = EOS;
		    result = record_a_match(d = old);
		    *d = EOS;
		    if (!result)
			break;
		} else {
		    *d++ = *s;
		}
	    }
	}
	if (*old != EOS) {
	    result = record_a_match(old);
	}
	npclose(cf);
    } else
	result = FALSE;

    return result;
}
#endif

#if OPT_GLOB_ENVIRON && UNIX_GLOBBING
/*
 * Expand environment variables in 'pattern[]'
 * It allows names of the form
 *
 *	$NAME
 *	$(NAME)
 *	${NAME}
 *
 * but ignores
 *	NAME$
 *	\$NAME
 */
static void
expand_environ(char *pattern)
{
    int j, k;
    int delim, left, right;
    const char *s;
    char save[NFILEN];

    if (vl_glob_opts & vl_GLOB_ENVIRON) {
	for (j = 0; pattern[j] != EOS; j++) {
	    if (j != 0 && isEscaped(pattern + j))
		continue;

	    k = j + 1;
	    if (pattern[j] == GLOB_ENVIRON[0] && pattern[k] != EOS) {
		if (pattern[k] == '(')
		    delim = ')';
		else if (pattern[k] == '{')
		    delim = '}';
		else if (isAlnum(pattern[k]))
		    delim = EOS;
		else
		    continue;

		if (delim != EOS)
		    k++;
		left =
		    right = k;

		while (pattern[k] != EOS) {
		    right = k;
		    if (delim != EOS) {
			if (pattern[k++] == delim)
			    break;
		    } else if (isname(pattern[k])) {
			k++;
		    } else {
			break;
		    }
		}
		if (delim == EOS)
		    right = k;

		(void) vl_strncpy(save, pattern + k, sizeof(save));
		if (right != left) {
		    pattern[right] = EOS;
#if SYS_MSDOS || SYS_OS2
		    mkupper(pattern + left);
#endif
		    if ((s = getenv(pattern + left)) == 0)
			s = "";
		} else {
		    s = "";
		}

		if ((int) (strlen(pattern) + strlen(s) + 2) < NFILEN) {
		    (void) strcpy(pattern + j, s);
		    (void) strcat(pattern, save);
		    j += (int) strlen(s) - 1;
		} else {
		    /* give up - substitution does not fit */
		    break;
		}
	    }
	}
    }
}

#else
#define	expand_environ(pattern)
#endif

/*
 * Notes:
 *	VMS's sys$search function (embedded in our fake 'readdir()') handles
 *	all of the VMS wildcards.
 *
 *	MS-DOS has non-UNIX functions that scan a directory and recognize DOS-style
 *	wildcards.  Use these to get the smallest executable.  However, DOS-
 *	style wildcards are crude and clumsy compared to UNIX, so we provide them as
 *	an option.  (For example, the DOS-wildcards won't match "..\*\*.bak").
 */
static int
expand_pattern(char *item)
{
    int result = FALSE;
#if OPT_VMS_PATH
    DIR *dp;
    DIRENT *de;
    char actual[NFILEN];
    char *leaf;

    strcpy(actual, item);
    /*
     * If we're given a Unix-style pathname, split off the leaf (which may
     * contain wildcards), translate the directory to VMS form, and put the
     * leaf back.  The unix2vms_path function would otherwise mangle the
     * wildcards in the leaf.  We only handle wildcards in the leaf
     * filename, since native VMS syntax for wildcards in the directory is
     * too cumbersome to use.
     */
    if (!is_vms_pathname(actual, -TRUE)) {
	if ((leaf = pathleaf(actual)) != actual)
	    *leaf = EOS;
	unix2vms_path(actual, actual);
	if (leaf != actual)
	    pathcat(actual, actual, pathleaf(item));
    }

    if ((dp = opendir(actual)) != 0) {
	result = TRUE;
	while ((de = readdir(dp)) != 0) {
	    char temp[NFILEN];
#if USE_D_NAMLEN
	    size_t len = de->d_namlen;
	    (void) strncpy(temp, de->d_name, len);
	    temp[len] = EOS;
#else
	    (void) strcpy(temp, de->d_name);
#endif
	    if (!record_a_match(temp)) {
		result = FALSE;
		break;
	    }
	}
	(void) closedir(dp);
    }
#else /* UNIX or MSDOS, etc. */

#if OPT_GLOB_PIPE
# ifdef GVAL_GLOB
    /*
     * The 'glob' mode value can be on/off or set to a pipe expression,
     * e.g., "!echo %s".  This allows using the shell to expand the
     * pattern, which is slower than vile's internal code, but may allow
     * using specific features to which the user is accustomed.
     *
     * As a special case, we read from a pipe if the expression begins with
     * a back-tick (e.g., `which script`).
     */
    if (isShellOrPipe(global_g_val_ptr(GVAL_GLOB))
	|| *item == BAKTIK) {
	result = glob_from_pipe(item);
    } else
# else
    result = glob_from_pipe(item);
#  if UNIX_GLOBBING
    huh ? ?			/* thought I turned that off ... */
#  endif
# endif
#endif
#if UNIX_GLOBBING
    {
	char builtup[NFILEN];
	char pattern[NFILEN];
	size_t first = myLen;

	(void) vl_strncpy(pattern, item, sizeof(pattern));
	*builtup = EOS;
#if OPT_MSDOS_PATH
	if (!global_g_val(GMDFILENAME_IC))
	    (void) mklower(pattern);
#endif
	expand_environ(pattern);
	if (string_has_globs(pattern)) {
	    /*
	     * FIXME - stripping escapes is done too early, in case we have
	     * mixed [pattern] and \[xxx\] token.
	     */
	    strip_escapes(pattern);
	    if ((result = expand_leaf(builtup, pattern)) != FALSE
		&& (myLen - first > 1)) {
		qsort((char *) &myVec[first], myLen - first,
		      sizeof(*myVec), compar);
	    }
	} else {
	    strip_escapes(pattern);
	    result = record_a_match(pattern);
	}
    }
#endif /* UNIX-style globbing */
#if (SYS_MSDOS || SYS_OS2 || SYS_WINNT) && !UNIX_GLOBBING
    /* native DOS-wildcards */
    DeclareFind(p);
    char temp[FILENAME_MAX + 1];
    char path[FILENAME_MAX + 1];
    char *cp = pathleaf(strcpy(temp, strcpy(path, item)));

    if (DirFindFirst(path, p)) {
	result = TRUE;
	do {
	    (void) strcpy(cp, DirEntryStr(p));
	    if (!record_a_match(temp)) {
		result = FALSE;
		break;
	    }
	} while (DirFindNext(p));
    }
#endif /* native MS-DOS globbing */
#endif /* OPT_VMS_PATH */
    return result;		/* true iff no errors noticed */
}

/*--------------------------------------------------------------------------*/

/*
 * Tests a list of items to see if at least one of them needs to be globbed.
 */
#if !SYS_UNIX
int
glob_needed(char **list_of_items)
{
    int n;

    for (n = 0; list_of_items[n] != 0; n++)
	if (string_has_wildcards(list_of_items[n]))
	    return TRUE;
    return FALSE;
}
#endif

/*
 * Expands the items in a list, returning an entirely new list (so it can be
 * freed without knowing where it came from originally).  This should only
 * return 0 if we run out of memory.
 */
static char **
glob_expand(char **list_of_items)
{
    int len = glob_length(list_of_items);
    int i;

    myMax = 0;
    myLen = 0;
    myVec = 0;

    for (i = 0; i < len; ++i) {
	char *item = list_of_items[i];
	/*
	 * Expand '~' expressions in case we've got a pattern like
	 * "~/test*.log".
	 */
#if !SMALLER
	char temp[NFILEN];
	item = home_path(vl_strncpy(temp, item, sizeof(temp)));
#endif
	if (!isInternalName(item)
	    && globbing_active()
	    && string_has_wildcards(item)) {
	    if (!expand_pattern(item))
		return 0;
	} else if (!record_a_match(item)) {
	    return 0;
	}
    }
    return myVec;
}

/*
 * A special case of 'glob_expand()', expands a single string into a list.
 */
char **
glob_string(char *item)
{
    char *vec[2];

    vec[0] = item;
    vec[1] = 0;

    return glob_expand(vec);
}

/*
 * Counts the number of items in a list of strings.  This is simpler (and
 * more useful) than returning the length and the list as arguments from
 * a procedure.  Note that since the standard argc/argv convention puts a
 * null pointer on the end, this function is applicable to the 'argv[]'
 * parameter of the main program as well.
 */
int
glob_length(char **list_of_items)
{
    int len;
    if (list_of_items != 0) {
	for (len = 0; list_of_items[len] != 0; len++) ;
    } else
	len = 0;
    return len;
}

/*
 * Frees the strings in a list, and the list itself.  Note that this should
 * not be used for the main program's original argv, because on some systems
 * it is a part of a larger data area, as are the command strings.
 */
char **
glob_free(char **list_of_items)
{
    int len;
    beginDisplay();
    if (list_of_items != 0) {
	for (len = 0; list_of_items[len] != 0; len++)
	    free(list_of_items[len]);
	free(list_of_items);
    }
    endofDisplay();
    return 0;
}

#if !SYS_UNIX
/*
 * Expand wildcards for the main program a la UNIX shell.
 */
void
expand_wild_args(int *argcp, char ***argvp)
{
#if SYS_VMS
    int j, k;
    int comma = 0;
    int option = 0;
    /*
     * VMS command-line arguments may be a comma-separated list of
     * filenames, with an optional "/read_only" flag appended.
     */
    for (j = 1; j < *argcp; j++) {
	char *s = (*argvp)[j];
	int c;
	while ((c = *s++) != EOS) {
	    if (c == ',')
		comma++;
	    if (c == '/')
		option++;
	}
    }
    if (comma || option) {
	char **newvec = typeallocn(char *, comma + *argcp + 1);

	if (newvec == 0) {
	    no_memory("expand_wild_args");
	    return;
	}

	for (j = k = 0; j < *argcp; j++) {
	    char *the_arg = strmalloc((*argvp)[j]);
	    char *item, *tmp;

	    if (the_arg == 0)
		break;

	    /*
	     * strip off supported VMS options, else don't muck
	     * with pseudo-unix path delimiters so that the
	     * glob routines will correctly handle filenames
	     * like these:
	     *
	     *     ../readme.txt   ~/vile.rc
	     *
	     * however don't mess with command line arguments
	     * that look like this:
	     *
	     *    +/<string>
	     */
	    if (!(the_arg[0] == '+' && the_arg[1] == '/')) {
		tmp = the_arg;
		while ((item = strrchr(tmp, '/')) != 0) {
		    mkupper(item);
		    if (!strncmp(item,
				 "/READ_ONLY",
				 strlen(item))) {
			set_global_b_val(MDVIEW, TRUE);
			*item = EOS;
		    } else
			tmp = item + 1;
		}
	    }
	    while (*the_arg != EOS) {
		item = strchr(the_arg, ',');
		if (item == 0)
		    item = skip_string(the_arg);
		else
		    *item++ = EOS;
		newvec[k++] = the_arg;
		the_arg = item;
	    }
	}
	newvec[k] = 0;
	*argcp = k;
	*argvp = newvec;
    }
#endif
    if (glob_needed(*argvp)) {
	char **newargs;
	int n;

	for (n = 0; n < *argcp; ++n) {
	    char *test = add_backslashes2((*argvp)[n], "\\$");
	    if (test != (*argvp)[n]) {
		(*argvp)[n] = strmalloc(test);
	    }
	}
	newargs = glob_expand(*argvp);
	if (newargs != 0) {
	    *argvp = newargs;
	    *argcp = glob_length(newargs);
	}
    }
}
#endif

/*
 * Expand a string, permitting only one match.
 */
int
doglob(char *path)
{
    char **expand = glob_string(path);
    int len = glob_length(expand);

    if (len > 1) {
	if (mlyesno("Too many filenames.  Use first") != TRUE) {
	    (void) glob_free(expand);
	    return FALSE;
	}
    }
    if (len > 0) {
	(void) strcpy(path, expand[0]);
	(void) glob_free(expand);
    }
    return TRUE;
}