Debian Codegraph @

jove.c

raw
1 /**************************************************************************
2 * This program is Copyright (C) 1986-2002 by Jonathan Payne. JOVE is *
3 * provided by Jonathan and Jovehacks without charge and without *
4 * warranty. You may copy, modify, and/or distribute JOVE, provided that *
5 * this notice is included in all the source files and documentation. *
6 **************************************************************************/
7
8 /* Contains the main loop initializations, and some system dependent
9 type things, e.g. putting terminal in CBREAK mode, etc. */
10
11 #include "jove.h"
12 #include "fp.h"
13 #include "jctype.h"
14 #include "chars.h"
15 #include "disp.h"
16 #include "re.h" /* for dosearch() */
17 #include "reapp.h" /* for find_tag(), UseRE */
18 #include "rec.h"
19 #include "ask.h"
20 #include "extend.h"
21 #include "fmt.h"
22 #include "macros.h"
23 #include "marks.h"
24 #include "mouse.h"
25 #ifndef MAC /* Mac does without! */
26 # include "paths.h"
27 #endif
28 #include "proc.h"
29 #include "screen.h"
30 #include "term.h"
31 #include "version.h"
32 #include "wind.h"
33
34 #ifdef IPROCS
35 # include "iproc.h"
36 #endif
37
38 #ifdef USE_SELECT
39 # include <sys/time.h>
40 # include "select.h"
41 #endif
42
43 #ifdef SCO /* ??? what is this for? */
44 # include <sys/stream.h>
45 # include <sys/ptem.h>
46 #endif
47
48 #include <signal.h>
49
50 #ifdef MAC
51 # include "mac.h"
52 #else /* !MAC */
53 # include <sys/stat.h>
54 #endif /* !MAC */
55
56 #ifdef MSDOS
57 # include <bios.h>
58 # include <dos.h>
59 # include <time.h>
60 # define SIGHUP 99
61 # ifdef OWCDOS
62 # include <malloc.h> /* for _heapgrow */
63 # endif
64 #endif /* MSDOS */
65
66 #ifdef WIN32
67 # undef Fill /* sigh, used as a field name in some windows header! */
68 # undef CR /* sigh, used as a field name in some windows header! */
69 # undef Fill /* sigh, used as a field name in some windows header! */
70 # include <windows.h> /* needed for CreateProcess */
71 # undef FIONREAD /* This is defined but ioctl isn't so we cannot use it. */
72 extern char *getLastErrorString(void);
73 #endif
74
75 #ifdef STACK_DECL /* provision for setting up appropriate stack */
76 STACK_DECL
77 #endif
78
79 /*
80 * This is the maximum length of the basename of files in
81 * ShareDir or LibDir (plus 1 for leading slash), as a check
82 * if the specified paths, even if they fit in FILESIZE, are
83 * too long to be used subsequently. At the moment, in
84 * ShareDir, "teach-jove" at 10 chars is currently the longest
85 * filename, while in LibDir, "portsrv" or "recover" only go
86 * over to 11 chars if ".exe" is appended to them for
87 * MSFILESYSTEM (DOS or Windows), so 14 seems plenty (and is
88 * also a little tribute to the traditional early Unix
89 * filesystem maximum!)
90 */
91 #define MAXBASENAMELEN (1+14+1)
92
93 private void
94 UnsetTerm(jbool),
95 DoKeys(jbool),
96 ShowKeyStrokes(void),
97 jexecpath(char *, size_t);
98
99 #ifdef NONBLOCKINGREAD
100 private void setblock(jbool on);
101 #endif
102
103 #ifdef POSIX_SIGS
104 /* simulate BSD's safe signal() */
105 SIGHANDLERTYPE
106 setsighandler(int signo, SIGHANDLERTYPE handler)
107 {
108 static struct sigaction act; /* static so unspecified fields are 0 */
109 struct sigaction oact;
110
111 act.sa_handler = handler;
112 sigemptyset(&act.sa_mask);
113 sigaddset(&act.sa_mask, signo);
114 sigaction(signo, &act, &oact);
115 return oact.sa_handler;
116 }
117 #endif
118
119 jbool TimeDisplayed = YES; /* is time actually displayed in modeline? */
120 char JoveFeatures[MAXCOLS]; /* VAR: list of compiled-in features */
121
122 #ifdef UNIX
123
124 /* set things up to update the modeline every UpdFreq seconds */
125
126 int UpdFreq = 30; /* VAR: how often to update modeline */
127 jbool InSlowRead = NO;
128
129 /* unset alarm if none needed */
130 void
131 SetClockAlarm(jbool unset)
132 {
133 if (TimeDisplayed && UpdFreq != 0)
134 (void) alarm((unsigned) (UpdFreq - (time((time_t *)NULL) % UpdFreq)));
135 else if (unset)
136 alarm((unsigned)0);
137 }
138
139 /* AlarmHandler gets all SIGALRMs. It decides, based on InWaitChar,
140 * whether this is an alarm for updating the mode line or for showing
141 * keystrokes. Theoretically, InWaitChar is a state variable that ought
142 * to be reset in complain and other exceptional cases, but waitchar
143 * is called often enough that it turns out to be self-correcting.
144 */
145
146 private volatile jbool InWaitChar = NO;
147
148 /*ARGSUSED*/
149 private SIGRESTYPE
150 AlarmHandler(int UNUSED(junk))
151 {
152 int save_errno = errno; /* Subtle, but necessary! */
153
154 resetsighandler(SIGALRM, AlarmHandler);
155 if (InWaitChar) {
156 if (InSlowRead) {
157 InSlowRead = NO;
158 ShowKeyStrokes();
159 redisplay();
160 InSlowRead = YES;
161 InWaitChar = NO; /* might as well allow modeline updates */
162 SetClockAlarm(NO);
163 } else {
164 alarm((unsigned)1); /* try again later */
165 }
166 } else {
167 UpdModLine = YES;
168 if (InSlowRead) {
169 /* needed because of stupid BSD restartable I/O */
170 InSlowRead = NO;
171 redisplay();
172 InSlowRead = YES;
173 }
174 SetClockAlarm(NO);
175 }
176 errno = save_errno;
177 return SIGRESVALUE;
178 }
179
180 #endif /* UNIX */
181
182 jbool stickymsg; /* the last message should stick around */
183
184 char NullStr[] = "";
185 jmp_buf mainjmp;
186
187 #ifdef USE_SELECT
188 fd_set global_fd; /* set of file descriptors of interest (for select) */
189 int global_maxfd;
190 #endif
191
192 /* paths */
193
194 /* VAR: directory path of machine-independent library with joverc, docs, etc */
195 char ShareDir[FILESIZE] = SHAREDIR;
196
197 /* VAR: directory/device to store tmp files */
198 char TmpDir[FILESIZE] = TMPDIR;
199
200 #ifdef SUBSHELL
201 char
202 Shell[FILESIZE] = DFLTSHELL, /* VAR: shell to use */
203 # ifdef MSFILESYSTEM
204 ShFlags[sizeof(ShFlags)] = "/c"; /* VAR: flags to shell */
205 # else
206 ShFlags[sizeof(ShFlags)] = "-c"; /* VAR: flags to shell */
207 # endif /* MSFILESYSTEM */
208 #endif
209
210 /* VAR: directory path of machine-dependent library (for Portsrv and Recover) */
211
212 #if defined(SUBSHELL) && (defined(PIPEPROCS) || defined(RECOVER))
213 # define NEED_LIBDIR 1
214 char LibDir[FILESIZE] = LIBDIR;
215 #endif
216
217 /* finish: handle bad-news signals.
218 * It also handles internally generated requests for termination.
219 * For most values of code (signal types) an attempt
220 * is made to save the buffers for recovery by "recover".
221 * For most values of code, this routine stops JOVE
222 * by calling abort, which causes a core dump under UNIX.
223 *
224 * - code -1 is an internally generated request to die with an
225 * attempt to save the buffers. It had better not be the code
226 * for some real signal (it cannot be one under UNIX).
227 *
228 * - code 0 is an internally generated request to die quietly.
229 * It had better not be the code for some real signal
230 * (it cannot be one under UNIX). This is the only code
231 * for which buffers are not saved.
232 *
233 * - SIGHUP is caused by loss of connection. This code and
234 * code 0 are the only ones which don't cause an abort.
235 * Generated by OS and by JOVE itself.
236 */
237
238 SIGRESTYPE
239 finish(int code)
240 {
241 #ifdef RECOVER
242 int save_errno = errno; /* Subtle, but necessary! */
243 #endif
244 jbool DelTmps = YES; /* Usually we delete them. */
245
246 DisabledRedisplay = YES;
247 #ifndef MAC
248 UnsetTerm(NO);
249 #endif
250 #ifdef PIPEPROCS
251 kbd_kill(); /* kill the keyboard process */
252 #endif
253 #ifdef RECOVER
254 if (code != 0) {
255 static jbool Crashing = NO; /* we are in the middle of crashing */
256
257 if (!Crashing) {
258 Crashing = YES;
259 lsave();
260 SyncRec();
261 writef("JOVE CRASH!! (code %d; last errno %d)\n",
262 code, save_errno);
263 if (ModBufs(YES)) {
264 writef("Your buffers have been saved.\n");
265 writef("Use \"jove -r\" to have a look at them.\n");
266 DelTmps = NO; /* Don't delete anymore. */
267 } else {
268 writef("No buffers needed saving: you didn't lose any work.\n");
269 }
270 } else {
271 writef("\r\nYou may have lost your work!\n");
272 }
273 }
274 #endif /* RECOVER */
275 flushscreen();
276 if (DelTmps) {
277 tmpremove();
278 #ifdef RECOVER
279 recremove();
280 #endif /* RECOVER */
281 }
282 #ifdef UNIX
283 if (code != 0 && code != SIGHUP)
284 abort();
285 #endif /* UNIX */
286 EXIT(0);
287 /*NOTREACHED*/
288 }
289
290 /* SIGINT is caused by the user hitting the INTR key.
291 * We give him a choice of death or continuation.
292 */
293 private SIGRESTYPE
294 handle_sigint(int code)
295 {
296 int save_errno = errno; /* Subtle, but necessary! */
297 char c;
298 #ifdef WIN32
299 c = FatalErrorMessage("Fatal interrupt encountered. Abort?");
300 #else /* !WIN32 */
301 # ifdef PIPEPROCS
302 jbool started;
303 # endif
304
305 resetsighandler(SIGINT, handle_sigint);
306 f_mess("Abort (Type 'n' if you're not sure)? ");
307 Placur(ILI, jmin(CO - 2, calc_pos(mesgbuf, MAXCOLS)));
308 flushscreen();
309 # ifdef UNIX
310 # ifdef PIPEPROCS
311 started = kbd_stop();
312 # endif
313 /*
314 * Yuk! This doesn't deal with all cases, we really need a
315 * standard jove input routine that's lower than kbd_getch so
316 * that this can use it. The code that this replaces was even
317 * more ugly. What about nonblocking reads? -- MM.
318 */
319 # ifdef NONBLOCKINGREAD
320 setblock(YES); /* turn blocking on (in case it was off) */
321 # endif
322 do {
323 c = 'n';
324 } while (read(0, &c, sizeof c) < 0 && RETRY_ERRNO(errno));
325 # ifdef PIPEPROCS
326 if (started)
327 kbd_strt();
328 # endif /* PIPEPROCS */
329 # endif /* UNIX */
330 # ifdef MSDOS
331 c = getrawinchar();
332 # endif /* MSDOS */
333 message(NullStr);
334 #endif /* !WIN32 */
335 if (c == 'y') {
336 errno = save_errno;
337 finish(code);
338 /* NOTREACHED */
339 }
340 redisplay();
341 errno = save_errno;
342 return SIGRESVALUE;
343 }
344
345 private char smbuf[20],
346 *bp = smbuf;
347 private int nchars = 0;
348
349 #ifdef NONBLOCKINGREAD
350
351 private void
352 setblock(jbool on) /* turn blocking on or off */
353 {
354 static int blockf, nonblockf;
355 static jbool first = YES;
356
357 if (first) {
358 int flags;
359
360 first = NO;
361 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
362 finish(SIGHUP);
363 # ifdef O_NONBLOCK /* POSIX form */
364 blockf = flags & ~O_NONBLOCK; /* make sure O_NONBLOCK is off */
365 nonblockf = flags | O_NONBLOCK; /* make sure O_NONBLOCK is on */
366 # else /* pre-POSIX form */
367 blockf = flags & ~O_NDELAY; /* make sure O_NDELAY is off */
368 nonblockf = flags | O_NDELAY; /* make sure O_NDELAY is on */
369 # endif
370 }
371 if (fcntl(0, F_SETFL, on ? blockf : nonblockf) == -1)
372 finish(SIGHUP);
373 }
374
375 #endif /* NONBLOCKINGREAD */
376
377 /* To optimize screen refreshing, we try to detect if there is pending input.
378 * If there is, we defer screen updating, hoping that when we eventually
379 * do an update it will be more efficient. To implement this, we use
380 * charp to poll for pending input (from any source but macro body).
381 * "InputPending" records the last value returned by charp, or what
382 * was known by kbd_getch or kbd_ungetch. Note that the kbd_* routines
383 * only consider keyboard input, but charp considers other sources of
384 * input. These are the only routines that should set InputPending
385 * (currently, a fudge to redisplay for the mac also sets it --
386 * this should be fixed).
387 *
388 * This heuristic confuses the user if a command takes a long time:
389 * the screen may be "frozen" in an inaccurate state until the command
390 * completes. The variable "SlowCmd" is a count of the nesting of slow
391 * commands. If it is positive, display updating is not pre-empted.
392 * The macros PreEmptOutput() and CheapPreEmptOutput() implement the tests.
393 */
394
395 int SlowCmd = 0; /* depth of nesting of slow commands */
396
397 jbool InputPending = NO; /* is there input waiting to be processed? */
398
399 /* Inputp is used to jam a NUL-terminated string into JOVE's input stream.
400 * It is used to feed each line of the joverc file, to fill in the default
401 * make_cmd in compile-it, and to fill in the default i-search string.
402 * To make this work, we prevent i-search and compile-it from using Inputp
403 * when it is already in use.
404 */
405 char *Inputp = NULL;
406
407 /* kbd_ungetch must only be used to push back a character that
408 * was just returned by kbd_getch.
409 */
410 private ZXchar kbdpeek = EOF;
411
412 void
413 kbd_ungetch(ZXchar c)
414 {
415 InputPending = YES;
416 kbdpeek = c;
417 }
418
419 ZXchar
420 kbd_getch(void)
421 {
422 ZXchar c;
423
424 if (kbdpeek != EOF) {
425 c = kbdpeek;
426 kbdpeek = EOF;
427 InputPending = nchars > 0;
428 return c;
429 }
430 #if NCHARS != UCHAR_ROOF
431 do {
432 #endif
433 while (nchars <= 0) {
434 bp = smbuf;
435 #ifdef MSDOS
436 *bp = getrawinchar();
437 nchars = 1;
438 #else /* !MSDOS */
439 # ifdef WIN32
440 if (UpdModLine || !charp()) {
441 redisplay();
442 flushscreen();
443 }
444 nchars = getInputEvents(smbuf, sizeof(smbuf));
445 # else /* !WIN32 */
446 # ifdef PTYPROCS
447 /* Get a character from the keyboard, first checking for
448 any input from a process. Handle that first, and then
449 deal with the terminal input. */
450 {
451 fd_set reads;
452 int
453 nfds,
454 fd;
455
456 bp = smbuf;
457 for (;;) {
458 while (procs_to_reap)
459 reap_procs(); /* synchronous process reaping */
460 reads = global_fd;
461 InSlowRead = YES;
462 nfds = select(global_maxfd,
463 &reads, (fd_set *)NULL, (fd_set *)NULL,
464 (struct timeval *)NULL);
465 InSlowRead = NO;
466 if (nfds >= 0)
467 break;
468
469 if (errno != EINTR) {
470 complain("\rerror in select: %s", strerror(errno));
471 /* NOTREACHED */
472 }
473 }
474
475 if (FD_ISSET(0, &reads)) {
476 do {
477 nchars = read(0, smbuf, sizeof smbuf);
478 } while (nchars < 0 && errno == EINTR);
479 if (nchars <= 0)
480 finish(SIGHUP);
481 nfds -= 1;
482 }
483 for (fd=1; nfds != 0; fd += 1) {
484 if (FD_ISSET(fd, &reads)) {
485 nfds -= 1;
486 read_pty_proc(fd);
487 if (UpdModLine)
488 redisplay();
489 }
490 }
491 }
492 # else /* !PTYPROCS */
493 # ifdef PIPEPROCS
494 if (NumProcs > 0) {
495 /* Handle process input until kbd input arrives */
496 struct header header;
497 size_t n;
498
499 InSlowRead = YES;
500 n = f_readn(ProcInput, (char *) &header, sizeof(header));
501 InSlowRead = NO;
502
503 if (n != sizeof(header)) {
504 raw_complain("\r\nError reading kbd process, expected %d, got %d bytes", sizeof header, n);
505 finish(SIGHUP);
506 /* NOTREACHED */
507 }
508 if (header.pid == kbd_pid) {
509 /* data is from the keyboard process */
510 nchars = f_readn(ProcInput, smbuf, (size_t)header.nbytes);
511 if (nchars != header.nbytes) {
512 raw_complain("\r\nError reading kbd process, expected %d, got %d bytes.", header.nbytes, nchars);
513 finish(SIGHUP);
514 /* NOTREACHED */
515 }
516 } else {
517 /* data is from an interactive process */
518 read_pipe_proc(header.pid, header.nbytes);
519 if (NumProcs == 0)
520 (void) kbd_stop();
521 if (UpdModLine)
522 redisplay();
523 }
524 } else /*...*/
525 # endif /* PIPEPROCS */
526 /*...*/ {
527 do {
528 # ifdef UNIX
529 InSlowRead = YES;
530 # endif
531 nchars = read(0, smbuf, sizeof smbuf);
532 # ifdef UNIX
533 InSlowRead = NO;
534 # endif
535 } while (nchars < 0 && RETRY_ERRNO(errno));
536 if (nchars <= 0)
537 finish(SIGHUP);
538 }
539 # endif /* !PTYPROCS */
540 # endif /* !WIN32 */
541 #endif /* !MSDOS */
542 }
543 c = ZXRC(*bp++);
544 #if !defined(PCNONASCII) && !defined(MAC) /* if not done elsewhere */
545 if ((c & METABIT) && MetaKey) {
546 *--bp = c & ~METABIT;
547 nchars += 1;
548 c = ESC;
549 }
550 #endif /* !defined(PCNONASCII) && !defined(MAC) */
551 InputPending = --nchars > 0;
552 #if NCHARS != UCHAR_ROOF
553 } while (c >= NCHARS); /* discard c if it is a bad char */
554 #endif
555 return c;
556 }
557
558 /* Returns YES if a character waiting (excluding macro body) */
559
560 jbool
561 charp(void)
562 {
563 if (InJoverc != 0 || kbdpeek != EOF || nchars > 0 || Inputp != NULL)
564 return InputPending = YES;
565
566 #ifdef FIONREAD
567 {
568 /*
569 * Some manual pages, notably SunOS4.1.3 say 'c' should be
570 * 'long', but that's a lie -- it's an 'int' according to all
571 * kernels I've seen (including SunOS4.1.3) and most other
572 * manual pages. At any rate, 'int' works correctly on 32- and
573 * 64-bit architectures, whereas long breaks on the 64
574 * bitters. -- MM.
575 */
576 int c;
577
578 if (ioctl(0, FIONREAD, &c) == -1)
579 c = 0;
580 return InputPending = c > 0;
581 }
582 #else /* !FIONREAD */
583 # ifdef NONBLOCKINGREAD
584 setblock(NO); /* turn blocking off */
585 nchars = read(0, smbuf, sizeof smbuf); /* Is anything there? */
586 setblock(YES); /* turn blocking on */
587 bp = smbuf; /* make sure bp points to it */
588 return InputPending = nchars > 0; /* just say we found something */
589 # else /* !NONBLOCKINGREAD */
590 # ifdef USE_SELECT
591 {
592 struct timeval timer;
593 fd_set readfds;
594
595 timer.tv_sec = 0;
596 timer.tv_usec = 0;
597 FD_ZERO(&readfds);
598 FD_SET(0, &readfds);
599 return InputPending = select(1,
600 &readfds, (fd_set *)NULL, (fd_set *)NULL,
601 &timer) > 0;
602 }
603 # else /* !USE_SELECT */
604 # ifdef MSDOS
605 return InputPending = rawkey_ready();
606 # else /* !MSDOS */
607 # ifdef MAC
608 return InputPending = rawchkc();
609 # else
610 # ifdef WIN32
611 return InputPending = inputEventWaiting(0);
612 # else
613 return InputPending = NO; /* who knows? */
614 # endif /* !WIN32 */
615 # endif /* !MAC */
616 # endif /* !MSDOS */
617 # endif /* !USE_SELECT */
618 # endif /* !NONBLOCKINGREAD */
619 #endif /* !FIONREAD */
620 }
621
622 /*
623 * Tries to pause for delay/10 seconds OR until a character is typed at the
624 * keyboard. This works well on systems with select() and not so well on the
625 * rest.
626 */
627
628 #ifdef MAC
629 # include <LoMem.h> /* defines Ticks */
630 #endif
631
632 void
633 SitFor(int delay)
634 {
635 #ifdef MAC
636 long
637 start,
638 end;
639
640 Keyonly = YES;
641 redisplay();
642 start = Ticks;
643
644 end = start + delay * 6;
645 do {} while (!charp() && Ticks < end);
646
647 #else /* !MAC */
648
649 # ifndef MSDOS
650 if (!charp()) {
651 # ifdef USE_SELECT
652 struct timeval timer;
653 fd_set readfds;
654
655 /* So messages that aren't error messages don't
656 * hang around forever.
657 * Gross that I had to snarf this from getch()
658 */
659 if (!UpdMesg && !Asking && mesgbuf[0] && !stickymsg)
660 message(NullStr);
661 redisplay();
662
663 timer.tv_sec = (delay / 10);
664 timer.tv_usec = (delay % 10) * 100000;
665 FD_ZERO(&readfds);
666 FD_SET(0, &readfds);
667 (void) select(1,
668 &readfds, (fd_set *)NULL, (fd_set *)NULL,
669 &timer);
670 # else /* ! USE_SELECT */
671 # ifdef WIN32
672 redisplay();
673 inputEventWaiting(delay*100);
674 # else /* ! WIN32 */
675 /* Pause by spitting NULs at the terminal. Ugh! */
676 static const int cps[] = {
677 0,
678 5,
679 7,
680 11,
681 13,
682 15,
683 20,
684 30,
685 60,
686 120,
687 180,
688 240,
689 480,
690 960,
691 1920,
692 1920,
693 };
694 int nchars,
695 check_cnt;
696
697 nchars = (delay * cps[ospeed]) / 10;
698 check_cnt = ScrBufSize;
699 redisplay();
700 if (!NP) {
701 while ((--nchars > 0) && !InputPending) {
702 scr_putchar(PC);
703 if (--check_cnt == 0) {
704 check_cnt = ScrBufSize;
705 (void) charp();
706 }
707 }
708 }
709 # endif /* !WIN32 */
710 # endif /* !USE_SELECT */
711 }
712 # else /* MSDOS */
713 /* All time representations must wrap eventually.
714 * Since all delays are much less than a minute, we represent
715 * time as hundredths of a second past the minute we start.
716 * NOTE: this is a busy wait. I know of no alternative.
717 */
718 int start,
719 now,
720 end;
721 struct dostime_t tc;
722
723 redisplay();
724 _dos_gettime(&tc);
725 start = tc.second * 100 + tc.hsecond;
726 end = start + delay * 10;
727 for (;;) {
728 if (charp())
729 break;
730
731 _dos_gettime(&tc);
732 now = tc.second * 100 + tc.hsecond;
733 if (now < start)
734 now += 60 * 100; /* must be in next minute */
735 if (now >= end)
736 break;
737 }
738 # endif /* MSDOS */
739 #endif /* !MAC */
740 }
741
742 #define WAITCHAR_CURSOR_DOWN 1 /* during slow keying, cursor is after displayed prefix */
743
744 private char
745 key_strokes[100],
746 *keys_p = key_strokes;
747
748 private jbool
749 in_ask_ks;
750
751 private volatile jbool
752 slow_keying = NO; /* for waitchar() */
753
754 void
755 cmd_sync(void)
756 {
757 if (this_cmd != ARG_CMD) {
758 clr_arg_value();
759 last_cmd = this_cmd;
760 slow_keying = NO;
761 in_ask_ks = NO;
762 keys_p = key_strokes;
763 }
764 }
765
766 ZXchar
767 ask_ks(void)
768 {
769 in_ask_ks = YES;
770 keys_p = key_strokes;
771 return waitchar();
772 }
773
774 void
775 add_stroke(ZXchar c)
776 {
777 if (keys_p < &key_strokes[sizeof (key_strokes) - 1])
778 *keys_p++ = c;
779 }
780
781 void
782 pp_key_strokes(char *buffer, size_t size)
783 {
784 char
785 *buf_end = buffer + size - 1,
786 *kp = key_strokes;
787
788 *buffer = '\0';
789 while (kp != keys_p) {
790 swritef(buffer, (size_t) (buf_end-buffer), "%p ", *kp++);
791 buffer += strlen(buffer);
792 }
793 }
794
795 private void
796 ShowKeyStrokes(void)
797 {
798 char buffer[100];
799
800 slow_keying = YES;
801 pp_key_strokes(buffer, sizeof (buffer));
802 f_mess(in_ask_ks? ": %f %s" : "%s", buffer);
803 #ifdef WAITCHAR_CURSOR_DOWN
804 Asking = YES;
805 AskingWidth = strlen(mesgbuf);
806 #endif
807 }
808
809 #define N_SEC 1 /* will be precisely 1 second on 4.2 */
810
811 ZXchar
812 waitchar(void)
813 {
814 ZXchar c;
815 #ifdef WAITCHAR_CURSOR_DOWN
816 jbool oldAsking;
817 int oldAskingWidth;
818 #endif
819
820 /* short circuit, if we can */
821 if (InJoverc || (!Interactive && in_macro()) || InputPending)
822 return getch();
823
824 #ifdef WAITCHAR_CURSOR_DOWN
825 oldAsking = Asking;
826 oldAskingWidth = AskingWidth;
827 #endif
828
829 #ifdef MAC
830 Keyonly = YES;
831 #endif
832 if (!slow_keying) {
833 /* not yet slow_keying */
834 #ifdef UNIX
835 /* set up alarm */
836 InWaitChar = YES;
837 (void) alarm((unsigned) N_SEC);
838 #else /* !UNIX */
839 # ifdef WIN32
840 if (!charp()) {
841 if ((slow_keying = !inputEventWaiting(N_SEC*1000))) {
842 ShowKeyStrokes();
843 }
844 }
845 # else /* !WIN32 */
846 /* NOTE: busy wait (until char typed or timeout)! */
847 time_t sw = N_SEC + time((time_t *)NULL);
848
849 while (!slow_keying && !charp()) {
850 if (time((time_t *)NULL) > sw) {
851 /* transition to slow_keying */
852 # ifdef MAC
853 menus_off();
854 # endif
855 ShowKeyStrokes();
856 }
857 }
858 # endif /* !WIN32 */
859 #endif /* !UNIX */
860 #ifdef WAITCHAR_CURSOR_DOWN
861 } else {
862 /* Already slow_keying: presume bottom line has old keystrokes.
863 * Tell refresh(?) to place cursor at end of them.
864 */
865 Asking = YES;
866 AskingWidth = strlen(mesgbuf);
867 #endif
868 }
869 c = getch();
870 if (slow_keying) {
871 ShowKeyStrokes();
872 #ifdef UNIX
873 } else {
874 /* not yet slow_keying: tear down alarm */
875 InWaitChar = NO;
876 SetClockAlarm(YES);
877 #endif
878 }
879
880 #ifdef WAITCHAR_CURSOR_DOWN
881 Asking = oldAsking;
882 AskingWidth = oldAskingWidth;
883 #endif
884 return c;
885 }
886
887 private void
888 SetTerm(void)
889 {
890 #ifdef IBMPCDOS
891 pcSetTerm();
892 #endif
893 ttysetattr(YES);
894 #ifdef TERMCAP
895 putpad(TI, 1); /* Cursor addressing start */
896 putpad(VS, 1); /* Visual start */
897 putpad(KS, 1); /* Keypad mode start */
898 # ifdef MOUSE
899 MouseOn();
900 # endif
901 #endif
902 #ifdef UNIX
903 (void) chkmail(YES); /* force it to check so we can be accurate */
904 #endif
905 }
906
907 private void
908 UnsetTerm(jbool WarnUnwritten)
909 {
910 #ifdef TERMCAP
911 # ifdef ID_CHAR
912 INSmode(NO);
913 # endif /* ID_CHAR */
914 # ifdef MOUSE
915 MouseOff();
916 # endif
917 putpad(KE, 1);
918 putpad(VE, 1);
919 Placur(ILI, 0);
920 putpad(CE, 1);
921 putpad(TE, 1);
922 #else /* !TERMCAP */
923 Placur(ILI, 0);
924 clr_eoln();
925 #endif /* !TERMCAP */
926 flushscreen();
927 #ifdef MSDOS
928 pcUnsetTerm();
929 #endif
930 ttysetattr(NO);
931 if (WarnUnwritten && ModBufs(NO))
932 raw_complain("[There are modified buffers]");
933 }
934
935 #ifdef JOB_CONTROL
936 void
937 PauseJove(void)
938 {
939 UnsetTerm(YES);
940 (void) kill(0, SIGTSTP);
941 SetTerm();
942 # ifdef WINRESIZE
943 /* Some systems (eg System V Release 4) don't give us SIGWINCHes
944 * that happen while we are away.
945 */
946 ResizePending = YES;
947 # endif
948 ClAndRedraw();
949 }
950 #endif /* JOB_CONTROL */
951
952 #ifdef SUBSHELL
953
954 # ifndef MSDOS
955 void
956 jcloseall(void)
957 {
958 tmpclose();
959 # ifdef RECOVER
960 recclose();
961 # endif
962 # ifdef IPROCS
963 closeiprocs();
964 # endif
965 }
966 # endif /* !MSDOS */
967
968 void
969 Push(void)
970 {
971 # ifdef MSDOS_PROCS
972 # ifdef MSDOS
973 UnsetTerm(YES);
974 /* Zortech's prototype for the third parameter to spawnl is missing "const" */
975 if (spawnl(0, Shell, (char *)jbasename(Shell), (char *)NULL) == -1)
976 s_mess("[Spawn failed %d]", errno);
977 SetTerm();
978 # ifdef WINRESIZE
979 /* Some systems (eg System V Release 4) don't give us SIGWINCHes
980 * that happen while we are away.
981 */
982 ResizePending = YES;
983 # endif
984 ClAndRedraw();
985 getCWD();
986 # else /* !MSDOS */
987 # ifdef WIN32
988 STARTUPINFO startinfo = { sizeof(STARTUPINFO) };
989 PROCESS_INFORMATION procinfo;
990 CreateProcess(Shell, NULL, NULL, NULL,
991 FALSE, CREATE_NEW_CONSOLE,
992 NULL, NULL,
993 &startinfo, &procinfo);
994 # endif /* WIN32 */
995 # endif /* !MSDOS */
996 # else /* !MSDOS_PROCS */
997 /* UNIX, or something like it */
998 SIGHANDLERTYPE old_int = setsighandler(SIGINT, SIG_IGN);
999 int forkerr = 0;
1000 # ifdef PIPEPROCS
1001 jbool started = kbd_stop();
1002 # endif
1003
1004 UnsetTerm(YES);
1005 switch (ChildPid = fork()) {
1006 case -1:
1007 /* parent, fork failed */
1008 forkerr = errno;
1009 break;
1010
1011 default:
1012 /* parent, fork worked */
1013 dowait((wait_status_t *) NULL);
1014 break;
1015
1016 case 0:
1017 /* child */
1018 /* (void) setsighandler(SIGTERM, SIG_DFL); */
1019 (void) setsighandler(SIGINT, SIG_DFL);
1020 jcloseall();
1021 /* note that curbuf->bfname may be NULL */
1022 execl(Shell, jbasename(Shell), "-is", pr_name(curbuf->b_fname, NO),
1023 (char *)NULL);
1024 raw_complain("[Execl failed: %s]", strerror(errno));
1025 _exit(1);
1026 /*NOTREACHED*/
1027 }
1028 SetTerm();
1029 # ifdef WINRESIZE
1030 /* Some systems (eg System V Release 4) don't give us SIGWINCHes
1031 * that happen while we are away.
1032 */
1033 ResizePending = YES;
1034 # endif
1035 ClAndRedraw();
1036 (void) setsighandler(SIGINT, old_int);
1037 SetClockAlarm(NO);
1038 # ifdef PIPEPROCS
1039 if (started)
1040 kbd_strt();
1041 # endif
1042 if (forkerr != 0) {
1043 complain("[Fork failed: %s]", strerror(errno));
1044 /* NOTREACHED */
1045 }
1046 # endif /* !MSDOS_PROCS */
1047 }
1048
1049 #endif /* SUBSHELL */
1050
1051 /* adjust the tty to reflect possible change to JOVE variables */
1052 void
1053 tty_adjust(void)
1054 {
1055 ttysetattr(YES);
1056 #ifdef MOUSE
1057 MouseOn(); /* XtermMouse might have changed */
1058 #endif
1059 }
1060
1061 jbool Interactive = NO; /* True when we invoke with the command handler? */
1062
1063 ZXchar
1064 peekchar = EOF, /* holds pushed-back getch output */
1065 LastKeyStruck; /* used by SelfInsert and friends */
1066
1067 jbool
1068 MetaKey = NO; /* VAR: this terminal has a meta key */
1069
1070 void
1071 Ungetc(ZXchar c)
1072 {
1073 peekchar = c;
1074 }
1075
1076 /*
1077 * input from macro always needs to be preceded by a check for
1078 * a character that may have been pushed back after a number
1079 * was gathered into argcount.
1080 */
1081 ZXchar
1082 peek_or_mac_getch(void)
1083 {
1084 ZXchar c;
1085 if ((c = peekchar) != EOF) {
1086 /* got input from pushback */
1087 peekchar = EOF;
1088 LastKeyStruck = c;
1089 } else if (!Interactive && (c = mac_getc()) != EOF) {
1090 /* might be in an execute-macro! */
1091 add_stroke(LastKeyStruck = c);
1092 }
1093 return c;
1094 }
1095
1096 /*
1097 * In joverc, or do_find, we need to run all macros to completion before
1098 * processing the next line, or any other input, which means reading and
1099 * dispatching mac_getc (while dealing with peekchar for numeric args)
1100 *
1101 * ??? This code (which was in do_find) is a fudge, and should be replaced
1102 * by a more elegant solution.
1103 */
1104 void
1105 dispatch_macros(void)
1106 {
1107 ZXchar c;
1108 int saved_tcmd = this_cmd;
1109 int saved_lcmd = last_cmd;
1110 int saved_as, saved_ac;
1111
1112 save_arg(saved_as, saved_ac);
1113 last_cmd = this_cmd = OTHER_CMD;
1114 for (;;) {
1115 cmd_sync();
1116 if ((c = peek_or_mac_getch()) == EOF)
1117 break;
1118 dispatch(c);
1119 }
1120 last_cmd = saved_lcmd;
1121 this_cmd = saved_tcmd;
1122 restore_arg(saved_as, saved_ac);
1123 }
1124
1125 ZXchar
1126 getch(void)
1127 {
1128 ZXchar c;
1129
1130 if (Inputp != NULL) {
1131 if ((c = ZXC(*Inputp++)) != '\0')
1132 return LastKeyStruck = c;
1133 /* done with all faux input */
1134 Inputp = NULL;
1135 }
1136 if (InJoverc && !in_macro()) {
1137 /* something is wrong if Inputp ran out (and
1138 * nothing from a macro) while reading a .joverc file.
1139 */
1140 complain("[command line too short]");
1141 /* NOTREACHED */
1142 }
1143
1144 #ifdef RECOVER
1145 if (ModCount >= SyncFreq) {
1146 ModCount = 0;
1147 SyncRec();
1148 }
1149 #endif /* RECOVER */
1150
1151 if ((c = peek_or_mac_getch()) == EOF) {
1152 if (!InJoverc) {
1153 /* So messages that aren't error messages don't
1154 * hang around forever.
1155 * Note: this code is duplicated in SitFor()!
1156 */
1157 if (!UpdMesg && !Asking && mesgbuf[0] != '\0' && !stickymsg)
1158 message(NullStr);
1159 redisplay();
1160 c = kbd_getch();
1161 if (!Interactive && InMacDefine)
1162 mac_putc(c);
1163 add_stroke(LastKeyStruck = c);
1164 }
1165 }
1166 return c;
1167 }
1168
1169 void
1170 TeachJove(void)
1171 {
1172 char tnamebuf[FILESIZE];
1173 PathCat(tnamebuf, sizeof(tnamebuf), HomeDir, TEACHJOVE);
1174 SetABuf(curbuf);
1175 SetBuf(do_find(curwind, tnamebuf, YES, NO));
1176 if (curbuf->b_first == curbuf->b_last) {
1177 char teachref[FILESIZE];
1178 PathCat(teachref, sizeof(teachref), ShareDir, TEACHJOVE);
1179 read_file(teachref, YES);
1180 }
1181 }
1182
1183 void
1184 ShowVersion(void)
1185 {
1186 s_mess("Jonathan's Own Version of Emacs (%s)", jversion);
1187 }
1188
1189 private void
1190 UNIX_cmdline(int argc, char *argv[])
1191 {
1192 long lineno = 0;
1193 int nwinds = 1;
1194 char *pattern = NULL;
1195
1196 while (argc > 1) {
1197 switch (argv[1][0]) {
1198 case '+':
1199 if ('0' <= argv[1][1] && argv[1][1] <= '9') {
1200 (void) chr_to_long(&argv[1][1], 10, NO, &lineno);
1201 break;
1202 } else switch (argv[1][1]) {
1203 case '\0':
1204 /* goto end of file just like some people's favourite editor */
1205 lineno = -1;
1206 break;
1207 case '/': /* search for pattern */
1208 /* check if syntax is +/pattern or +/ pattern */
1209 if (argv[1][2] != 0) {
1210 pattern = &argv[1][2];
1211 } else {
1212 argv += 1;
1213 argc -= 1;
1214 if (argv[1] != 0)
1215 pattern = &argv[1][0];
1216 }
1217 break;
1218 default:
1219 error("Invalid switch %s",argv[1]);
1220 /* NOTREACHED */
1221 }
1222 break;
1223 case '-':
1224 switch (argv[1][1]) {
1225 case 'd': /* Ignore current directory path */
1226 case 'D': /* Ignore debug file name */
1227 case 'l': /* Ignore libdir path */
1228 case 's': /* Ignore sharedir path */
1229 argv += 1;
1230 argc -= 1;
1231 break;
1232
1233 case 'J': /* Ignore jove.rc in SHAREDIR */
1234 case 'j': /* Ignore ~/.joverc */
1235 break;
1236 case 'p': /* parse errors in file */
1237 argv += 1;
1238 argc -= 1;
1239 if (argv[1] != NULL) {
1240 SetBuf(do_find(curwind, argv[1], YES, YES));
1241 ErrParse();
1242 nwinds = 0;
1243 }
1244 break;
1245 case 'T': /* teach-jove */
1246 TeachJove();
1247 break;
1248 case 't': /* find tag */
1249 /* check if syntax is -tTag or -t Tag */
1250 if (argv[1][2] != '\0') {
1251 find_tag(&(argv[1][2]), YES);
1252 } else {
1253 argv += 1;
1254 argc -= 1;
1255 if (argv[1] != NULL)
1256 find_tag(argv[1], YES);
1257 }
1258 break;
1259
1260 case 'w': /* multiple windows */
1261 if (argv[1][2] == '\0')
1262 nwinds += 1;
1263 else {
1264 int n;
1265
1266 (void) chr_to_int(&argv[1][2], 10, NO, &n);
1267 nwinds += -1 + n;
1268 }
1269 (void) div_wind(curwind, nwinds - 1);
1270 break;
1271 case '-': /* Ignore -- which visudo provides */
1272 break;
1273 default:
1274 error("Invalid switch %s",argv[1]);
1275 /* NOTREACHED */
1276 }
1277 break;
1278 default:
1279 /* Process a file argument.
1280 * We arrange that the last file that has a window
1281 * becomes the current buffer and that the last file
1282 * without a window (if any) becomes the alternate buffer.
1283 */
1284 minib_add(argv[1], nwinds > 0);
1285 if (nwinds > 0 || lineno != 0 || pattern != NULL) {
1286 Buffer
1287 *prevbuf = curbuf,
1288 *b = do_find(curwind, argv[1], YES, YES);
1289
1290 SetABuf(prevbuf);
1291 SetBuf(b);
1292 if (lineno > 0)
1293 SetLine(next_line(curbuf->b_first, lineno - 1));
1294 else if (lineno == -1)
1295 SetLine(curbuf->b_last);
1296 if (pattern != NULL) {
1297 Bufpos *bufp;
1298
1299 if ((bufp = dosearch(pattern, FORWARD, UseRE)) != NULL
1300 || (bufp = dosearch(pattern, BACKWARD, UseRE)) != NULL) {
1301 SetDot(bufp);
1302 } else {
1303 complain("Couldn't match pattern in file.");
1304 /* NOTREACHED */
1305 }
1306 }
1307 if (nwinds > 0) {
1308 nwinds -= 1;
1309 if (nwinds > 0)
1310 NextWindow();
1311 } else {
1312 /* We only borrowed the window:
1313 * let's restore the rightful tennant.
1314 * As a consolation, make this buffer the alternate.
1315 */
1316 SetABuf(b);
1317 SetBuf(prevbuf);
1318 tiewind(curwind, prevbuf);
1319 }
1320 } else {
1321 /* There is no need to actually read the file.
1322 * find the file, but don't force it, or select the buffer.
1323 * As a consolation, make this buffer the alternate.
1324 */
1325 SetABuf(do_find((Window *)NULL, argv[1], NO, YES));
1326 }
1327 lineno = 0;
1328 pattern = NULL;
1329 break;
1330 }
1331 argv += 1;
1332 argc -= 1;
1333 }
1334 }
1335
1336 void
1337 error(const char *fmt, ...)
1338 {
1339 va_list ap;
1340
1341 if (fmt) {
1342 va_start(ap, fmt);
1343 format(mesgbuf, sizeof mesgbuf, fmt, ap);
1344 va_end(ap);
1345 UpdMesg = YES;
1346 }
1347 rbell();
1348 longjmp(mainjmp, JMP_ERROR);
1349 /* NOTREACHED */
1350 }
1351
1352 void
1353 complain(const char *fmt, ...)
1354 {
1355 va_list ap;
1356
1357 if (fmt) {
1358 va_start(ap, fmt);
1359 format(mesgbuf, sizeof mesgbuf, fmt, ap);
1360 va_end(ap);
1361 UpdMesg = YES;
1362 }
1363 rbell();
1364 longjmp(mainjmp, JMP_COMPLAIN);
1365 /* NOTREACHED */
1366 }
1367
1368 /* format and display a message without using the normal display mechanisms */
1369
1370 void
1371 raw_complain(const char *fmt, ...)
1372 {
1373 char buf[MESG_SIZE];
1374 va_list ap;
1375 const char *bp;
1376 size_t rem;
1377 JSSIZE_T r;
1378
1379 va_start(ap, fmt);
1380 format(buf, sizeof(buf) - 2, fmt, ap);
1381 va_end(ap);
1382 strcat(buf, "\r\n"); /* \r *may* be redundant */
1383 for (bp = buf, rem = strlen(buf)
1384 ; rem > 0 && (r = write(2, bp, rem)) != (JSSIZE_T)rem
1385 ; bp += r, rem -= r) {
1386 if (r < 0 && !RETRY_ERRNO(errno))
1387 break; /* give up */
1388 }
1389 }
1390
1391 void
1392 confirm(const char *fmt, ...)
1393 {
1394 va_list ap;
1395
1396 va_start(ap, fmt);
1397 format(mesgbuf, sizeof mesgbuf, fmt, ap);
1398 va_end(ap);
1399 if (!yes_or_no_p("%s", mesgbuf)) {
1400 longjmp(mainjmp, JMP_COMPLAIN);
1401 /* NOTREACHED */
1402 }
1403 }
1404
1405 /* Recursive edit.
1406 * Guarantee: current buffer will still be current and
1407 * it will be in the current window. If not, complain!
1408 */
1409
1410 int RecDepth = 0;
1411
1412 void
1413 Recur(void)
1414 {
1415 Buffer *b = curbuf;
1416 Mark *m;
1417
1418 m = MakeMark(curline, curchar);
1419
1420 RecDepth += 1;
1421 UpdModLine = YES;
1422 DoKeys(NO); /* NO means not first time */
1423 UpdModLine = YES;
1424 RecDepth -= 1;
1425 if (!valid_bp(b)) {
1426 complain("Buffer gone!");
1427 /* NOTREACHED */
1428 }
1429 tiewind(curwind, b);
1430 SetBuf(b);
1431 if (!is_an_arg())
1432 ToMark(m);
1433 DelMark(m);
1434 }
1435
1436 jbool SaveOnExit = NO; /* VAR: offer to save buffers on exit */
1437
1438 private int iniargc; /* main sets these for DoKeys() */
1439 private char **iniargv;
1440
1441 private void
1442 DoKeys(jbool firsttime)
1443 {
1444 jmp_buf savejmp;
1445
1446 push_env(savejmp);
1447
1448 switch (setjmp(mainjmp)) {
1449 case 0:
1450 if (firsttime)
1451 UNIX_cmdline(iniargc, iniargv);
1452 break;
1453
1454 case JMP_QUIT:
1455 if (RecDepth == 0) {
1456 if (ModMacs()) {
1457 rbell();
1458 if (!yes_or_no_p("Some MACROS haven't been saved; leave anyway? "))
1459 break;
1460 }
1461 /* Maybe should offer to save macros too ? */
1462 if (ModBufs(NO)) {
1463 rbell();
1464 if (SaveOnExit)
1465 put_bufs(YES);
1466 else if (!yes_or_no_p("Some buffers haven't been saved; leave anyway? "))
1467 break;
1468 }
1469 #ifdef IPROCS
1470 if (!KillProcs())
1471 break; /* user chickened out */
1472 #endif
1473 }
1474 pop_env(savejmp);
1475 return;
1476
1477 case JMP_ERROR:
1478 getDOT(); /* God knows what state linebuf was in */
1479 /*FALLTHROUGH*/
1480 case JMP_COMPLAIN:
1481 {
1482 gc_openfiles(); /* close any files we left open */
1483 stickymsg = YES;
1484 unwind_macro_stack();
1485 Asking = NO;
1486 curwind->w_bufp = curbuf;
1487 DisabledRedisplay = NO;
1488 SlowCmd = 0;
1489 redisplay();
1490 break;
1491 }
1492 }
1493
1494 this_cmd = last_cmd = OTHER_CMD;
1495
1496 for (;;) {
1497 #ifdef MAC
1498 setjmp(auxjmp);
1499 #endif
1500 cmd_sync();
1501 #ifdef MAC
1502 HiliteMenu(0);
1503 EventCmd = NO;
1504 menus_on();
1505 #endif
1506 dispatch(getch());
1507 }
1508 }
1509
1510 private char **
1511 scanvec(char **args, char *str)
1512 {
1513 while (*args) {
1514 if (strcmp(*args, str) == 0)
1515 return args;
1516
1517 args += 1;
1518 }
1519 return NULL;
1520 }
1521
1522 #ifdef WINRESIZE
1523 /*ARGSUSED*/
1524 SIGRESTYPE
1525 win_reshape(int UNUSED(junk))
1526 {
1527 int save_errno = errno; /* Subtle, but necessary! */
1528
1529 ResizePending = YES;
1530 #ifdef UNIX
1531 resetsighandler(SIGWINCH, win_reshape);
1532 if (InSlowRead) {
1533 /* needed because of stupid BSD restartable I/O */
1534 InSlowRead = NO;
1535 redisplay();
1536 InSlowRead = YES;
1537 }
1538 #else
1539 redisplay();
1540 #endif
1541 errno = save_errno;
1542 return SIGRESVALUE;
1543 }
1544 #endif /* WINRESIZE */
1545
1546 private jbool
1547 carefulcpy(char *to, char *from, size_t maxsize, char *mess, jbool raw)
1548 {
1549 if (from != NULL) {
1550 const char *ugh;
1551
1552 if (strlen(from) >= maxsize)
1553 ugh = "too long";
1554 else if (*from == '\0')
1555 ugh = "empty";
1556 else {
1557 strcpy(to, from);
1558 return YES;
1559 }
1560 if (raw) {
1561 raw_complain("\r\n%s %s", mess, ugh);
1562 } else {
1563 swritef(mesgbuf, sizeof mesgbuf, "%s %s", mess, ugh);
1564 message(mesgbuf);
1565 }
1566 }
1567 return NO;
1568 }
1569
1570 #define envcpy(buf, varname) \
1571 carefulcpy(buf, getenv(varname), sizeof(buf), varname, NO)
1572
1573 private void
1574 dojovercs(jbool dosys, jbool dousr)
1575 {
1576 char Joverc[FILESIZE];
1577
1578 if (dosys) {
1579 PathCat(Joverc, sizeof(Joverc), ShareDir, "jove.rc");
1580 (void) joverc(Joverc); /* system wide jove.rc */
1581 }
1582
1583 if (dousr) {
1584 #ifdef MSFILESYSTEM
1585 /* We don't want to run the same rc file twice */
1586 if (!dosys || strcmp(HomeDir, ShareDir) != 0) {
1587 PathCat(Joverc, sizeof(Joverc), HomeDir, "jove.rc");
1588 (void) joverc(Joverc); /* jove.rc in home directory */
1589 }
1590 #else
1591 PathCat(Joverc, sizeof(Joverc), HomeDir, ".joverc");
1592 (void) joverc(Joverc); /* .joverc in home directory */
1593 #endif
1594 }
1595 }
1596
1597 private void
1598 setfeatures(void)
1599 {
1600 JoveFeatures[0] = '\0';
1601 #ifdef UNIX
1602 jamstrcat(JoveFeatures, ":unix", sizeof(JoveFeatures));
1603 #endif
1604 #ifdef MSDOS
1605 jamstrcat(JoveFeatures, ":msdos", sizeof(JoveFeatures));
1606 #endif
1607 #ifdef WIN32
1608 jamstrcat(JoveFeatures, ":win32", sizeof(JoveFeatures));
1609 #endif
1610 #ifdef MAC
1611 jamstrcat(JoveFeatures, ":mac", sizeof(JoveFeatures));
1612 #endif
1613 #ifdef IBMPCDOS
1614 jamstrcat(JoveFeatures, ":ibmpc", sizeof(JoveFeatures));
1615 #endif
1616 #ifdef ABBREV
1617 jamstrcat(JoveFeatures, ":abbr", sizeof(JoveFeatures));
1618 #endif
1619 #ifdef BACKUPFILES
1620 jamstrcat(JoveFeatures, ":bak", sizeof(JoveFeatures));
1621 #endif
1622 #ifdef CMT_FMT
1623 jamstrcat(JoveFeatures, ":cmtfmt", sizeof(JoveFeatures));
1624 #endif
1625 #ifdef F_COMPLETION
1626 jamstrcat(JoveFeatures, ":fcomp", sizeof(JoveFeatures));
1627 #endif
1628 #ifdef IPROCS
1629 jamstrcat(JoveFeatures, ":iproc", sizeof(JoveFeatures));
1630 #endif
1631 #ifdef PIPEPROCS
1632 jamstrcat(JoveFeatures, ":pipe", sizeof(JoveFeatures));
1633 #endif
1634 #ifdef PTYPROCS
1635 jamstrcat(JoveFeatures, ":pty", sizeof(JoveFeatures));
1636 #endif
1637 #ifdef LISP
1638 jamstrcat(JoveFeatures, ":lisp", sizeof(JoveFeatures));
1639 #endif
1640 #ifdef SUBSHELL
1641 jamstrcat(JoveFeatures, ":proc", sizeof(JoveFeatures));
1642 #endif
1643 #ifdef SPELL
1644 jamstrcat(JoveFeatures, ":spell", sizeof(JoveFeatures));
1645 #endif
1646 #ifdef RECOVER
1647 jamstrcat(JoveFeatures, ":rec", sizeof(JoveFeatures));
1648 #endif
1649 #ifdef JOB_CONTROL
1650 jamstrcat(JoveFeatures, ":job", sizeof(JoveFeatures));
1651 #endif
1652 #ifdef JSMALL
1653 jamstrcat(JoveFeatures, ":jsmall", sizeof(JoveFeatures));
1654 #endif
1655 #ifdef ID_CHAR
1656 jamstrcat(JoveFeatures, ":idchar", sizeof(JoveFeatures));
1657 #endif
1658 #ifdef HIGHLIGHTING
1659 jamstrcat(JoveFeatures, ":hl", sizeof(JoveFeatures));
1660 #endif
1661 #ifdef JTC
1662 jamstrcat(JoveFeatures, ":jtc", sizeof(JoveFeatures));
1663 #endif
1664 #ifdef TERMCAP
1665 jamstrcat(JoveFeatures, ":tcap", sizeof(JoveFeatures));
1666 #endif
1667 #ifdef TERMINFO
1668 jamstrcat(JoveFeatures, ":tinfo", sizeof(JoveFeatures));
1669 #endif
1670 #ifdef USE_CTYPE
1671 jamstrcat(JoveFeatures, ":ctype", sizeof(JoveFeatures));
1672 #endif
1673 #ifdef ISO_8859_1
1674 jamstrcat(JoveFeatures, ":iso88591", sizeof(JoveFeatures));
1675 #endif
1676 jamstrcat(JoveFeatures, ":", sizeof(JoveFeatures));
1677 jdbg("setfeatures \"%s\n", JoveFeatures);
1678 }
1679
1680 /*
1681 * returns NULL if the input path is absolute, else returns a
1682 * pointer to the start of the relative path, which will be
1683 * the same as path for POSIX machines, or will strip off a
1684 * leading drive: for MSFILESYSTEM
1685 */
1686 private const char *
1687 relpathstart(const char *path)
1688 {
1689 const char *cp = path, c = *cp;
1690 jdbg("relpathstart \"%s\"\n", path);
1691 if (c == '/'
1692 #ifdef MSFILESYSTEM
1693 || c == '\\'
1694 || (((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
1695 && *++cp == ':' && (*++cp == '/' || *cp == '\\'))
1696 #endif
1697 ) {
1698 jdbg("absolute \"%c\" \"%c\"\n", c, *cp);
1699 return NULL; /* absolute */
1700 }
1701 #ifdef MSFILESYSTEM
1702 if (cp > path && path[1] == ':') {
1703 /*
1704 * should we complain, having a drive spec on a
1705 * relative path for ShareDir, LibDir is
1706 * confusing? For now, just skip it
1707 */
1708 jdbg("relative-drive \"%s\"\n", path+2);
1709 return path+2;
1710 }
1711 #endif
1712 jdbg("relative \"%s\"\n", path);
1713 return path;
1714 }
1715
1716 /*
1717 * if val is non-NULL, it overrides current value of var,
1718 * else uses var. If relative, the path to the Jove binary is
1719 * prepended to val, canonicalized with PathParse and stored
1720 * in var. Typically, var is either ShareDir or LibDir.
1721 * varname holds the name to indicate which one, for error messages.
1722 */
1723 private void
1724 fixrelpath(const char *val, char *var, const char *varname)
1725 {
1726 const char *rel;
1727 char tempbuf[FILESIZE];
1728 if (val == NULL)
1729 val = var;
1730 rel = relpathstart(val); /* NULL if not relative */
1731 if (rel) {
1732 jexecpath(tempbuf, sizeof(tempbuf));
1733 jamstrcat(tempbuf, rel, sizeof(tempbuf));
1734 } else {
1735 jamstrsub(tempbuf, val, sizeof(tempbuf));
1736 }
1737 PathParse(tempbuf, var);
1738 /*
1739 * check that there will be enough space for the
1740 * basename of the files in LibDir or ShareDir
1741 */
1742 if (strlen(var) > FILESIZE-MAXBASENAMELEN) {
1743 complain("%s \"%s\" too long", varname, var);
1744 /* NOTREACHED */
1745 }
1746
1747 }
1748
1749 int
1750 main(int argc, char *argv[])
1751 {
1752 char **argp;
1753
1754 #ifdef MAC
1755 MacInit(); /* initializes all */
1756 argc = getArgs(&argv);
1757 #endif
1758
1759 #ifdef OWCDOS
1760 /* Watcom C under DOS won't grow the near heap after any far
1761 * allocation, so we must bump it up to the full 64K now.
1762 */
1763 _heapgrow();
1764 #endif
1765
1766 iniargc = argc;
1767 iniargv = argv;
1768
1769 if ((argp = scanvec(argv, "-D")) != NULL) {
1770 jdpath = argp[1];
1771 jdbg("jove debug started %s\n",
1772 get_time((time_t *)NULL, (char *)NULL, 0, -1));
1773 }
1774 jdbg("MAXCOLS=%d\n", MAXCOLS);
1775 jdbg("NBUF=%d\n", NBUF);
1776 jdbg("JBUFSIZ=%d\n", JBUFSIZ);
1777 jdbg("NCHARS=%d\n", NCHARS);
1778
1779 if (setjmp(mainjmp)) {
1780 ttysetattr(NO);
1781 writef("\nAck! I can't deal with error \"%s\" now.\n", mesgbuf);
1782 flushscreen();
1783 return 1;
1784 }
1785
1786 #if defined(USE_CTYPE) && !defined(NO_SETLOCALE)
1787 /* make ctype reflect "native environment" */
1788 locale_adjust();
1789 #endif
1790
1791 #ifndef MAC /* no environment in MacOS */
1792 if (getenv("METAKEY"))
1793 MetaKey = YES;
1794
1795 if ((argp = scanvec(argv, "-d")) != NULL && chkCWD(argp[1]))
1796 setCWD(argp[1]);
1797 else
1798 getCWD(); /* After we setup curbuf in case we have to getwd() */
1799
1800 #ifdef MAC
1801 HomeDir = gethome();
1802 #else /* !MAC */
1803 HomeDir = getenv("HOME");
1804 if (HomeDir == NULL) {
1805 # ifdef MSDOS
1806 HomeDir = copystr(pwd()); /* guess at current (initial) directory */
1807 # else
1808 # ifdef WIN32
1809 /* Following are set up automatically by NT on logon. */
1810 char *homedrive = getenv("HOMEDRIVE");
1811 char *homepath = getenv("HOMEPATH");
1812
1813 if (homedrive != NULL && homepath != NULL) {
1814 char *p = emalloc(strlen(homedrive) + strlen(homepath) + 1);
1815
1816 strcpy(p, homedrive);
1817 strcat(p, homepath);
1818 HomeDir = p;
1819 } else {
1820 HomeDir = copystr(pwd());
1821 }
1822 # else /* !WIN32 */
1823 HomeDir = "/";
1824 # endif /* !WIN32 */
1825 # endif /* !MSDOS */
1826 }
1827 #endif /* !MAC */
1828 HomeLen = strlen(HomeDir);
1829
1830 /* Handle overrides for ShareDir and LibDir.
1831 * We take care to use the last specification.
1832 * LibDir is only accepted via -l, -sl, -ls, or
1833 * JOVELIB if NEED_LIBDIR is defined. PWD and HomeDir
1834 * must be setup before fixrelpath is called.
1835 */
1836 {
1837 char *so = getenv("JOVESHARE");
1838 # ifdef NEED_LIBDIR
1839 char *lo = getenv("JOVELIB");
1840 # endif
1841
1842 for (argp = argv; argp[0] != NULL && argp[1] != NULL; argp++) {
1843 if (strcmp(*argp, "-s") == 0)
1844 so = *++argp;
1845 # ifdef NEED_LIBDIR
1846 else if (strcmp(*argp, "-l") == 0)
1847 lo = *++argp;
1848 else if (strcmp(*argp, "-ls") == 0 || strcmp(*argp, "-sl") == 0)
1849 lo = so = *++argp;
1850 # endif
1851 }
1852 fixrelpath(so, ShareDir, "ShareDir");
1853 # ifdef NEED_LIBDIR
1854 fixrelpath(lo, LibDir, "LibDir");
1855 # endif /* NEED_LIBDIR */
1856
1857
1858 # ifdef PIPEPROCS
1859 PathCat(Portsrv, sizeof(Portsrv), LibDir, "portsrv");
1860 # endif
1861 }
1862
1863 /* import the temporary file path from the environment
1864 * and fix the string, so that we can append a slash
1865 * safely
1866 */
1867 # ifdef MSFILESYSTEM
1868 envcpy(TmpDir, "TEMP");
1869 # else
1870 envcpy(TmpDir, "TMPDIR");
1871 # endif
1872 {
1873 char *cp = &TmpDir[strlen(TmpDir)];
1874
1875 do {} while (cp != TmpDir && (*--cp == '/'
1876 # ifdef MSFILESYSTEM
1877 || *cp == '\\'
1878 # endif
1879 ));
1880 cp[1] = '\0';
1881 }
1882
1883 # ifdef SUBSHELL
1884 # ifdef MSFILESYSTEM /* ??? Is this the right test? */
1885 envcpy(Shell, "COMSPEC");
1886 /* SHELL, if present in DOS environment, will take precedence over COMSPEC */
1887 # endif /* MSFILESYSTEM */
1888 envcpy(Shell, "SHELL");
1889 # ifdef RECOVER
1890 if (scanvec(argv, "-r") != NULL) {
1891 char Recover[FILESIZE]; /* path to recover program (in LibDir) */
1892
1893 PathCat(Recover, sizeof(Recover), LibDir, "recover");
1894 # ifdef MSFILESYSTEM
1895 jamstrcat(Recover, ".exe", sizeof(Recover));
1896 if (spawnl(P_WAIT, Recover, "recover", "-d", TmpDir, (char *)NULL) == -1)
1897 # else /* !MSFILESYSTEM */
1898 if (execl(Recover, "recover", "-d", TmpDir, (char *) NULL) == -1)
1899 # endif /* !MSFILESYSTEM */
1900 {
1901 writef("%s: execl failed! %s\n", Recover, strerror(errno));
1902 EXIT(-1);
1903 }
1904 EXIT(0); /* only Win32, but no harm otherwise, avoids another ifdef */
1905 /* NOTREACHED */
1906 }
1907 # endif /* RECOVER */
1908 # endif /* SUBSHELL */
1909 #endif /* ! MAC */
1910
1911 getTERM(); /* Get terminal. */
1912 ttysetattr(YES);
1913 ttsize();
1914
1915 #ifdef UNIX
1916 # ifdef WINRESIZE
1917 (void) setsighandler(SIGWINCH, win_reshape);
1918 # endif
1919 #endif
1920
1921 #ifdef MAC
1922 InitEvents();
1923 #endif
1924 d_cache_init(); /* initialize the disk buffer cache */
1925 make_scr();
1926 flushscreen(); /* kludge: prevent interleaving output with diagnostic */
1927 mac_init(); /* Initialize Macros */
1928 winit(); /* Initialize Window */
1929 #ifdef PTYPROCS
1930 # ifdef SIGCHLD
1931 (void) setsighandler(SIGCHLD, sigchld_handler);
1932 # endif
1933 #endif
1934 #ifdef USE_SELECT
1935 FD_ZERO(&global_fd);
1936 FD_SET(0, &global_fd);
1937 global_maxfd = 1;
1938 #endif
1939 buf_init();
1940 InitKeymaps();
1941 settout(); /* not until we know baudrate */
1942 SetTerm();
1943 setfeatures();
1944 #ifdef UNIX
1945 envcpy(Mailbox, "MAIL");
1946 #endif
1947 dojovercs(scanvec(argv, "-J") == NULL, scanvec(argv, "-j") == NULL);
1948 ShowVersion(); /* but the 'carefulcpy's which follow might overwrite it */
1949 #ifdef SIGINT
1950 /*
1951 * Jove binds INTR to a key, typically ^], which can
1952 * sometimes get hit accidentally, but it prompts in the handler.
1953 */
1954 (void) setsighandler(SIGINT, handle_sigint);
1955 #endif
1956 #ifdef UNIX
1957 /*
1958 * always cleanup on HUP (terminal disconnected), or
1959 * TERM (typically, system going down)
1960 */
1961 (void) setsighandler(SIGHUP, finish);
1962 (void) setsighandler(SIGTERM, finish);
1963 # ifndef DEBUGCRASH
1964 /*
1965 * DEBUGCRASH means we do not set handlers for SIGBUS,
1966 * SIGSEGV, and SIGPIPE, so this can drop into a debugger or
1967 * leave a core file to assist debugging.
1968 */
1969 # ifdef SIGBUS
1970 (void) setsighandler(SIGBUS, finish);
1971 # endif /* SIGBUS */
1972 (void) setsighandler(SIGSEGV, finish);
1973 (void) setsighandler(SIGPIPE, finish);
1974 # endif /* DEBUGCRASH */
1975 (void) setsighandler(SIGALRM, AlarmHandler);
1976 SetClockAlarm(NO);
1977 #else
1978 UpdModLine = YES; /* so Windows updates mode line on first display */
1979 #endif /* UNIX */
1980 ClAndRedraw();
1981 flushscreen();
1982 RedrawDisplay(); /* start the redisplay process. */
1983 DoKeys(YES);
1984 finish(0);
1985 /* NOTREACHED */
1986 }
1987
1988 #ifdef PNAME_SYSCTL_OID
1989 /* FreeBSD, NetBSD */
1990 # include <sys/sysctl.h>
1991 #endif
1992
1993 #ifdef PNAME_DYLD
1994 # include <mach-o/dyld.h> /* MacOSX */
1995 #endif
1996
1997 /* determine and return the directory in which the jove executable resides */
1998 private void
1999 jexecpath(char *namebuf, size_t namebufsz)
2000 {
2001 const char *cp;
2002 namebuf[0] = '\0';
2003 #ifdef PNAME_GETEXECNAME
2004 if (namebuf[0] == '\0') {
2005 const char *ename = getexecname();
2006 if (ename) {
2007 jamstrsub(namebuf, ename, namebufsz);
2008 } else {
2009 complain("getexecname failed: %s", strerror(errno));
2010 /* NOTREACHED */
2011 }
2012 }
2013 #endif
2014 #ifdef PNAME_SYSCTL_OID
2015 /* FreeBSD, NetBSD */
2016 if (namebuf[0] == '\0') {
2017 static int oid[] = PNAME_SYSCTL_OID;
2018 size_t sz = namebufsz;
2019 int rc = sysctl(oid, sizeof(oid)/sizeof(oid[0]), namebuf, &sz, NULL, 0);
2020 if (rc < 0 || sz == 0) {
2021 complain("sysctl failed: %s", strerror(errno));
2022 /* NOTREACHED */
2023 }
2024 }
2025 #endif
2026 #ifdef PNAME_DYLD
2027 /* MacOSX */
2028 if (namebuf[0] == '\0') {
2029 size_t sz = namebufsz;
2030 int rc = _NSGetExecutablePath(namebuf, &sz);
2031 if (rc < 0 || sz == 0) {
2032 complain("_NSGetExecutablePath failed: %s", strerror(errno));
2033 /* NOTREACHED */
2034 }
2035 }
2036 #endif
2037 #ifdef WIN32
2038 /* Windows */
2039 if (namebuf[0] == '\0') {
2040 DWORD nc = GetModuleFileNameA(NULL, namebuf, namebufsz);
2041 if (nc == 0 || nc == namebufsz) {
2042 complain("GetModuleFileNameA failed: %s", getLastErrorString());
2043 /* NOTREACHED */
2044 }
2045 }
2046 #endif
2047 #ifdef PNAME_PROC_SELF
2048 /* Linux */
2049 if (namebuf[0] == '\0') {
2050 JSSIZE_T linklen;
2051 struct stat stbuf;
2052 const char *procself = "/proc/self/exe";
2053
2054 if (lstat(procself, &stbuf) == 0) {
2055 linklen = readlink(procself, namebuf, namebufsz);
2056 if (linklen < 0) {
2057 complain("readlink(%s) failed: %s", procself, strerror(errno));
2058 /* NOTREACHED */
2059 }
2060 namebuf[linklen] = '\0';
2061 }
2062 }
2063 #endif
2064 if (namebuf[0] == '\0') {
2065 jamstrsub(namebuf, iniargv[0], namebufsz);
2066 }
2067 cp = jbasename(namebuf);
2068 if (!cp) {
2069 complain("could not find basename for %s", namebuf);
2070 /* NOTREACHED */
2071 }
2072 namebuf[cp-namebuf] = '\0';
2073 }
2074