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
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.
31 #include "zle_main.pro"
36 #if defined(HAVE_POLL) && !defined(POLLIN) && !defined(POLLNORM)
40 /* The input line assembled so far */
43 mod_export ZLE_STRING_T zleline
;
45 /* Cursor position and line length in zle */
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). */
54 mod_export
int incompctlfunc
;
56 /* != 0 if we are in a new style completion function */
59 mod_export
int incompfunc
;
61 /* != 0 if completion module is loaded */
64 mod_export
int hascompmod
;
66 /* ZLRF_* flags passed to zleread() */
71 /* ZLCON_* flags passed to zleread() */
76 /* != 0 if we're done editing */
81 /* location of 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
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.
103 #ifdef MULTIBYTE_SUPPORT
105 mod_export ZLE_INT_T lastchar_wide
;
111 /* the bindings for the previous and for this key */
114 mod_export Thingy lbindk
, bindk
;
116 /* insert mode/overwrite mode flag */
122 mod_export
int eofchar
;
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 */
135 static long costmult
;
138 /* flags associated with last command */
141 mod_export
int lastcmd
;
144 mod_export Widget compwidget
;
146 /* the status line, a null-terminated metafied string */
149 mod_export
char *statusline
;
151 /* The current history line and cursor position for the top line *
152 * on the buffer stack. */
155 int stackhist
, stackcs
;
157 /* != 0 if we are making undo records */
162 /* current modifier status */
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 *
178 /* Number of characters waiting to be read by the ungetbytes mechanism */
183 mod_export
char *zlenoargs
[1] = { NULL
};
185 static char **raw_lp
, **raw_rp
;
188 static int delayzsetterm
;
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.
196 int nwatch
; /* Number of fd's we are watching */
198 int *watch_fds
; /* The list of fds, not terminated! */
200 char **watch_funcs
; /* The corresponding functions to call, normal array */
202 /* set up terminal */
209 #if defined(FIONREAD)
215 * User requested terminal to be returned to normal use,
216 * so remember the terminal settings if not frozen.
219 gettyinfo(&shttyinfo
);
223 #if defined(FIONREAD)
224 ioctl(SHTTY
, FIONREAD
, (char *)&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.
247 /* sanitize the tty */
249 shttyinfo
.tio
.c_lflag
|= ICANON
| ECHO
;
251 shttyinfo
.tio
.c_lflag
&= ~FLUSHO
;
253 #else /* not HAS_TIO */
254 shttyinfo
.sgttyb
.sg_flags
= (shttyinfo
.sgttyb
.sg_flags
& ~CBREAK
) | ECHO
;
255 shttyinfo
.lmodes
&= ~LFLUSHO
;
261 if (unset(FLOWCONTROL
))
262 ti
.tio
.c_iflag
&= ~IXON
;
263 ti
.tio
.c_lflag
&= ~(ICANON
| ECHO
269 ti
.tio
.c_oflag
&= ~TAB3
;
272 ti
.tio
.c_oflag
&= ~OXTABS
;
275 ti
.tio
.c_oflag
&= ~XTABS
;
280 ti
.tio
.c_oflag
|= ONLCR
;
284 ti
.tio
.c_cc
[VDISCARD
] =
290 ti
.tio
.c_cc
[VDSUSP
] =
293 ti
.tio
.c_cc
[VSWTCH
] =
296 ti
.tio
.c_cc
[VLNEXT
] =
299 # if defined(VSTART) && defined(VSTOP)
300 if (unset(FLOWCONTROL
))
301 ti
.tio
.c_cc
[VSTART
] = ti
.tio
.c_cc
[VSTOP
] = VDISABLEVAL
;
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'
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
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
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
;
338 ti
.ltchars
.t_flushc
=
339 ti
.ltchars
.t_dsuspc
= ti
.ltchars
.t_lnextc
= -1;
342 #if defined(TTY_NEEDS_DRAINING) && defined(TIOCOUTQ) && defined(HAVE_SELECT)
346 while ((ioctl(SHTTY
, TIOCOUTQ
, (char *)&n
) >= 0) && n
) {
349 tv
.tv_sec
= n
/ baud
;
350 tv
.tv_usec
= ((n
% baud
) * 1000000) / baud
;
351 select(0, NULL
, NULL
, NULL
, &tv
);
359 static char *kungetbuf
;
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.
373 if (kungetct
== kungetsz
)
374 kungetbuf
= realloc(kungetbuf
, kungetsz
*= 2);
375 kungetbuf
[kungetct
++] = ch
;
380 ungetbytes(char *s
, int len
)
387 #if defined(pyr) && defined(HAVE_SELECT)
389 breakread(int fd
, char *buf
, int n
)
396 return (select(fd
+ 1, (SELECT_ARG_2_T
) & f
, NULL
, NULL
, NULL
) == -1 ?
397 EOF
: read(fd
, buf
, n
));
400 # define read breakread
404 * Possible forms of timeout.
407 /* No timeout in use. */
410 * Key timeout in use (do_keytmout flag set). If this goes off
411 * we return without anything being read.
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.
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.
437 #define ZMAXTIMEOUT ((time_t)1 << (sizeof(time_t)*8-11))
441 /* Type of timeout setting, see enum above */
444 * Value for timeout in 100ths of a second if type is not ZTM_NONE.
450 * See if we need a timeout either for a key press or for a
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.
462 calc_timeout(struct ztmout
*tmoutp
, long do_keytmout
)
464 if (do_keytmout
&& (keytimeout
> 0 || 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;
470 tmoutp
->exp100ths
= keytimeout
;
471 tmoutp
->tp
= ZTM_KEY
;
473 tmoutp
->tp
= ZTM_NONE
;
477 LinkNode tfnode
= firstnode(timedfns
);
479 time_t diff
, exp100ths
;
484 tfdat
= (Timedfn
)getdata(tfnode
);
485 diff
= tfdat
->when
- time(NULL
);
487 /* Already due; call it and rescan. */
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
;
505 /* In case we called a function which messed up the display... */
511 /* see calc_timeout for use of do_keytmout */
514 raw_getbyte(long do_keytmout
, char *cptr
)
518 #if defined(HAS_TIO) && \
519 (defined(sun) || (!defined(HAVE_POLL) && !defined(HAVE_SELECT)))
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
)
544 #if defined(HAVE_SELECT) || defined(HAVE_POLL)
545 int i
, errtry
= 0, selret
;
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
565 ti
.tio
.c_cc
[VMIN
] = 0;
567 ret
= read(SHTTY
, cptr
, 1);
568 ti
.tio
.c_cc
[VMIN
] = 1;
575 /* First pollfd is SHTTY, following are the nwatch fds */
576 fds
= zalloc(sizeof(struct pollfd
) * nfds
);
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
;
592 if (tmout
.tp
!= ZTM_NONE
)
593 poll_timeout
= tmout
.exp100ths
* 10;
597 selret
= poll(fds
, errtry
? 1 : nfds
, poll_timeout
);
600 struct timeval
*tvptr
;
601 struct timeval expire_tv
;
604 FD_SET(SHTTY
, &foofd
);
606 for (i
= 0; i
< nwatch
; i
++) {
607 int fd
= watch_fds
[i
];
614 if (tmout
.tp
!= ZTM_NONE
) {
615 expire_tv
.tv_sec
= tmout
.exp100ths
/ 100;
616 expire_tv
.tv_usec
= (tmout
.exp100ths
% 100) * 10000L;
622 selret
= select(fdmax
+1, (SELECT_ARG_2_T
) & foofd
,
626 * Make sure a user interrupt gets passed on straight away.
628 if (selret
< 0 && errflag
)
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
) {
641 * Nothing ready and no error, so we timed out.
645 /* keeps compiler happy if not debugging */
647 dputs("BUG: timeout fired with no timeout set.");
649 /* treat as if a key timeout triggered */
652 /* Special value -2 signals nothing ready */
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
)
670 /* Function may have messed up the display */
673 /* We need to recalculate the timeout */
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
);
688 * If we handled the timeout successfully,
694 /* If error or unhandled timeout, give up. */
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.
704 (fds
[0].revents
& POLLIN
)
706 FD_ISSET(SHTTY
, &foofd
)
710 if (nwatch
&& !errtry
) {
712 * Copy the details of the watch fds in case the
713 * user decides to delete one from inside the
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
++) {
723 (fds
[i
+1].revents
& POLLIN
)
725 FD_ISSET(lwatch_fds
[i
], &foofd
)
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
));
738 if (fds
[i
+1].revents
& POLLERR
)
739 zaddlinknode(funcargs
, ztrdup("err"));
742 if (fds
[i
+1].revents
& POLLHUP
)
743 zaddlinknode(funcargs
, ztrdup("hup"));
746 if (fds
[i
+1].revents
& POLLNVAL
)
747 zaddlinknode(funcargs
, ztrdup("nval"));
752 callhookfunc(lwatch_funcs
[i
], funcargs
, 0, NULL
);
754 /* No sensible way of handling errors here */
757 * Paranoia: don't run the hooks again this
762 freelinklist(funcargs
, freestr
);
765 /* Function may have invalidated the display. */
768 zfree(lwatch_fds
, lnwatch
*sizeof(int));
769 freearray(lwatch_funcs
);
773 zfree(fds
, sizeof(struct pollfd
) * nfds
);
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
);
786 ioctl(SHTTY
, TCSETA
, &ti
.tio
);
788 ret
= read(SHTTY
, cptr
, 1);
789 # ifdef HAVE_TERMIOS_H
790 tcsetattr(SHTTY
, TCSANOW
, &shttyinfo
.tio
);
792 ioctl(SHTTY
, TCSETA
, &shttyinfo
.tio
);
794 return (ret
<= 0) ? ret
: *cptr
;
799 ret
= read(SHTTY
, cptr
, 1);
804 /* see calc_timeout for use of do_keytmout */
808 getbyte(long do_keytmout
, int *timeout
)
812 int die
= 0, r
, icnt
= 0;
813 int old_errno
= errno
, obreaks
= breaks
;
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;
828 ret
= STOUC(kungetbuf
[--kungetct
]);
833 ioctl(SHTTY
, FIONREAD
, (char *)&val
);
839 int q
= queue_signal_level();
840 dont_queue_signals();
841 r
= raw_getbyte(do_keytmout
, &cc
);
842 restore_queue_signals(q
);
847 return lastchar
= EOF
;
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)
868 if (errno
== EINTR
) {
870 if (!errflag
&& !retflag
&& !breaks
)
875 return lastchar
= EOF
;
876 } else if (errno
== EWOULDBLOCK
) {
877 fcntl(0, F_SETFL
, 0);
878 } else if (errno
== EIO
&& !die
) {
882 zrefresh(); /* kludge! */
885 } else if (errno
!= 0) {
886 zerr("error on TTY read: %e", errno
);
891 if (cc
== '\r') /* undo the exchange of \n and \r determined by */
892 cc
= '\n'; /* zsetterm() */
899 * vichgbuf is raw bytes, not wide characters, so is dealt
903 if (vichgbufptr
== vichgbufsz
)
904 vichgbuf
= realloc(vichgbuf
, vichgbufsz
*= 2);
905 vichgbuf
[vichgbufptr
++] = ret
;
908 return lastchar
= ret
;
913 * Get a full character rather than just a single byte.
918 getfullchar(int do_keytmout
)
920 int inchar
= getbyte((long)do_keytmout
, NULL
);
922 #ifdef MULTIBYTE_SUPPORT
923 return getrestchar(inchar
);
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.
941 getrestchar(int inchar
)
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;
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.
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
)
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;
987 memset(&mbs
, 0, sizeof mbs
);
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.
997 return lastchar_wide
= L
'?';
1000 return lastchar_wide
= WEOF
;
1004 return lastchar_wide
= (ZLE_INT_T
)outchar
;
1014 #if !defined(HAVE_POLL) && defined(HAVE_SELECT)
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
1029 while (!done
&& !errflag
&& !exit_pending
) {
1035 selectlocalmap(NULL
);
1036 bindk
= getkeycmd();
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
1050 if (execzlefunc(bindk
, zlenoargs
, 0)) {
1051 handlefeep(zlenoargs
);
1056 /* for vi mode, make sure the cursor isn't somewhere illegal */
1057 if (invicmdmode() && zlecs
> findbol() &&
1058 (zlecs
== zlell
|| zleline
[zlecs
] == ZWC('\n')))
1067 if (baud
&& !(lastcmd
& ZLE_MENUCMP
)) {
1069 int to
= cost
* costmult
/ 1000; /* milliseconds */
1074 pfd
.events
= POLLIN
;
1075 if (!kungetct
&& poll(&pfd
, 1, to
) <= 0)
1080 if (baud
&& !(lastcmd
& ZLE_MENUCMP
)) {
1081 FD_SET(SHTTY
, &foofd
);
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)
1101 /* Read a line. It is returned metafied. */
1105 zleread(char **lp
, char **rp
, int flags
, int context
)
1108 int old_errno
= errno
;
1109 int tmout
= getiparam("TMOUT");
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;
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. */
1125 pptbuf
= unmetafy(promptexpand(lp
? *lp
: NULL
, 0, NULL
, NULL
,
1128 write(2, (WRITE_ARG_2_T
)pptbuf
, pptlen
);
1130 return shingetline();
1133 keytimeout
= (time_t)getiparam("KEYTIMEOUT");
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
)
1150 insmode
= unset(OVERSTRIKE
);
1156 lpromptbuf
= promptexpand(lp
? *lp
: NULL
, 1, NULL
, NULL
, &pmpt_attr
);
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
;
1166 zleline
= (ZLE_STRING_T
)zalloc(((linesz
= 256) + 2) * ZLE_CHAR_SIZE
);
1167 *zleline
= ZWC('\0');
1168 virangeflag
= lastcmd
= done
= zlecs
= zlell
= mark
= 0;
1172 selectkeymap("main", 1);
1173 selectlocalmap(NULL
);
1175 if ((s
= getlinknode(bufstack
))) {
1176 setline(s
, ZSL_TOEND
);
1178 if (stackcs
!= -1) {
1185 if (stackhist
!= -1) {
1186 histline
= stackhist
;
1191 if (isset(PROMPTCR
))
1197 errflag
= retflag
= 0;
1199 initmodifier(&zmod
);
1204 if ((initthingy
= rthingy_nocreate("zle-line-init"))) {
1206 args
[0] = initthingy
->nam
;
1208 execzlefunc(initthingy
, args
, 1);
1209 unrefthingy(initthingy
);
1210 errflag
= retflag
= 0;
1215 if (done
&& !exit_pending
&& !errflag
&&
1216 (initthingy
= rthingy_nocreate("zle-line-finish"))) {
1217 int saverrflag
= errflag
;
1218 int savretflag
= retflag
;
1220 args
[0] = initthingy
->nam
;
1222 execzlefunc(initthingy
, args
, 1);
1223 unrefthingy(initthingy
);
1224 errflag
= saverrflag
;
1225 retflag
= savretflag
;
1233 zleactive
= zlereadflags
= lastlistlen
= zlecontext
= 0;
1240 zleline
[zlell
++] = ZWC('\n');
1241 s
= zlegetline(NULL
, NULL
);
1247 /* highlight no longer valid */
1248 set_region_highlight(NULL
, NULL
);
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.
1260 execzlefunc(Thingy func
, char **args
, int set_bindk
)
1262 int r
= 0, ret
= 0, remetafy
= 0;
1264 Thingy save_bindk
= bindk
;
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
, "'");
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;
1299 if(!(wflags
& ZLE_KEEPSUFFIX
))
1301 if(!(wflags
& ZLE_MENUCMP
)) {
1305 if (wflags
& ZLE_LINEMOVE
)
1307 if(!(wflags
& ZLE_LASTCOL
))
1309 if (wflags
& WIDGET_NCOMP
) {
1310 int atcurhist
= histline
== curhist
;
1312 ret
= completecall(args
);
1315 } else if (!w
->u
.fn
) {
1316 handlefeep(zlenoargs
);
1319 ret
= w
->u
.fn(args
);
1322 if (!(wflags
& ZLE_NOTCOMMAND
))
1327 Shfunc shf
= (Shfunc
) shfunctab
->getnode(shfunctab
, w
->u
.fnnam
);
1330 /* the shell function doesn't exist */
1331 char *nm
= nicedup(w
->u
.fnnam
, 0);
1332 char *msg
= tricat("No such shell function `", nm
, "'");
1339 int osc
= sfcontext
, osi
= movefd(0);
1340 int oxt
= isset(XTRACE
);
1341 LinkList largs
= NULL
;
1344 largs
= newlinklist();
1345 addlinknode(largs
, dupstring(w
->u
.fnnam
));
1347 addlinknode(largs
, dupstring(*args
++));
1351 sfcontext
= SFC_WIDGET
;
1353 ret
= doshfunc(shf
, largs
, 1);
1363 unrefthingy(lbindk
);
1370 * Goodness knows where the user's left us; make sure
1371 * it's not on a combining character that won't be displayed
1380 /* initialise command modifiers */
1384 initmodifier(struct modifier
*mp
)
1393 /* Reset command modifiers, unless the command just executed was a prefix. *
1394 * Also set zmult, if the multiplier has been amended. */
1398 handleprefixes(void)
1402 if(zmod
.flags
& MOD_TMULT
) {
1403 zmod
.flags
|= MOD_MULT
;
1404 zmod
.mult
= zmod
.tmult
;
1407 initmodifier(&zmod
);
1412 savekeymap(char *cmdname
, char *oldname
, char *newname
, Keymap
*savemapptr
)
1414 Keymap km
= openkeymap(newname
);
1417 *savemapptr
= openkeymap(oldname
);
1418 /* I love special cases */
1419 if (*savemapptr
== km
)
1422 /* make sure this doesn't get deleted. */
1424 refkeymap(*savemapptr
);
1425 linkkeymap(km
, oldname
, 0);
1429 zwarnnam(cmdname
, "no such keymap: %s", newname
);
1436 restorekeymap(char *cmdname
, char *oldname
, char *newname
, Keymap 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? */
1445 "keymap %s was not defined, not restored", oldname
);
1449 /* this exports the argument we are currently vared'iting if != NULL */
1452 mod_export
char *varedarg
;
1454 /* vared: edit (literally) a parameter value */
1458 bin_vared(char *name
, char **args
, Options ops
, UNUSED(int func
))
1460 char *s
, *t
, *ova
= varedarg
;
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");
1475 zwarnnam(name
, "ZLE cannot be used recursively (yet)");
1479 if (OPT_ISSET(ops
,'A'))
1481 if (OPT_ISSET(ops
, 'a'))
1483 zwarnnam(name
, "specify only one of -a and -A");
1488 else if (OPT_ISSET(ops
,'a'))
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 */
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')) {
1506 zwarnnam(name
, "no such variable: %s", args
[0]);
1510 zwarnnam(name
, "not an identifier: `%s'", args
[0]);
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
;
1521 * See if this word contains a separator character
1525 for (t
= *aptr
; *t
; ) {
1530 t
+= MB_METACHARLENCONV(t
, &c
);
1531 if (WC_ZISTYPE(c
, ISEP
))
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 */
1541 for (t
= *aptr
, nptr
= newstr
; *t
; ) {
1546 clen
= MB_METACHARLENCONV(t
, &c
);
1547 if (WC_ZISTYPE(c
, ISEP
))
1554 /* Stick this into the array of words to join up */
1557 *tptr
++ = *aptr
; /* No, keep original array element */
1560 s
= sepjoin(tmparr
, NULL
, 0);
1562 s
= ztrdup(getstrvalue(v
));
1567 zwarnnam(name
, "invalid parameter name: %s", args
[0]);
1574 if (SHTTY
== -1 || OPT_ISSET(ops
,'t')) {
1575 /* need to open /dev/tty specially */
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");
1583 if (!isatty(SHTTY
)) {
1584 zwarnnam(name
, "%s: not a terminal", OPT_ARG(ops
,'t'));
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
;
1607 if (OPT_ISSET(ops
,'h'))
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'))
1616 restorekeymap(name
, "main", main_keymapname
, main_keymapsave
);
1617 restorekeymap(name
, "vicmd", vicmd_keymapname
, vicmd_keymapsave
);
1620 fclose(shout
); /* close(SHTTY) */
1624 if (!t
|| errflag
) {
1625 /* error in editing */
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
);
1641 pm
= (Param
) paramtab
->getnode(paramtab
, args
[0]);
1642 if (pm
&& (PM_TYPE(pm
->node
.flags
) & (PM_ARRAY
|PM_HASHED
))) {
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);
1651 if (PM_TYPE(pm
->node
.flags
) == PM_ARRAY
)
1652 setaparam(args
[0], a
);
1654 sethparam(args
[0], a
);
1656 setsparam(args
[0], t
);
1663 describekeybriefly(UNUSED(char **args
))
1665 char *seq
, *str
, *msg
, *is
;
1671 statusline
= "Describe key briefly: _";
1673 seq
= getkeymapcmd(curkeymap
, &func
, &str
);
1677 msg
= bindztrdup(seq
);
1678 msg
= appstr(msg
, " is ");
1680 is
= bindztrdup(str
);
1682 is
= nicedup(func
->nam
, 0);
1683 msg
= appstr(msg
, is
);
1700 scanfindfunc(char *seq
, Thingy func
, UNUSED(char *str
), void *magic
)
1702 struct findfunc
*ff
= magic
;
1704 if(func
!= ff
->func
)
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
);
1719 whereis(UNUSED(char **args
))
1723 if (!(ff
.func
= executenamedcommand("Where is: ")))
1726 ff
.msg
= nicedup(ff
.func
->nam
, 0);
1727 scankeymap(curkeymap
, 1, scanfindfunc
, &ff
);
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");
1739 recursiveedit(UNUSED(char **args
))
1747 errflag
= done
= eofsent
= 0;
1754 reexpandprompt(void)
1756 static int reexpanding
;
1758 if (!reexpanding
++) {
1760 lpromptbuf
= promptexpand(raw_lp
? *raw_lp
: NULL
, 1, NULL
, NULL
,
1762 rpmpt_attr
= pmpt_attr
;
1764 rpromptbuf
= promptexpand(raw_rp
? *raw_rp
: NULL
, 1, NULL
, NULL
,
1772 resetprompt(UNUSED(char **args
))
1775 return redisplay(NULL
);
1778 /* same bug called from outside zle */
1782 zle_resetprompt(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
;
1806 if (clearflag
&& tccan(TCCLEAREOD
)) {
1808 clearflag
= listshown
= 0;
1811 fprintf(shout
, "%s", postedit
);
1814 if (!(zlereadflags
& ZLRF_NOSETTY
))
1815 settyinfo(&shttyinfo
);
1822 /* Hook functions. Used to allow access to zle parameters if zle is
1826 zlebeforetrap(UNUSED(Hookdef dummy
), UNUSED(void *dat
))
1836 zleaftertrap(UNUSED(Hookdef dummy
), UNUSED(void *dat
))
1845 zle_main_entry(int cmd
, va_list ap
)
1848 case ZLE_CMD_GET_LINE
:
1851 ll
= va_arg(ap
, int *);
1852 cs
= va_arg(ap
, int *);
1853 return zlegetline(ll
, cs
);
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));
1877 case ZLE_CMD_RESET_PROMPT
:
1881 case ZLE_CMD_REFRESH
:
1885 case ZLE_CMD_SET_KEYMAP
:
1886 zlesetkeymap(va_arg(ap
, int));
1889 case ZLE_CMD_GET_KEY
:
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
);
1903 dputs("Bad command %d in zle_main_entry", cmd
);
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 */
1920 mod_export
struct hookdef zlehooks
[] = {
1921 /* LISTMATCHESHOOK */
1922 HOOKDEF("list_matches", NULL
, 0),
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
),
1947 setup_(UNUSED(Module m
))
1949 /* Set up editor entry points */
1950 zle_entry_ptr
= zle_main_entry
;
1953 /* initialise the thingies */
1957 /* miscellaneous initialisations */
1958 stackhist
= stackcs
= -1;
1959 kungetbuf
= (char *) zalloc(kungetsz
= 32);
1963 /* initialise the keymap system */
1968 incompfunc
= incompctlfunc
= hascompmod
= 0;
1971 clwords
= (char **) zshcalloc((clwsize
= 16) * sizeof(char *));
1978 features_(Module m
, char ***features
)
1980 *features
= featuresarray(m
, &module_features
);
1986 enables_(Module m
, int **enables
)
1988 return handlefeatures(m
, &module_features
, enables
);
1995 addhookfunc("before_trap", (Hookfn
) zlebeforetrap
);
1996 addhookfunc("after_trap", (Hookfn
) zleaftertrap
);
1997 (void)addhookdefs(m
, zlehooks
, sizeof(zlehooks
)/sizeof(*zlehooks
));
2007 zerrnam(m
->node
.nam
,
2008 "can't unload the zle module while zle is active");
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
);
2019 finish_(UNUSED(Module m
))
2023 unrefthingy(lbindk
);
2026 deletehashtable(thingytab
);
2028 zfree(vichgbuf
, vichgbufsz
);
2029 zfree(kungetbuf
, kungetsz
);
2032 freelinklist(rdstrs
, freestr
);
2035 for(i
= kringsize
; i
--; )
2037 zfree(kring
, kringsize
* sizeof(struct cutbuffer
));
2040 zfree(vibuf
[i
].buf
, vibuf
[i
].len
);
2042 /* editor entry points */
2043 zle_entry_ptr
= (ZleEntryPoint
)0;
2046 zfree(clwords
, clwsize
* sizeof(char *));
2047 zle_refresh_finish();