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
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
|
/*
* 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"
#ifdef HAVE_POLL_H
# include <poll.h>
#endif
#if defined(HAVE_POLL) && !defined(POLLIN) && !defined(POLLNORM)
# undef HAVE_POLL
#endif
/* != 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). */
/**/
mod_export int incompctlfunc;
/* != 0 if we are in a new style completion function */
/**/
mod_export int incompfunc;
/* != 0 if completion module is loaded */
/**/
mod_export int hascompmod;
/* ZLRF_* flags passed to zleread() */
/**/
int zlereadflags;
/* != 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 */
/**/
mod_export Thingy lbindk, bindk;
/* insert mode/overwrite mode flag */
/**/
int insmode;
/**/
mod_export int eofchar;
static int eofsent;
static long keytimeout;
#if defined(HAVE_SELECT) || defined(HAVE_POLL)
/* Terminal baud rate */
static int baud;
static long costmult;
#endif
/* flags associated with last command */
/**/
mod_export int lastcmd;
/**/
mod_export 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 */
/**/
mod_export 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;
/**/
mod_export char *zlenoargs[1] = { NULL };
#ifdef FIONREAD
static int delayzsetterm;
#endif
/*
* File descriptors we are watching as well as the terminal fd.
* These are all for reading; we don't watch for writes or exceptions.
*/
/**/
int nwatch; /* Number of fd's we are watching */
/**/
int *watch_fds; /* The list of fds, not terminated! */
/**/
char **watch_funcs; /* The corresponding functions to call, normal array */
/* set up terminal */
/**/
mod_export 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
static int
raw_getkey(int keytmout, char *cptr)
{
long exp100ths;
int ret;
#ifdef HAS_TIO
struct ttyinfo ti;
#endif
#ifndef HAVE_POLL
# ifdef HAVE_SELECT
fd_set foofd;
# endif
#endif
/*
* Handle timeouts and watched fd's. We only do one at once;
* key timeouts take precedence. This saves tricky timing
* problems with the key timeout.
*/
if ((nwatch || keytmout)
#ifdef FIONREAD
&& ! delayzsetterm
#endif
) {
if (!keytmout || keytimeout <= 0)
exp100ths = 0;
else if (keytimeout > 500)
exp100ths = 500;
else
exp100ths = keytimeout;
#if defined(HAVE_SELECT) || defined(HAVE_POLL)
if (!keytmout || exp100ths) {
int i, errtry = 0, selret;
# ifdef HAVE_POLL
int poll_timeout;
int nfds;
struct pollfd *fds;
# else
int fdmax;
struct timeval *tvptr;
struct timeval expire_tv;
# endif
# if defined(HAS_TIO) && defined(sun)
/*
* Yes, I know this is complicated. Yes, I know we
* already have three bits of code to poll the terminal
* down below. No, I don't want to do this either.
* However, it turns out on certain OSes, specifically
* Solaris, that you can't poll typeahead for love nor
* money without actually trying to read it. But
* if we are trying to select (and we need to if we
* are watching other fd's) we won't pick that up.
* So we just try and read it without blocking in
* the time-honoured (i.e. absurdly baroque) termios
* fashion.
*/
gettyinfo(&ti);
ti.tio.c_cc[VMIN] = 0;
settyinfo(&ti);
ret = read(SHTTY, cptr, 1);
ti.tio.c_cc[VMIN] = 1;
settyinfo(&ti);
if (ret > 0)
return 1;
# endif
# ifdef HAVE_POLL
nfds = keytmout ? 1 : 1 + nwatch;
/* First pollfd is SHTTY, following are the nwatch fds */
fds = zalloc(sizeof(struct pollfd) * nfds);
if (exp100ths)
poll_timeout = exp100ths * 10;
else
poll_timeout = -1;
fds[0].fd = SHTTY;
/*
* POLLIN, POLLIN, POLLIN,
* Keep those fd's POLLIN...
*/
fds[0].events = POLLIN;
if (!keytmout) {
for (i = 0; i < nwatch; i++) {
fds[i+1].fd = watch_fds[i];
fds[i+1].events = POLLIN;
}
}
# else
fdmax = SHTTY;
tvptr = NULL;
if (exp100ths) {
expire_tv.tv_sec = exp100ths / 100;
expire_tv.tv_usec = (exp100ths % 100) * 10000L;
tvptr = &expire_tv;
}
# endif
do {
# ifdef HAVE_POLL
selret = poll(fds, errtry ? 1 : nfds, poll_timeout);
# else
FD_ZERO(&foofd);
FD_SET(SHTTY, &foofd);
if (!keytmout && !errtry) {
for (i = 0; i < nwatch; i++) {
int fd = watch_fds[i];
FD_SET(fd, &foofd);
if (fd > fdmax)
fdmax = fd;
}
}
selret = select(fdmax+1, (SELECT_ARG_2_T) & foofd,
NULL, NULL, tvptr);
# endif
/*
* Make sure a user interrupt gets passed on straight away.
*/
if (selret < 0 && errflag)
break;
/*
* Try to avoid errors on our special fd's from
* messing up reads from the terminal. Try first
* with all fds, then try unsetting the special ones.
*/
if (selret < 0 && !keytmout && !errtry) {
errtry = 1;
continue;
}
if (selret == 0) {
/* Special value -2 signals nothing ready */
selret = -2;
}
if (selret < 0)
break;
if (!keytmout && nwatch) {
/*
* Copy the details of the watch fds in case the
* user decides to delete one from inside the
* handler function.
*/
int lnwatch = nwatch;
int *lwatch_fds = zalloc(lnwatch*sizeof(int));
char **lwatch_funcs = zarrdup(watch_funcs);
memcpy(lwatch_fds, watch_fds, lnwatch*sizeof(int));
for (i = 0; i < lnwatch; i++) {
if (
# ifdef HAVE_POLL
(fds[i+1].revents & POLLIN)
# else
FD_ISSET(lwatch_fds[i], &foofd)
# endif
) {
/* Handle the fd. */
LinkList funcargs = znewlinklist();
zaddlinknode(funcargs, ztrdup(lwatch_funcs[i]));
{
char buf[BDIGBUFSIZE];
convbase(buf, lwatch_fds[i], 10);
zaddlinknode(funcargs, ztrdup(buf));
}
# ifdef HAVE_POLL
# ifdef POLLERR
if (fds[i+1].revents & POLLERR)
zaddlinknode(funcargs, ztrdup("err"));
# endif
# ifdef POLLHUP
if (fds[i+1].revents & POLLHUP)
zaddlinknode(funcargs, ztrdup("hup"));
# endif
# ifdef POLLNVAL
if (fds[i+1].revents & POLLNVAL)
zaddlinknode(funcargs, ztrdup("nval"));
# endif
# endif
callhookfunc(lwatch_funcs[i], funcargs);
if (errflag) {
/* No sensible way of handling errors here */
errflag = 0;
/*
* Paranoia: don't run the hooks again this
* time.
*/
errtry = 1;
}
freelinklist(funcargs, freestr);
}
}
/* Function may have invalidated the display. */
if (resetneeded)
zrefresh();
zfree(lwatch_fds, lnwatch*sizeof(int));
freearray(lwatch_funcs);
}
} while (!
# ifdef HAVE_POLL
(fds[0].revents & POLLIN)
# else
FD_ISSET(SHTTY, &foofd)
# endif
);
# ifdef HAVE_POLL
zfree(fds, sizeof(struct pollfd) * nfds);
# endif
if (selret < 0)
return selret;
}
#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
ret = read(SHTTY, cptr, 1);
# ifdef HAVE_TERMIOS_H
tcsetattr(SHTTY, TCSANOW, &shttyinfo.tio);
# else
ioctl(SHTTY, TCSETA, &shttyinfo.tio);
# endif
return (ret <= 0) ? ret : *cptr;
# endif
#endif
}
ret = read(SHTTY, cptr, 1);
return ret;
}
/**/
mod_export int
getkey(int keytmout)
{
char cc;
unsigned int ret;
int die = 0, r, icnt = 0;
int old_errno = errno, obreaks = breaks;
if (kungetct)
ret = STOUC(kungetbuf[--kungetct]);
else {
#ifdef FIONREAD
if (delayzsetterm) {
int val;
ioctl(SHTTY, FIONREAD, (char *)&val);
if (!val)
zsetterm();
}
#endif
for (;;) {
int q = queue_signal_level();
dont_queue_signals();
r = raw_getkey(keytmout, &cc);
restore_queue_signals(q);
if (r == -2) /* timeout */
return EOF;
if (r == 1)
break;
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 ((zlereadflags & ZLRF_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;
}
/**/
void
zlecore(void)
{
#if !defined(HAVE_POLL) && defined(HAVE_SELECT)
struct timeval tv;
fd_set foofd;
FD_ZERO(&foofd);
#endif
zrefresh();
while (!done && !errflag) {
statusline = NULL;
vilinerange = 0;
reselectkeymap();
selectlocalmap(NULL);
bindk = getkeycmd();
if (!ll && isfirstln && !(zlereadflags & ZLRF_IGNOREEOF) &&
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_POLL
if (baud && !(lastcmd & ZLE_MENUCMP)) {
struct pollfd pfd;
int to = cost * costmult / 1000; /* milliseconds */
if (to > 500)
to = 500;
pfd.fd = SHTTY;
pfd.events = POLLIN;
if (!kungetct && poll(&pfd, 1, to) <= 0)
zrefresh();
} else
#else
# 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
#endif
if (!kungetct)
zrefresh();
}
}
/* 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");
#if defined(HAVE_POLL) || defined(HAVE_SELECT)
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;
free_prepostdisplay();
zlereadflags = flags;
histline = curhist;
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;
resetneeded = 1;
errflag = retflag = 0;
lastcol = -1;
initmodifier(&zmod);
prefixflag = 0;
zlecore();
statusline = NULL;
invalidatelist();
trashzle();
free(lpromptbuf);
free(rpromptbuf);
zleactive = zlereadflags = lastlistlen = 0;
alarm(0);
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 (keybuf[0] == eofchar && !keybuf[1] &&
!ll && isfirstln && (zlereadflags & ZLRF_IGNOREEOF)) {
showmsg((!islogin) ? "zsh: use 'exit' to exit." :
"zsh: use 'logout' to logout.");
ret = 1;
} else {
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) {
int atcurhist = histline == curhist;
compwidget = w;
ret = completecall(args);
if (atcurhist)
histline = curhist;
} else {
queue_signals();
ret = w->u.fn(args);
unqueue_signals();
}
if (!(wflags & ZLE_NOTCOMMAND))
lastcmd = wflags;
}
r = 1;
} else {
Shfunc shf = (Shfunc) shfunctab->getnode(shfunctab, w->u.fnnam);
Eprog prog = (shf ? shf->funcdef : &dummy_eprog);
if(prog == &dummy_eprog) {
/* 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;
int oxt = isset(XTRACE);
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;
opts[XTRACE] = 0;
doshfunc(w->u.fnnam, prog, largs, shf->flags, 0);
opts[XTRACE] = oxt;
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 */
/**/
mod_export char *varedarg;
/* vared: edit (literally) a parameter value */
/**/
static int
bin_vared(char *name, char **args, Options ops, int func)
{
char *s, *t, *ova = varedarg;
struct value vbuf;
Value v;
Param pm = 0;
int create = 0, ifl;
int type = PM_SCALAR, obreaks = breaks, haso = 0;
char *p1 = NULL, *p2 = NULL;
FILE *oshout = NULL;
if ((interact && unset(USEZLE)) || !strcmp(term, "emacs")) {
zwarnnam(name, "ZLE not enabled", NULL, 0);
return 1;
}
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->ind['h'] = 1;
break;
case 'e':
/* -e option -- enable EOF */
ops->ind['e'] = 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];
queue_signals();
v = fetchvalue(&vbuf, &s, (!create || type == PM_SCALAR),
SCANPM_WANTKEYS|SCANPM_WANTVALS|SCANPM_MATCHMANY);
if (!v && !create) {
unqueue_signals();
zwarnnam(name, "no such variable: %s", args[0], 0);
return 1;
} else if (v) {
if (v->isarr) {
/* Array: check for separators and quote them. */
char **arr = getarrvalue(v), **aptr, **tmparr, **tptr;
tptr = tmparr = (char **)zhalloc(sizeof(char *)*(arrlen(arr)+1));
for (aptr = arr; *aptr; aptr++) {
int sepcount = 0;
/*
* See if this word contains a separator character
* or backslash
*/
for (t = *aptr; *t; t++) {
if (*t == Meta) {
if (isep(t[1] ^ 32))
sepcount++;
t++;
} else if (isep(*t) || *t == '\\')
sepcount++;
}
if (sepcount) {
/* Yes, so allocate enough space to quote it. */
char *newstr, *nptr;
newstr = zhalloc(strlen(*aptr)+sepcount+1);
/* Go through string quoting separators */
for (t = *aptr, nptr = newstr; *t; ) {
if (*t == Meta) {
if (isep(t[1] ^ 32))
*nptr++ = '\\';
*nptr++ = *t++;
} else if (isep(*t) || *t == '\\')
*nptr++ = '\\';
*nptr++ = *t++;
}
*nptr = '\0';
/* Stick this into the array of words to join up */
*tptr++ = newstr;
} else
*tptr++ = *aptr; /* No, keep original array element */
}
*tptr = NULL;
s = sepjoin(tmparr, NULL, 0);
} else {
s = ztrdup(getstrvalue(v));
}
unqueue_signals();
} else if (*s) {
unqueue_signals();
zwarnnam(name, "invalid parameter name: %s", args[0], 0);
return 1;
} else {
unqueue_signals();
s = ztrdup(s);
}
if (SHTTY == -1) {
/* need to open /dev/tty specially */
if ((SHTTY = open("/dev/tty", O_RDWR|O_NOCTTY)) == -1) {
zwarnnam(name, "can't access terminal", NULL, 0);
return 1;
}
oshout = shout;
init_shout();
haso = 1;
}
/* edit the parameter value */
zpushnode(bufstack, s);
varedarg = *args;
ifl = isfirstln;
if (OPT_ISSET(ops,'h'))
hbegin(2);
isfirstln = OPT_ISSET(ops,'e');
t = (char *) zleread(p1, p2, OPT_ISSET(ops,'h') ? ZLRF_HISTORY : 0);
if (OPT_ISSET(ops,'h'))
hend(NULL);
isfirstln = ifl;
varedarg = ova;
if (haso) {
fclose(shout); /* close(SHTTY) */
shout = oshout;
SHTTY = -1;
}
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) {
unsetparam(args[0]);
createparam(args[0], type);
}
queue_signals();
pm = (Param) paramtab->getnode(paramtab, args[0]);
if (pm && (PM_TYPE(pm->flags) & (PM_ARRAY|PM_HASHED))) {
char **a;
/*
* Use spacesplit with fourth argument 1: identify quoted separators,
* and unquote. This duplicates the string, so we still need to free.
*/
a = spacesplit(t, 1, 0, 1);
zsfree(t);
if (PM_TYPE(pm->flags) == PM_ARRAY)
setaparam(args[0], a);
else
sethparam(args[0], a);
} else
setsparam(args[0], t);
unqueue_signals();
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;
}
/**/
int
recursiveedit(char **args)
{
int locerror;
zlecore();
locerror = errflag;
errflag = done = 0;
return locerror;
}
/**/
mod_export 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;
trashedzle = 1;
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 (!(zlereadflags & ZLRF_NOSETTY))
settyinfo(&shttyinfo);
}
if (errflag)
kungetct = 0;
}
/* Hook functions. Used to allow access to zle parameters if zle is
* active. */
static int
zlebeforetrap(Hookdef dummy, void *dat)
{
if (zleactive) {
startparamscope();
makezleparams(1);
}
return 0;
}
static int
zleaftertrap(Hookdef dummy, void *dat)
{
if (zleactive)
endparamscope();
return 0;
}
static struct builtin bintab[] = {
BUILTIN("bindkey", 0, bin_bindkey, 0, -1, 0, "evaMldDANmrsLRp", NULL),
BUILTIN("vared", 0, bin_vared, 1, 7, 0, NULL, NULL),
BUILTIN("zle", 0, bin_zle, 0, -1, 0, "aAcCDFgGIKlLmMNRU", NULL),
};
/* The order of the entries in this table has to match the *HOOK
* macros in zle.h */
/**/
mod_export 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_(Module m)
{
/* Set up editor entry points */
trashzleptr = trashzle;
refreshptr = zrefresh;
spaceinlineptr = spaceinline;
zlereadptr = zleread;
zlesetkeymapptr = zlesetkeymap;
getkeyptr = getkey;
/* initialise the thingies */
init_thingies();
lbindk = NULL;
/* miscellaneous initialisations */
stackhist = stackcs = -1;
kungetbuf = (char *) zalloc(kungetsz = 32);
comprecursive = 0;
rdstrs = NULL;
/* initialise the keymap system */
init_keymaps();
varedarg = NULL;
incompfunc = incompctlfunc = hascompmod = 0;
hascompwidgets = 0;
clwords = (char **) zcalloc((clwsize = 16) * sizeof(char *));
return 0;
}
/**/
int
boot_(Module m)
{
addhookfunc("before_trap", (Hookfn) zlebeforetrap);
addhookfunc("after_trap", (Hookfn) zleaftertrap);
addbuiltins(m->nam, bintab, sizeof(bintab)/sizeof(*bintab));
addhookdefs(m->nam, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
return 0;
}
/**/
int
cleanup_(Module m)
{
if(zleactive) {
zerrnam(m->nam, "can't unload the zle module while zle is active",
NULL, 0);
return 1;
}
deletehookfunc("before_trap", (Hookfn) zlebeforetrap);
deletehookfunc("after_trap", (Hookfn) zleaftertrap);
deletebuiltins(m->nam, bintab, sizeof(bintab)/sizeof(*bintab));
deletehookdefs(m->nam, zlehooks, sizeof(zlehooks)/sizeof(*zlehooks));
return 0;
}
/**/
int
finish_(Module m)
{
int i;
unrefthingy(lbindk);
cleanup_keymaps();
deletehashtable(thingytab);
zfree(vichgbuf, vichgbufsz);
zfree(kungetbuf, kungetsz);
free_isrch_spots();
if (rdstrs)
freelinklist(rdstrs, freestr);
zfree(cutbuf.buf, cutbuf.len);
if (kring) {
for(i = kringsize; i--; )
zfree(kring[i].buf, kring[i].len);
zfree(kring, kringsize * sizeof(struct cutbuffer));
}
for(i = 35; i--; )
zfree(vibuf[i].buf, vibuf[i].len);
/* editor entry points */
trashzleptr = noop_function;
refreshptr = noop_function;
spaceinlineptr = noop_function_int;
zlereadptr = fallback_zleread;
zlesetkeymapptr= noop_function_int;
getkeyptr = NULL;
zfree(clwords, clwsize * sizeof(char *));
return 0;
}
|