xref: /original-bsd/usr.bin/ex/ex_io.c (revision ba762ddc)
1 /*-
2  * Copyright (c) 1980 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.proprietary.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)ex_io.c	7.19 (Berkeley) 04/17/91";
10 #endif /* not lint */
11 
12 #include "ex.h"
13 #include "ex_argv.h"
14 #include "ex_temp.h"
15 #include "ex_tty.h"
16 #include "ex_vis.h"
17 #include <sys/file.h>
18 #include <sys/exec.h>
19 #include "pathnames.h"
20 
21 /*
22  * File input/output, source, preserve and recover
23  */
24 
25 /*
26  * Following remember where . was in the previous file for return
27  * on file switching.
28  */
29 int	altdot;
30 int	oldadot;
31 bool	wasalt;
32 short	isalt;
33 
34 long	cntch;			/* Count of characters on unit io */
35 #ifndef VMUNIX
36 short	cntln;			/* Count of lines " */
37 #else
38 int	cntln;
39 #endif
40 long	cntnull;		/* Count of nulls " */
41 long	cntodd;			/* Count of non-ascii characters " */
42 
43 #ifdef	FLOCKFILE
44 /*
45  * The alternate, saved and current file are locked the extent of the
46  * time that they are active. If the saved file is exchanged
47  * with the alternate file, the file descriptors are exchanged
48  * and the lock is not released.
49  */
50 int	io_savedfile, io_altfile, io_curr ;
51 int	lock_savedfile, lock_altfile, lock_curr ;
52 #endif	FLOCKFILE
53 
54 /*
55  * Parse file name for command encoded by comm.
56  * If comm is E then command is doomed and we are
57  * parsing just so user won't have to retype the name.
58  */
59 filename(comm)
60 	int comm;
61 {
62 	register int c = comm, d;
63 	register int i;
64 #ifdef	FLOCKFILE
65 	int lock ;
66 
67 	lock = 0 ;
68 #endif	FLOCKFILE
69 
70 	d = ex_getchar();
71 	if (endcmd(d)) {
72 		if (savedfile[0] == 0 && comm != 'f')
73 			error("No file|No current filename");
74 		CP(file, savedfile);
75 #ifdef	FLOCKFILE
76 		if (io_curr && io_curr != io_savedfile) close(io_curr) ;
77 		lock = lock_curr = lock_savedfile ;
78 		io_curr = io_savedfile ;
79 #endif	FLOCKFILE
80 		wasalt = (isalt > 0) ? isalt-1 : 0;
81 		isalt = 0;
82 		oldadot = altdot;
83 		if (c == 'e' || c == 'E')
84 			altdot = lineDOT();
85 		if (d == EOF)
86 			ungetchar(d);
87 	} else {
88 		ungetchar(d);
89 		getone();
90 		eol();
91 		if (savedfile[0] == 0 && c != 'E' && c != 'e') {
92 			c = 'e';
93 			edited = 0;
94 		}
95 		wasalt = strcmp(file, altfile) == 0;
96 		oldadot = altdot;
97 		switch (c) {
98 
99 		case 'f':
100 			edited = 0;
101 			/* fall into ... */
102 
103 		case 'e':
104 			if (savedfile[0]) {
105 #ifdef	FLOCKFILE
106 				if (strcmp(file,savedfile) == 0) break ;
107 #endif	FLOCKFILE
108 				altdot = lineDOT();
109 				CP(altfile, savedfile);
110 #ifdef	FLOCKFILE
111 				if (io_altfile) close (io_altfile) ;
112 				io_altfile = io_savedfile ;
113 				lock_altfile = lock_savedfile ;
114 				io_savedfile = 0 ;
115 #endif	FLOCKFILE
116 			}
117 			CP(savedfile, file);
118 #ifdef	FLOCKFILE
119 			io_savedfile = io_curr ;
120 			lock_savedfile = lock_curr ;
121 			io_curr = 0 ;		lock = lock_curr = 0 ;
122 #endif	FLOCKFILE
123 			break;
124 
125 		default:
126 			if (file[0]) {
127 #ifdef	FLOCKFILE
128 				if (wasalt) break ;
129 #endif
130 				if (c != 'E')
131 					altdot = lineDOT();
132 				CP(altfile, file);
133 #ifdef	FLOCKFILE
134 				if (io_altfile
135 				&& io_altfile != io_curr) close (io_altfile) ;
136 				io_altfile = io_curr ;
137 				lock_altfile = lock_curr ;
138 				io_curr = 0 ;		lock = lock_curr = 0 ;
139 #endif	FLOCKFILE
140 			}
141 			break;
142 		}
143 	}
144 	if (hush && comm != 'f' || comm == 'E')
145 		return;
146 	if (file[0] != 0) {
147 		lprintf("\"%s\"", file);
148 		if (comm == 'f') {
149 			if (value(READONLY))
150 				ex_printf(" [Read only]");
151 			if (!edited)
152 				ex_printf(" [Not edited]");
153 			if (tchng)
154 				ex_printf(" [Modified]");
155 #ifdef	FLOCKFILE
156 			if (lock == LOCK_SH)
157 				ex_printf(" [Shared lock]") ;
158 			else if (lock == LOCK_EX)
159 				ex_printf(" [Exclusive lock]") ;
160 #endif	FLOCKFILE
161 		}
162 		flush();
163 	} else
164 		ex_printf("No file ");
165 	if (comm == 'f') {
166 		if (!(i = lineDOL()))
167 			i++;
168 		ex_printf(" line %d of %d --%ld%%--", lineDOT(), lineDOL(),
169 		    (long) 100 * lineDOT() / i);
170 	}
171 }
172 
173 /*
174  * Get the argument words for a command into genbuf
175  * expanding # and %.
176  */
177 getargs()
178 {
179 	register int c;
180 	register char *cp, *fp;
181 	static char fpatbuf[32];	/* hence limit on :next +/pat */
182 
183 	pastwh();
184 	if (peekchar() == '+') {
185 		for (cp = fpatbuf;;) {
186 			c = *cp++ = ex_getchar();
187 			if (cp >= &fpatbuf[sizeof(fpatbuf)])
188 				error("Pattern too long");
189 			if (c == '\\' && isspace(peekchar()))
190 				c = ex_getchar();
191 			if (c == EOF || isspace(c)) {
192 				ungetchar(c);
193 				*--cp = 0;
194 				firstpat = &fpatbuf[1];
195 				break;
196 			}
197 		}
198 	}
199 	if (skipend())
200 		return (0);
201 	CP(genbuf, "echo "); cp = &genbuf[5];
202 	for (;;) {
203 		c = ex_getchar();
204 		if (endcmd(c)) {
205 			ungetchar(c);
206 			break;
207 		}
208 		switch (c) {
209 
210 		case '\\':
211 			if (any(peekchar(), "#%|"))
212 				c = ex_getchar();
213 			/* fall into... */
214 
215 		default:
216 			if (cp > &genbuf[LBSIZE - 2])
217 flong:
218 				error("Argument buffer overflow");
219 			*cp++ = c;
220 			break;
221 
222 		case '#':
223 			fp = altfile;
224 			if (*fp == 0)
225 				error("No alternate filename@to substitute for #");
226 			goto filexp;
227 
228 		case '%':
229 			fp = savedfile;
230 			if (*fp == 0)
231 				error("No current filename@to substitute for %%");
232 filexp:
233 			while (*fp) {
234 				if (cp > &genbuf[LBSIZE - 2])
235 					goto flong;
236 				*cp++ = *fp++;
237 			}
238 			break;
239 		}
240 	}
241 	*cp = 0;
242 	return (1);
243 }
244 
245 /*
246  * Glob the argument words in genbuf, or if no globbing
247  * is implied, just split them up directly.
248  */
249 glob(gp)
250 	struct glob *gp;
251 {
252 	int pvec[2];
253 	register char **argv = gp->argv;
254 	register char *cp = gp->argspac;
255 	register int c;
256 	char ch;
257 	int nleft = NCARGS;
258 
259 	gp->argc0 = 0;
260 	if (gscan() == 0) {
261 		register char *v = genbuf + 5;		/* strlen("echo ") */
262 
263 		for (;;) {
264 			while (isspace(*v))
265 				v++;
266 			if (!*v)
267 				break;
268 			*argv++ = cp;
269 			while (*v && !isspace(*v))
270 				*cp++ = *v++;
271 			*cp++ = 0;
272 			gp->argc0++;
273 		}
274 		*argv = 0;
275 		return;
276 	}
277 	if (pipe(pvec) < 0)
278 		error("Can't make pipe to glob");
279 	pid = vfork();
280 	io = pvec[0];
281 	if (pid < 0) {
282 		close(pvec[1]);
283 		error("Can't fork to do glob");
284 	}
285 	if (pid == 0) {
286 		int oerrno;
287 
288 		if (genbuf) {
289 			register char *ccp = genbuf;
290 			while (*ccp)
291 				*ccp++ &= TRIM;
292 		}
293 		close(1);
294 		dup(pvec[1]);
295 		close(pvec[0]);
296 		close(2);	/* so errors don't mess up the screen */
297 		ignore(open(_PATH_DEVNULL, 1));
298 		execl(svalue(SHELL), "sh", "-c", genbuf, 0);
299 		oerrno = errno;
300 		close(1);
301 		dup(2);
302 		errno = oerrno;
303 		filioerr(svalue(SHELL));
304 	}
305 	close(pvec[1]);
306 	do {
307 		*argv = cp;
308 		for (;;) {
309 			if (read(io, &ch, 1) != 1) {
310 				close(io);
311 				c = -1;
312 			} else
313 				c = ch & TRIM;
314 			if (c <= 0 || isspace(c))
315 				break;
316 			*cp++ = c;
317 			if (--nleft <= 0)
318 				error("Arg list too long");
319 		}
320 		if (cp != *argv) {
321 			--nleft;
322 			*cp++ = 0;
323 			gp->argc0++;
324 			if (gp->argc0 >= NARGS)
325 				error("Arg list too long");
326 			argv++;
327 		}
328 	} while (c >= 0);
329 	waitfor();
330 	if (gp->argc0 == 0)
331 		error("No match");
332 }
333 
334 /*
335  * Scan genbuf for shell metacharacters.
336  * Set is union of v7 shell and csh metas.
337  */
338 gscan()
339 {
340 #ifndef	vms			/* Never have meta-characters in vms */
341 	register char *cp;
342 
343 	for (cp = genbuf; *cp; cp++)
344 		if (any(*cp, "~{[*?$`'\"\\"))
345 			return (1);
346 #endif
347 	return (0);
348 }
349 
350 /*
351  * Parse one filename into file.
352  */
353 struct glob G;
354 getone()
355 {
356 	register char *str;
357 
358 	if (getargs() == 0)
359 		error("Missing filename");
360 	glob(&G);
361 	if (G.argc0 > 1)
362 		error("Ambiguous|Too many file names");
363 	str = G.argv[G.argc0 - 1];
364 	if (strlen(str) > FNSIZE - 4)
365 		error("Filename too long");
366 	CP(file, str);
367 }
368 
369 /*
370  * Read a file from the world.
371  * C is command, 'e' if this really an edit (or a recover).
372  */
373 rop(c)
374 	int c;
375 {
376 	register int i;
377 	struct stat stbuf;
378 	struct exec head;
379 	static int ovro;	/* old value(READONLY) */
380 	static int denied;	/* 1 if READONLY was set due to file permissions */
381 #ifdef	FLOCKFILE
382 	int *lp, *iop;
383 #endif	FLOCKFILE
384 
385 	io = open(file, 0);
386 	if (io < 0) {
387 		if (c == 'e' && errno == ENOENT) {
388 			edited++;
389 			/*
390 			 * If the user just did "ex foo" he is probably
391 			 * creating a new file.  Don't be an error, since
392 			 * this is ugly, and it screws up the + option.
393 			 */
394 			if (!seenprompt) {
395 				ex_printf(" [New file]");
396 				noonl();
397 				return;
398 			}
399 		}
400 		syserror();
401 	}
402 	if (fstat(io, &stbuf))
403 		syserror();
404 	switch (stbuf.st_mode & S_IFMT) {
405 
406 	case S_IFBLK:
407 		error(" Block special file");
408 
409 	case S_IFCHR:
410 		if (isatty(io))
411 			error(" Teletype");
412 		if (samei(&stbuf, _PATH_DEVNULL))
413 			break;
414 		error(" Character special file");
415 
416 	case S_IFDIR:
417 		error(" Directory");
418 
419 	case S_IFREG:
420 #ifdef CRYPT
421 		if (xflag)
422 			break;
423 #endif
424 		i = read(io, (char *)&head, sizeof(head));
425 		(void)lseek(io, 0L, L_SET);
426 		if (i != sizeof(head))
427 			break;
428 #ifndef vms
429 		switch ((int)head.a_magic) {
430 
431 		case 0405:	/* data overlay on exec */
432 		case OMAGIC:	/* unshared */
433 		case NMAGIC:	/* shared text */
434 		case 0411:	/* separate I/D */
435 		case ZMAGIC:	/* VM/Unix demand paged */
436 		case 0430:	/* PDP-11 Overlay shared */
437 		case 0431:	/* PDP-11 Overlay sep I/D */
438 			error(" Executable");
439 
440 		/*
441 		 * We do not forbid the editing of portable archives
442 		 * because it is reasonable to edit them, especially
443 		 * if they are archives of text files.  This is
444 		 * especially useful if you archive source files together
445 		 * and copy them to another system with ~%take, since
446 		 * the files sometimes show up munged and must be fixed.
447 		 */
448 		case 0177545:
449 		case 0177555:
450 			error(" Archive");
451 		case 070707:
452 			error(" Cpio file");
453 
454 		default:
455 			{
456 				char *bp = (char *)&head;
457 				if ((u_char)bp[0] == (u_char)'\037' &&
458 				    (u_char)bp[1] == (u_char)'\235')
459 					error(" Compressed file");
460 				if (!strncmp(bp, "!<arch>\n__.SYMDEF", 17)
461 				    || !strncmp(bp, "!<arch>\n", 8))
462 					error(" Archive");
463 			}
464 			break;
465 		}
466 #endif
467 	}
468 	if (c != 'r') {
469 		if (value(READONLY) && denied) {
470 			value(READONLY) = ovro;
471 			denied = 0;
472 		}
473 		if ((stbuf.st_mode & 0222) == 0 || access(file, 2) < 0) {
474 			ovro = value(READONLY);
475 			denied = 1;
476 			value(READONLY) = 1;
477 		}
478 	}
479 	if (value(READONLY)) {
480 		ex_printf(" [Read only]");
481 		flush();
482 	}
483 #ifdef	FLOCKFILE
484 	/*
485 	 * Attempt to lock the file. We use an sharable lock if reading
486 	 * the file, and an exclusive lock if editting a file.
487 	 * The lock will be released when the file is no longer being
488 	 * referenced. At any time, the editor can have as many as
489 	 * three files locked, and with different lock statuses.
490 	 */
491 	/*
492 	 * if this is either the saved or alternate file or current file,
493 	 * point to the appropriate descriptor and file lock status.
494 	 */
495 	if (strcmp (file,savedfile) == 0) {
496 		if (!io_savedfile) io_savedfile = dup(io) ;
497 		lp = &lock_savedfile ;	iop = &io_savedfile ;
498 	} else if (strcmp (file,altfile) == 0) {
499 		if (!io_altfile) io_altfile = dup(io) ;
500 		lp = &lock_altfile ;	iop = &io_altfile ;
501 	} else {
502 		/* throw away current lock, accquire new current lock */
503 		if (io_curr) close (io_curr) ;
504 		io_curr = dup(io) ;
505 		lp = &lock_curr ;	iop = &io_curr ;
506 		lock_curr = 0 ;
507 	}
508 	if (c == 'r' || value(READONLY) || *lp == 0) {
509 		/* if we have a lock already, don't bother */
510 		if (!*lp) {
511 			/* try for a shared lock */
512 			if (flock(*iop, LOCK_SH|LOCK_NB) < 0
513 			&& errno == EWOULDBLOCK) {
514 				ex_printf (
515 			" [FILE BEING MODIFIED BY ANOTHER PROCESS]") ;
516 				flush();
517 				goto fail_lock ;
518 			} else *lp = LOCK_SH ;
519 		}
520 	}
521 	if ( c != 'r'  && !value(READONLY) && *lp != LOCK_EX) {
522 		/* if we are editting the file, upgrade to an exclusive lock. */
523 		if (flock(*iop, LOCK_EX|LOCK_NB) < 0 && errno == EWOULDBLOCK) {
524 			ex_printf (" [File open by another process]") ;
525 			flush();
526 		} else *lp = LOCK_EX ;
527 	}
528 fail_lock:
529 #endif	FLOCKFILE
530 	if (c == 'r')
531 		setdot();
532 	else
533 		setall();
534 	if (FIXUNDO && inopen && c == 'r')
535 		undap1 = undap2 = dot + 1;
536 	rop2();
537 	rop3(c);
538 }
539 
540 rop2()
541 {
542 	line *first, *last, *a;
543 	struct stat statb;
544 
545 	deletenone();
546 	clrstats();
547 	first = addr2 + 1;
548 	if (fstat(io, &statb) < 0)
549 		bsize = LBSIZE;
550 	else {
551 		bsize = statb.st_blksize;
552 		if (bsize <= 0)
553 			bsize = LBSIZE;
554 	}
555 	ignore(append(getfile, addr2));
556 	last = dot;
557 	/*
558 	 *	if the modeline variable is set,
559 	 *	check the first and last five lines of the file
560 	 *	for a mode line.
561 	 */
562 	if (value(MODELINE)) {
563 		for (a=first; a<=last; a++) {
564 			if (a==first+5 && last-first > 10)
565 				a = last - 4;
566 			getline(*a);
567 			checkmodeline(linebuf);
568 		}
569 	}
570 }
571 
572 rop3(c)
573 	int c;
574 {
575 
576 	if (iostats() == 0 && c == 'e')
577 		edited++;
578 	if (c == 'e') {
579 		if (wasalt || firstpat) {
580 			register line *addr = zero + oldadot;
581 
582 			if (addr > dol)
583 				addr = dol;
584 			if (firstpat) {
585 				globp = (*firstpat) ? firstpat : "$";
586 				commands(1,1);
587 				firstpat = 0;
588 			} else if (addr >= one) {
589 				if (inopen)
590 					dot = addr;
591 				markpr(addr);
592 			} else
593 				goto other;
594 		} else
595 other:
596 			if (dol > zero) {
597 				if (inopen)
598 					dot = one;
599 				markpr(one);
600 			}
601 		if(FIXUNDO)
602 			undkind = UNDNONE;
603 		if (inopen) {
604 			vcline = 0;
605 			vreplace(0, LINES, lineDOL());
606 		}
607 	}
608 }
609 
610 /*
611  * Are these two really the same inode?
612  */
613 samei(sp, cp)
614 	struct stat *sp;
615 	char *cp;
616 {
617 	struct stat stb;
618 
619 	if (stat(cp, &stb) < 0 || sp->st_dev != stb.st_dev)
620 		return (0);
621 	return (sp->st_ino == stb.st_ino);
622 }
623 
624 /* Returns from edited() */
625 #define	EDF	0		/* Edited file */
626 #define	NOTEDF	-1		/* Not edited file */
627 #define	PARTBUF	1		/* Write of partial buffer to Edited file */
628 
629 /*
630  * Write a file.
631  */
632 wop(dofname)
633 bool dofname;	/* if 1 call filename, else use savedfile */
634 {
635 	register int c, exclam, nonexist;
636 	line *saddr1, *saddr2;
637 	struct stat stbuf;
638 #ifdef	FLOCKFILE
639 	int *lp, *iop ;
640 #endif	FLOCKFILE
641 
642 	c = 0;
643 	exclam = 0;
644 	if (dofname) {
645 		if (peekchar() == '!')
646 			exclam++, ignchar();
647 		ignore(skipwh());
648 		while (peekchar() == '>')
649 			ignchar(), c++, ignore(skipwh());
650 		if (c != 0 && c != 2)
651 			error("Write forms are 'w' and 'w>>'");
652 		filename('w');
653 	} else {
654 		if (savedfile[0] == 0)
655 			error("No file|No current filename");
656 		saddr1=addr1;
657 		saddr2=addr2;
658 		addr1=one;
659 		addr2=dol;
660 		CP(file, savedfile);
661 		if (inopen) {
662 			vclrech(0);
663 			splitw++;
664 		}
665 		lprintf("\"%s\"", file);
666 	}
667 	nonexist = stat(file, &stbuf);
668 #ifdef	FLOCKFILE
669 	/*
670 	 * if this is either the saved or alternate file or current file,
671 	 * point to the appropriate descriptor and file lock status.
672 	 */
673 	if (strcmp (file,savedfile) == 0) {
674 		lp = &lock_savedfile ;	iop = &io_savedfile ;
675 	} else if (strcmp (file,altfile) == 0) {
676 		lp = &lock_altfile ;	iop = &io_altfile ;
677 	} else {
678 		lp = &lock_curr ;	iop = &io_curr ;
679 	}
680 	if (!*iop && !nonexist){
681 		*lp = 0 ;
682 		if ((*iop = open(file, 1)) < 0) *iop = 0 ;
683 	}
684 #endif	FLOCKFILE
685 	switch (c) {
686 
687 	case 0:
688 		if (!exclam && (!value(WRITEANY) || value(READONLY)))
689 		switch (edfile()) {
690 
691 		case NOTEDF:
692 			if (nonexist)
693 				break;
694 			if ((stbuf.st_mode & S_IFMT) == S_IFCHR) {
695 				if (samei(&stbuf, _PATH_DEVNULL))
696 					break;
697 				if (samei(&stbuf, _PATH_TTY))
698 					break;
699 			}
700 			io = open(file, 1);
701 			if (io < 0)
702 				syserror();
703 			if (!isatty(io))
704 				serror(" File exists| File exists - use \"w! %s\" to overwrite", file);
705 			close(io);
706 			break;
707 
708 		case EDF:
709 			if (value(READONLY))
710 				error(" File is read only");
711 			break;
712 
713 		case PARTBUF:
714 			if (value(READONLY))
715 				error(" File is read only");
716 			error(" Use \"w!\" to write partial buffer");
717 		}
718 cre:
719 /*
720 		synctmp();
721 */
722 #ifdef	FLOCKFILE
723 	if (*iop && !*lp != LOCK_EX && !exclam) {
724 		/*
725 		 * upgrade to a exclusive lock. if can't get, someone else
726 		 * has the exclusive lock. bitch to the user.
727 		 */
728 		if (flock(*iop, LOCK_EX|LOCK_NB) < 0 && errno == EWOULDBLOCK)
729 	error (" File being modified by another process - use \"w!\" to write");
730 		 else *lp = LOCK_EX ;
731 	}
732 #endif	FLOCKFILE
733 #ifdef V6
734 		io = creat(file, 0644);
735 #else
736 		io = creat(file, 0666);
737 #ifdef vms	/* to retain file protection modes on newer version of file */
738 		if (!nonexist)
739 			chmod(file, stbuf.st_mode & 0777);
740 #endif
741 #endif
742 		if (io < 0)
743 			syserror();
744 		writing = 1;
745 		if (hush == 0)
746 			if (nonexist)
747 				ex_printf(" [New file]");
748 			else if (value(WRITEANY) && edfile() != EDF)
749 				ex_printf(" [Existing file]");
750 #ifdef	FLOCKFILE
751 		if (!*iop)
752 			*iop = dup(io) ;
753 #endif	FLOCKFILE
754 		break;
755 
756 	case 2:
757 		io = open(file, 1);
758 		if (io < 0) {
759 			if (exclam || value(WRITEANY))
760 				goto cre;
761 			syserror();
762 		}
763 		lseek(io, 0l, 2);
764 #ifdef	FLOCKFILE
765 		if (!*iop) *iop = dup(io) ;
766 		if (*lp != LOCK_EX && !exclam) {
767 			/*
768 		 	 * upgrade to a exclusive lock. if can't get,
769 			 * someone else has the exclusive lock.
770 			 * bitch to the user.
771 		 	 */
772 			if (flock(*iop, LOCK_SH|LOCK_NB) < 0
773 			&& errno == EWOULDBLOCK)
774 				error (
775 " File being modified by another process - use \"w!>>\" to write");
776 		 	else *lp = LOCK_EX ;
777 		}
778 #endif	FLOCKFILE
779 		break;
780 	}
781 #ifdef	FLOCKFILE
782 	if (flock(*iop, LOCK_EX|LOCK_NB) >= 0)
783 		*lp = LOCK_EX ;
784 #endif	FLOCKFILE
785 	putfile(0);
786 #ifndef	vms
787 	(void) fsync(io);
788 #endif
789 	ignore(iostats());
790 	if (c != 2 && addr1 == one && addr2 == dol) {
791 		if (eq(file, savedfile))
792 			edited = 1;
793 		ex_sync();
794 	}
795 	if (!dofname) {
796 		addr1 = saddr1;
797 		addr2 = saddr2;
798 	}
799 	writing = 0;
800 }
801 
802 /*
803  * Is file the edited file?
804  * Work here is that it is not considered edited
805  * if this is a partial buffer, and distinguish
806  * all cases.
807  */
808 edfile()
809 {
810 
811 	if (!edited || !eq(file, savedfile))
812 		return (NOTEDF);
813 	return (addr1 == one && addr2 == dol ? EDF : PARTBUF);
814 }
815 
816 /*
817  * Extract the next line from the io stream.
818  */
819 char *nextip;
820 
821 getfile()
822 {
823 	register short c;
824 	register char *lp, *fp;
825 
826 	lp = linebuf;
827 	fp = nextip;
828 	do {
829 		if (--ninbuf < 0) {
830 			ninbuf = read(io, genbuf, (int) bsize) - 1;
831 			if (ninbuf < 0) {
832 				if (lp != linebuf) {
833 					lp++;
834 					ex_printf(" [Incomplete last line]");
835 					break;
836 				}
837 				return (EOF);
838 			}
839 #ifdef CRYPT
840 			if (kflag) {
841 				fp = genbuf;
842 				while(fp < &genbuf[ninbuf]) {
843 					if (*fp++ & 0200) {
844 						crblock(perm, genbuf, ninbuf+1,
845 	cntch);
846 						break;
847 					}
848 				}
849 			}
850 #endif
851 			fp = genbuf;
852 			cntch += ninbuf+1;
853 		}
854 		if (lp >= &linebuf[LBSIZE]) {
855 			error(" Line too long");
856 		}
857 		c = *fp++;
858 		if (c == 0) {
859 			cntnull++;
860 			continue;
861 		}
862 		if (c & QUOTE) {
863 			cntodd++;
864 			c &= TRIM;
865 			if (c == 0)
866 				continue;
867 		}
868 		*lp++ = c;
869 	} while (c != '\n');
870 	*--lp = 0;
871 	nextip = fp;
872 	cntln++;
873 	return (0);
874 }
875 
876 /*
877  * Write a range onto the io stream.
878  */
879 /* ARGSUSED */
880 putfile(isfilter)
881 int isfilter;
882 {
883 	line *a1;
884 	register char *fp, *lp;
885 	register int nib;
886 	struct stat statb;
887 
888 	a1 = addr1;
889 	clrstats();
890 	cntln = addr2 - a1 + 1;
891 	if (cntln == 0)
892 		return;
893 	if (fstat(io, &statb) < 0)
894 		bsize = LBSIZE;
895 	else {
896 		bsize = statb.st_blksize;
897 		if (bsize <= 0)
898 			bsize = LBSIZE;
899 	}
900 	nib = bsize;
901 	fp = genbuf;
902 	do {
903 		getline(*a1++);
904 		lp = linebuf;
905 		for (;;) {
906 			if (--nib < 0) {
907 				nib = fp - genbuf;
908 #ifdef CRYPT
909                 		if(kflag && !isfilter)
910                                         crblock(perm, genbuf, nib, cntch);
911 #endif
912 				if (write(io, genbuf, nib) != nib) {
913 					wrerror();
914 				}
915 				cntch += nib;
916 				nib = bsize - 1;
917 				fp = genbuf;
918 			}
919 			if ((*fp++ = *lp++) == 0) {
920 				fp[-1] = '\n';
921 				break;
922 			}
923 		}
924 	} while (a1 <= addr2);
925 	nib = fp - genbuf;
926 #ifdef CRYPT
927 	if(kflag && !isfilter)
928 		crblock(perm, genbuf, nib, cntch);
929 #endif
930 	if (write(io, genbuf, nib) != nib) {
931 		wrerror();
932 	}
933 	cntch += nib;
934 }
935 
936 /*
937  * A write error has occurred;  if the file being written was
938  * the edited file then we consider it to have changed since it is
939  * now likely scrambled.
940  */
941 wrerror()
942 {
943 
944 	if (eq(file, savedfile) && edited)
945 		change();
946 	syserror();
947 }
948 
949 /*
950  * Source command, handles nested sources.
951  * Traps errors since it mungs unit 0 during the source.
952  */
953 short slevel;
954 short ttyindes;
955 
956 source(fil, okfail)
957 	char *fil;
958 	bool okfail;
959 {
960 	jmp_buf osetexit;
961 	register int saveinp, ointty, oerrno;
962 	char *saveglobp;
963 	short savepeekc;
964 
965 	signal(SIGINT, SIG_IGN);
966 	saveinp = dup(0);
967 	savepeekc = peekc;
968 	saveglobp = globp;
969 	peekc = 0; globp = 0;
970 	if (saveinp < 0)
971 		error("Too many nested sources");
972 	if (slevel <= 0)
973 		ttyindes = saveinp;
974 	close(0);
975 	if (open(fil, 0) < 0) {
976 		oerrno = errno;
977 		setrupt();
978 		dup(saveinp);
979 		close(saveinp);
980 		errno = oerrno;
981 		if (!okfail)
982 			filioerr(fil);
983 		return;
984 	}
985 	slevel++;
986 	ointty = intty;
987 	intty = isatty(0);
988 	oprompt = value(PROMPT);
989 	value(PROMPT) &= intty;
990 	getexit(osetexit);
991 	setrupt();
992 	if (setexit() == 0)
993 		commands(1, 1);
994 	else if (slevel > 1) {
995 		close(0);
996 		dup(saveinp);
997 		close(saveinp);
998 		slevel--;
999 		resexit(osetexit);
1000 		reset();
1001 	}
1002 	intty = ointty;
1003 	value(PROMPT) = oprompt;
1004 	close(0);
1005 	dup(saveinp);
1006 	close(saveinp);
1007 	globp = saveglobp;
1008 	peekc = savepeekc;
1009 	slevel--;
1010 	resexit(osetexit);
1011 }
1012 
1013 /*
1014  * Clear io statistics before a read or write.
1015  */
1016 clrstats()
1017 {
1018 
1019 	ninbuf = 0;
1020 	cntch = 0;
1021 	cntln = 0;
1022 	cntnull = 0;
1023 	cntodd = 0;
1024 }
1025 
1026 /*
1027  * Io is finished, close the unit and print statistics.
1028  */
1029 iostats()
1030 {
1031 
1032 	close(io);
1033 	io = -1;
1034 	if (hush == 0) {
1035 		if (value(TERSE))
1036 			ex_printf(" %d/%D", cntln, cntch);
1037 		else
1038 			ex_printf(" %d line%s, %D character%s", cntln, plural((long) cntln),
1039 			    cntch, plural(cntch));
1040 		if (cntnull || cntodd) {
1041 			ex_printf(" (");
1042 			if (cntnull) {
1043 				ex_printf("%D null", cntnull);
1044 				if (cntodd)
1045 					ex_printf(", ");
1046 			}
1047 			if (cntodd)
1048 				ex_printf("%D non-ASCII", cntodd);
1049 			ex_putchar(')');
1050 		}
1051 		noonl();
1052 		flush();
1053 	}
1054 	return (cntnull != 0 || cntodd != 0);
1055 }
1056 
1057 #ifdef USG
1058 # define index strchr
1059 # define rindex strrchr
1060 #endif
1061 #ifdef USG3TTY
1062 # define index strchr
1063 # define rindex strrchr
1064 #endif
1065 #ifdef vms
1066 # define index strchr
1067 # define rindex strrchr
1068 #endif
1069 
1070 checkmodeline(l)
1071 char *l;
1072 {
1073 	char *beg, *end;
1074 	char cmdbuf[1024];
1075 	char *index(), *rindex(), *strncpy();
1076 
1077 	beg = index(l, ':');
1078 	if (beg == NULL)
1079 		return;
1080 	if (&beg[-3] < l)
1081 		return;
1082 	if (!(  ( (beg[-3] == ' ' || beg[-3] == '\t')
1083 	        && beg[-2] == 'e'
1084 		&& beg[-1] == 'x')
1085 	     || ( (beg[-3] == ' ' || beg[-3] == '\t')
1086 	        && beg[-2] == 'v'
1087 		&& beg[-1] == 'i'))) return;
1088 	strncpy(cmdbuf, beg+1, sizeof cmdbuf);
1089 	end = rindex(cmdbuf, ':');
1090 	if (end == NULL)
1091 		return;
1092 	*end = 0;
1093 	globp = cmdbuf;
1094 	commands(1, 1);
1095 }
1096