26763: fix problem on failed cd -s to relative path
[zsh.git] / Src / Zle / zle_main.c
blobef14342bc1ef1d475bd13cea1f31bc94ea68b1fe
1 /*
2 * zle_main.c - main routines for line editor
4 * This file is part of zsh, the Z shell.
6 * Copyright (c) 1992-1997 Paul Falstad
7 * All rights reserved.
9 * Permission is hereby granted, without written agreement and without
10 * license or royalty fees, to use, copy, modify, and distribute this
11 * software and to distribute modified versions of this software for any
12 * purpose, provided that the above copyright notice and the following
13 * two paragraphs appear in all copies of this software.
15 * In no event shall Paul Falstad or the Zsh Development Group be liable
16 * to any party for direct, indirect, special, incidental, or consequential
17 * damages arising out of the use of this software and its documentation,
18 * even if Paul Falstad and the Zsh Development Group have been advised of
19 * the possibility of such damage.
21 * Paul Falstad and the Zsh Development Group specifically disclaim any
22 * warranties, including, but not limited to, the implied warranties of
23 * merchantability and fitness for a particular purpose. The software
24 * provided hereunder is on an "as is" basis, and Paul Falstad and the
25 * Zsh Development Group have no obligation to provide maintenance,
26 * support, updates, enhancements, or modifications.
30 #include "zle.mdh"
31 #include "zle_main.pro"
33 #ifdef HAVE_POLL_H
34 # include <poll.h>
35 #endif
36 #if defined(HAVE_POLL) && !defined(POLLIN) && !defined(POLLNORM)
37 # undef HAVE_POLL
38 #endif
40 /* The input line assembled so far */
42 /**/
43 mod_export ZLE_STRING_T zleline;
45 /* Cursor position and line length in zle */
47 /**/
48 mod_export int zlecs, zlell;
50 /* != 0 if in a shell function called from completion, such that read -[cl] *
51 * will work (i.e., the line is metafied, and the above word arrays are OK). */
53 /**/
54 mod_export int incompctlfunc;
56 /* != 0 if we are in a new style completion function */
58 /**/
59 mod_export int incompfunc;
61 /* != 0 if completion module is loaded */
63 /**/
64 mod_export int hascompmod;
66 /* ZLRF_* flags passed to zleread() */
68 /**/
69 int zlereadflags;
71 /* ZLCON_* flags passed to zleread() */
73 /**/
74 int zlecontext;
76 /* != 0 if we're done editing */
78 /**/
79 int done;
81 /* location of mark */
83 /**/
84 int mark;
87 * Last character pressed.
89 * Depending how far we are with processing, the lastcharacter may
90 * be a single byte read (lastchar_wide_valid is 0, lastchar_wide is not
91 * valid) or a full wide character. This is needed because we can't be
92 * sure whether the user is typing old \M-style commands or multibyte
93 * input.
95 * Calling getfullchar or getrestchar is guaranteed to ensure we have
96 * a valid wide character (although this may be WEOF). In many states
97 * we know this and don't need to test lastchar_wide_valid.
100 /**/
101 mod_export int
102 lastchar;
103 #ifdef MULTIBYTE_SUPPORT
104 /**/
105 mod_export ZLE_INT_T lastchar_wide;
106 /**/
107 mod_export int
108 lastchar_wide_valid;
109 #endif
111 /* the bindings for the previous and for this key */
113 /**/
114 mod_export Thingy lbindk, bindk;
116 /* insert mode/overwrite mode flag */
118 /**/
119 int insmode;
121 /**/
122 mod_export int eofchar;
124 static int eofsent;
126 * Key timeout in hundredths of a second: we use time_t so
127 * that we only have the limits on one integer type to worry about.
129 static time_t keytimeout;
131 #if defined(HAVE_SELECT) || defined(HAVE_POLL)
132 /* Terminal baud rate */
134 static int baud;
135 static long costmult;
136 #endif
138 /* flags associated with last command */
140 /**/
141 mod_export int lastcmd;
143 /**/
144 mod_export Widget compwidget;
146 /* the status line, a null-terminated metafied string */
148 /**/
149 mod_export char *statusline;
151 /* The current history line and cursor position for the top line *
152 * on the buffer stack. */
154 /**/
155 int stackhist, stackcs;
157 /* != 0 if we are making undo records */
159 /**/
160 int undoing;
162 /* current modifier status */
164 /**/
165 mod_export struct modifier zmod;
167 /* Current command prefix status. This is normally 0. Prefixes set *
168 * this to 1. Each time round the main loop, this is checked: if it *
169 * is 0, the modifier status is reset; if it is 1, the modifier *
170 * status is left unchanged, and this flag is reset to 0. The *
171 * effect is that several prefix commands can be executed, and have *
172 * cumulative effect, but any other command execution will clear the *
173 * modifiers. */
175 /**/
176 int prefixflag;
178 /* Number of characters waiting to be read by the ungetbytes mechanism */
179 /**/
180 int kungetct;
182 /**/
183 mod_export char *zlenoargs[1] = { NULL };
185 static char **raw_lp, **raw_rp;
187 #ifdef FIONREAD
188 static int delayzsetterm;
189 #endif
192 * File descriptors we are watching as well as the terminal fd.
193 * These are all for reading; we don't watch for writes or exceptions.
195 /**/
196 int nwatch; /* Number of fd's we are watching */
197 /**/
198 int *watch_fds; /* The list of fds, not terminated! */
199 /**/
200 char **watch_funcs; /* The corresponding functions to call, normal array */
202 /* set up terminal */
204 /**/
205 mod_export void
206 zsetterm(void)
208 struct ttyinfo ti;
209 #if defined(FIONREAD)
210 int val;
211 #endif
213 if (fetchttyinfo) {
215 * User requested terminal to be returned to normal use,
216 * so remember the terminal settings if not frozen.
218 if (!ttyfrozen)
219 gettyinfo(&shttyinfo);
220 fetchttyinfo = 0;
223 #if defined(FIONREAD)
224 ioctl(SHTTY, FIONREAD, (char *)&val);
225 if (val) {
227 * Problems can occur on some systems when switching from
228 * canonical to non-canonical input. The former is usually
229 * set while running programmes, but the latter is necessary
230 * for zle. If there is input in canonical mode, then we
231 * need to read it without setting up the terminal. Furthermore,
232 * while that input gets processed there may be more input
233 * being typed (i.e. further typeahead). This means that
234 * we can't set up the terminal for zle *at all* until
235 * we are sure there is no more typeahead to come. So
236 * if there is typeahead, we set the flag delayzsetterm.
237 * Then getbyte() performs another FIONREAD call; if that is
238 * 0, we have finally used up all the typeahead, and it is
239 * safe to alter the terminal, which we do at that point.
241 delayzsetterm = 1;
242 return;
243 } else
244 delayzsetterm = 0;
245 #endif
247 /* sanitize the tty */
248 #ifdef HAS_TIO
249 shttyinfo.tio.c_lflag |= ICANON | ECHO;
250 # ifdef FLUSHO
251 shttyinfo.tio.c_lflag &= ~FLUSHO;
252 # endif
253 #else /* not HAS_TIO */
254 shttyinfo.sgttyb.sg_flags = (shttyinfo.sgttyb.sg_flags & ~CBREAK) | ECHO;
255 shttyinfo.lmodes &= ~LFLUSHO;
256 #endif
258 attachtty(mypgrp);
259 ti = shttyinfo;
260 #ifdef HAS_TIO
261 if (unset(FLOWCONTROL))
262 ti.tio.c_iflag &= ~IXON;
263 ti.tio.c_lflag &= ~(ICANON | ECHO
264 # ifdef FLUSHO
265 | FLUSHO
266 # endif
268 # ifdef TAB3
269 ti.tio.c_oflag &= ~TAB3;
270 # else
271 # ifdef OXTABS
272 ti.tio.c_oflag &= ~OXTABS;
273 # else
274 # ifdef XTABS
275 ti.tio.c_oflag &= ~XTABS;
276 # endif
277 # endif
278 # endif
279 #ifdef ONLCR
280 ti.tio.c_oflag |= ONLCR;
281 #endif
282 ti.tio.c_cc[VQUIT] =
283 # ifdef VDISCARD
284 ti.tio.c_cc[VDISCARD] =
285 # endif
286 # ifdef VSUSP
287 ti.tio.c_cc[VSUSP] =
288 # endif
289 # ifdef VDSUSP
290 ti.tio.c_cc[VDSUSP] =
291 # endif
292 # ifdef VSWTCH
293 ti.tio.c_cc[VSWTCH] =
294 # endif
295 # ifdef VLNEXT
296 ti.tio.c_cc[VLNEXT] =
297 # endif
298 VDISABLEVAL;
299 # if defined(VSTART) && defined(VSTOP)
300 if (unset(FLOWCONTROL))
301 ti.tio.c_cc[VSTART] = ti.tio.c_cc[VSTOP] = VDISABLEVAL;
302 # endif
303 eofchar = ti.tio.c_cc[VEOF];
304 ti.tio.c_cc[VMIN] = 1;
305 ti.tio.c_cc[VTIME] = 0;
306 ti.tio.c_iflag |= (INLCR | ICRNL);
307 /* this line exchanges \n and \r; it's changed back in getbyte
308 so that the net effect is no change at all inside the shell.
309 This double swap is to allow typeahead in common cases, eg.
311 % bindkey -s '^J' 'echo foo^M'
312 % sleep 10
313 echo foo<return> <--- typed before sleep returns
315 The shell sees \n instead of \r, since it was changed by the kernel
316 while zsh wasn't looking. Then in getbyte() \n is changed back to \r,
317 and it sees "echo foo<accept line>", as expected. Without the double
318 swap the shell would see "echo foo\n", which is translated to
319 "echo fooecho foo<accept line>" because of the binding.
320 Note that if you type <line-feed> during the sleep the shell just sees
321 \n, which is translated to \r in getbyte(), and you just get another
322 prompt. For type-ahead to work in ALL cases you have to use
323 stty inlcr.
325 Unfortunately it's IMPOSSIBLE to have a general solution if both
326 <return> and <line-feed> are mapped to the same character. The shell
327 could check if there is input and read it before setting it's own
328 terminal modes but if we get a \n we don't know whether to keep it or
329 change to \r :-(
332 #else /* not HAS_TIO */
333 ti.sgttyb.sg_flags = (ti.sgttyb.sg_flags | CBREAK) & ~ECHO & ~XTABS;
334 ti.lmodes &= ~LFLUSHO;
335 eofchar = ti.tchars.t_eofc;
336 ti.tchars.t_quitc =
337 ti.ltchars.t_suspc =
338 ti.ltchars.t_flushc =
339 ti.ltchars.t_dsuspc = ti.ltchars.t_lnextc = -1;
340 #endif
342 #if defined(TTY_NEEDS_DRAINING) && defined(TIOCOUTQ) && defined(HAVE_SELECT)
343 if (baud) { /**/
344 int n = 0;
346 while ((ioctl(SHTTY, TIOCOUTQ, (char *)&n) >= 0) && n) {
347 struct timeval tv;
349 tv.tv_sec = n / baud;
350 tv.tv_usec = ((n % baud) * 1000000) / baud;
351 select(0, NULL, NULL, NULL, &tv);
354 #endif
356 settyinfo(&ti);
359 static char *kungetbuf;
360 static int kungetsz;
363 * Note on ungetbyte and ungetbytes for the confused (pws):
364 * these are low level and deal with bytes before they
365 * have been converted into (possibly wide) characters.
366 * Hence the names.
369 /**/
370 void
371 ungetbyte(int ch)
373 if (kungetct == kungetsz)
374 kungetbuf = realloc(kungetbuf, kungetsz *= 2);
375 kungetbuf[kungetct++] = ch;
378 /**/
379 void
380 ungetbytes(char *s, int len)
382 s += len;
383 while (len--)
384 ungetbyte(*--s);
387 #if defined(pyr) && defined(HAVE_SELECT)
388 static int
389 breakread(int fd, char *buf, int n)
391 fd_set f;
393 FD_ZERO(&f);
394 FD_SET(fd, &f);
396 return (select(fd + 1, (SELECT_ARG_2_T) & f, NULL, NULL, NULL) == -1 ?
397 EOF : read(fd, buf, n));
400 # define read breakread
401 #endif
404 * Possible forms of timeout.
406 enum ztmouttp {
407 /* No timeout in use. */
408 ZTM_NONE,
410 * Key timeout in use (do_keytmout flag set). If this goes off
411 * we return without anything being read.
413 ZTM_KEY,
415 * Function timeout in use (from timedfns list).
416 * If this goes off we call any functions which have reached
417 * the time and then continue processing.
419 ZTM_FUNC,
421 * Timeout hit the maximum allowed; if it fires we
422 * need to recalculate. As we may use poll() for the timeout,
423 * which takes an int value in milliseconds, we might need this
424 * for times long in the future. (We make no attempt to extend
425 * the range of time beyond that of time_t, however; that seems
426 * like a losing battle.)
428 * For key timeouts we just limit the value to
429 * ZMAXTIMEOUT; that's already absurdly large.
431 * The following is the maximum signed range over 1024 (2^10), which
432 * is a little more convenient than 1000, but done differently
433 * to avoid problems with unsigned integers. We assume 8-bit bytes;
434 * there's no general way to fix up if that's wrong.
436 ZTM_MAX
437 #define ZMAXTIMEOUT ((time_t)1 << (sizeof(time_t)*8-11))
440 struct ztmout {
441 /* Type of timeout setting, see enum above */
442 enum ztmouttp tp;
444 * Value for timeout in 100ths of a second if type is not ZTM_NONE.
446 time_t exp100ths;
450 * See if we need a timeout either for a key press or for a
451 * timed function.
453 * do_keytmout is passed down from getbyte() here. If it is positive,
454 * we use the keytimeout value, which is in 100ths of a second (directly
455 * set from the parameter). If it is negative, we use -(do_keytmout+1)
456 * (i.e. the one's complement, to allow a zero value to be set). This
457 * is only used when calling into zle from outside to specify an
458 * explicit timeout. This is also in 100ths of a second.
461 static void
462 calc_timeout(struct ztmout *tmoutp, long do_keytmout)
464 if (do_keytmout && (keytimeout > 0 || do_keytmout < 0)) {
465 if (do_keytmout < 0)
466 tmoutp->exp100ths = (time_t)-do_keytmout;
467 else if (keytimeout > ZMAXTIMEOUT * 100 /* 24 days for a keypress???? */)
468 tmoutp->exp100ths = ZMAXTIMEOUT * 100;
469 else
470 tmoutp->exp100ths = keytimeout;
471 tmoutp->tp = ZTM_KEY;
472 } else
473 tmoutp->tp = ZTM_NONE;
475 if (timedfns) {
476 for (;;) {
477 LinkNode tfnode = firstnode(timedfns);
478 Timedfn tfdat;
479 time_t diff, exp100ths;
481 if (!tfnode)
482 break;
484 tfdat = (Timedfn)getdata(tfnode);
485 diff = tfdat->when - time(NULL);
486 if (diff < 0) {
487 /* Already due; call it and rescan. */
488 tfdat->func();
489 continue;
492 if (diff > ZMAXTIMEOUT) {
493 tmoutp->exp100ths = ZMAXTIMEOUT * 100;
494 tmoutp->tp = ZTM_MAX;
495 } else if (diff > 0) {
496 exp100ths = diff * 100;
497 if (tmoutp->tp != ZTM_KEY ||
498 exp100ths < tmoutp->exp100ths) {
499 tmoutp->exp100ths = exp100ths;
500 tmoutp->tp = ZTM_FUNC;
503 break;
505 /* In case we called a function which messed up the display... */
506 if (resetneeded)
507 zrefresh();
511 /* see calc_timeout for use of do_keytmout */
513 static int
514 raw_getbyte(long do_keytmout, char *cptr)
516 int ret;
517 struct ztmout tmout;
518 #if defined(HAS_TIO) && \
519 (defined(sun) || (!defined(HAVE_POLL) && !defined(HAVE_SELECT)))
520 struct ttyinfo ti;
521 #endif
522 #ifndef HAVE_POLL
523 # ifdef HAVE_SELECT
524 fd_set foofd;
525 # endif
526 #endif
528 calc_timeout(&tmout, do_keytmout);
531 * Handle timeouts and watched fd's. If a watched fd or a function
532 * timeout triggers we restart any key timeout. This is likely to
533 * be harmless: the combination is extremely rare and a function
534 * is likely to occupy the user for a little while anyway. We used
535 * to make timeouts take precedence, but we can't now that the
536 * timeouts may be external, so we may have both a permanent watched
537 * fd and a long-term timeout.
539 if ((nwatch || tmout.tp != ZTM_NONE)
540 #ifdef FIONREAD
541 && ! delayzsetterm
542 #endif
544 #if defined(HAVE_SELECT) || defined(HAVE_POLL)
545 int i, errtry = 0, selret;
546 # ifdef HAVE_POLL
547 int nfds;
548 struct pollfd *fds;
549 # endif
550 # if defined(HAS_TIO) && defined(sun)
552 * Yes, I know this is complicated. Yes, I know we
553 * already have three bits of code to poll the terminal
554 * down below. No, I don't want to do this either.
555 * However, it turns out on certain OSes, specifically
556 * Solaris, that you can't poll typeahead for love nor
557 * money without actually trying to read it. But
558 * if we are trying to select (and we need to if we
559 * are watching other fd's) we won't pick that up.
560 * So we just try and read it without blocking in
561 * the time-honoured (i.e. absurdly baroque) termios
562 * fashion.
564 gettyinfo(&ti);
565 ti.tio.c_cc[VMIN] = 0;
566 settyinfo(&ti);
567 ret = read(SHTTY, cptr, 1);
568 ti.tio.c_cc[VMIN] = 1;
569 settyinfo(&ti);
570 if (ret > 0)
571 return 1;
572 # endif
573 # ifdef HAVE_POLL
574 nfds = 1 + nwatch;
575 /* First pollfd is SHTTY, following are the nwatch fds */
576 fds = zalloc(sizeof(struct pollfd) * nfds);
577 fds[0].fd = SHTTY;
579 * POLLIN, POLLIN, POLLIN,
580 * Keep those fd's POLLIN...
582 fds[0].events = POLLIN;
583 for (i = 0; i < nwatch; i++) {
584 fds[i+1].fd = watch_fds[i];
585 fds[i+1].events = POLLIN;
587 # endif
588 for (;;) {
589 # ifdef HAVE_POLL
590 int poll_timeout;
592 if (tmout.tp != ZTM_NONE)
593 poll_timeout = tmout.exp100ths * 10;
594 else
595 poll_timeout = -1;
597 selret = poll(fds, errtry ? 1 : nfds, poll_timeout);
598 # else
599 int fdmax = SHTTY;
600 struct timeval *tvptr;
601 struct timeval expire_tv;
603 FD_ZERO(&foofd);
604 FD_SET(SHTTY, &foofd);
605 if (!errtry) {
606 for (i = 0; i < nwatch; i++) {
607 int fd = watch_fds[i];
608 FD_SET(fd, &foofd);
609 if (fd > fdmax)
610 fdmax = fd;
614 if (tmout.tp != ZTM_NONE) {
615 expire_tv.tv_sec = tmout.exp100ths / 100;
616 expire_tv.tv_usec = (tmout.exp100ths % 100) * 10000L;
617 tvptr = &expire_tv;
619 else
620 tvptr = NULL;
622 selret = select(fdmax+1, (SELECT_ARG_2_T) & foofd,
623 NULL, NULL, tvptr);
624 # endif
626 * Make sure a user interrupt gets passed on straight away.
628 if (selret < 0 && errflag)
629 break;
631 * Try to avoid errors on our special fd's from
632 * messing up reads from the terminal. Try first
633 * with all fds, then try unsetting the special ones.
635 if (selret < 0 && !errtry) {
636 errtry = 1;
637 continue;
639 if (selret == 0) {
641 * Nothing ready and no error, so we timed out.
643 switch (tmout.tp) {
644 case ZTM_NONE:
645 /* keeps compiler happy if not debugging */
646 #ifdef DEBUG
647 dputs("BUG: timeout fired with no timeout set.");
648 #endif
649 /* treat as if a key timeout triggered */
650 /*FALLTHROUGH*/
651 case ZTM_KEY:
652 /* Special value -2 signals nothing ready */
653 selret = -2;
654 break;
656 case ZTM_FUNC:
657 while (firstnode(timedfns)) {
658 Timedfn tfdat = (Timedfn)getdata(firstnode(timedfns));
660 * It's possible a previous function took
661 * a long time to run (though it can't
662 * call zle recursively), so recalculate
663 * the time on each iteration.
665 time_t now = time(NULL);
666 if (tfdat->when > now)
667 break;
668 tfdat->func();
670 /* Function may have messed up the display */
671 if (resetneeded)
672 zrefresh();
673 /* We need to recalculate the timeout */
674 /*FALLTHROUGH*/
675 case ZTM_MAX:
677 * Reached the limit of our range, but not the
678 * actual timeout; recalculate the timeout.
679 * We're cheating with the key timeout here:
680 * if one clashed with a function timeout we
681 * reconsider the key timeout from scratch.
682 * The effect of this is microscopic.
684 calc_timeout(&tmout, do_keytmout);
685 break;
688 * If we handled the timeout successfully,
689 * carry on.
691 if (selret == 0)
692 continue;
694 /* If error or unhandled timeout, give up. */
695 if (selret < 0)
696 break;
698 * If there's user input handle it straight away.
699 * This improves the user's ability to handle exceptional
700 * conditions like runaway output.
702 if (
703 # ifdef HAVE_POLL
704 (fds[0].revents & POLLIN)
705 # else
706 FD_ISSET(SHTTY, &foofd)
707 # endif
709 break;
710 if (nwatch && !errtry) {
712 * Copy the details of the watch fds in case the
713 * user decides to delete one from inside the
714 * handler function.
716 int lnwatch = nwatch;
717 int *lwatch_fds = zalloc(lnwatch*sizeof(int));
718 char **lwatch_funcs = zarrdup(watch_funcs);
719 memcpy(lwatch_fds, watch_fds, lnwatch*sizeof(int));
720 for (i = 0; i < lnwatch; i++) {
721 if (
722 # ifdef HAVE_POLL
723 (fds[i+1].revents & POLLIN)
724 # else
725 FD_ISSET(lwatch_fds[i], &foofd)
726 # endif
728 /* Handle the fd. */
729 LinkList funcargs = znewlinklist();
730 zaddlinknode(funcargs, ztrdup(lwatch_funcs[i]));
732 char buf[BDIGBUFSIZE];
733 convbase(buf, lwatch_fds[i], 10);
734 zaddlinknode(funcargs, ztrdup(buf));
736 # ifdef HAVE_POLL
737 # ifdef POLLERR
738 if (fds[i+1].revents & POLLERR)
739 zaddlinknode(funcargs, ztrdup("err"));
740 # endif
741 # ifdef POLLHUP
742 if (fds[i+1].revents & POLLHUP)
743 zaddlinknode(funcargs, ztrdup("hup"));
744 # endif
745 # ifdef POLLNVAL
746 if (fds[i+1].revents & POLLNVAL)
747 zaddlinknode(funcargs, ztrdup("nval"));
748 # endif
749 # endif
752 callhookfunc(lwatch_funcs[i], funcargs, 0, NULL);
753 if (errflag) {
754 /* No sensible way of handling errors here */
755 errflag = 0;
757 * Paranoia: don't run the hooks again this
758 * time.
760 errtry = 1;
762 freelinklist(funcargs, freestr);
765 /* Function may have invalidated the display. */
766 if (resetneeded)
767 zrefresh();
768 zfree(lwatch_fds, lnwatch*sizeof(int));
769 freearray(lwatch_funcs);
772 # ifdef HAVE_POLL
773 zfree(fds, sizeof(struct pollfd) * nfds);
774 # endif
775 if (selret < 0)
776 return selret;
777 #else
778 # ifdef HAS_TIO
779 ti = shttyinfo;
780 ti.tio.c_lflag &= ~ICANON;
781 ti.tio.c_cc[VMIN] = 0;
782 ti.tio.c_cc[VTIME] = tmout.exp100ths / 10;
783 # ifdef HAVE_TERMIOS_H
784 tcsetattr(SHTTY, TCSANOW, &ti.tio);
785 # else
786 ioctl(SHTTY, TCSETA, &ti.tio);
787 # endif
788 ret = read(SHTTY, cptr, 1);
789 # ifdef HAVE_TERMIOS_H
790 tcsetattr(SHTTY, TCSANOW, &shttyinfo.tio);
791 # else
792 ioctl(SHTTY, TCSETA, &shttyinfo.tio);
793 # endif
794 return (ret <= 0) ? ret : *cptr;
795 # endif
796 #endif
799 ret = read(SHTTY, cptr, 1);
801 return ret;
804 /* see calc_timeout for use of do_keytmout */
806 /**/
807 mod_export int
808 getbyte(long do_keytmout, int *timeout)
810 char cc;
811 unsigned int ret;
812 int die = 0, r, icnt = 0;
813 int old_errno = errno, obreaks = breaks;
815 if (timeout)
816 *timeout = 0;
818 #ifdef MULTIBYTE_SUPPORT
820 * Reading a single byte always invalidates the status
821 * of lastchar_wide. We may fix this up in getrestchar
822 * if this is the last byte of a wide character.
824 lastchar_wide_valid = 0;
825 #endif
827 if (kungetct)
828 ret = STOUC(kungetbuf[--kungetct]);
829 else {
830 #ifdef FIONREAD
831 if (delayzsetterm) {
832 int val;
833 ioctl(SHTTY, FIONREAD, (char *)&val);
834 if (!val)
835 zsetterm();
837 #endif
838 for (;;) {
839 int q = queue_signal_level();
840 dont_queue_signals();
841 r = raw_getbyte(do_keytmout, &cc);
842 restore_queue_signals(q);
843 if (r == -2) {
844 /* timeout */
845 if (timeout)
846 *timeout = 1;
847 return lastchar = EOF;
849 if (r == 1)
850 break;
851 if (r == 0) {
852 /* The test for IGNOREEOF was added to make zsh ignore ^Ds
853 that were typed while commands are running. Unfortuantely
854 this caused trouble under at least one system (SunOS 4.1).
855 Here shells that lost their xterm (e.g. if it was killed
856 with -9) didn't fail to read from the terminal but instead
857 happily continued to read EOFs, so that the above read
858 returned with 0, and, with IGNOREEOF set, this caused
859 an infinite loop. The simple way around this was to add
860 the counter (icnt) so that this happens 20 times and than
861 the shell gives up (yes, this is a bit dirty...). */
862 if ((zlereadflags & ZLRF_IGNOREEOF) && icnt++ < 20)
863 continue;
864 stopmsg = 1;
865 zexit(1, 0);
867 icnt = 0;
868 if (errno == EINTR) {
869 die = 0;
870 if (!errflag && !retflag && !breaks)
871 continue;
872 errflag = 0;
873 breaks = obreaks;
874 errno = old_errno;
875 return lastchar = EOF;
876 } else if (errno == EWOULDBLOCK) {
877 fcntl(0, F_SETFL, 0);
878 } else if (errno == EIO && !die) {
879 ret = opts[MONITOR];
880 opts[MONITOR] = 1;
881 attachtty(mypgrp);
882 zrefresh(); /* kludge! */
883 opts[MONITOR] = ret;
884 die = 1;
885 } else if (errno != 0) {
886 zerr("error on TTY read: %e", errno);
887 stopmsg = 1;
888 zexit(1, 0);
891 if (cc == '\r') /* undo the exchange of \n and \r determined by */
892 cc = '\n'; /* zsetterm() */
893 else if (cc == '\n')
894 cc = '\r';
896 ret = STOUC(cc);
899 * vichgbuf is raw bytes, not wide characters, so is dealt
900 * with here.
902 if (vichgflag) {
903 if (vichgbufptr == vichgbufsz)
904 vichgbuf = realloc(vichgbuf, vichgbufsz *= 2);
905 vichgbuf[vichgbufptr++] = ret;
907 errno = old_errno;
908 return lastchar = ret;
913 * Get a full character rather than just a single byte.
916 /**/
917 mod_export ZLE_INT_T
918 getfullchar(int do_keytmout)
920 int inchar = getbyte((long)do_keytmout, NULL);
922 #ifdef MULTIBYTE_SUPPORT
923 return getrestchar(inchar);
924 #else
925 return inchar;
926 #endif
930 /**/
931 #ifdef MULTIBYTE_SUPPORT
933 * Get the remainder of a character if we support multibyte
934 * input strings. It may not require any more input, but
935 * we haven't yet checked. The character previously returned
936 * by getbyte() is passed down as inchar.
939 /**/
940 mod_export ZLE_INT_T
941 getrestchar(int inchar)
943 char c = inchar;
944 wchar_t outchar;
945 int timeout;
946 static mbstate_t mbs;
949 * We are guaranteed to set a valid wide last character,
950 * although it may be WEOF (which is technically not
951 * a wide character at all...)
953 lastchar_wide_valid = 1;
955 if (inchar == EOF) {
956 /* End of input, so reset the shift state. */
957 memset(&mbs, 0, sizeof mbs);
958 return lastchar_wide = WEOF;
962 * Return may be zero if we have a NULL; handle this like
963 * any other character.
965 while (1) {
966 size_t cnt = mbrtowc(&outchar, &c, 1, &mbs);
967 if (cnt == MB_INVALID) {
969 * Invalid input. Hmm, what's the right thing to do here?
971 memset(&mbs, 0, sizeof mbs);
972 return lastchar_wide = WEOF;
974 if (cnt != MB_INCOMPLETE)
975 break;
978 * Always apply KEYTIMEOUT to the remains of the input
979 * character. The parts of a multibyte character should
980 * arrive together. If we don't do this the input can
981 * get stuck if an invalid byte sequence arrives.
983 inchar = getbyte(1L, &timeout);
984 /* getbyte deliberately resets lastchar_wide_valid */
985 lastchar_wide_valid = 1;
986 if (inchar == EOF) {
987 memset(&mbs, 0, sizeof mbs);
988 if (timeout)
991 * This case means that we got a valid initial byte
992 * (since we tested for EOF above), but the followup
993 * timed out. This probably indicates a duff character.
994 * Return a '?'.
996 lastchar = '?';
997 return lastchar_wide = L'?';
999 else
1000 return lastchar_wide = WEOF;
1002 c = inchar;
1004 return lastchar_wide = (ZLE_INT_T)outchar;
1006 /**/
1007 #endif
1010 /**/
1011 void
1012 zlecore(void)
1014 #if !defined(HAVE_POLL) && defined(HAVE_SELECT)
1015 struct timeval tv;
1016 fd_set foofd;
1018 FD_ZERO(&foofd);
1019 #endif
1021 pushheap();
1024 * A widget function may decide to exit the shell.
1025 * We never exit directly from functions, to allow
1026 * the shell to tidy up, so we have to test for
1027 * that explicitly.
1029 while (!done && !errflag && !exit_pending) {
1030 UNMETACHECK();
1032 statusline = NULL;
1033 vilinerange = 0;
1034 reselectkeymap();
1035 selectlocalmap(NULL);
1036 bindk = getkeycmd();
1037 if (bindk) {
1038 if (!zlell && isfirstln && !(zlereadflags & ZLRF_IGNOREEOF) &&
1039 lastchar == eofchar) {
1041 * Slight hack: this relies on getkeycmd returning
1042 * a value for the EOF character. However,
1043 * undefined-key is fine. That's necessary because
1044 * otherwise we can't distinguish this case from
1045 * a ^C.
1047 eofsent = 1;
1048 break;
1050 if (execzlefunc(bindk, zlenoargs, 0)) {
1051 handlefeep(zlenoargs);
1052 if (eofsent)
1053 break;
1055 handleprefixes();
1056 /* for vi mode, make sure the cursor isn't somewhere illegal */
1057 if (invicmdmode() && zlecs > findbol() &&
1058 (zlecs == zlell || zleline[zlecs] == ZWC('\n')))
1059 DECCS();
1060 if (undoing)
1061 handleundo();
1062 } else {
1063 errflag = 1;
1064 break;
1066 #ifdef HAVE_POLL
1067 if (baud && !(lastcmd & ZLE_MENUCMP)) {
1068 struct pollfd pfd;
1069 int to = cost * costmult / 1000; /* milliseconds */
1071 if (to > 500)
1072 to = 500;
1073 pfd.fd = SHTTY;
1074 pfd.events = POLLIN;
1075 if (!kungetct && poll(&pfd, 1, to) <= 0)
1076 zrefresh();
1077 } else
1078 #else
1079 # ifdef HAVE_SELECT
1080 if (baud && !(lastcmd & ZLE_MENUCMP)) {
1081 FD_SET(SHTTY, &foofd);
1082 tv.tv_sec = 0;
1083 if ((tv.tv_usec = cost * costmult) > 500000)
1084 tv.tv_usec = 500000;
1085 if (!kungetct && select(SHTTY+1, (SELECT_ARG_2_T) & foofd,
1086 NULL, NULL, &tv) <= 0)
1087 zrefresh();
1088 } else
1089 # endif
1090 #endif
1091 if (!kungetct)
1092 zrefresh();
1094 freeheap();
1097 region_active = 0;
1098 popheap();
1101 /* Read a line. It is returned metafied. */
1103 /**/
1104 char *
1105 zleread(char **lp, char **rp, int flags, int context)
1107 char *s;
1108 int old_errno = errno;
1109 int tmout = getiparam("TMOUT");
1110 Thingy initthingy;
1112 #if defined(HAVE_POLL) || defined(HAVE_SELECT)
1113 /* may not be set, but that's OK since getiparam() returns 0 == off */
1114 baud = getiparam("BAUD");
1115 costmult = (baud) ? 3840000L / baud : 0;
1116 #endif
1118 /* ZLE doesn't currently work recursively. This is needed in case a *
1119 * select loop is used in a function called from ZLE. vared handles *
1120 * this differently itself. */
1121 if(zleactive) {
1122 char *pptbuf;
1123 int pptlen;
1125 pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL,
1126 &pmpt_attr),
1127 &pptlen);
1128 write(2, (WRITE_ARG_2_T)pptbuf, pptlen);
1129 free(pptbuf);
1130 return shingetline();
1133 keytimeout = (time_t)getiparam("KEYTIMEOUT");
1134 if (!shout) {
1135 if (SHTTY != -1)
1136 init_shout();
1138 if (!shout)
1139 return NULL;
1140 /* We could be smarter and default to a system read. */
1142 /* If we just got a new shout, make sure the terminal is set up. */
1143 if (termflags & TERM_UNKNOWN)
1144 init_term();
1147 fflush(shout);
1148 fflush(stderr);
1149 intr();
1150 insmode = unset(OVERSTRIKE);
1151 eofsent = 0;
1152 resetneeded = 0;
1153 fetchttyinfo = 0;
1154 trashedzle = 0;
1155 raw_lp = lp;
1156 lpromptbuf = promptexpand(lp ? *lp : NULL, 1, NULL, NULL, &pmpt_attr);
1157 raw_rp = rp;
1158 rpmpt_attr = pmpt_attr;
1159 rpromptbuf = promptexpand(rp ? *rp : NULL, 1, NULL, NULL, &rpmpt_attr);
1160 free_prepostdisplay();
1162 zlereadflags = flags;
1163 zlecontext = context;
1164 histline = curhist;
1165 undoing = 1;
1166 zleline = (ZLE_STRING_T)zalloc(((linesz = 256) + 2) * ZLE_CHAR_SIZE);
1167 *zleline = ZWC('\0');
1168 virangeflag = lastcmd = done = zlecs = zlell = mark = 0;
1169 vichgflag = 0;
1170 viinsbegin = 0;
1171 statusline = NULL;
1172 selectkeymap("main", 1);
1173 selectlocalmap(NULL);
1174 fixsuffix();
1175 if ((s = getlinknode(bufstack))) {
1176 setline(s, ZSL_TOEND);
1177 zsfree(s);
1178 if (stackcs != -1) {
1179 zlecs = stackcs;
1180 stackcs = -1;
1181 if (zlecs > zlell)
1182 zlecs = zlell;
1183 CCLEFT();
1185 if (stackhist != -1) {
1186 histline = stackhist;
1187 stackhist = -1;
1190 initundo();
1191 if (isset(PROMPTCR))
1192 putc('\r', shout);
1193 if (tmout)
1194 alarm(tmout);
1195 zleactive = 1;
1196 resetneeded = 1;
1197 errflag = retflag = 0;
1198 lastcol = -1;
1199 initmodifier(&zmod);
1200 prefixflag = 0;
1202 zrefresh();
1204 if ((initthingy = rthingy_nocreate("zle-line-init"))) {
1205 char *args[2];
1206 args[0] = initthingy->nam;
1207 args[1] = NULL;
1208 execzlefunc(initthingy, args, 1);
1209 unrefthingy(initthingy);
1210 errflag = retflag = 0;
1213 zlecore();
1215 if (done && !exit_pending && !errflag &&
1216 (initthingy = rthingy_nocreate("zle-line-finish"))) {
1217 int saverrflag = errflag;
1218 int savretflag = retflag;
1219 char *args[2];
1220 args[0] = initthingy->nam;
1221 args[1] = NULL;
1222 execzlefunc(initthingy, args, 1);
1223 unrefthingy(initthingy);
1224 errflag = saverrflag;
1225 retflag = savretflag;
1228 statusline = NULL;
1229 invalidatelist();
1230 trashzle();
1231 free(lpromptbuf);
1232 free(rpromptbuf);
1233 zleactive = zlereadflags = lastlistlen = zlecontext = 0;
1234 alarm(0);
1236 freeundo();
1237 if (eofsent) {
1238 s = NULL;
1239 } else {
1240 zleline[zlell++] = ZWC('\n');
1241 s = zlegetline(NULL, NULL);
1243 free(zleline);
1244 zleline = NULL;
1245 forget_edits();
1246 errno = old_errno;
1247 /* highlight no longer valid */
1248 set_region_highlight(NULL, NULL);
1249 return s;
1253 * Execute a widget. The third argument indicates that the global
1254 * variable bindk should be set temporarily so that WIDGET etc.
1255 * reflect the command being executed.
1258 /**/
1260 execzlefunc(Thingy func, char **args, int set_bindk)
1262 int r = 0, ret = 0, remetafy = 0;
1263 Widget w;
1264 Thingy save_bindk = bindk;
1266 if (set_bindk)
1267 bindk = func;
1268 if (zlemetaline) {
1269 unmetafy_line();
1270 remetafy = 1;
1273 if(func->flags & DISABLED) {
1274 /* this thingy is not the name of a widget */
1275 char *nm = nicedup(func->nam, 0);
1276 char *msg = tricat("No such widget `", nm, "'");
1278 zsfree(nm);
1279 showmsg(msg);
1280 zsfree(msg);
1281 ret = 1;
1282 } else if((w = func->widget)->flags & (WIDGET_INT|WIDGET_NCOMP)) {
1283 int wflags = w->flags;
1286 * The rule is that "zle -N" widgets suppress EOF warnings. When
1287 * a "zle -N" widget invokes "zle another-widget" we pass through
1288 * this code again, but with actual arguments rather than with the
1289 * zlenoargs placeholder.
1291 if (keybuf[0] == eofchar && !keybuf[1] && args == zlenoargs &&
1292 !zlell && isfirstln && (zlereadflags & ZLRF_IGNOREEOF)) {
1293 showmsg((!islogin) ? "zsh: use 'exit' to exit." :
1294 "zsh: use 'logout' to logout.");
1295 use_exit_printed = 1;
1296 eofsent = 1;
1297 ret = 1;
1298 } else {
1299 if(!(wflags & ZLE_KEEPSUFFIX))
1300 removesuffix();
1301 if(!(wflags & ZLE_MENUCMP)) {
1302 fixsuffix();
1303 invalidatelist();
1305 if (wflags & ZLE_LINEMOVE)
1306 vilinerange = 1;
1307 if(!(wflags & ZLE_LASTCOL))
1308 lastcol = -1;
1309 if (wflags & WIDGET_NCOMP) {
1310 int atcurhist = histline == curhist;
1311 compwidget = w;
1312 ret = completecall(args);
1313 if (atcurhist)
1314 histline = curhist;
1315 } else if (!w->u.fn) {
1316 handlefeep(zlenoargs);
1317 } else {
1318 queue_signals();
1319 ret = w->u.fn(args);
1320 unqueue_signals();
1322 if (!(wflags & ZLE_NOTCOMMAND))
1323 lastcmd = wflags;
1325 r = 1;
1326 } else {
1327 Shfunc shf = (Shfunc) shfunctab->getnode(shfunctab, w->u.fnnam);
1329 if (!shf) {
1330 /* the shell function doesn't exist */
1331 char *nm = nicedup(w->u.fnnam, 0);
1332 char *msg = tricat("No such shell function `", nm, "'");
1334 zsfree(nm);
1335 showmsg(msg);
1336 zsfree(msg);
1337 ret = 1;
1338 } else {
1339 int osc = sfcontext, osi = movefd(0);
1340 int oxt = isset(XTRACE);
1341 LinkList largs = NULL;
1343 if (*args) {
1344 largs = newlinklist();
1345 addlinknode(largs, dupstring(w->u.fnnam));
1346 while (*args)
1347 addlinknode(largs, dupstring(*args++));
1349 startparamscope();
1350 makezleparams(0);
1351 sfcontext = SFC_WIDGET;
1352 opts[XTRACE] = 0;
1353 ret = doshfunc(shf, largs, 1);
1354 opts[XTRACE] = oxt;
1355 sfcontext = osc;
1356 endparamscope();
1357 lastcmd = 0;
1358 r = 1;
1359 redup(osi, 0);
1362 if (r) {
1363 unrefthingy(lbindk);
1364 refthingy(func);
1365 lbindk = func;
1367 if (set_bindk)
1368 bindk = save_bindk;
1370 * Goodness knows where the user's left us; make sure
1371 * it's not on a combining character that won't be displayed
1372 * directly.
1374 CCRIGHT();
1375 if (remetafy)
1376 metafy_line();
1377 return ret;
1380 /* initialise command modifiers */
1382 /**/
1383 static void
1384 initmodifier(struct modifier *mp)
1386 mp->flags = 0;
1387 mp->mult = 1;
1388 mp->tmult = 1;
1389 mp->vibuf = 0;
1390 mp->base = 10;
1393 /* Reset command modifiers, unless the command just executed was a prefix. *
1394 * Also set zmult, if the multiplier has been amended. */
1396 /**/
1397 static void
1398 handleprefixes(void)
1400 if (prefixflag) {
1401 prefixflag = 0;
1402 if(zmod.flags & MOD_TMULT) {
1403 zmod.flags |= MOD_MULT;
1404 zmod.mult = zmod.tmult;
1406 } else
1407 initmodifier(&zmod);
1410 /**/
1411 static int
1412 savekeymap(char *cmdname, char *oldname, char *newname, Keymap *savemapptr)
1414 Keymap km = openkeymap(newname);
1416 if (km) {
1417 *savemapptr = openkeymap(oldname);
1418 /* I love special cases */
1419 if (*savemapptr == km)
1420 *savemapptr = NULL;
1421 else {
1422 /* make sure this doesn't get deleted. */
1423 if (*savemapptr)
1424 refkeymap(*savemapptr);
1425 linkkeymap(km, oldname, 0);
1427 return 0;
1428 } else {
1429 zwarnnam(cmdname, "no such keymap: %s", newname);
1430 return 1;
1434 /**/
1435 static void
1436 restorekeymap(char *cmdname, char *oldname, char *newname, Keymap savemap)
1438 if (savemap) {
1439 linkkeymap(savemap, oldname, 0);
1440 /* we incremented the reference count above */
1441 unrefkeymap(savemap);
1442 } else if (newname) {
1443 /* urr... can this happen? */
1444 zwarnnam(cmdname,
1445 "keymap %s was not defined, not restored", oldname);
1449 /* this exports the argument we are currently vared'iting if != NULL */
1451 /**/
1452 mod_export char *varedarg;
1454 /* vared: edit (literally) a parameter value */
1456 /**/
1457 static int
1458 bin_vared(char *name, char **args, Options ops, UNUSED(int func))
1460 char *s, *t, *ova = varedarg;
1461 struct value vbuf;
1462 Value v;
1463 Param pm = 0;
1464 int ifl;
1465 int type = PM_SCALAR, obreaks = breaks, haso = 0, oSHTTY = 0;
1466 char *p1, *p2, *main_keymapname, *vicmd_keymapname;
1467 Keymap main_keymapsave = NULL, vicmd_keymapsave = NULL;
1468 FILE *oshout = NULL;
1470 if ((interact && unset(USEZLE)) || !strcmp(term, "emacs")) {
1471 zwarnnam(name, "ZLE not enabled");
1472 return 1;
1474 if (zleactive) {
1475 zwarnnam(name, "ZLE cannot be used recursively (yet)");
1476 return 1;
1479 if (OPT_ISSET(ops,'A'))
1481 if (OPT_ISSET(ops, 'a'))
1483 zwarnnam(name, "specify only one of -a and -A");
1484 return 1;
1486 type = PM_HASHED;
1488 else if (OPT_ISSET(ops,'a'))
1489 type = PM_ARRAY;
1490 p1 = OPT_ARG_SAFE(ops,'p');
1491 p2 = OPT_ARG_SAFE(ops,'r');
1492 main_keymapname = OPT_ARG_SAFE(ops,'M');
1493 vicmd_keymapname = OPT_ARG_SAFE(ops,'m');
1495 if (type != PM_SCALAR && !OPT_ISSET(ops,'c')) {
1496 zwarnnam(name, "-%s ignored", type == PM_ARRAY ? "a" : "A");
1499 /* handle non-existent parameter */
1500 s = args[0];
1501 queue_signals();
1502 v = fetchvalue(&vbuf, &s, (!OPT_ISSET(ops,'c') || type == PM_SCALAR),
1503 SCANPM_WANTKEYS|SCANPM_WANTVALS|SCANPM_MATCHMANY);
1504 if (!v && !OPT_ISSET(ops,'c')) {
1505 unqueue_signals();
1506 zwarnnam(name, "no such variable: %s", args[0]);
1507 return 1;
1508 } else if (v) {
1509 if (*s) {
1510 zwarnnam(name, "not an identifier: `%s'", args[0]);
1511 return 1;
1513 if (v->isarr) {
1514 /* Array: check for separators and quote them. */
1515 char **arr = getarrvalue(v), **aptr, **tmparr, **tptr;
1516 tptr = tmparr = (char **)zhalloc(sizeof(char *)*(arrlen(arr)+1));
1517 for (aptr = arr; *aptr; aptr++) {
1518 int sepcount = 0, clen;
1519 convchar_t c;
1521 * See if this word contains a separator character
1522 * or backslash
1524 MB_METACHARINIT();
1525 for (t = *aptr; *t; ) {
1526 if (*t == '\\') {
1527 t++;
1528 sepcount++;
1529 } else {
1530 t += MB_METACHARLENCONV(t, &c);
1531 if (WC_ZISTYPE(c, ISEP))
1532 sepcount++;
1535 if (sepcount) {
1536 /* Yes, so allocate enough space to quote it. */
1537 char *newstr, *nptr;
1538 newstr = zhalloc(strlen(*aptr)+sepcount+1);
1539 /* Go through string quoting separators */
1540 MB_METACHARINIT();
1541 for (t = *aptr, nptr = newstr; *t; ) {
1542 if (*t == '\\') {
1543 *nptr++ = '\\';
1544 *nptr++ = *t++;
1545 } else {
1546 clen = MB_METACHARLENCONV(t, &c);
1547 if (WC_ZISTYPE(c, ISEP))
1548 *nptr++ = '\\';
1549 while (clen--)
1550 *nptr++ = *t++;
1553 *nptr = '\0';
1554 /* Stick this into the array of words to join up */
1555 *tptr++ = newstr;
1556 } else
1557 *tptr++ = *aptr; /* No, keep original array element */
1559 *tptr = NULL;
1560 s = sepjoin(tmparr, NULL, 0);
1561 } else {
1562 s = ztrdup(getstrvalue(v));
1564 unqueue_signals();
1565 } else if (*s) {
1566 unqueue_signals();
1567 zwarnnam(name, "invalid parameter name: %s", args[0]);
1568 return 1;
1569 } else {
1570 unqueue_signals();
1571 s = ztrdup(s);
1574 if (SHTTY == -1 || OPT_ISSET(ops,'t')) {
1575 /* need to open /dev/tty specially */
1576 oSHTTY = SHTTY;
1577 if ((SHTTY = open(OPT_ISSET(ops,'t') ? OPT_ARG(ops,'t') : "/dev/tty",
1578 O_RDWR|O_NOCTTY)) == -1) {
1579 zwarnnam(name, "can't access terminal");
1580 zsfree(s);
1581 return 1;
1583 if (!isatty(SHTTY)) {
1584 zwarnnam(name, "%s: not a terminal", OPT_ARG(ops,'t'));
1585 close(SHTTY);
1586 SHTTY = oSHTTY;
1587 zsfree(s);
1588 return 1;
1590 oshout = shout;
1591 init_shout();
1593 haso = 1;
1595 /* edit the parameter value */
1596 zpushnode(bufstack, s);
1598 if (main_keymapname &&
1599 savekeymap(name, "main", main_keymapname, &main_keymapsave))
1600 main_keymapname = NULL;
1601 if (vicmd_keymapname &&
1602 savekeymap(name, "vicmd", vicmd_keymapname, &vicmd_keymapsave))
1603 vicmd_keymapname = NULL;
1605 varedarg = *args;
1606 ifl = isfirstln;
1607 if (OPT_ISSET(ops,'h'))
1608 hbegin(2);
1609 isfirstln = OPT_ISSET(ops,'e');
1610 t = zleread(&p1, &p2, OPT_ISSET(ops,'h') ? ZLRF_HISTORY : 0, ZLCON_VARED);
1611 if (OPT_ISSET(ops,'h'))
1612 hend(NULL);
1613 isfirstln = ifl;
1614 varedarg = ova;
1616 restorekeymap(name, "main", main_keymapname, main_keymapsave);
1617 restorekeymap(name, "vicmd", vicmd_keymapname, vicmd_keymapsave);
1619 if (haso) {
1620 fclose(shout); /* close(SHTTY) */
1621 shout = oshout;
1622 SHTTY = oSHTTY;
1624 if (!t || errflag) {
1625 /* error in editing */
1626 errflag = 0;
1627 breaks = obreaks;
1628 if (t)
1629 zsfree(t);
1630 return 1;
1632 /* strip off trailing newline, if any */
1633 if (t[strlen(t) - 1] == '\n')
1634 t[strlen(t) - 1] = '\0';
1635 /* final assignment of parameter value */
1636 if (OPT_ISSET(ops,'c')) {
1637 unsetparam(args[0]);
1638 createparam(args[0], type);
1640 queue_signals();
1641 pm = (Param) paramtab->getnode(paramtab, args[0]);
1642 if (pm && (PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED))) {
1643 char **a;
1646 * Use spacesplit with fourth argument 1: identify quoted separators,
1647 * and unquote. This duplicates the string, so we still need to free.
1649 a = spacesplit(t, 1, 0, 1);
1650 zsfree(t);
1651 if (PM_TYPE(pm->node.flags) == PM_ARRAY)
1652 setaparam(args[0], a);
1653 else
1654 sethparam(args[0], a);
1655 } else
1656 setsparam(args[0], t);
1657 unqueue_signals();
1658 return 0;
1661 /**/
1663 describekeybriefly(UNUSED(char **args))
1665 char *seq, *str, *msg, *is;
1666 Thingy func;
1668 if (statusline)
1669 return 1;
1670 clearlist = 1;
1671 statusline = "Describe key briefly: _";
1672 zrefresh();
1673 seq = getkeymapcmd(curkeymap, &func, &str);
1674 statusline = NULL;
1675 if(!*seq)
1676 return 1;
1677 msg = bindztrdup(seq);
1678 msg = appstr(msg, " is ");
1679 if (!func)
1680 is = bindztrdup(str);
1681 else
1682 is = nicedup(func->nam, 0);
1683 msg = appstr(msg, is);
1684 zsfree(is);
1685 showmsg(msg);
1686 zsfree(msg);
1687 return 0;
1690 #define MAXFOUND 4
1692 struct findfunc {
1693 Thingy func;
1694 int found;
1695 char *msg;
1698 /**/
1699 static void
1700 scanfindfunc(char *seq, Thingy func, UNUSED(char *str), void *magic)
1702 struct findfunc *ff = magic;
1704 if(func != ff->func)
1705 return;
1706 if (!ff->found++)
1707 ff->msg = appstr(ff->msg, " is on");
1708 if(ff->found <= MAXFOUND) {
1709 char *b = bindztrdup(seq);
1711 ff->msg = appstr(ff->msg, " ");
1712 ff->msg = appstr(ff->msg, b);
1713 zsfree(b);
1717 /**/
1719 whereis(UNUSED(char **args))
1721 struct findfunc ff;
1723 if (!(ff.func = executenamedcommand("Where is: ")))
1724 return 1;
1725 ff.found = 0;
1726 ff.msg = nicedup(ff.func->nam, 0);
1727 scankeymap(curkeymap, 1, scanfindfunc, &ff);
1728 if (!ff.found)
1729 ff.msg = appstr(ff.msg, " is not bound to any key");
1730 else if(ff.found > MAXFOUND)
1731 ff.msg = appstr(ff.msg, " et al");
1732 showmsg(ff.msg);
1733 zsfree(ff.msg);
1734 return 0;
1737 /**/
1739 recursiveedit(UNUSED(char **args))
1741 int locerror;
1743 zrefresh();
1744 zlecore();
1746 locerror = errflag;
1747 errflag = done = eofsent = 0;
1749 return locerror;
1752 /**/
1753 void
1754 reexpandprompt(void)
1756 static int reexpanding;
1758 if (!reexpanding++) {
1759 free(lpromptbuf);
1760 lpromptbuf = promptexpand(raw_lp ? *raw_lp : NULL, 1, NULL, NULL,
1761 &pmpt_attr);
1762 rpmpt_attr = pmpt_attr;
1763 free(rpromptbuf);
1764 rpromptbuf = promptexpand(raw_rp ? *raw_rp : NULL, 1, NULL, NULL,
1765 &rpmpt_attr);
1767 reexpanding--;
1770 /**/
1772 resetprompt(UNUSED(char **args))
1774 reexpandprompt();
1775 return redisplay(NULL);
1778 /* same bug called from outside zle */
1780 /**/
1781 mod_export void
1782 zle_resetprompt(void)
1784 reexpandprompt();
1785 if (zleactive)
1786 redisplay(NULL);
1790 /**/
1791 mod_export void
1792 trashzle(void)
1794 if (zleactive && !trashedzle) {
1795 /* This zrefresh() is just to get the main editor display right and *
1796 * get the cursor in the right place. For that reason, we disable *
1797 * list display (which would otherwise result in infinite *
1798 * recursion [at least, it would if zrefresh() didn't have its *
1799 * extra `inlist' check]). */
1800 int sl = showinglist;
1801 showinglist = 0;
1802 trashedzle = 1;
1803 zrefresh();
1804 showinglist = sl;
1805 moveto(nlnct, 0);
1806 if (clearflag && tccan(TCCLEAREOD)) {
1807 tcout(TCCLEAREOD);
1808 clearflag = listshown = 0;
1810 if (postedit)
1811 fprintf(shout, "%s", postedit);
1812 fflush(shout);
1813 resetneeded = 1;
1814 if (!(zlereadflags & ZLRF_NOSETTY))
1815 settyinfo(&shttyinfo);
1817 if (errflag)
1818 kungetct = 0;
1822 /* Hook functions. Used to allow access to zle parameters if zle is
1823 * active. */
1825 static int
1826 zlebeforetrap(UNUSED(Hookdef dummy), UNUSED(void *dat))
1828 if (zleactive) {
1829 startparamscope();
1830 makezleparams(1);
1832 return 0;
1835 static int
1836 zleaftertrap(UNUSED(Hookdef dummy), UNUSED(void *dat))
1838 if (zleactive)
1839 endparamscope();
1841 return 0;
1844 static char *
1845 zle_main_entry(int cmd, va_list ap)
1847 switch (cmd) {
1848 case ZLE_CMD_GET_LINE:
1850 int *ll, *cs;
1851 ll = va_arg(ap, int *);
1852 cs = va_arg(ap, int *);
1853 return zlegetline(ll, cs);
1856 case ZLE_CMD_READ:
1858 char **lp, **rp;
1859 int flags, context;
1861 lp = va_arg(ap, char **);
1862 rp = va_arg(ap, char **);
1863 flags = va_arg(ap, int);
1864 context = va_arg(ap, int);
1866 return zleread(lp, rp, flags, context);
1869 case ZLE_CMD_ADD_TO_LINE:
1870 zleaddtoline(va_arg(ap, int));
1871 break;
1873 case ZLE_CMD_TRASH:
1874 trashzle();
1875 break;
1877 case ZLE_CMD_RESET_PROMPT:
1878 zle_resetprompt();
1879 break;
1881 case ZLE_CMD_REFRESH:
1882 zrefresh();
1883 break;
1885 case ZLE_CMD_SET_KEYMAP:
1886 zlesetkeymap(va_arg(ap, int));
1887 break;
1889 case ZLE_CMD_GET_KEY:
1891 long do_keytmout;
1892 int *timeout, *chrp;
1894 do_keytmout = va_arg(ap, long);
1895 timeout = va_arg(ap, int *);
1896 chrp = va_arg(ap, int *);
1897 *chrp = getbyte(do_keytmout, timeout);
1898 break;
1901 default:
1902 #ifdef DEBUG
1903 dputs("Bad command %d in zle_main_entry", cmd);
1904 #endif
1905 break;
1907 return NULL;
1910 static struct builtin bintab[] = {
1911 BUILTIN("bindkey", 0, bin_bindkey, 0, -1, 0, "evaM:ldDANmrsLRp", NULL),
1912 BUILTIN("vared", 0, bin_vared, 1, 1, 0, "aAcehM:m:p:r:t:", NULL),
1913 BUILTIN("zle", 0, bin_zle, 0, -1, 0, "aAcCDFgGIKlLmMNRU", NULL),
1916 /* The order of the entries in this table has to match the *HOOK
1917 * macros in zle.h */
1919 /**/
1920 mod_export struct hookdef zlehooks[] = {
1921 /* LISTMATCHESHOOK */
1922 HOOKDEF("list_matches", NULL, 0),
1923 /* COMPLETEHOOK */
1924 HOOKDEF("complete", NULL, 0),
1925 /* BEFORECOMPLETEHOOK */
1926 HOOKDEF("before_complete", NULL, 0),
1927 /* AFTERCOMPLETEHOOK */
1928 HOOKDEF("after_complete", NULL, 0),
1929 /* ACCEPTCOMPHOOK */
1930 HOOKDEF("accept_completion", NULL, 0),
1931 /* REVERSEMENUHOOK */
1932 HOOKDEF("reverse_menu", NULL, 0),
1933 /* INVALIDATELISTHOOK */
1934 HOOKDEF("invalidate_list", NULL, 0),
1937 static struct features module_features = {
1938 bintab, sizeof(bintab)/sizeof(*bintab),
1939 NULL, 0,
1940 NULL, 0,
1941 NULL, 0,
1945 /**/
1947 setup_(UNUSED(Module m))
1949 /* Set up editor entry points */
1950 zle_entry_ptr = zle_main_entry;
1951 zle_load_state = 1;
1953 /* initialise the thingies */
1954 init_thingies();
1955 lbindk = NULL;
1957 /* miscellaneous initialisations */
1958 stackhist = stackcs = -1;
1959 kungetbuf = (char *) zalloc(kungetsz = 32);
1960 comprecursive = 0;
1961 rdstrs = NULL;
1963 /* initialise the keymap system */
1964 init_keymaps();
1966 varedarg = NULL;
1968 incompfunc = incompctlfunc = hascompmod = 0;
1969 hascompwidgets = 0;
1971 clwords = (char **) zshcalloc((clwsize = 16) * sizeof(char *));
1973 return 0;
1976 /**/
1978 features_(Module m, char ***features)
1980 *features = featuresarray(m, &module_features);
1981 return 0;
1984 /**/
1986 enables_(Module m, int **enables)
1988 return handlefeatures(m, &module_features, enables);
1991 /**/
1993 boot_(Module m)
1995 addhookfunc("before_trap", (Hookfn) zlebeforetrap);
1996 addhookfunc("after_trap", (Hookfn) zleaftertrap);
1997 (void)addhookdefs(m, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
1998 zle_refresh_boot();
1999 return 0;
2002 /**/
2004 cleanup_(Module m)
2006 if(zleactive) {
2007 zerrnam(m->node.nam,
2008 "can't unload the zle module while zle is active");
2009 return 1;
2011 deletehookfunc("before_trap", (Hookfn) zlebeforetrap);
2012 deletehookfunc("after_trap", (Hookfn) zleaftertrap);
2013 (void)deletehookdefs(m, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
2014 return setfeatureenables(m, &module_features, NULL);
2017 /**/
2019 finish_(UNUSED(Module m))
2021 int i;
2023 unrefthingy(lbindk);
2025 cleanup_keymaps();
2026 deletehashtable(thingytab);
2028 zfree(vichgbuf, vichgbufsz);
2029 zfree(kungetbuf, kungetsz);
2030 free_isrch_spots();
2031 if (rdstrs)
2032 freelinklist(rdstrs, freestr);
2033 free(cutbuf.buf);
2034 if (kring) {
2035 for(i = kringsize; i--; )
2036 free(kring[i].buf);
2037 zfree(kring, kringsize * sizeof(struct cutbuffer));
2039 for(i = 35; i--; )
2040 zfree(vibuf[i].buf, vibuf[i].len);
2042 /* editor entry points */
2043 zle_entry_ptr = (ZleEntryPoint)0;
2044 zle_load_state = 0;
2046 zfree(clwords, clwsize * sizeof(char *));
2047 zle_refresh_finish();
2049 return 0;