about summary refs log tree commit diff
path: root/Src/Zle/zle_main.c
blob: f29da3e0ea5cedf29e9e53f7d950f161ead732b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
/*
 * zle_main.c - main routines for line editor
 *
 * This file is part of zsh, the Z shell.
 *
 * Copyright (c) 1992-1997 Paul Falstad
 * All rights reserved.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and to distribute modified versions of this software for any
 * purpose, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 *
 * In no event shall Paul Falstad or the Zsh Development Group be liable
 * to any party for direct, indirect, special, incidental, or consequential
 * damages arising out of the use of this software and its documentation,
 * even if Paul Falstad and the Zsh Development Group have been advised of
 * the possibility of such damage.
 *
 * Paul Falstad and the Zsh Development Group specifically disclaim any
 * warranties, including, but not limited to, the implied warranties of
 * merchantability and fitness for a particular purpose.  The software
 * provided hereunder is on an "as is" basis, and Paul Falstad and the
 * Zsh Development Group have no obligation to provide maintenance,
 * support, updates, enhancements, or modifications.
 *
 */

#include "zle.mdh"
#include "zle_main.pro"

/* != 0 if in a shell function called from completion, such that read -[cl]  *
 * will work (i.e., the line is metafied, and the above word arrays are OK). */

/**/
int incompctlfunc;

/* != 0 if we are in a new style completion function */

/**/
int incompfunc;

/* != 0 if completion module is loaded */

/**/
int hascompmod;

/* != 0 if we're done editing */

/**/
int done;

/* location of mark */

/**/
int mark;

/* last character pressed */

/**/
int c;

/* the bindings for the previous and for this key */

/**/
Thingy lbindk, bindk;

/* insert mode/overwrite mode flag */

/**/
int insmode;

static int eofchar, eofsent;
static long keytimeout;

#ifdef HAVE_SELECT
/* Terminal baud rate */

static int baud;
#endif

/* flags associated with last command */

/**/
int lastcmd;

/**/
Widget compwidget;

/* the status line, and its length */

/**/
char *statusline;
/**/
int statusll;

/* The current history line and cursor position for the top line *
 * on the buffer stack.                                          */

/**/
int stackhist, stackcs;

/* != 0 if we are making undo records */

/**/
int undoing;

/* current modifier status */

/**/
struct modifier zmod;

/* Current command prefix status.  This is normally 0.  Prefixes set *
 * this to 1.  Each time round the main loop, this is checked: if it *
 * is 0, the modifier status is reset; if it is 1, the modifier      *
 * status is left unchanged, and this flag is reset to 0.  The       *
 * effect is that several prefix commands can be executed, and have  *
 * cumulative effect, but any other command execution will clear the *
 * modifiers.                                                        */

/**/
int prefixflag;

/* Number of characters waiting to be read by the ungetkeys mechanism */
/**/
int kungetct;

/**/
char *zlenoargs[1] = { NULL };

#ifdef FIONREAD
static int delayzsetterm;
#endif

/* set up terminal */

/**/
void
zsetterm(void)
{
    struct ttyinfo ti;

#if defined(FIONREAD)
    int val;

    ioctl(SHTTY, FIONREAD, (char *)&val);
    if (val) {
	/*
	 * Problems can occur on some systems when switching from
	 * canonical to non-canonical input.  The former is usually
	 * set while running programmes, but the latter is necessary
	 * for zle.  If there is input in canonical mode, then we
	 * need to read it without setting up the terminal.  Furthermore,
	 * while that input gets processed there may be more input
	 * being typed (i.e. further typeahead).  This means that
	 * we can't set up the terminal for zle *at all* until
	 * we are sure there is no more typeahead to come.  So
	 * if there is typeahead, we set the flag delayzsetterm.
	 * Then getkey() performs another FIONREAD call; if that is
	 * 0, we have finally used up all the typeahead, and it is
	 * safe to alter the terminal, which we do at that point.
	 */
	delayzsetterm = 1;
	return;
    } else
	delayzsetterm = 0;
#endif

/* sanitize the tty */
#ifdef HAS_TIO
    shttyinfo.tio.c_lflag |= ICANON | ECHO;
# ifdef FLUSHO
    shttyinfo.tio.c_lflag &= ~FLUSHO;
# endif
#else				/* not HAS_TIO */
    shttyinfo.sgttyb.sg_flags = (shttyinfo.sgttyb.sg_flags & ~CBREAK) | ECHO;
    shttyinfo.lmodes &= ~LFLUSHO;
#endif

    attachtty(mypgrp);
    ti = shttyinfo;
#ifdef HAS_TIO
    if (unset(FLOWCONTROL))
	ti.tio.c_iflag &= ~IXON;
    ti.tio.c_lflag &= ~(ICANON | ECHO
# ifdef FLUSHO
			| FLUSHO
# endif
	);
# ifdef TAB3
    ti.tio.c_oflag &= ~TAB3;
# else
#  ifdef OXTABS
    ti.tio.c_oflag &= ~OXTABS;
#  else
#   ifdef XTABS
    ti.tio.c_oflag &= ~XTABS;
#   endif
#  endif
# endif
#ifdef ONLCR
    ti.tio.c_oflag |= ONLCR;
#endif
    ti.tio.c_cc[VQUIT] =
# ifdef VDISCARD
	ti.tio.c_cc[VDISCARD] =
# endif
# ifdef VSUSP
	ti.tio.c_cc[VSUSP] =
# endif
# ifdef VDSUSP
	ti.tio.c_cc[VDSUSP] =
# endif
# ifdef VSWTCH
	ti.tio.c_cc[VSWTCH] =
# endif
# ifdef VLNEXT
	ti.tio.c_cc[VLNEXT] =
# endif
	VDISABLEVAL;
# if defined(VSTART) && defined(VSTOP)
    if (unset(FLOWCONTROL))
	ti.tio.c_cc[VSTART] = ti.tio.c_cc[VSTOP] = VDISABLEVAL;
# endif
    eofchar = ti.tio.c_cc[VEOF];
    ti.tio.c_cc[VMIN] = 1;
    ti.tio.c_cc[VTIME] = 0;
    ti.tio.c_iflag |= (INLCR | ICRNL);
 /* this line exchanges \n and \r; it's changed back in getkey
	so that the net effect is no change at all inside the shell.
	This double swap is to allow typeahead in common cases, eg.

	% bindkey -s '^J' 'echo foo^M'
	% sleep 10
	echo foo<return>  <--- typed before sleep returns

	The shell sees \n instead of \r, since it was changed by the kernel
	while zsh wasn't looking. Then in getkey() \n is changed back to \r,
	and it sees "echo foo<accept line>", as expected. Without the double
	swap the shell would see "echo foo\n", which is translated to
	"echo fooecho foo<accept line>" because of the binding.
	Note that if you type <line-feed> during the sleep the shell just sees
	\n, which is translated to \r in getkey(), and you just get another
	prompt. For type-ahead to work in ALL cases you have to use
	stty inlcr.

	Unfortunately it's IMPOSSIBLE to have a general solution if both
	<return> and <line-feed> are mapped to the same character. The shell
	could check if there is input and read it before setting it's own
	terminal modes but if we get a \n we don't know whether to keep it or
	change to \r :-(
	*/

#else				/* not HAS_TIO */
    ti.sgttyb.sg_flags = (ti.sgttyb.sg_flags | CBREAK) & ~ECHO & ~XTABS;
    ti.lmodes &= ~LFLUSHO;
    eofchar = ti.tchars.t_eofc;
    ti.tchars.t_quitc =
	ti.ltchars.t_suspc =
	ti.ltchars.t_flushc =
	ti.ltchars.t_dsuspc = ti.ltchars.t_lnextc = -1;
#endif

#if defined(TTY_NEEDS_DRAINING) && defined(TIOCOUTQ) && defined(HAVE_SELECT)
    if (baud) {			/**/
	int n = 0;

	while ((ioctl(SHTTY, TIOCOUTQ, (char *)&n) >= 0) && n) {
	    struct timeval tv;

	    tv.tv_sec = n / baud;
	    tv.tv_usec = ((n % baud) * 1000000) / baud;
	    select(0, NULL, NULL, NULL, &tv);
	}
    }
#endif

    settyinfo(&ti);
}

static char *kungetbuf;
static int kungetsz;

/**/
void
ungetkey(int ch)
{
    if (kungetct == kungetsz)
	kungetbuf = realloc(kungetbuf, kungetsz *= 2);
    kungetbuf[kungetct++] = ch;
}

/**/
void
ungetkeys(char *s, int len)
{
    s += len;
    while (len--)
	ungetkey(*--s);
}

#if defined(pyr) && defined(HAVE_SELECT)
static int
breakread(int fd, char *buf, int n)
{
    fd_set f;

    FD_ZERO(&f);
    FD_SET(fd, &f);
    return (select(fd + 1, (SELECT_ARG_2_T) & f, NULL, NULL, NULL) == -1 ?
	    EOF : read(fd, buf, n));
}

# define read    breakread
#endif

/**/
int
getkey(int keytmout)
{
    char cc;
    unsigned int ret;
    long exp100ths;
    int die = 0, r, icnt = 0;
    int old_errno = errno, obreaks = breaks;

#ifdef HAVE_SELECT
    fd_set foofd;

#else
# ifdef HAS_TIO
    struct ttyinfo ti;

# endif
#endif

    if (kungetct)
	ret = STOUC(kungetbuf[--kungetct]);
    else {
#ifdef FIONREAD
	if (delayzsetterm) {
	    int val;
	    ioctl(SHTTY, FIONREAD, (char *)&val);
	    if (!val)
		zsetterm();
	}
#endif
	if (keytmout
#ifdef FIONREAD
	    && ! delayzsetterm
#endif
	    ) {
	    if (keytimeout > 500)
		exp100ths = 500;
	    else if (keytimeout > 0)
		exp100ths = keytimeout;
	    else
		exp100ths = 0;
#ifdef HAVE_SELECT
	    if (exp100ths) {
		struct timeval expire_tv;

		expire_tv.tv_sec = exp100ths / 100;
		expire_tv.tv_usec = (exp100ths % 100) * 10000L;
		FD_ZERO(&foofd);
		FD_SET(SHTTY, &foofd);
		if (select(SHTTY+1, (SELECT_ARG_2_T) & foofd,
			   NULL, NULL, &expire_tv) <= 0)
		    return EOF;
	    }
#else
# ifdef HAS_TIO
	    ti = shttyinfo;
	    ti.tio.c_lflag &= ~ICANON;
	    ti.tio.c_cc[VMIN] = 0;
	    ti.tio.c_cc[VTIME] = exp100ths / 10;
#  ifdef HAVE_TERMIOS_H
	    tcsetattr(SHTTY, TCSANOW, &ti.tio);
#  else
	    ioctl(SHTTY, TCSETA, &ti.tio);
#  endif
	    r = read(SHTTY, &cc, 1);
#  ifdef HAVE_TERMIOS_H
	    tcsetattr(SHTTY, TCSANOW, &shttyinfo.tio);
#  else
	    ioctl(SHTTY, TCSETA, &shttyinfo.tio);
#  endif
	    return (r <= 0) ? EOF : cc;
# endif
#endif
	}
	while ((r = read(SHTTY, &cc, 1)) != 1) {
	    if (r == 0) {
		/* The test for IGNOREEOF was added to make zsh ignore ^Ds
		   that were typed while commands are running.  Unfortuantely
		   this caused trouble under at least one system (SunOS 4.1).
		   Here shells that lost their xterm (e.g. if it was killed
		   with -9) didn't fail to read from the terminal but instead
		   happily continued to read EOFs, so that the above read
		   returned with 0, and, with IGNOREEOF set, this caused
		   an infinite loop.  The simple way around this was to add
		   the counter (icnt) so that this happens 20 times and than
		   the shell gives up (yes, this is a bit dirty...). */
		if (isset(IGNOREEOF) && icnt++ < 20)
		    continue;
		stopmsg = 1;
		zexit(1, 0);
	    }
	    icnt = 0;
	    if (errno == EINTR) {
		die = 0;
		if (!errflag && !retflag && !breaks)
		    continue;
		errflag = 0;
		breaks = obreaks;
		errno = old_errno;
		return EOF;
	    } else if (errno == EWOULDBLOCK) {
		fcntl(0, F_SETFL, 0);
	    } else if (errno == EIO && !die) {
		ret = opts[MONITOR];
		opts[MONITOR] = 1;
		attachtty(mypgrp);
		zrefresh();	/* kludge! */
		opts[MONITOR] = ret;
		die = 1;
	    } else if (errno != 0) {
		zerr("error on TTY read: %e", NULL, errno);
		stopmsg = 1;
		zexit(1, 0);
	    }
	}
	if (cc == '\r')		/* undo the exchange of \n and \r determined by */
	    cc = '\n';		/* zsetterm() */
	else if (cc == '\n')
	    cc = '\r';

	ret = STOUC(cc);
    }
    if (vichgflag) {
	if (vichgbufptr == vichgbufsz)
	    vichgbuf = realloc(vichgbuf, vichgbufsz *= 2);
	vichgbuf[vichgbufptr++] = ret;
    }
    errno = old_errno;
    return ret;
}

static int no_restore_tty;

/* Read a line.  It is returned metafied. */

/**/
unsigned char *
zleread(char *lp, char *rp, int flags)
{
    unsigned char *s;
    int old_errno = errno;
    int tmout = getiparam("TMOUT");

#ifdef HAVE_SELECT
    long costmult;
    struct timeval tv;
    fd_set foofd;

    baud = getiparam("BAUD");
    costmult = (baud) ? 3840000L / baud : 0;
#endif

    /* ZLE doesn't currently work recursively.  This is needed in case a *
     * select loop is used in a function called from ZLE.  vared handles *
     * this differently itself.                                          */
    if(zleactive) {
	char *pptbuf;
	int pptlen;

	pptbuf = unmetafy(promptexpand(lp, 0, NULL, NULL), &pptlen);
	write(2, (WRITE_ARG_2_T)pptbuf, pptlen);
	free(pptbuf);
	return (unsigned char *)shingetline();
    }

    keytimeout = getiparam("KEYTIMEOUT");
    if (!shout) {
	if (SHTTY != -1)
	    init_shout();

	if (!shout)
	    return NULL;
	/* We could be smarter and default to a system read. */

	/* If we just got a new shout, make sure the terminal is set up. */
	if (termflags & TERM_UNKNOWN)
	    init_term();
    }

    fflush(shout);
    fflush(stderr);
    intr();
    insmode = unset(OVERSTRIKE);
    eofsent = 0;
    resetneeded = 0;
    lpromptbuf = promptexpand(lp, 1, NULL, NULL);
    pmpt_attr = txtchange;
    rpromptbuf = promptexpand(rp, 1, NULL, NULL);
    rpmpt_attr = txtchange;
    histallowed = (flags & ZLRF_HISTORY);
    PERMALLOC {
	histline = curhist;
#ifdef HAVE_SELECT
	FD_ZERO(&foofd);
#endif
	undoing = 1;
	line = (unsigned char *)zalloc((linesz = 256) + 2);
	virangeflag = lastcmd = done = cs = ll = mark = 0;
	vichgflag = 0;
	viinsbegin = 0;
	statusline = NULL;
	selectkeymap("main", 1);
	selectlocalmap(NULL);
	fixsuffix();
	if ((s = (unsigned char *)getlinknode(bufstack))) {
	    setline((char *)s);
	    zsfree((char *)s);
	    if (stackcs != -1) {
		cs = stackcs;
		stackcs = -1;
		if (cs > ll)
		    cs = ll;
	    }
	    if (stackhist != -1) {
		histline = stackhist;
		stackhist = -1;
	    }
	}
	initundo();
	if (isset(PROMPTCR))
	    putc('\r', shout);
	if (tmout)
	    alarm(tmout);
	zleactive = 1;
	if (flags & ZLRF_NOSETTY)
	  no_restore_tty = 1;
	resetneeded = 1;
	errflag = retflag = 0;
	lastcol = -1;
	initmodifier(&zmod);
	prefixflag = 0;
	zrefresh();
	while (!done && !errflag) {

	    statusline = NULL;
	    vilinerange = 0;
	    reselectkeymap();
	    selectlocalmap(NULL);
	    bindk = getkeycmd();
	    if (!ll && isfirstln && c == eofchar) {
		eofsent = 1;
		break;
	    }
	    if (bindk) {
		if (execzlefunc(bindk, zlenoargs))
		    handlefeep(zlenoargs);
		handleprefixes();
		/* for vi mode, make sure the cursor isn't somewhere illegal */
		if (invicmdmode() && cs > findbol() &&
		    (cs == ll || line[cs] == '\n'))
		    cs--;
		if (undoing)
		    handleundo();
	    } else {
		errflag = 1;
		break;
	    }
#ifdef HAVE_SELECT
	    if (baud && !(lastcmd & ZLE_MENUCMP)) {
		FD_SET(SHTTY, &foofd);
		tv.tv_sec = 0;
		if ((tv.tv_usec = cost * costmult) > 500000)
		    tv.tv_usec = 500000;
		if (!kungetct && select(SHTTY+1, (SELECT_ARG_2_T) & foofd,
					NULL, NULL, &tv) <= 0)
		    zrefresh();
	    } else
#endif
		if (!kungetct)
		    zrefresh();
	}
	statusline = NULL;
	invalidatelist();
	trashzle();
	free(lpromptbuf);
	free(rpromptbuf);
	zleactive = no_restore_tty = 0;
	alarm(0);
    } LASTALLOC;
    freeundo();
    if (eofsent) {
	free(line);
	line = NULL;
    } else {
	line[ll++] = '\n';
	line = (unsigned char *) metafy((char *) line, ll, META_REALLOC);
    }
    forget_edits();
    errno = old_errno;
    return line;
}

/* execute a widget */

/**/
int
execzlefunc(Thingy func, char **args)
{
    int r = 0, ret = 0;
    Widget w;

    if(func->flags & DISABLED) {
	/* this thingy is not the name of a widget */
	char *nm = niceztrdup(func->nam);
	char *msg = tricat("No such widget `", nm, "'");

	zsfree(nm);
	showmsg(msg);
	zsfree(msg);
	ret = 1;
    } else if((w = func->widget)->flags & (WIDGET_INT|WIDGET_NCOMP)) {
	int wflags = w->flags;

	if(!(wflags & ZLE_KEEPSUFFIX))
	    removesuffix();
	if(!(wflags & ZLE_MENUCMP)) {
	    fixsuffix();
	    invalidatelist();
	}
	if (wflags & ZLE_LINEMOVE)
	    vilinerange = 1;
	if(!(wflags & ZLE_LASTCOL))
	    lastcol = -1;
	if (wflags & WIDGET_NCOMP) {
	    compwidget = w;
	    ret = completecall(args);
	} else
	    ret = w->u.fn(args);
	if (!(wflags & ZLE_NOTCOMMAND))
	    lastcmd = wflags;
	r = 1;
    } else {
	List l = getshfunc(w->u.fnnam);

	if(l == &dummy_list) {
	    /* the shell function doesn't exist */
	    char *nm = niceztrdup(w->u.fnnam);
	    char *msg = tricat("No such shell function `", nm, "'");

	    zsfree(nm);
	    showmsg(msg);
	    zsfree(msg);
	    ret = 1;
	} else {
	    int osc = sfcontext, osi = movefd(0), olv = lastval;
	    LinkList largs = NULL;

	    if (*args) {
		largs = newlinklist();
		addlinknode(largs, dupstring(w->u.fnnam));
		while (*args)
		    addlinknode(largs, dupstring(*args++));
	    }
	    startparamscope();
	    makezleparams(0);
	    sfcontext = SFC_WIDGET;
	    doshfunc(w->u.fnnam, l, largs, 0, 0);
	    ret = lastval;
	    lastval = olv;
	    sfcontext = osc;
	    endparamscope();
	    lastcmd = 0;
	    r = 1;
	    redup(osi, 0);
	}
    }
    if (r) {
	unrefthingy(lbindk);
	refthingy(func);
	lbindk = func;
    }
    return ret;
}

/* initialise command modifiers */

/**/
static void
initmodifier(struct modifier *mp)
{
    mp->flags = 0;
    mp->mult = 1;
    mp->tmult = 1;
    mp->vibuf = 0;
}

/* Reset command modifiers, unless the command just executed was a prefix. *
 * Also set zmult, if the multiplier has been amended.                     */

/**/
static void
handleprefixes(void)
{
    if (prefixflag) {
	prefixflag = 0;
	if(zmod.flags & MOD_TMULT) {
	    zmod.flags |= MOD_MULT;
	    zmod.mult = zmod.tmult;
	}
    } else
	initmodifier(&zmod);
}

/* this exports the argument we are currently vared'iting if != NULL */

/**/
char *varedarg;

/* vared: edit (literally) a parameter value */

/**/
static int
bin_vared(char *name, char **args, char *ops, int func)
{
    char *s, *t, *ova = varedarg;
    Value v;
    Param pm = 0;
    int create = 0;
    int type = PM_SCALAR, obreaks = breaks;
    char *p1 = NULL, *p2 = NULL;

    if (zleactive) {
	zwarnnam(name, "ZLE cannot be used recursively (yet)", NULL, 0);
	return 1;
    }

    /* all options are handled as arguments */
    while (*args && **args == '-') {
	while (*++(*args))
	    switch (**args) {
	    case 'c':
		/* -c option -- allow creation of the parameter if it doesn't
		yet exist */
		create = 1;
		break;
	    case 'a':
		type = PM_ARRAY;
		break;
	    case 'A':
		type = PM_HASHED;
		break;
	    case 'p':
		/* -p option -- set main prompt string */
		if ((*args)[1])
		    p1 = *args + 1, *args = "" - 1;
		else if (args[1])
		    p1 = *(++args), *args = "" - 1;
		else {
		    zwarnnam(name, "prompt string expected after -%c", NULL,
			     **args);
		    return 1;
		}
		break;
	    case 'r':
		/* -r option -- set right prompt string */
		if ((*args)[1])
		    p2 = *args + 1, *args = "" - 1;
		else if (args[1])
		    p2 = *(++args), *args = "" - 1;
		else {
		    zwarnnam(name, "prompt string expected after -%c", NULL,
			     **args);
		    return 1;
		}
		break;
	    case 'h':
		/* -h option -- enable history */
		ops['h'] = 1;
		break;
	    default:
		/* unrecognised option character */
		zwarnnam(name, "unknown option: %s", *args, 0);
		return 1;
	    }
	args++;
    }
    if (type && !create) {
	zwarnnam(name, "-%s ignored", type == PM_ARRAY ? "a" : "A", 0);
    }

    /* check we have a parameter name */
    if (!*args) {
	zwarnnam(name, "missing variable", NULL, 0);
	return 1;
    }
    /* handle non-existent parameter */
    s = args[0];
    v = fetchvalue(&s, (!create || type == PM_SCALAR),
		   SCANPM_WANTKEYS|SCANPM_WANTVALS|SCANPM_MATCHMANY);
    if (!v && !create) {
	zwarnnam(name, "no such variable: %s", args[0], 0);
	return 1;
    } else if (v) {
	s = getstrvalue(v);
	pm = v->pm;
    } else if (*s) {
	zwarnnam(name, "invalid parameter name: %s", args[0], 0);
	return 1;
    }

    /* edit the parameter value */
    PERMALLOC {
	pushnode(bufstack, ztrdup(s));
    } LASTALLOC;
    varedarg = *args;
    t = (char *) zleread(p1, p2, ops['h'] ? ZLRF_HISTORY : 0);
    varedarg = ova;
    if (!t || errflag) {
	/* error in editing */
	errflag = 0;
	breaks = obreaks;
	return 1;
    }
    /* strip off trailing newline, if any */
    if (t[strlen(t) - 1] == '\n')
	t[strlen(t) - 1] = '\0';
    /* final assignment of parameter value */
    if (create && (!pm || (type && PM_TYPE(pm->flags) != type))) {
	if (pm)
	    unsetparam(args[0]);
	createparam(args[0], type);
	pm = 0;
    }
    if (!pm)
	pm = (Param) paramtab->getnode(paramtab, args[0]);
    if (pm && (PM_TYPE(pm->flags) & (PM_ARRAY|PM_HASHED))) {
	char **a;

	PERMALLOC {
	    a = spacesplit(t, 1);
	} LASTALLOC;
	if (PM_TYPE(pm->flags) == PM_ARRAY)
	    setaparam(args[0], a);
	else
	    sethparam(args[0], a);
    } else
	setsparam(args[0], t);
    return 0;
}

/**/
int
describekeybriefly(char **args)
{
    char *seq, *str, *msg, *is;
    Thingy func;

    if (statusline)
	return 1;
    clearlist = 1;
    statusline = "Describe key briefly: _";
    statusll = strlen(statusline);
    zrefresh();
    seq = getkeymapcmd(curkeymap, &func, &str);
    statusline = NULL;
    if(!*seq)
	return 1;
    msg = bindztrdup(seq);
    msg = appstr(msg, " is ");
    if (!func)
	is = bindztrdup(str);
    else
	is = niceztrdup(func->nam);
    msg = appstr(msg, is);
    zsfree(is);
    showmsg(msg);
    zsfree(msg);
    return 0;
}

#define MAXFOUND 4

struct findfunc {
    Thingy func;
    int found;
    char *msg;
};

/**/
static void
scanfindfunc(char *seq, Thingy func, char *str, void *magic)
{
    struct findfunc *ff = magic;

    if(func != ff->func)
	return;
    if (!ff->found++)
	ff->msg = appstr(ff->msg, " is on");
    if(ff->found <= MAXFOUND) {
	char *b = bindztrdup(seq);

	ff->msg = appstr(ff->msg, " ");
	ff->msg = appstr(ff->msg, b);
	zsfree(b);
    }
}

/**/
int
whereis(char **args)
{
    struct findfunc ff;

    if (!(ff.func = executenamedcommand("Where is: ")))
	return 1;
    ff.found = 0;
    ff.msg = niceztrdup(ff.func->nam);
    scankeymap(curkeymap, 1, scanfindfunc, &ff);
    if (!ff.found)
	ff.msg = appstr(ff.msg, " is not bound to any key");
    else if(ff.found > MAXFOUND)
	ff.msg = appstr(ff.msg, " et al");
    showmsg(ff.msg);
    zsfree(ff.msg);
    return 0;
}

/**/
void
trashzle(void)
{
    if (zleactive) {
	/* This zrefresh() is just to get the main editor display right and *
	 * get the cursor in the right place.  For that reason, we disable  *
	 * list display (which would otherwise result in infinite           *
	 * recursion [at least, it would if zrefresh() didn't have its      *
	 * extra `inlist' check]).                                          */
	int sl = showinglist;
	showinglist = 0;
	zrefresh();
	showinglist = sl;
	moveto(nlnct, 0);
	if (clearflag && tccan(TCCLEAREOD)) {
	    tcout(TCCLEAREOD);
	    clearflag = listshown = 0;
	}
	if (postedit)
	    fprintf(shout, "%s", postedit);
	fflush(shout);
	resetneeded = 1;
	if (!no_restore_tty)
	  settyinfo(&shttyinfo);
    }
    if (errflag)
	kungetct = 0;
}

static struct builtin bintab[] = {
    BUILTIN("bindkey", 0, bin_bindkey, 0, -1, 0, "evaMldDANmrsLR", NULL),
    BUILTIN("vared",   0, bin_vared,   1,  7, 0, NULL,             NULL),
    BUILTIN("zle",     0, bin_zle,     0, -1, 0, "lDANCLmMgGcRaU", NULL),
};

/* The order of the entries in this table has to match the *HOOK
 * macros in zle.h */

/**/
struct hookdef zlehooks[] = {
    HOOKDEF("list_matches", NULL, 0),
    HOOKDEF("complete", NULL, 0),
    HOOKDEF("before_complete", NULL, 0),
    HOOKDEF("after_complete", NULL, 0),
    HOOKDEF("accept_completion", NULL, 0),
    HOOKDEF("reverse_menu", NULL, 0),
    HOOKDEF("invalidate_list", NULL, 0),
};

/**/
int
setup_zle(Module m)
{
    /* Set up editor entry points */
    trashzleptr = trashzle;
    gotwordptr = gotword;
    refreshptr = zrefresh;
    spaceinlineptr = spaceinline;
    zlereadptr = zleread;

    getkeyptr = getkey;

    /* initialise the thingies */
    init_thingies();
    lbindk = NULL;

    /* miscellaneous initialisations */
    stackhist = stackcs = -1;
    kungetbuf = (char *) zalloc(kungetsz = 32);

    /* initialise the keymap system */
    init_keymaps();

    varedarg = NULL;

    incompfunc = incompctlfunc = hascompmod = 0;

    clwords = (char **) zcalloc((clwsize = 16) * sizeof(char *));

    return 0;
}

/**/
int
boot_zle(Module m)
{
    addbuiltins(m->nam, bintab, sizeof(bintab)/sizeof(*bintab));
    addhookdefs(m->nam, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
    return 0;
}

#ifdef MODULE

/**/
int
cleanup_zle(Module m)
{
    if(zleactive) {
	zerrnam(m->nam, "can't unload the zle module while zle is active",
	    NULL, 0);
	return 1;
    }
    deletebuiltins(m->nam, bintab, sizeof(bintab)/sizeof(*bintab));
    deletehookdefs(m->nam, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
    return 0;
}

/**/
int
finish_zle(Module m)
{
    int i;

    unrefthingy(lbindk);

    cleanup_keymaps();
    deletehashtable(thingytab);

    zfree(vichgbuf, vichgbufsz);
    zfree(kungetbuf, kungetsz);
    free_isrch_spots();

    zfree(cutbuf.buf, cutbuf.len);
    for(i = KRINGCT; i--; )
	zfree(kring[i].buf, kring[i].len);
    for(i = 35; i--; )
	zfree(vibuf[i].buf, vibuf[i].len);

    /* editor entry points */
    trashzleptr = noop_function;
    gotwordptr = noop_function;
    refreshptr = noop_function;
    spaceinlineptr = noop_function_int;
    zlereadptr = fallback_zleread;

    getkeyptr = NULL;

    zfree(clwords, clwsize * sizeof(char *));

    return 0;
}

#endif /* MODULE */