aboutsummaryrefslogtreecommitdiffstats
path: root/pw.c
blob: bf27dad19dd609c8aef1b1eca6958e0f8b6283c1 (plain)
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
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
// Pipe Watch ("pw")
// Copyright 2022 Kaz Kylheku <kaz@kylheku.com>
//
// BSD-2 License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <regex.h>

#define ctrl(ch) ((ch) & 0x1f)
#define BS 8
#define CR 13
#define ESC 27
#define DEL 127

#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))

#ifdef __GNUC__
#define printf_attr(fmtpos, vargpos) __attribute__ ((format (printf, \
                                                             fmtpos, vargpos)))
#else
#define printf_attr(fmtpos, vargpos)
#endif

#define cmdsize 256
#define maxgrep 64
#define maxtrig 100
#define snhistsize 20
#define workmax 4096

enum status_flags {
  stat_dirty =    0x0001, // display needs refresh
  stat_eof =      0x0002, // end of data reached
  stat_susp =     0x0004, // display refresh suspended
  stat_htmode =   0x0008, // head trigger mode
  stat_ttmode =   0x0010, // tail trigger mode
  stat_trgrd =    0x0020, // triggered flag
  stat_grep =     0x0040, // grep mode
  stat_force =    0x0080, // force refresh even if clean
  stat_lino =     0x0100, // render line numbers
  stat_bkgnd =    0x0200, // running in the background
  stat_hlite =    0x0400, // running in the background
  stat_oneshot =  0x0800, // running in the background
  stat_save =     stat_susp | stat_lino | stat_hlite
};

typedef enum execode {
  exec_ok, exec_msg, exec_failed
} execode;

typedef struct pwstate {
  char **circbuf;
  int nlines, maxlines;
  int hpos;
  int vsplit1, vsplit2, vs2pos;
  int hist;
  int columns;
  unsigned stat;
  int sncount, tcount;
  char *curcmd, *savedcmd;
  char cmdbuf[cmdsize];
} pwstate;

typedef struct grep {
  char *pat;
  regex_t rx;
  int inv;
  int flags;
  int err;
  void (*dtor)(char *);
} grep;

typedef struct dstr {
  int refs;
  size_t len;
  char str[];
} dstr;

#define dstr_of(str) ((dstr *) ((str) - sizeof (dstr)))

static char *pw_name;
static int poll_interval = 1000;
static int long_interval = 10000;
static int regex_flags = 0;

static char **snapshot[snhistsize];
static int snaplines[snhistsize];

static grep grepstack[maxgrep];
static int ngrep;

static grep *triglist[maxtrig];
static int sncount;
static int tfreq;

static char **cmdhist;
static int ncmdhist;

static char **pathist;
static int npathist;

volatile sig_atomic_t winch;

static void panic(const char *fmt, ...)
{
  va_list vl;
  va_start (vl, fmt);
  fprintf(stderr, "%s: ", pw_name);
  vfprintf(stderr, fmt, vl);
  abort();
}

printf_attr(1, 2)
static void error(const char *fmt, ...)
{
  va_list vl;
  va_start (vl, fmt);
  fprintf(stderr, "%s: ", pw_name);
  vfprintf(stderr, fmt, vl);
}

static char *dsref(char *str)
{
  dstr *ds = dstr_of(str);
  ds->refs++;
  return str;
}

static void dsdrop(char *str)
{
  if (str) {
    dstr *ds = dstr_of(str);
    assert (ds->refs > 0);
    if (!--ds->refs)
      free(ds);
  }
}

static size_t dslen(const char *str)
{
  if (str) {
    const dstr *ds = dstr_of(str);
    return ds->len;
  }
  return 0;
}

static char *dsgrow(char *str, size_t len)
{
  dstr *ds = str ? dstr_of(str) : 0;
  size_t size = sizeof *ds + len + 1;

  assert (ds == 0 || ds->refs == 1);

  if (size < len)
    panic("string size overflow");
  ds = realloc(ds, size);
  if (ds == 0)
    panic("out of memory");

  ds->refs = 1;
  ds->len = len;
  ds->str[len] = 0;

  return ds->str;
}

static char *dsensure(char *str)
{
  if (str)
    return str;
  return dsgrow(0, 0);
}

static char *dsdup(const char *str)
{
  size_t len = strlen(str);
  char *copy = dsgrow(0, len);
  memcpy(copy, str, len);
  return copy;
}

printf_attr(1, 2)
static char *dsdupf(char *fmt, ...)
{
  size_t len = 256, needed;
  char *out = dsgrow(0, len);

  for (;;) {
    va_list vl;
    va_start (vl, fmt);
    needed = vsnprintf(out, len + 1, fmt, vl);
    va_end (vl);
    if (needed <= len)
      break;
    len = needed;
  }

  return dsgrow(out, needed);
}

static char *addch(char *line, int ch)
{
  size_t len = line ? dslen(line) : 0;

  if (len + 1 > len) {
    char *nline = dsgrow(line, len + 1);

    if (nline == 0)
      panic("out of memory");

    nline[len] = ch;
    return nline;
  }

  panic("line overflow");
  abort();
}

static char *addchesc(char *line, int ch)
{
  if (ch == DEL) {
    line = addch(line, '^');
    line = addch(line, '?');
  } else if (ch < 32) {
    line = addch(line, '^');
    line = addch(line, ch + 64);
  } else {
    line = addch(line, ch);
  }

  return line;
}

static char *getln(FILE *stream)
{
  for (char *line = 0;;) {
    int ch = getc(stream);
    if (ch == EOF)
      return line;
    if (ch == '\n')
      return dsensure(line);
    line = addchesc(line, ch);
  }
}

static void usage(void)
{
  fprintf(stderr,
          "\nUsage: <command> | %s [options]\n\n"
          "-i realnum      poll interval (s)\n"
          "-l realnum      long update interval (s)\n"
          "-n integer      display size (# of lines)\n"
          "-d              do not quit on end-of-input\n"
          "-q integer      Require this many repetitions of q to quit\n"
          "-E              treat regular expressions as extended\n"
          "-B              treat regular expressions as basic (default)\n"
          "-g [!]pattern   add pattern to grep stack; ! inverts\n"
          "-m integer      specify maixmum line length\n"
          "-p values       set display parameters\n"
          "-e command      execute : /  ? command\n"
          "-f file         execute : /  ? commands from file\n\n"
          "<command> represents an arbitrary command that generates the\n"
          "output to be monitored by %s.\n\n"
          "Standard input must be redirected; it cannot be the same device\n"
          "as the controlling tty (/dev/tty) of the terminal session.\n\n"
          "For a full description, see the manual page.\n\n",
          pw_name, pw_name);
  exit(EXIT_FAILURE);
}

static int grinit(grep *gr, char *pat, int inv, void (*dtor)(char *))

{
  gr->pat = pat;
  gr->inv = inv;
  gr->dtor = dtor;
  gr->flags = regex_flags;
  return (gr->err = regcomp(&gr->rx, pat, regex_flags | REG_NOSUB)) != 0;
}

static void grclean(grep *gr)
{
  if (gr->err == 0)
    regfree(&gr->rx);
  if (gr->dtor)
    gr->dtor(gr->pat);
  memset(gr, 0, sizeof *gr);
}

static int grerr(grep *gr)
{
  return gr->err;
}

static size_t grerrstr(grep *gr, char *buf, size_t size)
{
  return regerror(gr->err, &gr->rx, buf, size);
}

static grep *grnew(char *pat, int inv, void (*dtor)(char *))
{
  grep *gr = calloc(sizeof *gr, 1);
  if (gr == 0)
    panic("out of memory");
  (void) grinit(gr, pat, inv, dtor);
  return gr;
}

static void grfree(grep *gr)
{
  if (gr != 0)  {
    grclean(gr);
    free(gr);
  }
}

static int grexec(grep *gr, const char *line)
{
  int match = regexec(&gr->rx, line, 0, NULL, 0) == 0;
  return match != gr->inv;
}

static void clrline(unsigned stat)
{
  if ((stat & stat_bkgnd) == 0)
    printf("\r\033[J");
}

static void clreol(int nl)
{
  printf("\033[K");
  if (nl)
    putchar('\n');
}

static void hlon(void)
{
  printf("\033[7m");
}

static void hloff(void)
{
  printf("\033[m");
}

#define with_hl(pw, expr) do {                                                \
  if ((pw)->stat & stat_hlite)                                                \
    hlon();                                                                   \
  expr;                                                                       \
  if ((pw)->stat & stat_hlite)                                                \
    hloff();                                                                  \
} while (0)

static void hlchar(pwstate *pw, int ch)
{
  with_hl(pw, putchar(ch));
}

static void drawline(pwstate *pw, const char *line, int lineno)
{
  const char *oline = line;
  int olen = (int) dslen(line), len = olen;
  int columns = pw->columns;
  int vsplit1 = pw->vsplit1;
  int vsplit2 = pw->vsplit2;
  int vs2pos = pw->vs2pos;
  int endmark = 0;

  if (lineno >= 0)
    columns -= printf("%3d ", lineno);

  if (vsplit1 > 0) {
    if (len <= vsplit1) {
      if (!vsplit2) {
        fputs(line, stdout);
        columns -= len;
      } else {
        int spaces = vsplit1 - len;
        fputs(line, stdout);
        for (int i = 0; i < spaces; i++)
          putchar(' ');
        columns -= vsplit1;
      }
      line += len;
      len = 0;
    } else {
      for (int i = 0; i < vsplit1; i++)
        putchar(line[i]);
      len -= vsplit1;
      line += vsplit1;
      columns -= vsplit1;
      endmark = 1;
    }
  }

  if (vsplit2 > 0) {
    int width = vsplit2;
    int i = 0;

    if (vsplit1 || vs2pos) {
      hlchar(pw, '|');
      i++;
    }

    if (vs2pos < olen) {
      int nchar = min(olen - vs2pos, width);
      const char *ptr = oline + vs2pos + i;
      for (; i < nchar; i++)
        putchar(*ptr++);
      endmark = 1;
    }

    if (len > vsplit2 + pw->hpos) {
      for (; i < width; i++)
        putchar(' ');

      columns -= vsplit2;
      line += vsplit2;
      len -= vsplit2;
      endmark = 1;
    } else {
      line += len;
      len = 0;
      endmark = (i == width);
    }
  }

  if (pw->hpos < len) {
    if (pw->hpos || vsplit1 || vsplit2) {
      line += pw->hpos + 1;
      len -= pw->hpos + 1;
      hlchar(pw, '>');
      columns--;
    }
    if (len < columns) {
      fputs(line, stdout);
      clreol(1);
    } else {
      for (int i = 0; i < columns - 1; i++)
        putchar(line[i]);
      hlchar(pw, '<');
      putchar('\n');
    }
  } else {
    if (endmark)
      hlchar(pw, '>');
    clreol(1);
  }
}

static void drawstatus(pwstate *pw)
{
  char status[cmdsize] = "", *ptr = status;
  size_t lim = sizeof status;

  if ((pw->stat & stat_bkgnd))
    return;

  if (pw->columns - 1 < (int) lim)
    lim = pw->columns - 1;

  char *end = ptr + lim;

  if (pw->curcmd) {
    snprintf(status, lim, "%s", pw->curcmd);
  } else if (pw->hist > 0 ||
             (pw->stat & (stat_eof | stat_susp | stat_htmode | stat_ttmode |
                          stat_grep)))
  {
    if (pw->hist > 0)
      ptr += snprintf(ptr, end - ptr, "HIST%u ", pw->hist);

    if ((pw->stat & stat_eof))
      ptr += snprintf(ptr, end - ptr, "EOF ");

    if ((pw->stat & stat_grep)) {
      ptr += snprintf(ptr, end - ptr, "GREP (");
      for (int i = 0; i < ngrep; i++) {
        grep *gr = &grepstack[i];
        ptr += snprintf(ptr, end - ptr, "%s%s%c ",
                        gr->inv ? "!" : "", gr->pat,
                        (i < ngrep - 1) ? ',' : ')');
      }
    }

    if ((pw->stat & (stat_htmode | stat_ttmode))) {
      ptr += snprintf(ptr, end - ptr, "TRIG%c (",
                      (pw->stat & stat_htmode) ? '/' : '?');
      for (int i = 0, first = 1; i < maxtrig; i++) {
        grep *gr = triglist[i];
        if (gr) {
          if (!first)
            ptr += snprintf(ptr, end - ptr, ", ");
          if (i > 0)
            ptr += snprintf(ptr, end - ptr, "[%d]", i + 1);
          ptr += snprintf(ptr, end - ptr, "%s%s", gr->inv ? "!" : "", gr->pat);
          first = 0;
        }
      }
      ptr += snprintf(ptr, end - ptr, ") ");
    }

    if ((pw->stat & stat_susp))
      ptr += snprintf(ptr, end - ptr, "SUSPENDED ");
  }

  fputs(status, stdout);
  clreol(0);
  fflush(stdout);
}

static void freebuf(char **buf, size_t size)
{
  if (buf != 0)
    for (size_t i = 0; i < size; i++)
      dsdrop(buf[i]);
}

static void redraw(pwstate *pw)
{
  int updln = 0;

  if ((pw->stat & (stat_dirty | stat_susp)) == stat_dirty &&
      (pw->stat & (stat_htmode | stat_trgrd)) != stat_htmode &&
      (pw->stat & (stat_ttmode | stat_trgrd)) != stat_ttmode)
  {
    if (snapshot[snhistsize - 1]) {
      freebuf(snapshot[snhistsize - 1], snaplines[snhistsize - 1]);
      free(snapshot[snhistsize - 1]);
    }
    memmove(snapshot + 1, snapshot, sizeof *snapshot * (snhistsize - 1));
    memmove(snaplines + 1, snaplines, sizeof *snaplines * (snhistsize - 1));
    snapshot[0] = calloc(sizeof *snapshot[0], pw->nlines);
    snaplines[0] = pw->nlines;
    updln = 1;
    for (int i = 0; i < pw->nlines; i++)
      snapshot[0][i] = dsref(pw->circbuf[i]);
    if ((pw->stat & stat_oneshot))
      pw->stat |= stat_susp;
    pw->stat &= ~(stat_dirty | stat_trgrd | stat_oneshot);
    updln = 1;
  } else if ((pw->stat & stat_force)) {
    pw->stat &= ~stat_force;
    updln = 1;
  }

  if ((pw->stat & stat_bkgnd))
    return;

  if (updln && snaplines[pw->hist] > 0) {
    printf("\r\033[%dA", snaplines[pw->hist]);
    if ((pw->stat & stat_lino) == 0) {
      for (int i = 0; i < snaplines[pw->hist]; i++)
        drawline(pw, snapshot[pw->hist][i], -1);
    } else {
      int start = 1, step = 1;
      if (pw->stat & stat_htmode) {
        start = snaplines[pw->hist];
        step = -1;
      }
      for (int i = 0, l = start; i < snaplines[pw->hist]; i++, l += step)
        drawline(pw, snapshot[pw->hist][i], l);
    }
  } else {
    clrline(pw->stat);
  }

  drawstatus(pw);
}

static int getznn(const char *str, char **err)
{
  char *endp;
  long val = strtol(str, &endp, 10);

  if (endp == str) {
    *err = dsdup("number expected");
    return -1;
  }
  if (val < 0) {
    *err = dsdup("non-negative value required");
    return -1;
  }

  if (val >= INT_MAX) {
    *err = dsdup("unreasonably large value");
    return -1;
  }

  return val;
}

static int getzp(const char *str, char **err)
{
  int val = getznn(str, err);

  if (val <= 0) {
    *err = dsdup("positive value required");
    return -1;
  }

  return val;
}

static int getms(const char *str, char **err)
{
  errno = 0;
  char *endp;
  double sec = strtod(str, &endp);

  if (endp == str) {
    *err = dsdup("number expected");
    return -1;
  }

  if ((sec == 0 || sec == HUGE_VAL) && errno != 0) {
    *err = dsdup("unreasonable real value");
    return -1;
  }

  if (sec < 0) {
    *err = dsdup("positive value required");
    return -1;
  }

  double msec = sec * 1000;

  if (msec > (double) INT_MAX) {
    *err = dsdupf("maximum interval is %f", INT_MAX / 1000.0);
    return -1;
  }

  return msec;
}

static int decodeparms(pwstate *pw, char *parms,
                       char *resbuf, size_t size)
{
  char *err;
  char *hpos = strtok(parms, ", \t");
  char *lpane = strtok(0, ", \t");
  char *rpane = strtok(0, ", \t");
  char *vs2pos = strtok(0, ", \t");
  char *flags = strtok(0, ", \t");

  if (hpos && (pw->hpos = getznn(hpos, &err)) < 0) {
    snprintf(resbuf, size, "bad horizontal scroll offset %s: %s\n", hpos, err);
    return 0;
  }

  if (lpane && (pw->vsplit1 = getznn(lpane, &err)) < 0) {
    snprintf(resbuf, size, "bad left pane width %s: %s\n", lpane, err);
    return 0;
  }

  if (rpane && (pw->vsplit2 = getznn(rpane, &err)) < 0) {
    snprintf(resbuf, size, "bad right pane width %s: %s\n", rpane, err);
    return 0;
  }

  if (vs2pos && (pw->vs2pos = getznn(vs2pos, &err)) < 0) {
    snprintf(resbuf, size, "bad right pane view offset %s: %s\n", vs2pos, err);
    return 0;
  }

  if (flags) {
    int stat = getznn(flags, &err);
    if (stat < 0) {
      snprintf(resbuf, size, "bad flags %s: %s\n", flags, err);
      return 0;
    }
    pw->stat &= ~stat_save;
    pw->stat |= (stat & stat_save);
  }

  return 1;
}

static execode execute(pwstate *pw, char *cmd, char *resbuf,
                       size_t size, int count)
{
  execode res = exec_failed;
  char *arg = cmd + 2 + strspn(cmd + 2, " \t");

  clrline(0);

  if (cmd[0] == ':') switch (cmd[1]) {
  case 'w': case 'a':
    if (arg[0] == 0) {
      snprintf(resbuf, size, "file name required!");
      break;
    } else {
      FILE *f = fopen(arg, cmd[1] == 'w' ? "w" : "a");

      if (!f) {
        snprintf(resbuf, size, "unable to open file");
        break;
      }

      res = exec_msg;

      for (int i = 0; res == exec_msg && i < snaplines[pw->hist]; i++)
        if (fprintf(f, "%s\n", snapshot[pw->hist][i]) < 0) {
          snprintf(resbuf, size, "write error!");
          res = exec_failed;
          break;
        }

      fclose(f);
      if (res == exec_msg)
        snprintf(resbuf, size, "saved!");
    }
    break;
  case '!':
    if (arg[0] == 0) {
      snprintf(resbuf, size, "command required!");
      break;
    } else {
      FILE *p = popen(arg, "w");

      if (!p) {
        snprintf(resbuf, size, "unable to open command");
        break;
      }

      res = exec_msg;

      for (int i = 0; i < snaplines[pw->hist] && res == exec_msg; i++)
        if (fprintf(p, "%s\n", snapshot[pw->hist][i]) < 0) {
          snprintf(resbuf, size, "write error!");
          res = exec_failed;
          break;
        }

      pclose(p);
      if (res == exec_msg)
        snprintf(resbuf, size, "piped!");
    }
    break;
  case 'g':
  case 'v':
    {
      grep *gr = &grepstack[ngrep];

      if (arg[0] == 0) {
        snprintf(resbuf, size, "pattern required!");
        break;
      }

      if (ngrep >= maxgrep) {
        snprintf(resbuf, size, "too many greps");
        break;
      }

      if ((grinit(gr, dsdup(arg), cmd[1] == 'v', dsdrop)) != 0) {
        grerrstr(gr, resbuf, size);
        grclean(gr);
        break;
      }

      if (ngrep++ == 0)
        pw->stat |= stat_grep;

      res = exec_ok;
    }
    break;
  case 'r':
    while (ngrep > 0) {
      grclean(&grepstack[--ngrep]);
      if (cmd[2] != '!')
        break;
    }
    if (ngrep == 0)
      pw->stat &= ~stat_grep;
    res = exec_ok;
    break;
  case 'i': case 'l':
    {
      char *err = 0;
      int interval = getms(arg, &err);

      if (interval < 0) {
        snprintf(resbuf, size, "%s", err);
        break;
      }

      if (cmd[1] == 'i')
        poll_interval = interval;
      else
        long_interval = interval;

      dsdrop(err);
      res = exec_ok;
    }
    break;
  case 'E':
    regex_flags = REG_EXTENDED;
    res = exec_ok;
    break;
  case 'B':
    regex_flags = 0;
    res = exec_ok;
    break;
  case 'c':
    if (arg[0] == 0) {
      pw->sncount = 0;
    } else  {
      char *err = 0;
      int val = getznn(arg, &err);
      if (val < 0) {
        snprintf(resbuf, size, "bad trigger count: %s", err);
        break;
      }
      sncount = val;
      dsdrop(err);
      res = exec_ok;
    }
    break;
  case 'f':
    if (arg[0] == 0) {
      snprintf(resbuf, size, "frequency argument required!");
      break;
    }
    {
      char *err = 0;
      int val = getznn(arg, &err);
      if (val < 0) {
        snprintf(resbuf, size, "bad trigger freq: %s", err);
        break;
      }
      tfreq = val;
      dsdrop(err);
      res = exec_ok;
    }
    break;
  case 'p':
    {
      if (decodeparms(pw, arg, resbuf, size)) {
        pw->stat |= stat_force;
        res = exec_ok;
      }
    }
    break;
  case 's':
    {
      int rflg = 0;
      FILE *f;

      if (arg[0] == 0) {
        snprintf(resbuf, size, "file name required!");
        break;
      }

      if ((f = fopen(arg, "w")) == 0) {
        snprintf(resbuf, size, "unable to open %s", arg);
        break;
      }

      fprintf(f, ":p%d,%d,%d,%d,%d\n", pw->hpos, pw->vsplit1, pw->vsplit2,
              pw->vs2pos, (int) pw->stat & stat_save);

      if (pw->tcount)
        fprintf(f, ":f%d\n", pw->tcount);
      if (pw->sncount)
        fprintf(f, ":c%d\n", pw->sncount);

      for (int i = 0; i < ngrep; i++) {
        grep *gr = &grepstack[i];
        if (gr->flags != rflg) {
          rflg = gr->flags;
          fputs(((gr->flags & REG_EXTENDED)) ? ":E\n" : ":B\n", f);
        }
        fputs(gr->inv ? ":v" : ":g", f);
        fputs(gr->pat, f);
        putc('\n', f);
      }

      if ((pw->stat & (stat_htmode | stat_ttmode))) {
        int tch = ((pw->stat & stat_htmode)) ? '/' : '?';
        for (int i = 0; i < maxtrig; i++) {
          grep *gr = triglist[i];
          if (gr != 0) {
            if (gr->flags != rflg) {
              rflg = gr->flags;
              fputs(((gr->flags & REG_EXTENDED)) ? ":E\n" : ":B\n", f);
            }
            if (gr->inv)
              fprintf(f, "%d%c!%s\n", i + 1, tch, gr->pat);
            else if (gr->pat[0] == '!')
              fprintf(f, "%d%c\\!%s\n", i + 1, tch, gr->pat);
            else
              fprintf(f, "%d%c%s\n", i + 1, tch, gr->pat);
          }
        }
      }

      if (ferror(f)) {
        snprintf(resbuf, size, "write error!");
      } else {
        snprintf(resbuf, size, "config saved!");
        res = exec_msg;
      }

      fclose(f);
    }
    break;
  case 0:
    res = exec_ok;
    break;
  default:
    snprintf(resbuf, size, "bad command");
    break;
  } else {
    int trig = count > 0 ? count - 1 : count;

    if (trig < pw->maxlines && trig < maxtrig)
    {
      const char *rx = cmd + 1;
      int inv = 0;
      grep *gr = 0;

      if (strncmp(rx, "\\!", 2) == 0) {
        rx++;
      } else if (rx[0] == '!') {
        rx++;
        inv = 1;
      }

      char *pat = dsdup(rx);

      if (*pat && (gr = grnew(dsref(pat), inv, dsdrop),
                   grerr(gr) != 0))
      {
        grerrstr(gr, resbuf, size);
        grfree(gr);
      } else {
        if ((cmd[0] == '/' && (pw->stat & stat_ttmode)) ||
            (cmd[0] == '?' && (pw->stat & stat_htmode)))
        {
          for (int i = 0; i < maxtrig; i++) {
            grfree(triglist[i]);
            triglist[i] = 0;
          }
        }

        grfree(triglist[trig]);
        triglist[trig] = gr;
        res = exec_ok;
      }
      dsdrop(pat);
    } else {
      snprintf(resbuf, size, "trigger position out of range");
      res = exec_failed;
    }

    if (res == exec_ok) {
      pw->stat &= ~(stat_htmode | stat_ttmode);
      for (int i = 0; i < maxtrig; i++) {
        if (triglist[i]) {
          pw->stat |= (cmd[0] == '/'
                       ? stat_htmode : stat_ttmode);
          break;
        }
      }
    }
  }

  return res;
}

static execode batchexe(pwstate *pw, char *cmd, char *resbuf, size_t size)
{
  size_t ndigits = strspn(cmd, "0123456789");
  int count = 0;

  if (ndigits > 3) {
    snprintf(resbuf, size, "command count out of 0-999 range");
    return exec_failed;
  } else if (ndigits) {
    (void) sscanf(cmd, "%3d", &count);
    cmd += ndigits;
  }
  switch (cmd[0]) {
  case ':': case '?': case '/':
    return execute(pw, cmd, resbuf, size, count);
  }
  snprintf(resbuf, size, "missing command prefix [:/?]");
  return exec_failed;
}

static void ttyset(int fd, struct termios *tty)
{
  if (tcsetattr(fd, TCSANOW, tty) < 0)
    panic("unable to set TTY parameters");
}

static void ttyget(int fd, struct termios *tty)
{
  if (tcgetattr(fd, tty) < 0)
    panic("unable to get TTY parameters");
}

static void sigwinch(int sig)
{
  (void) sig;
  winch = 1;
}

static char **resizebuf(char **buf, size_t nlfrom, size_t nlto)
{
  if (nlfrom > nlto) {
    for (size_t i = nlto; i < nlfrom; i++)
      dsdrop(buf[i]);
  } else if (nlfrom < nlto) {
    if ((buf = realloc(buf, sizeof *buf * nlto)) == 0)
      panic("out of memory");
    memset(buf + nlfrom, 0, (nlto - nlfrom) * sizeof *buf);
  }
  return buf;
}

int isbkgnd(FILE *tty)
{
  int fd = fileno(tty);
  pid_t grp = getpgrp();
  pid_t fgrp = tcgetpgrp(fd);
  return (grp != fgrp);
}

void clipsplits(pwstate *pw)
{
  int columns = pw->columns;

  if ((pw->stat & stat_lino))
    columns -= 4;

  if (columns < 8 || (int) pw->vsplit1 > columns - 2) {
    pw->vsplit2 = 0;
    pw->vsplit1 = columns - 2;
  } else if ((int) (pw->vsplit1 + pw->vsplit2) >= columns - 2) {
    pw->vsplit2 = columns - 2 - pw->vsplit1;
  }
}

int main(int argc, char **argv)
{
  struct pwstate pw = { .columns = 80, .maxlines = 15 };
  char *line = 0;
  FILE *tty = fopen("/dev/tty", "r+");
  int maxed = 0;
  size_t maxlen = 2047;
  int opt;
  int ifd = fileno(stdin);
  int ttyfd = tty ? fileno(tty) : -1;
  struct termios tty_saved, tty_new;
  struct winsize ws = { 0 };
  enum kbd_state {
    kbd_cmd, kbd_esc, kbd_bkt, kbd_exit,
    kbd_lcmd, kbd_result
  };
  int auto_quit = 1;
  int quit_count = 1, quit_countdown = quit_count;
  int exit_status = EXIT_FAILURE;
#ifdef SIGWINCH
  static struct sigaction sa;
#endif

  pw_name = argv[0] ? argv[0] : "pw";

  if (ifd < 0)
    panic("unable to obtain input file descriptor\n");

  if (ttyfd < 0)
    panic("unable to open /dev/tty\n");

  {
    pid_t igrp = tcgetpgrp(ifd);
    pid_t tgrp = tcgetpgrp(ttyfd);

    if (igrp == tgrp) {
      error("standard input cannot be the TTY used for display\n");
      usage();
    }
  }

  while ((opt = getopt(argc, argv, "n:i:l:dEBg:q:m:p:e:f:")) != -1) {
    switch (opt) {
    case 'n':
      {
        char *err;
        if ((pw.maxlines = getzp(optarg, &err)) < 0) {
          error("-%c option: %s\n", opt, err);
          return EXIT_FAILURE;
        }
      }
      break;
    case 'i': case 'l':
      {
        char *err;
        int interval = getms(optarg, &err);

        if (interval < 0) {
          error("-%c option: %s\n", opt, err);
          return EXIT_FAILURE;
        }

        if (opt == 'i')
          poll_interval = interval;
        else
          long_interval = interval;
      }
      break;
    case 'd':
      auto_quit = 0;
      break;
    case 'q':
      {
        char *err;
        if ((quit_countdown = quit_count = getzp(optarg, &err)) < 0) {
          error("-%c option: %s\n", opt, err);
          return EXIT_FAILURE;
        }
        break;
      }
    case 'E':
      regex_flags = REG_EXTENDED;
      break;
    case 'B':
      regex_flags = 0;
      break;
    case 'g':
      {
        grep *gr = &grepstack[ngrep];
        char *pat = optarg;
        int inv = 0;

        if (ngrep >= maxgrep) {
          error("too many patterns specified with -g\n");
          return EXIT_FAILURE;
        }

        if (*pat == '!') {
          inv = 1;
          pat++;
        } else if (strncmp(pat, "\\!", 2) == 0) {
          pat++;
        }

        if ((grinit(gr, dsdup(pat), inv, dsdrop)) != 0) {
          char grmsg[cmdsize];
          grerrstr(gr, grmsg, sizeof grmsg);
          error("-%c option: bad pattern %s: %s\n", opt, pat, grmsg);
          return EXIT_FAILURE;
        }

        ngrep++;
        pw.stat |= stat_grep;
      }
      break;
    case 'm':
      {
        char *err;
        int val = getzp(optarg, &err);
        if (val < 0) {
          error("-%c option: bad value %s: %s\n", opt, optarg, err);
          return EXIT_FAILURE;
        }

        if ((int) (size_t) val != val)
          val = -1;
        maxlen = max(72, val);
      }
      break;
    case 'p':
      {
        int ok = decodeparms(&pw, optarg, pw.cmdbuf, cmdsize);
        if (!ok) {
          error("-%c option: %s\n", opt, pw.cmdbuf);
          return EXIT_FAILURE;
        }
      }
      break;
    case 'e':
      {
        if (batchexe(&pw, optarg, pw.cmdbuf, cmdsize) == exec_failed) {
          error("-%c option: %s: %s\n", opt, optarg, pw.cmdbuf);
          return EXIT_FAILURE;
        }
      }
      break;
    case 'f':
      {
        FILE *f = fopen(optarg, "r");
        long lino = 1;
        int errors = 0;
        char *line;
        if (f == 0) {
          error("-%c option: unable to open %s\n", opt, optarg);
          return EXIT_FAILURE;
        }
        for (; (line = getln(f)) != 0; lino++) {
          if (line[0] == '#')
            continue;
          if (batchexe(&pw, line, pw.cmdbuf, cmdsize) == exec_failed) {
            error("%s:%ld: %s\n", optarg, lino, pw.cmdbuf);
            errors = 1;
          }
          dsdrop(line);
        }
        fclose(f);
        if (errors) {
          return EXIT_FAILURE;
          dsdrop(line);
        }
      }
      break;
    default:
      usage();
    }
  }

  if (pw.maxlines <= 0 || pw.maxlines > 1000) {
    error("%d is an unreasonable number of lines to display\n", pw.maxlines);
    return EXIT_FAILURE;
  }

  if ((pw.circbuf = calloc(sizeof *pw.circbuf, pw.maxlines)) == 0)
    panic("out of memory");
  if ((snapshot[0] = calloc(sizeof *snapshot[0], pw.maxlines)) == 0)
    panic("out of memory");

  if (ioctl(ttyfd, TIOCGWINSZ, &ws) == 0 && ws.ws_row != 0) {
    if (pw.maxlines >= ws.ws_row) {
      pw.maxlines = ws.ws_row - 1;
      maxed = 1;
    }
    pw.columns = ws.ws_col;
  }

  clipsplits(&pw);

  ttyget(ttyfd, &tty_saved);

  tty_new = tty_saved;

  tty_new.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP |
                       INLCR | IGNCR | ICRNL);
  tty_new.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);

  tty_new.c_cc[VMIN] = 1;
  tty_new.c_cc[VTIME] = 0;

  setvbuf(tty, NULL, _IONBF, 0);

  if (fcntl(ifd, F_SETFL, O_NONBLOCK) < 0)
    panic("unable to set stdin nonblocking");

  if (!isbkgnd(stdout))
    ttyset(ttyfd, &tty_new);
  else
    pw.stat = stat_bkgnd;

#ifdef SIGWINCH
  sa.sa_handler = sigwinch;
  sigaction(SIGWINCH, &sa, NULL);
#endif

  for (int kbd_state = kbd_cmd, kbd_prev = kbd_cmd, lasttime = -1,
           workbout = workmax, work = workbout, histpos = 0,
           cmdcount = INT_MAX, prevcmd = 0, prevcount = 0;
       kbd_state != kbd_exit ;)
  {
    int force = 0, nfds = 2, pollms = poll_interval;
    struct pollfd pe[2] = {
      { .fd = ttyfd, .events = POLLIN | POLLHUP | POLLERR },
      { .fd = ifd, .events = POLLIN | POLLHUP | POLLERR },
    };

    if ((pw.stat & stat_eof) == 0) {
      int ch;
      while ((ch = getc(stdin)) != EOF && ch != '\n' && dslen(line) < maxlen)
        line = addchesc(line, ch);
      if (ch == EOF) {
        if (feof(stdin) || (errno != EAGAIN && errno != EWOULDBLOCK)) {
          nfds = 1;
          if (!ferror(stdin))
            exit_status = 0;
          if (auto_quit) {
            if ((pw.stat & stat_bkgnd) == 0)
              clrline(pw.stat);
            break;
          }
          pw.stat |= stat_eof;
          clrline(pw.stat);
          drawstatus(&pw);
        }
        clearerr(stdin);
      } else if (ch == '\n') {
        nfds = 1;
        line = dsensure(line);
        if ((pw.stat & stat_grep)) {
          int i;
          for (i = 0; i < ngrep; i++)
            if (!grexec(&grepstack[i], line))
              break;
          if (i < ngrep) {
            dsdrop(line);
            line = 0;
          }
        }
        if (line) {
          if (pw.nlines == pw.maxlines) {
            int trig = 0;
            dsdrop(pw.circbuf[0]);
            memmove(pw.circbuf, pw.circbuf + 1,
                    (pw.nlines - 1) * sizeof *pw.circbuf);
            pw.circbuf[pw.nlines - 1] = line;
            pw.stat |= stat_dirty;
            if ((pw.stat & (stat_ttmode | stat_susp)) == stat_ttmode) {
              int lim = min(maxtrig, pw.nlines);
              int match = 1;
              for (int i = 0; i < lim; i++) {
                grep *gr = triglist[i];
                if (gr && !grexec(gr, pw.circbuf[i])) {
                  match = 0;
                  break;
                }
              }
              trig = match;
            } else if ((pw.stat & (stat_htmode | stat_susp)) == stat_htmode) {
              int match = 1;
              for (int j = pw.nlines- 1, i = 0; j >= 0 && i < maxtrig;
                   j--, i++)
              {
                grep *gr = triglist[i];
                if (gr && !grexec(gr, pw.circbuf[j])) {
                  match = 0;
                  break;
                }
              }
              trig = match;
            }

            if (trig) {
              if (tfreq == 0 || ++pw.tcount >= tfreq) {
                pw.tcount = 0;
                if (sncount == 0 || ++pw.sncount < sncount) {
                  pw.stat |= stat_trgrd;
                } else if (sncount) {
                  pw.stat |= stat_trgrd | stat_oneshot;
                  pw.sncount = 0;
                }
              }
            }
          } else {
            pw.circbuf[pw.nlines++] = line;
            if ((pw.stat & (stat_susp | stat_bkgnd)) == 0) {
              snapshot[0] = resizebuf(snapshot[0], snaplines[0],
                                      snaplines[0] + 1);
              snapshot[0][snaplines[0]++] = dsref(line);
              clrline(pw.stat);
              drawline(&pw, line, (pw.stat & stat_lino) ? 0: -1);
              drawstatus(&pw);
            }
          }
          line = 0;
        }
      }
    } else {
      nfds = 1;
    }

    if (winch) {
      winch = 0;
      if (ioctl(ttyfd, TIOCGWINSZ, &ws) == 0) {
        if (maxed) {
          pw.hist = 0;
          pw.circbuf = resizebuf(pw.circbuf, pw.maxlines, ws.ws_row - 1);
          snapshot[0] = resizebuf(snapshot[0], pw.maxlines, ws.ws_row - 1);
          for (int i = 1; i < snhistsize; i++) {
            freebuf(snapshot[i], snaplines[i]);
            free(snapshot[i]);
            snapshot[i] = 0;
          }
        } else {
          if (pw.maxlines >= ws.ws_row) {
            pw.maxlines = ws.ws_row - 1;
            maxed = 1;
          }
        }

        if (pw.nlines > pw.maxlines)
          pw.nlines = pw.maxlines;
        if (snaplines[0] > pw.maxlines)
          snaplines[0] = pw.maxlines;

        pw.columns = ws.ws_col;

        clipsplits(&pw);
      }
      pw.stat |= stat_force;
      force = 1;
    }

    if ((pw.stat & stat_eof))
      pollms = -1;
    else if (nfds < 2)
      pollms = 0;

    if ((pw.stat & (stat_trgrd | stat_susp)) == stat_trgrd)
      force = 1;

    if (pollms == 0 && !force && work-- > 0)
      continue;

    work = workbout;

    if ((pw.stat & stat_bkgnd)) {
      if (!isbkgnd(stdout)) {
        pw.stat &= ~stat_bkgnd;
        ttyset(ttyfd, &tty_new);
        for (int i = 0; i < pw.nlines; i++)
          puts("");
        pw.stat |= stat_force;
        redraw(&pw);
      } else {
        if ((pw.stat & stat_eof)) {
          sleep(1);
          continue;
        } else {
          pe[0].events = 0;
        }
      }
    }

    if ((pw.stat & (stat_bkgnd | stat_susp)) == 0) {
      if (!force) {
        struct timeval tv;
        int now;

        gettimeofday(&tv, NULL);
        now = tv.tv_sec % 1000000 * 1000 + tv.tv_usec / 1000;
        if (lasttime == -1 || now - lasttime > long_interval) {
          if ((pw.stat & stat_dirty) && pw.nlines == pw.maxlines)
            force = 1;
          lasttime = now;
        }
      }

      if (force)
        redraw(&pw);
    }

    if (poll(pe, nfds, pollms) <= 0) {
      if (pollms) {
        if ((pw.stat & stat_dirty) && pw.nlines == pw.maxlines)
          redraw(&pw);
        if (kbd_state == kbd_esc) {
          kbd_state = kbd_cmd;
          pw.curcmd = 0;
          clrline(pw.stat);
          drawstatus(&pw);
        }
      }
      if (workbout < workmax)
        work = workbout += workbout / 4;
    } else {
      if ((pe[0].revents)) {
        int ch = getc(tty);

        if (workbout > 16)
          work = workbout /= 2;

        if (ch == ctrl('z')) {
          ttyset(ttyfd, &tty_saved);
          pw.stat |= stat_bkgnd;
          kill(0, SIGTSTP);
          continue;
        }

      fakecmd:
        switch (kbd_state) {
        case kbd_result:
          kbd_state = kbd_cmd;
          pw.stat |= stat_force;
          pw.curcmd = 0;
          if (ch == CR)  // Prevent accidental resume of suspended mode.
            break;
          // fallthrough
        case kbd_cmd:
          if (ch != 'q' && ch != 3)
            quit_countdown = quit_count;
          switch (ch) {
          case 'q': case 3:
            if (--quit_countdown == 0) {
              kbd_state = kbd_exit;
            } else {
              sprintf(pw.cmdbuf, "%d more to quit", quit_countdown);
              pw.curcmd = pw.cmdbuf;
              kbd_state = kbd_result;
            }
            break;
          case 'h':
            if (cmdcount == INT_MAX)
              cmdcount = 8;
            if (pw.hpos >= cmdcount)
              pw.hpos -= cmdcount;
            else
              pw.hpos = 0;
            pw.stat |= stat_force;
            break;
          case 'l':
            if (cmdcount == INT_MAX)
              cmdcount = 8;
            if ((size_t) pw.hpos < maxlen)
              pw.hpos += cmdcount;
            pw.stat |= stat_force;
            break;
          case '>':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            pw.vsplit1 += cmdcount;
            clipsplits(&pw);
            pw.stat |= stat_force;
            break;
          case '<':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            pw.vsplit1 = max(0, pw.vsplit1 - cmdcount);
            pw.stat |= stat_force;
            break;
          case ']':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            if (pw.vsplit2 == 0)
              pw.vs2pos = pw.hpos + pw.vsplit1;
            pw.vsplit2 += cmdcount;
            clipsplits(&pw);
            pw.stat |= stat_force;
            break;
          case '[':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            pw.vsplit2 = max(0, pw.vsplit2 - cmdcount);
            pw.stat |= stat_force;
            break;
          case '}':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            pw.vs2pos = min((int) maxlen, pw.vs2pos + cmdcount);
            pw.stat |= stat_force;
            break;
          case '{':
            if (cmdcount == INT_MAX)
              cmdcount = 1;
            pw.vs2pos = max(0, pw.vs2pos - cmdcount);
            pw.stat |= stat_force;
            break;
          case ctrl('i'):
            pw.stat ^= stat_hlite;
            pw.stat |= stat_force;
            break;
          case 'j':
            if (pw.hist > 0) {
              pw.hist--;
              pw.stat |= stat_force;
            }
            break;
          case 'k':
            if (pw.hist < snhistsize - 1 && snapshot[pw.hist + 1]) {
              pw.hist++;
              pw.stat |= stat_force;
            }
            break;
          case ' ':
            if ((pw.stat & stat_eof) == 0)
              pw.stat |= stat_susp;
            break;
          case CR:
            pw.stat &= ~stat_susp;
            break;
          case ESC:
            kbd_prev = kbd_state;
            kbd_state = kbd_esc;
            break;
          case ':': case '/': case '?':
            kbd_state = kbd_lcmd;
            histpos = 0;
            pw.cmdbuf[0] = ch;
            pw.cmdbuf[1] = 0;
            pw.curcmd = pw.cmdbuf;
            break;
          case 'a': case 'd':
            if ((pw.stat & (stat_htmode | stat_ttmode))) {
              int step = ((((pw.stat & stat_htmode) && ch == 'a') ||
                           ((pw.stat & stat_ttmode) && ch == 'd'))
                          ? -1 : 1);

              if (cmdcount == INT_MAX)
                cmdcount = 1;

              if (step < 0) {
                for (; cmdcount && !triglist[0]; cmdcount --) {
                  memmove(triglist, triglist + 1,
                          (maxtrig - 1) * sizeof *triglist);
                  triglist[maxtrig - 1] = 0;
                }
              } else if (pw.nlines <= maxtrig) {
                for (; (cmdcount &&
                        !triglist[pw.nlines - 1] &&
                        !triglist[maxtrig - 1]);
                     cmdcount --)
                {
                  memmove(triglist + 1, triglist,
                          (maxtrig - 1) * sizeof *triglist);
                  triglist[0] = 0;
                }
              }
            }
            break;
          case '+':
            if (pw.hist > 0 || (ws.ws_row && pw.maxlines >= ws.ws_row - 1)) {
              break;
            } else {
              int count = (cmdcount == INT_MAX) ? 1 : cmdcount;

              pw.maxlines += count;

              if (pw.maxlines >= ws.ws_row - 1) {
                maxed = 1;
                pw.maxlines = ws.ws_row - 1;
              }

              pw.circbuf = resizebuf(pw.circbuf, pw.maxlines, pw.maxlines + 1);
              snapshot[0] = resizebuf(snapshot[0], pw.maxlines, pw.maxlines + 1);
              for (int i = 1; i < snhistsize; i++) {
                freebuf(snapshot[i], snaplines[i]);
                free(snapshot[i]);
                snapshot[i] = 0;
              }
            }
            break;
          case '#':
            pw.stat ^= stat_lino;
            if ((pw.stat & stat_lino))
              clipsplits(&pw);
            // fallthrough
          case ctrl('l'):
            pw.stat |= stat_force;
            break;
          case ctrl('g'):
            snprintf(pw.cmdbuf, sizeof pw.cmdbuf, "-p %d,%d,%d,%d,%d",
                     pw.hpos, pw.vsplit1, pw.vsplit2, pw.vs2pos,
                     (int) pw.stat & stat_save);
            pw.curcmd = pw.cmdbuf;
            kbd_state = kbd_result;
            break;
          case '.':
            if (prevcmd) {
              ch = prevcmd;
              cmdcount = prevcount;
              goto fakecmd;
            }
            break;
          case '0':
            if (cmdcount == INT_MAX) {
              pw.hpos = 0;
              pw.stat |= stat_force;
              break;
            }
            // fallthrough
          default:
            if (isdigit(ch)) {
              if (cmdcount == INT_MAX)
                cmdcount = 0;
              cmdcount = (cmdcount * 10 + (ch - '0')) % 1000;
              break;
            }
            ch = 0;
            break;
          }
          if (!isdigit(ch)) {
            if (ch && ch != '.') {
              prevcmd = ch;
              prevcount = cmdcount;
            }
            if (kbd_state == kbd_cmd)
              cmdcount = INT_MAX;
          }
          break;
        case kbd_esc:
          if (ch == '[') {
            kbd_state = kbd_bkt;
            break;
          }
          kbd_state = kbd_cmd;
          pw.curcmd = 0;
          break;
        case kbd_bkt:
          kbd_state = kbd_prev;
          if (kbd_prev == kbd_cmd) switch (ch) {
          case 'D':
            ch = 'h';
            goto fakecmd;
          case 'C':
            ch = 'l';
            goto fakecmd;
          case 'H':
            ch = '0';
            goto fakecmd;
          case 'A':
            ch = 'k';
            goto fakecmd;
          case 'B':
            ch = 'j';
            goto fakecmd;
          }
          switch (ch) {
          case 'A':
            ch = ctrl('p');
            goto fakecmd;
          case 'B':
            ch = ctrl('n');
            goto fakecmd;
          }
          break;
        case kbd_lcmd:
          switch (ch) {
          case ESC:
            kbd_prev = kbd_state;
            kbd_state = kbd_esc;
            break;
          case CR: case ctrl('c'):
            if (ch == CR) {
              int count = (cmdcount == INT_MAX) ? 0 : cmdcount;
              if (pw.cmdbuf[1]) {
                int *pnhist = (kbd_state == kbd_lcmd ? &ncmdhist : &npathist);
                int nhist = *pnhist;
                char ***hist = (kbd_state == kbd_lcmd ?
                                &cmdhist : &pathist);

                if (nhist == 0 || strcmp(pw.cmdbuf, (*hist)[0]) != 0) {
                  if ((*hist = resizebuf(*hist, nhist, nhist + 1)) == 0)
                    panic("out of memory");
                  memmove(*hist + 1, *hist, sizeof **hist * nhist);
                  *pnhist = nhist + 1;
                  (*hist)[0] = dsdup(pw.cmdbuf);
                }
              }

              if (execute(&pw, pw.cmdbuf, pw.cmdbuf,
                          cmdsize, count) != exec_ok)
              {
                if (pw.columns < cmdsize)
                  pw.cmdbuf[pw.columns] = 0;
                kbd_state = kbd_result;
                cmdcount = INT_MAX;
                break;
              }
            }

            kbd_state = kbd_cmd;
            pw.curcmd = 0;
            cmdcount = INT_MAX;
            prevcmd = 0;
            break;
          case BS: case DEL:
            {
              size_t len = strlen(pw.cmdbuf);
              if (len == 1) {
                kbd_state = kbd_cmd;
                pw.curcmd = 0;
                // cmdcount deliberately not reset to INT_MAX
              } else {
                pw.cmdbuf[--len] = 0;
              }
            }
            break;
          case ctrl('u'):
            pw.cmdbuf[1] = 0;
            break;
          case ctrl('w'):
            {
              size_t len = strlen(pw.cmdbuf);
              while (len > 1 && isspace((unsigned char) pw.cmdbuf[len - 1]))
                len--;
              while (len > 1 && !isspace((unsigned char) pw.cmdbuf[len - 1]))
                len--;
              pw.cmdbuf[len] = 0;
            }
            break;
          case ctrl('p'):
          case ctrl('n'):
            {
              int nhist = (kbd_state == kbd_lcmd ? ncmdhist : npathist);
              char ***hist = (kbd_state == kbd_lcmd ? &cmdhist : &pathist);

              if (ch == ctrl('p')) {
                if (histpos == 0) {
                  dsdrop(pw.savedcmd);
                  pw.savedcmd = dsdup(pw.cmdbuf);
                } else {
                  dsdrop((*hist)[histpos-1]);
                  (*hist)[histpos-1] = dsdup(pw.cmdbuf);
                }
                if (histpos < nhist) {
                  char *cmd = (*hist)[histpos++];
                  strcpy(pw.cmdbuf, cmd);
                }
              } else {
                if (histpos >= 1) {
                  dsdrop((*hist)[histpos-1]);
                  (*hist)[histpos-1] = dsdup(pw.cmdbuf);
                }
                if (histpos > 1) {
                  char *cmd = (*hist)[--histpos - 1];
                  strcpy(pw.cmdbuf, cmd);
                } else if (histpos == 1) {
                  --histpos;
                  strcpy(pw.cmdbuf, pw.savedcmd);
                  dsdrop(pw.savedcmd);
                  pw.savedcmd = 0;
                }
              }
            }
            break;
          default:
            if (isprint(ch))
            {
              size_t len = strlen(pw.cmdbuf);
              if (len < sizeof pw.cmdbuf - 1 && (int) len < pw.columns - 1) {
                pw.cmdbuf[len++] = ch;
                pw.cmdbuf[len] = 0;
              }
            }
            break;
          }
          break;
        case kbd_exit:
          break;
        }

        if ((pw.stat & (stat_dirty | stat_force))) {
          redraw(&pw);
        } else switch (kbd_state) {
        case kbd_lcmd: case kbd_result: case kbd_cmd:
          clrline(pw.stat);
          drawstatus(&pw);
        }
      } else {
        if (workbout < workmax)
          work = workbout += workbout / 4;
      }
    }
  }

  if ((pw.stat & stat_bkgnd) == 0) {
    clrline(pw.stat);
    ttyset(ttyfd, &tty_saved);
  }

#if CONFIG_DEBUG_LEAKS
  freebuf(pw.circbuf, pw.maxlines);
  free(pw.circbuf);
  for (int i = 0; i < snhistsize; i++) {
    freebuf(snapshot[i], snaplines[i]);
    free(snapshot[i]);
  }
  for (int i = 0; i < ngrep; i++)
    grclean(&grepstack[i]);
  for (int i = 0; i < maxtrig; i++) {
    if (triglist[i])
      grclean(triglist[i]);
  }
  freebuf(cmdhist, ncmdhist);
  freebuf(pathist, npathist);
  fclose(tty);
#endif

  return exit_status;
}