forked from maandree/util-linux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg.c
1672 lines (1597 loc) · 35.4 KB
/
pg.c
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
/*
* pg - A clone of the System V CRT paging utility.
*
* Copyright (c) 2000-2001 Gunnar Ritter. All rights reserved.
*
* 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.
* 3. [deleted]
* 4. Neither the name of Gunnar Ritter nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GUNNAR RITTER 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 GUNNAR RITTER 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.
*/
/* Sccsid @(#)pg.c 1.44 (gritter) 2/8/02 - modified for util-linux */
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#ifndef TIOCGWINSZ
# include <sys/ioctl.h>
#endif
#include <sys/termios.h>
#include <fcntl.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#include <libgen.h>
#ifdef HAVE_NCURSES_H
# include <ncurses.h>
#elif defined(HAVE_NCURSES_NCURSES_H)
# include <ncurses/ncurses.h>
#endif
#include <term.h>
#include "nls.h"
#include "xalloc.h"
#include "widechar.h"
#include "all-io.h"
#include "closestream.h"
#include "strutils.h"
#define READBUF LINE_MAX /* size of input buffer */
#define CMDBUF 255 /* size of command buffer */
#define TABSIZE 8 /* spaces consumed by tab character */
#define cuc(c) ((c) & 0377)
enum { FORWARD = 1, BACKWARD = 2 }; /* search direction */
enum { TOP, MIDDLE, BOTTOM }; /* position of matching line */
/* States for syntax-aware command line editor. */
enum {
COUNT,
SIGN,
CMD_FIN,
SEARCH,
SEARCH_FIN,
ADDON_FIN,
STRING,
INVALID
};
/* Current command */
struct {
char cmdline[CMDBUF];
size_t cmdlen;
int count;
int key;
char pattern[CMDBUF];
char addon;
} cmd;
/* Position of file arguments on argv[] to main() */
struct {
int first;
int current;
int last;
} files;
void (*oldint) (int); /* old SIGINT handler */
void (*oldquit) (int); /* old SIGQUIT handler */
void (*oldterm) (int); /* old SIGTERM handler */
char *tty; /* result of ttyname(1) */
unsigned ontty; /* whether running on tty device */
unsigned exitstatus; /* exit status */
int pagelen = 23; /* lines on a single screen page */
int ttycols = 79; /* screen columns (starting at 0) */
struct termios otio; /* old termios settings */
int tinfostat = -1; /* terminfo routines initialized */
int searchdisplay = TOP; /* matching line position */
regex_t re; /* regular expression to search for */
int remembered; /* have a remembered search string */
int cflag; /* clear screen before each page */
int eflag; /* suppress (EOF) */
int fflag; /* do not split lines */
int nflag; /* no newline for commands required */
int rflag; /* "restricted" pg */
int sflag; /* use standout mode */
const char *pstring = ":"; /* prompt string */
char *searchfor; /* search pattern from argv[] */
int havepagelen; /* page length is manually defined */
long startline; /* start line from argv[] */
int nextfile = 1; /* files to advance */
jmp_buf jmpenv; /* jump from signal handlers */
int canjump; /* jmpenv is valid */
wchar_t wbuf[READBUF]; /* used in several widechar routines */
char *copyright;
const char *helpscreen = N_("\
-------------------------------------------------------\n\
h this screen\n\
q or Q quit program\n\
<newline> next page\n\
f skip a page forward\n\
d or ^D next halfpage\n\
l next line\n\
$ last page\n\
/regex/ search forward for regex\n\
?regex? or ^regex^ search backward for regex\n\
. or ^L redraw screen\n\
w or z set page size and go to next page\n\
s filename save current file to filename\n\
!command shell escape\n\
p go to previous file\n\
n go to next file\n\
\n\
Many commands accept preceding numbers, for example:\n\
+1<newline> (next page); -1<newline> (previous page); 1<newline> (first page).\n\
\n\
See pg(1) for more information.\n\
-------------------------------------------------------\n");
#ifndef HAVE_FSEEKO
static int fseeko(FILE *f, off_t off, int whence)
{
return fseek(f, (long)off, whence);
}
static off_t ftello(FILE *f)
{
return (off_t) ftell(f);
}
#endif
#ifdef USE_SIGSET /* never defined */
/* sigset and sigrelse are obsolete - use when POSIX stuff is unavailable */
# define my_sigset sigset
# define my_sigrelse sigrelse
#else
static int my_sigrelse(int sig)
{
sigset_t sigs;
if (sigemptyset(&sigs) || sigaddset(&sigs, sig))
return -1;
return sigprocmask(SIG_UNBLOCK, &sigs, NULL);
}
typedef void (*my_sighandler_t) (int);
static my_sighandler_t my_sigset(int sig, my_sighandler_t disp)
{
struct sigaction act, oact;
act.sa_handler = disp;
if (sigemptyset(&act.sa_mask))
return SIG_ERR;
act.sa_flags = 0;
if (sigaction(sig, &act, &oact))
return SIG_ERR;
if (my_sigrelse(sig))
return SIG_ERR;
return oact.sa_handler;
}
#endif /* USE_SIGSET */
/* Quit pg. */
static void __attribute__((__noreturn__)) quit(int status)
{
exit(status < 0100 ? status : 077);
}
/* Usage message and similar routines. */
static void __attribute__((__noreturn__)) usage(FILE *out)
{
fputs(USAGE_HEADER, out);
fprintf(out,
_(" %s [options] [+line] [+/pattern/] [files]\n"),
program_invocation_short_name);
fputs(USAGE_OPTIONS, out);
fputs(_(" -number lines per page\n"), out);
fputs(_(" -c clear screen before displaying\n"), out);
fputs(_(" -e do not pause at end of a file\n"), out);
fputs(_(" -f do not split long lines\n"), out);
fputs(_(" -n terminate command with new line\n"), out);
fputs(_(" -p <prompt> specify prompt\n"), out);
fputs(_(" -r disallow shell escape\n"), out);
fputs(_(" -s print messages to stdout\n"), out);
fputs(_(" +number start at the given line\n"), out);
fputs(_(" +/pattern/ start at the line containing pattern\n"), out);
fputs(USAGE_SEPARATOR, out);
fputs(USAGE_HELP, out);
fputs(USAGE_VERSION, out);
fprintf(out, USAGE_MAN_TAIL("pg(1)"));
quit(out == stderr ? 2 : 0);
}
static void __attribute__((__noreturn__)) needarg(const char *s)
{
warnx(_("option requires an argument -- %s"), s);
usage(stderr);
}
static void __attribute__((__noreturn__)) invopt(const char *s)
{
warnx(_("illegal option -- %s"), s);
usage(stderr);
}
#ifdef HAVE_WIDECHAR
/* A mbstowcs()-alike function that transparently handles invalid
* sequences. */
static size_t xmbstowcs(wchar_t * pwcs, const char *s, size_t nwcs)
{
size_t n = nwcs;
int c;
ignore_result(mbtowc(pwcs, NULL, MB_CUR_MAX)); /* reset shift state */
while (*s && n) {
if ((c = mbtowc(pwcs, s, MB_CUR_MAX)) < 0) {
s++;
*pwcs = L'?';
} else
s += c;
pwcs++;
n--;
}
if (n)
*pwcs = L'\0';
ignore_result(mbtowc(pwcs, NULL, MB_CUR_MAX));
return nwcs - n;
}
#endif
/* Helper function for tputs(). */
static int outcap(int i)
{
char c = i;
return write_all(STDOUT_FILENO, &c, 1) == 0 ? 1 : -1;
}
/* Write messages to terminal. */
static void mesg(const char *message)
{
if (ontty == 0)
return;
if (*message != '\n' && sflag)
vidputs(A_STANDOUT, outcap);
write_all(STDOUT_FILENO, message, strlen(message));
if (*message != '\n' && sflag)
vidputs(A_NORMAL, outcap);
}
/* Get the window size. */
static void getwinsize(void)
{
static int initialized, envlines, envcols, deflines, defcols;
#ifdef TIOCGWINSZ
struct winsize winsz;
int badioctl;
#endif
char *p;
if (initialized == 0) {
if ((p = getenv("LINES")) != NULL && *p != '\0')
if ((envlines = atoi(p)) < 0)
envlines = 0;
if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
if ((envcols = atoi(p)) < 0)
envcols = 0;
/* terminfo values. */
if (tinfostat != 1 || columns == 0)
defcols = 24;
else
defcols = columns;
if (tinfostat != 1 || lines == 0)
deflines = 80;
else
deflines = lines;
initialized = 1;
}
#ifdef TIOCGWINSZ
badioctl = ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsz);
#endif
if (envcols)
ttycols = envcols - 1;
#ifdef TIOCGWINSZ
else if (!badioctl)
ttycols = winsz.ws_col - 1;
#endif
else
ttycols = defcols - 1;
if (havepagelen == 0) {
if (envlines)
pagelen = envlines - 1;
#ifdef TIOCGWINSZ
else if (!badioctl)
pagelen = winsz.ws_row - 1;
#endif
else
pagelen = deflines - 1;
}
}
/* Message if skipping parts of files. */
static void skip(int direction)
{
if (direction > 0)
mesg(_("...skipping forward\n"));
else
mesg(_("...skipping backward\n"));
}
/* Signal handler while reading from input file. */
static void sighandler(int signum)
{
if (canjump && (signum == SIGINT || signum == SIGQUIT))
longjmp(jmpenv, signum);
tcsetattr(STDOUT_FILENO, TCSADRAIN, &otio);
quit(exitstatus);
}
/* Check whether the requested file was specified on the command line. */
static int checkf(void)
{
if (files.current + nextfile >= files.last) {
mesg(_("No next file"));
return 1;
}
if (files.current + nextfile < files.first) {
mesg(_("No previous file"));
return 1;
}
return 0;
}
#ifdef HAVE_WIDECHAR
/* Return the last character that will fit on the line at col columns in
* case MB_CUR_MAX > 1. */
static char *endline_for_mb(unsigned col, char *s)
{
size_t pos = 0;
wchar_t *p = wbuf;
wchar_t *end;
size_t wl;
char *t = s;
if ((wl = xmbstowcs(wbuf, t, sizeof wbuf - 1)) == (size_t)-1)
return s + 1;
wbuf[wl] = L'\0';
while (*p != L'\0') {
switch (*p) {
/* Cursor left. */
case L'\b':
if (pos > 0)
pos--;
break;
/* No cursor movement. */
case L'\a':
break;
/* Special. */
case L'\r':
pos = 0;
break;
case L'\n':
end = p + 1;
goto ended;
/* Cursor right. */
case L'\t':
pos += TABSIZE - (pos % TABSIZE);
break;
default:
if (iswprint(*p))
pos += wcwidth(*p);
else
pos += wcwidth(L'?');
}
if (pos > col) {
if (*p == L'\t')
p++;
else if (pos > col + 1)
/* wcwidth() found a character that has
* multiple columns. What happens now?
* Assume the terminal will print the
* entire character onto the next row. */
p--;
if (*++p == L'\n')
p++;
end = p;
goto ended;
}
p++;
}
end = p;
ended:
*end = L'\0';
p = wbuf;
if ((pos = wcstombs(NULL, p, READBUF)) == (size_t)-1)
return s + 1;
return s + pos;
}
#endif /* HAVE_WIDECHAR */
/* Return the last character that will fit on the line at col columns. */
static char *endline(unsigned col, char *s)
{
unsigned pos = 0;
char *t = s;
#ifdef HAVE_WIDECHAR
if (MB_CUR_MAX > 1)
return endline_for_mb(col, s);
#endif
while (*s != '\0') {
switch (*s) {
/* Cursor left. */
case '\b':
if (pos > 0)
pos--;
break;
/* No cursor movement. */
case '\a':
break;
/* Special. */
case '\r':
pos = 0;
break;
case '\n':
t = s + 1;
goto cend;
/* Cursor right. */
case '\t':
pos += TABSIZE - (pos % TABSIZE);
break;
default:
pos++;
}
if (pos > col) {
if (*s == '\t')
s++;
if (*++s == '\n')
s++;
t = s;
goto cend;
}
s++;
}
t = s;
cend:
return t;
}
/* Clear the current line on the terminal's screen. */
static void cline(void)
{
char *buf = xmalloc(ttycols + 2);
memset(buf, ' ', ttycols + 2);
buf[0] = '\r';
buf[ttycols + 1] = '\r';
write_all(STDOUT_FILENO, buf, ttycols + 2);
free(buf);
}
/* Evaluate a command character's semantics. */
static int getstate(int c)
{
switch (c) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '\0':
return COUNT;
case '-':
case '+':
return SIGN;
case 'l':
case 'd':
case '\004':
case 'f':
case 'z':
case '.':
case '\014':
case '$':
case 'n':
case 'p':
case 'w':
case 'h':
case 'q':
case 'Q':
return CMD_FIN;
case '/':
case '?':
case '^':
return SEARCH;
case 's':
case '!':
return STRING;
case 'm':
case 'b':
case 't':
return ADDON_FIN;
default:
#ifdef PG_BELL
if (bell)
tputs(bell, STDOUT_FILENO, outcap);
#endif
return INVALID;
}
}
/* Get the count and ignore last character of string. */
static int getcount(char *cmdstr)
{
char *buf;
char *p;
int i;
if (*cmdstr == '\0')
return 1;
buf = xmalloc(strlen(cmdstr) + 1);
strcpy(buf, cmdstr);
if (cmd.key != '\0') {
if (cmd.key == '/' || cmd.key == '?' || cmd.key == '^') {
if ((p = strchr(buf, cmd.key)) != NULL)
*p = '\0';
} else
*(buf + strlen(buf) - 1) = '\0';
}
if (*buf == '\0') {
free(buf);
return 1;
}
if (buf[0] == '-' && buf[1] == '\0') {
i = -1;
} else {
if (*buf == '+')
i = atoi(buf + 1);
else
i = atoi(buf);
}
free(buf);
return i;
}
/* Read what the user writes at the prompt. This is tricky because we
* check for valid input. */
static void prompt(long long pageno)
{
struct termios tio;
char key;
int state = COUNT;
int escape = 0;
char b[LINE_MAX], *p;
if (pageno != -1) {
if ((p = strstr(pstring, "%d")) == NULL) {
mesg(pstring);
} else {
strcpy(b, pstring);
sprintf(b + (p - pstring), "%lld", pageno);
strcat(b, p + 2);
mesg(b);
}
}
cmd.key = cmd.addon = cmd.cmdline[0] = '\0';
cmd.cmdlen = 0;
tcgetattr(STDOUT_FILENO, &tio);
tio.c_lflag &= ~(ICANON | ECHO);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
tcsetattr(STDOUT_FILENO, TCSADRAIN, &tio);
tcflush(STDOUT_FILENO, TCIFLUSH);
for (;;) {
switch (read(STDOUT_FILENO, &key, 1)) {
case 0:
quit(0);
/* NOTREACHED */
case -1:
quit(1);
}
if (key == tio.c_cc[VERASE]) {
if (cmd.cmdlen) {
write_all(STDOUT_FILENO, "\b \b", 3);
cmd.cmdline[--cmd.cmdlen] = '\0';
switch (state) {
case ADDON_FIN:
state = SEARCH_FIN;
cmd.addon = '\0';
break;
case CMD_FIN:
cmd.key = '\0';
state = COUNT;
break;
case SEARCH_FIN:
state = SEARCH;
/* FALLTHRU */
case SEARCH:
if (cmd.cmdline[cmd.cmdlen - 1] == '\\') {
escape = 1;
while (cmd.cmdline[cmd.cmdlen
- escape - 1]
== '\\')
escape++;
escape %= 2;
} else {
escape = 0;
if (strchr(cmd.cmdline, cmd.key)
== NULL) {
cmd.key = '\0';
state = COUNT;
}
}
break;
}
}
if (cmd.cmdlen == 0) {
state = COUNT;
cmd.key = '\0';
}
continue;
}
if (key == tio.c_cc[VKILL]) {
cline();
cmd.cmdlen = 0;
cmd.cmdline[0] = '\0';
state = COUNT;
cmd.key = '\0';
continue;
}
if (key == '\n' || (nflag && state == COUNT && key == ' '))
break;
if (cmd.cmdlen >= CMDBUF - 1)
continue;
switch (state) {
case STRING:
break;
case SEARCH:
if (!escape) {
if (key == cmd.key)
state = SEARCH_FIN;
if (key == '\\')
escape = 1;
} else
escape = 0;
break;
case SEARCH_FIN:
if (getstate(key) != ADDON_FIN)
continue;
state = ADDON_FIN;
cmd.addon = key;
switch (key) {
case 't':
searchdisplay = TOP;
break;
case 'm':
searchdisplay = MIDDLE;
break;
case 'b':
searchdisplay = BOTTOM;
break;
}
break;
case CMD_FIN:
case ADDON_FIN:
continue;
default:
state = getstate(key);
switch (state) {
case SIGN:
if (cmd.cmdlen != 0) {
state = INVALID;
continue;
}
state = COUNT;
/* FALLTHRU */
case COUNT:
break;
case ADDON_FIN:
case INVALID:
continue;
default:
cmd.key = key;
}
}
write_all(STDOUT_FILENO, &key, 1);
cmd.cmdline[cmd.cmdlen++] = key;
cmd.cmdline[cmd.cmdlen] = '\0';
if (nflag && state == CMD_FIN)
goto endprompt;
}
endprompt:
tcsetattr(STDOUT_FILENO, TCSADRAIN, &otio);
cline();
cmd.count = getcount(cmd.cmdline);
}
#ifdef HAVE_WIDECHAR
/* Remove backspace formatting, for searches in case MB_CUR_MAX > 1. */
static char *colb_for_mb(char *s)
{
char *p = s;
wchar_t *wp, *wq;
size_t l = strlen(s), wl;
unsigned i;
if ((wl = xmbstowcs(wbuf, p, sizeof wbuf)) == (size_t)-1)
return s;
for (wp = wbuf, wq = wbuf, i = 0; *wp != L'\0' && i < wl; wp++, wq++) {
if (*wp == L'\b') {
if (wq != wbuf)
wq -= 2;
else
wq--;
} else
*wq = *wp;
}
*wq = L'\0';
wp = wbuf;
wcstombs(s, wp, l + 1);
return s;
}
#endif
/* Remove backspace formatting, for searches. */
static char *colb(char *s)
{
char *p = s, *q;
#ifdef HAVE_WIDECHAR
if (MB_CUR_MAX > 1)
return colb_for_mb(s);
#endif
for (q = s; *p != '\0'; p++, q++) {
if (*p == '\b') {
if (q != s)
q -= 2;
else
q--;
} else
*q = *p;
}
*q = '\0';
return s;
}
#ifdef HAVE_WIDECHAR
/* Convert nonprintable characters to spaces in case MB_CUR_MAX > 1. */
static void makeprint_for_mb(char *s, size_t l)
{
char *t = s;
wchar_t *wp = wbuf;
size_t wl;
if ((wl = xmbstowcs(wbuf, t, sizeof wbuf)) == (size_t)-1)
return;
while (wl--) {
if (!iswprint(*wp) && *wp != L'\n' && *wp != L'\r'
&& *wp != L'\b' && *wp != L'\t')
*wp = L'?';
wp++;
}
wp = wbuf;
wcstombs(s, wp, l);
}
#endif
/* Convert nonprintable characters to spaces. */
static void makeprint(char *s, size_t l)
{
#ifdef HAVE_WIDECHAR
if (MB_CUR_MAX > 1) {
makeprint_for_mb(s, l);
return;
}
#endif
while (l--) {
if (!isprint(cuc(*s)) && *s != '\n' && *s != '\r'
&& *s != '\b' && *s != '\t')
*s = '?';
s++;
}
}
/* Strip backslash characters from the given string. */
static void striprs(char *s)
{
char *p = s;
do {
if (*s == '\\') {
s++;
}
*p++ = *s;
} while (*s++ != '\0');
}
/* Extract the search pattern off the command line. */
static char *makepat(void)
{
char *p;
if (cmd.addon == '\0')
p = cmd.cmdline + strlen(cmd.cmdline) - 1;
else
p = cmd.cmdline + strlen(cmd.cmdline) - 2;
if (*p == cmd.key)
*p = '\0';
else
*(p + 1) = '\0';
if ((p = strchr(cmd.cmdline, cmd.key)) != NULL) {
p++;
striprs(p);
}
return p;
}
/* Process errors that occurred in temporary file operations. */
static void __attribute__((__noreturn__)) tmperr(FILE *f, const char *ftype)
{
if (ferror(f))
warn(_("Read error from %s file"), ftype);
else if (feof(f))
/* Most likely '\0' in input. */
warnx(_("Unexpected EOF in %s file"), ftype);
else
warn(_("Unknown error in %s file"), ftype);
quit(++exitstatus);
}
/* Read the file and respond to user input. Beware: long and ugly. */
static void pgfile(FILE *f, const char *name)
{
off_t pos, oldpos, fpos;
/* These are the line counters:
* line the line desired to display
* fline the current line of the input file
* bline the current line of the file buffer
* oldline the line before a search was started
* eofline the last line of the file if it is already reached
* dline the line on the display */
off_t line = 0, fline = 0, bline = 0, oldline = 0, eofline = 0;
int dline = 0;
int search = 0;
unsigned searchcount = 0;
/* Advance to EOF immediately. */
int seekeof = 0;
/* EOF has been reached by `line'. */
int eof = 0;
/* f and fbuf refer to the same file. */
int nobuf = 0;
int sig;
int rerror;
size_t sz;
char b[READBUF + 1];
char *p;
/* fbuf an exact copy of the input file as it gets read
* find index table for input, one entry per line
* save for the s command, to save to a file */
FILE *fbuf, *find, *save;
if (ontty == 0) {
/* Just copy stdin to stdout. */
while ((sz = fread(b, sizeof *b, READBUF, f)) != 0)
write_all(STDOUT_FILENO, b, sz);
if (ferror(f)) {
warn("%s", name);
exitstatus++;
}
return;
}
if ((fpos = fseeko(f, (off_t)0, SEEK_SET)) == -1)
fbuf = tmpfile();
else {
fbuf = f;
nobuf = 1;
}
find = tmpfile();
if (fbuf == NULL || find == NULL) {
warn(_("Cannot create tempfile"));
quit(++exitstatus);
}
if (searchfor) {
search = FORWARD;
oldline = 0;
searchcount = 1;
rerror = regcomp(&re, searchfor, REG_NOSUB | REG_NEWLINE);
if (rerror != 0) {
mesg(_("RE error: "));
regerror(rerror, &re, b, READBUF);
mesg(b);
goto newcmd;
}
remembered = 1;
}
for (line = startline;;) {
/* Get a line from input file or buffer. */
if (line < bline) {
fseeko(find, line * sizeof pos, SEEK_SET);
if (fread(&pos, sizeof pos, 1, find) == 0)
tmperr(find, "index");
fseeko(find, (off_t)0, SEEK_END);
fseeko(fbuf, pos, SEEK_SET);
if (fgets(b, READBUF, fbuf) == NULL)
tmperr(fbuf, "buffer");
} else if (eofline == 0) {
fseeko(find, (off_t)0, SEEK_END);
do {
if (!nobuf)
fseeko(fbuf, (off_t)0, SEEK_END);
pos = ftello(fbuf);
if ((sig = setjmp(jmpenv)) != 0) {
/* We got a signal. */
canjump = 0;
my_sigrelse(sig);
fseeko(fbuf, pos, SEEK_SET);
*b = '\0';
dline = pagelen;
break;
} else {
if (nobuf)
fseeko(f, fpos, SEEK_SET);
canjump = 1;
p = fgets(b, READBUF, f);
if (nobuf)
if ((fpos = ftello(f)) == -1)
warn("%s", name);
canjump = 0;
}
if (p == NULL || *b == '\0') {
if (ferror(f))
warn("%s", name);
eofline = fline;
eof = 1;
break;
} else {
if (!nobuf)
fputs(b, fbuf);
fwrite_all(&pos, sizeof pos, 1, find);
if (!fflag) {
oldpos = pos;
p = b;
while (*(p = endline(ttycols,
p))
!= '\0') {
pos = oldpos + (p - b);
fwrite_all(&pos,
sizeof pos,
1, find);
fline++;