xref: /original-bsd/usr.bin/ex/ex.c (revision 1511614f)
1 /*-
2  * Copyright (c) 1980, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.proprietary.c%
6  */
7 
8 #ifndef lint
9 static char copyright[] =
10 "@(#) Copyright (c) 1980, 1993\n\
11 	The Regents of the University of California.  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)ex.c	8.1.1.1 (Berkeley) 08/19/93";
16 #endif /* not lint */
17 
18 #include "ex.h"
19 #include "ex_argv.h"
20 #include "ex_temp.h"
21 #include "ex_tty.h"
22 #include "pathnames.h"
23 
24 #ifdef TRACE
25 #ifdef	vms
26 char	tttrace[]	= { 't','r','a','c','e','.','l','i','s' };
27 #else
28 char	tttrace[]	= { '/','d','e','v','/','t','t','y','x','x',0 };
29 #endif
30 #endif
31 
32 /*
33  * The code for ex is divided as follows:
34  *
35  * ex.c			Entry point and routines handling interrupt, hangup
36  *			signals; initialization code.
37  *
38  * ex_addr.c		Address parsing routines for command mode decoding.
39  *			Routines to set and check address ranges on commands.
40  *
41  * ex_cmds.c		Command mode command decoding.
42  *
43  * ex_cmds2.c		Subroutines for command decoding and processing of
44  *			file names in the argument list.  Routines to print
45  *			messages and reset state when errors occur.
46  *
47  * ex_cmdsub.c		Subroutines which implement command mode functions
48  *			such as append, delete, join.
49  *
50  * ex_data.c		Initialization of options.
51  *
52  * ex_get.c		Command mode input routines.
53  *
54  * ex_io.c		General input/output processing: file i/o, unix
55  *			escapes, filtering, source commands, preserving
56  *			and recovering.
57  *
58  * ex_put.c		Terminal driving and optimizing routines for low-level
59  *			output (cursor-positioning); output line formatting
60  *			routines.
61  *
62  * ex_re.c		Global commands, substitute, regular expression
63  *			compilation and execution.
64  *
65  * ex_set.c		The set command.
66  *
67  * ex_subr.c		Loads of miscellaneous subroutines.
68  *
69  * ex_temp.c		Editor buffer routines for main buffer and also
70  *			for named buffers (Q registers if you will.)
71  *
72  * ex_tty.c		Terminal dependent initializations from termcap
73  *			data base, grabbing of tty modes (at beginning
74  *			and after escapes).
75  *
76  * ex_unix.c		Routines for the ! command and its variations.
77  *
78  * ex_v*.c		Visual/open mode routines... see ex_v.c for a
79  *			guide to the overall organization.
80  */
81 
82 /*
83  * Main procedure.  Process arguments and then
84  * transfer control to the main command processing loop
85  * in the routine commands.  We are entered as either "ex", "edit", "vi"
86  * or "view" and the distinction is made here.  Actually, we are "vi" if
87  * there is a 'v' in our name, "view" is there is a 'w', and "edit" if
88  * there is a 'd' in our name.  For edit we just diddle options;
89  * for vi we actually force an early visual command.
90  */
main(ac,av)91 main(ac, av)
92 	register int ac;
93 	register char *av[];
94 {
95 #ifdef EXSTRINGS
96 	char *erpath = EXSTRINGS;
97 #endif
98 	register char *cp;
99 	register int c;
100 	bool recov = 0;
101 	bool ivis;
102 	bool itag = 0;
103 	bool fast = 0;
104 	extern void onemt();
105 #ifdef UNIX_SBRK
106 	extern char *sbrk();
107 #else
108 	extern char *malloc();
109 #endif
110 #ifdef TRACE
111 	register char *tracef;
112 #endif
113 #ifdef	vms
114 	char termtype[20];
115 #endif
116 
117 	/*
118 	 * Immediately grab the tty modes so that we wont
119 	 * get messed up if an interrupt comes in quickly.
120 	 */
121 	ex_gTTY(1);
122 #ifndef USG3TTY
123 	normf = tty.sg_flags;
124 #else
125 	normf = tty;
126 #endif
127 	ppid = getpid();
128 	/*
129 	 * Defend against d's, v's, w's, and a's in directories of
130 	 * path leading to our true name.
131 	 */
132 #ifndef	vms
133 	av[0] = tailpath(av[0]);
134 #else
135 	/*
136 	 * This program has to be invoked by using the following
137 	 * string definitions:
138 	 *
139 	 * vi == "$dir:ex.exe vi"
140 	 * view == "$dir:ex.exe view"
141 	 * ex == "$dir:ex.exe ex"
142 	 * edit == "$dir:ex.exe edit"
143 	 */
144 	ac--;
145 	av++;
146 #endif
147 
148 	/*
149 	 * Figure out how we were invoked: ex, edit, vi, view.
150 	 */
151 	ivis = any('v', av[0]);	/* "vi" */
152 	if (any('w', av[0]))	/* "view" */
153 		value(READONLY) = 1;
154 	if (any('d', av[0])) {	/* "edit" */
155 		value(OPEN) = 0;
156 		value(REPORT) = 1;
157 		value(MAGIC) = 0;
158 	}
159 
160 #ifdef EXSTRINGS
161 	/*
162 	 * For debugging take files out of . if name is a.out.
163 	 */
164 	if (av[0][0] == 'a')
165 		erpath = tailpath(erpath);
166 #endif
167 	/*
168 	 * Open the error message file.
169 	 */
170 	draino();
171 #ifdef EXSTRINGS
172 	erfile = open(erpath+4, 0);
173 	if (erfile < 0) {
174 		erfile = open(erpath, 0);
175 	}
176 #endif
177 	pstop();
178 
179 	/*
180 	 * Initialize interrupt handling.
181 	 */
182 	oldhup = signal(SIGHUP, SIG_IGN);
183 	if (oldhup == SIG_DFL)
184 		signal(SIGHUP, onhup);
185 	oldquit = signal(SIGQUIT, SIG_IGN);
186 	ruptible = signal(SIGINT, SIG_IGN) == SIG_DFL;
187 	if (signal(SIGTERM, SIG_IGN) == SIG_DFL)
188 		signal(SIGTERM, onhup);
189 	if (signal(SIGEMT, SIG_IGN) == SIG_DFL)
190 		signal(SIGEMT, onemt);
191 
192 	/*
193 	 * Process flag arguments.
194 	 */
195 	ac--, av++;
196 	while (ac && av[0][0] == '-') {
197 		c = av[0][1];
198 		if (c == 0) {
199 			hush = 1;
200 			value(AUTOPRINT) = 0;
201 			fast++;
202 		} else switch (c) {
203 
204 		case 'R':
205 			value(READONLY) = 1;
206 			break;
207 
208 #ifdef TRACE
209 		case 'T':
210 			if (av[0][2] == 0)
211 				tracef = "trace";
212 			else {
213 				tracef = tttrace;
214 				tracef[8] = av[0][2];
215 				if (tracef[8])
216 					tracef[9] = av[0][3];
217 				else
218 					tracef[9] = 0;
219 			}
220 			trace = fopen(tracef, "w");
221 #define tracbuf NULL
222 			if (trace == NULL)
223 				ex_printf("Trace create error\n");
224 			else
225 				setbuf(trace, tracbuf);
226 			break;
227 
228 #endif
229 
230 #ifdef LISPCODE
231 		case 'l':
232 			value(LISP) = 1;
233 			value(SHOWMATCH) = 1;
234 			break;
235 #endif
236 
237 		case 'r':
238 			recov++;
239 			break;
240 
241 		case 't':
242 			if (ac > 1 && av[1][0] != '-') {
243 				ac--, av++;
244 				itag = 1;
245 				/* BUG: should check for too long tag. */
246 				CP(lasttag, av[0]);
247 			}
248 			break;
249 
250 		case 'v':
251 			ivis = 1;
252 			break;
253 
254 		case 'w':
255 			defwind = 0;
256 			if (av[0][2] == 0) defwind = 3;
257 			else for (cp = &av[0][2]; isdigit(*cp); cp++)
258 				defwind = 10*defwind + *cp - '0';
259 			break;
260 
261 
262 		default:
263 			smerror("Unknown option %s\n", av[0]);
264 			break;
265 		}
266 		ac--, av++;
267 	}
268 
269 #ifdef SIGTSTP
270 	if (!hush && signal(SIGTSTP, SIG_IGN) == SIG_DFL)
271 		signal(SIGTSTP, onsusp), dosusp++;
272 #endif
273 
274 	if (ac && av[0][0] == '+') {
275 		firstpat = &av[0][1];
276 		ac--, av++;
277 	}
278 
279 
280 	/*
281 	 * If we are doing a recover and no filename
282 	 * was given, then execute an exrecover command with
283 	 * the -r option to type out the list of saved file names.
284 	 * Otherwise set the remembered file name to the first argument
285 	 * file name so the "recover" initial command will find it.
286 	 */
287 	if (recov) {
288 		if (ac == 0) {
289 			ppid = 0;
290 			setrupt();
291 			execl(_PATH_EXRECOVER, "exrecover", "-r", 0);
292 			filioerr(_PATH_EXRECOVER);
293 			ex_exit(1);
294 		}
295 		CP(savedfile, *av++), ac--;
296 	}
297 
298 	/*
299 	 * Initialize the argument list.
300 	 */
301 	argv0 = av;
302 	argc0 = ac;
303 	args0 = av[0];
304 	erewind();
305 
306 	/*
307 	 * Initialize a temporary file (buffer) and
308 	 * set up terminal environment.  Read user startup commands.
309 	 */
310 	if (setexit() == 0) {
311 		setrupt();
312 		intty = isatty(0);
313 		value(PROMPT) = intty;
314 #ifndef	vms
315 		if (cp = getenv("SHELL"))
316 #else
317 		if (cp = getlog("SHELL"))
318 #endif
319 			CP(shell, cp);
320 		if (fast || !intty)
321 			setterm("dumb");
322 		else {
323 			gettmode();
324 #ifndef	vms
325 			if ((cp = getenv("TERM")) != 0 && *cp)
326 				setterm(cp);
327 #else
328 			if ((cp = getlog("TERM")) != 0 && *cp) {
329 				/*
330 				 * Can't just use it directly since getlog
331 				 * returns a pointer to a static buffer that
332 				 * tgetent() will eventually use
333 				 */
334 				CP(termtype, cp);
335 				setterm(termtype);
336 			}
337 #endif
338 		}
339 	}
340 	if (setexit() == 0 && !fast && intty) {
341 #ifndef	vms
342 		if ((globp = getenv("EXINIT")) && *globp)
343 #else
344 		if ((globp = getlog("EXINIT")) && *globp)
345 #endif
346 			commands(1,1);
347 		else {
348 			globp = 0;
349 			if ((cp = getenv("HOME")) != 0 && *cp) {
350 				(void) strcat(strcpy(genbuf, cp), "/.exrc");
351 				if (iownit(genbuf))
352 					source(genbuf, 1);
353 			}
354 		}
355 		/*
356 		 * Allow local .exrc too.  This loses if . is $HOME,
357 		 * but nobody should notice unless they do stupid things
358 		 * like putting a version command in .exrc.  Besides,
359 		 * they should be using EXINIT, not .exrc, right?
360 		 */
361 		 if (iownit(".exrc"))
362 			source(".exrc", 1);
363 	}
364 #ifdef	UNIX_SBRK
365 	/*
366 	 * Initialize end of core pointers.
367 	 * Normally we avoid breaking back to fendcore after each
368 	 * file since this can be expensive (much core-core copying).
369 	 * If your system can scatter load processes you could do
370 	 * this as ed does, saving a little core, but it will probably
371 	 * not often make much difference.
372 	 */
373 	fendcore = (line *) sbrk(0);
374 	endcore = fendcore - 2;
375 #else
376 	/*
377 	 * Allocate all the memory we will ever use in one chunk.
378 	 * This is for system such as VMS where sbrk() does not
379 	 * guarantee that the memory allocated beyond the end is
380 	 * consecutive.  VMS's RMS does all sorts of memory allocation
381 	 * and screwed up ex royally because ex assumes that all
382 	 * memory up to "endcore" belongs to it and RMS has different
383 	 * ideas.
384 	 */
385 	fendcore = (line *) malloc((unsigned)
386 		value(LINELIMIT) * sizeof (line *));
387 	if (fendcore == NULL) {
388 		lprintf("ex: cannot handle %d lines\n", value(LINELIMIT));
389 		lprintf("ex: set \"linelimit\" lower\n");
390 		flush();
391 		ex_exit(1);
392 	}
393 	endcore = fendcore + (value(LINELIMIT) - 1);
394 #endif
395 	init();	/* moved after prev 2 chunks to fix directory option */
396 
397 	/*
398 	 * Initial processing.  Handle tag, recover, and file argument
399 	 * implied next commands.  If going in as 'vi', then don't do
400 	 * anything, just set initev so we will do it later (from within
401 	 * visual).
402 	 */
403 	if (setexit() == 0) {
404 		if (recov)
405 			globp = "recover";
406 		else if (itag)
407 			globp = ivis ? "tag" : "tag|p";
408 		else if (argc)
409 			globp = "next";
410 		if (ivis)
411 			initev = globp;
412 		else if (globp) {
413 			inglobal = 1;
414 			commands(1, 1);
415 			inglobal = 0;
416 		}
417 	}
418 
419 	/*
420 	 * Vi command... go into visual.
421 	 * Strange... everything in vi usually happens
422 	 * before we ever "start".
423 	 */
424 	if (ivis) {
425 		/*
426 		 * Don't have to be upward compatible with stupidity
427 		 * of starting editing at line $.
428 		 */
429 		if (dol > zero)
430 			dot = one;
431 		globp = "visual";
432 		if (setexit() == 0)
433 			commands(1, 1);
434 	}
435 
436 	/*
437 	 * Clear out trash in state accumulated by startup,
438 	 * and then do the main command loop for a normal edit.
439 	 * If you quit out of a 'vi' command by doing Q or ^\,
440 	 * you also fall through to here.
441 	 */
442 	seenprompt = 1;
443 	ungetchar(0);
444 	globp = 0;
445 	initev = 0;
446 	setlastchar('\n');
447 	setexit();
448 	commands(0, 0);
449 	cleanup(1);
450 	ex_exit(0);
451 }
452 
453 /*
454  * Initialization, before editing a new file.
455  * Main thing here is to get a new buffer (in fileinit),
456  * rest is peripheral state resetting.
457  */
init()458 init()
459 {
460 	register int i;
461 
462 	fileinit();
463 	dot = zero = truedol = unddol = dol = fendcore;
464 	one = zero+1;
465 	undkind = UNDNONE;
466 	chng = 0;
467 	edited = 0;
468 	for (i = 0; i <= 'z'-'a'+1; i++)
469 		names[i] = 1;
470 	anymarks = 0;
471 }
472 
473 /*
474  * Return last component of unix path name p.
475  */
476 char *
tailpath(p)477 tailpath(p)
478 register char *p;
479 {
480 	register char *r;
481 
482 	for (r=p; *p; p++)
483 		if (*p == '/')
484 			r = p+1;
485 	return(r);
486 }
487 
488 /*
489  * Check ownership of file.  Return nonzero if it exists and is owned by the
490  * user or the option sourceany is used
491  */
iownit(file)492 iownit(file)
493 char *file;
494 {
495 	struct stat sb;
496 
497 	if (stat(file, &sb) == 0 && (value(SOURCEANY) || sb.st_uid == getuid()))
498 		return(1);
499 	else
500 		return(0);
501 }
502