Pager/Perl.pm untested

filter: Statementstmt 0.0% 0 / 593 Branchbran 0.0% 0 / 288 Conditioncond 0.0% 0 / 148 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 65 Podpod 0.0% 0 / 59 totaltotal 0.0% 0 / 1153 SCAR 99.6
CC
145
Cov
0%
line
306.0
more
182.0
next_match
156.0
CRAP 21170.0
1 package IO::Pager::Perl;
2 our $VERSION = '2.01'; #Untouched since 2.01
3  
4 use strict;
5 use warnings;
6 use Term::Cap;
7  
8 #Signal handling, only needs to be set once, and does not have access to object
9 my($SP, $RT) = $|;
10 local $SIG{INT} = local $SIG{QUIT} = \&close;
11  
12 #Stubs for ReadKey functions that we fill in with code refs if it's not loaded
13 sub ReadMode;
14 sub ReadKey;
15  
16 sub new {
17 print "\e[?1000;1006;1015h";
18 my $class = shift;
19 my %param = @_;
20 local $ENV{TERM} = $ENV{TERM} || '';
21 local $ENV{TERMCAP} = $ENV{TERM} || '';
22  
23 my %dims = get_size(cols =>$param{cols} ||80,
24 rows =>$param{rows} ||25,
25 speed=>$param{speed}||38400);
26 $dims{rows}--;
27  
28 #screen is vt100 compatible but does not list sf?!
29 #No matter, it's only used for workaround mode.
30 if( $ENV{TERM} eq 'screen' && $ENV{TERMCAP} !~ /sf/ ){
31 $ENV{TERM} = 'vt100';
32 }
33  
34 #cm=>cup, ce=>el, cl=>clear, sf=>ind, sr=>ri
35 #md=>bold, me=>sgr0, mr=>rev, us=>smul
36 #Speed is mostly useless except Term::Cap expects it?
37 my $t = Term::Cap->Tgetent({ OSPEED => $param{speed} });
38 eval{ $t->Trequire(qw/cm ce cl sf sr/) };
39 my $dumb = $@ ? 1 : 0;
40  
41 my %primitives = (
42 # if the entries don't exist, nothing bad will happen
43 BLD => $t->Tputs('md'), # Bold
44 ULN => $t->Tputs('us'), # Underscore
45 REV => $t->Tputs('mr'), # Reverse
46 NOR => $t->Tputs('me'), # Normal
47 );
48  
49 my $text;
50 if( defined( $param{text} ) ){
51 my $ref = ref( $param{text} );
52 if( $ref eq 'ARRAY' ){
53 die "Invalid text, must be string, code ref, or [string, code ref]"
54 unless (scalar( @{$param{text}} ) ==2) and
55 ref( $param{text}->[0] ) eq '' and
56 ref( $param{text}->[1] ) eq 'CODE';
57  
58 $text = $param{text}->[0];
59 $param{text} = $param{text}->[1]
60 }
61 elsif( $ref eq '' ){
62 $text = delete( $param{text} );
63 }
64 }
65  
66 $param{visualBell} = delete($param{visualBeep}) if
67 defined($param{visualBeep}) and not defined($param{visualBell});
68  
69 my $me = bless {
70 # default values
71 _cursor => 0, _end => 0, _left => 0,
72 _term => $t, _dumb => $dumb, _txtN => 0,
73 _search => '', _statCols => 0, _lineNo=>[0],
74 lineNo => 0, pause => '', #pause=>"\cL" #more
75 raw => 0, statusCol => 0, squeeze=>0,
76 visualBell => 0, fold => 0, _fileN => 1,
77 _mark => {1=>0}, scrollBar => 0,
78 %dims,
79  
80 # if the termcap entries don't exist, nothing bad will happen
81 %primitives,
82 #UI Composites
83 MENU => $primitives{BLD}.$primitives{REV}, # popup menus
84 HILT => $primitives{BLD}.$primitives{ULN}, # search entry
85 SRCH => $primitives{BLD}.$primitives{ULN}, # search entry
86  
87 # user supplied values override
88 %param,
89 }, $class;
90  
91 $me->add_text($text) if defined $text;
92  
93 $me->{_I18N}={
94 prompt=> '',
95 404=> 'Not Found',
96 top=> 'Top',
97 bottom=> 'Bottom',
98 minihelp=> "<h>=help \000<space>=down <b>=back <q>=quit",
99 continue=> 'press any key to continue',
100 searchwrap=> 'No more matches, next search will wrap',
101 nowrap=> 'Text::Wrap unavailable, disabling folding',
102 help=> <<EOH
103 q quit \000 h help
104 r C-l refresh \000 R flush buffers
105 / search \000 ? search backwards
106 n P next match \000 p N previous match
107 space C-v page down \000 b M-v page up
108 enter down line down \000 y up line up
109 d half page down \000 u half page up
110 g < goto top \000 G > goto bottom
111 left scroll left 1 tab\000 right scroll right 1 tab
112 S-left scroll left 1/2 \000 S-right scroll right 1/2
113 m mark position \000 ' return to mark
114 # line numbering \000 \\d+\\n jump to line \\d+
115 :n next file \000 :p previous file
116 C toogle raw \000 S toggle folding
117 EOH
118 };
119  
120 our %config;
121 add_keys(\&help, 'h', 'H');
122 add_keys(\&close, 'q', 'Q', ':q', ':Q');
123 add_keys(\&refresh, 'r', "\cL", "\cR");
124 add_keys(\&next_match,'n', 'P');
125 add_keys(\&prev_match,'p', 'N');
126 add_keys(\&to_bott, '>', 'G', '$', "\e>", "\e[F", "\e0E", "\e0W", "\e[4~");
127 #M-> ? End End End
128 add_keys(\&downpage, ' ', 'z', "\cV", , 'f', "\cF", "\e ", "\e[6~"); #M- PgDn
129 add_keys(\&downhalf, 'd', "\cD");
130 add_keys(\&downline, 'e', 'j', 'J', "\cE", "\cN", "\e[B"); #down
131 add_keys(\&downline_raw, "\n");
132 add_keys(\&upline, 'y', 'k', "\cY", "\cK", 'K', 'Y', "\cP", "\e[A"); #up
133 add_keys(\&uphalf, 'u', "\cU");
134 add_keys(\&uppage, 'w', 'b', "\cB", "\ev", "\e[5~"); #M-v PgUp
135 add_keys(\&to_top, '<', 'g', "\e<", "\e[H", "\e0", "\e[1~");
136 #M-< Home Home Home
137 add_keys(\&next_file, ':n', "\e[1;4C");
138 add_keys(\&prev_file, ':p', "\e[1;4D");
139 add_keys(\&save_mark, 'm', "\e[2~"); #Ins
140 add_keys(\&shift_left, "\e\[1;2D", "\e("); #S-left S-M-9
141 #Cannot have M-[ for left, \e[ conflicts with other codes
142 add_keys(\&shift_right,"\e\[1;2C", "\e)"); #S-right S-M-0
143  
144 # Home PgUp PgDn End Ins
145 # terminfo khome kpp knp kend kich1
146 # eterm \E0y \E0q \E0s
147 # rxvt \E[7~ \E[5~ \E[6~ \E[8~ \e[2~ #
148 # xterm \EOH \E[5~ \E6~ \EOF \e[2~ #
149 #nxterm \e[\C-@ \e[e
150 #"\e\[1;3C"=> #M-left
151 #"\e\[1;3D"=> #M-right
152  
153 $me->add_func(%config,
154 "\e[<" => \&mouse,
155 '/(\d+)/' => 1, #jump to line
156 "\e[D" => \&tab_left, #left
157 "\e[C" => \&tab_right, #right,
158 '&' => \&grep,
159 '/' => \&search,
160 '?' => \&hcraes,
161 "'" => \&goto_mark,
162 '#' => \&toggle_num, #XXX Change toggle* to '-' initiated
163 'C' => \&toggle_raw, #input mode like : to mimic less?
164 'S' => \&toggle_fold,
165 'R' => \&flush_buffer,
166 ':w'=> \&write_buffer,
167 ':e'=> \&open_file,
168 );
169
170 #Mise-en-place; prepare to cook some characters
171 #\000-\010\013-\037/@A-HK-Z[\\]^_/
172 $me->{_raw}->{chr($_)} = chr(64+$_) foreach (0..8, 11..31);
173  
174 $me->{_end} = $me->{rows} - 1;
175  
176 $SIG{WINCH} = sub{ $me->resize() };
177 $me->{cols}-- if $me->{scrollBar};
178  
179 #Can we fold?
180 eval "use Text::Wrap";
181 if( $@ ){
182 sub wrap{ join '', @_ }
183 $me->{fold} = 0;
184 }
185  
186 $me;
187 }
188  
189 sub resize {
190 my $me = shift;
191 my %dims = get_size();
192 $dims{rows}--;
193 $dims{cols}-- if $me->{scrollBar};
194 $me->{$_} = $dims{$_} foreach keys %dims;
195  
196 $me->{_end} = $me->{rows} - 1;
197  
198 if( $me->{fold} ){
199 $me->reflow();
200 #XXX Crude attempt to mintain position,
201 #XXX only works if all rows folded same amount
202 #$me->jump( int($me->{_cursor} * $me->{cols) / $dims{cols})-1 );
203 #XXX need to somehow use _lineNo instead?
204 }
205 else{
206 $me->refresh();
207 }
208 $me->status();
209  
210 $me->{WINCH}->() if ref($me->{WINCH}) eq 'CODE';
211 }
212  
213 sub get_size {
214 my %dims = @_;
215  
216 if( defined($Term::ReadKey::VERSION) ){
217 Term::ReadKey->import();
218 local $SIG{__WARN__} = sub{};
219 my @Tsize = Term::ReadKey::GetTerminalSize(*STDOUT);
220 @dims{'rows','cols'} = @Tsize[1,0];
221 $dims{speed} ||= (Term::ReadKey::GetSpeed())[1];
222 }
223 else{
224 *ReadMode = sub{
225 if( $_[0] == 3 ){
226 system('stty -icanon -echo min 1'); }
227 elsif( $_[0] == 0 ){
228 system('stty icanon echo'); }
229 };
230 *ReadKey = sub{ getc() };
231  
232 #Can we get better defaults?
233 if( `stty` =~ /speed/ ){
234 @dims{'rows','cols'} = ($1-1,$2-1) if `stty size` =~ /^(\d+)\s+(\d+)$/;
235 $dims{speed} = $1 if `stty speed` =~ /^(\d+)$/;
236 }
237 else{
238 $dims{rows} = `tput lines` || $dims{rows};
239 $dims{cols} = `tput cols` || $dims{cols};
240 }
241 }
242 return %dims;
243 }
244  
245  
246 sub add_text {
247 return unless defined($_[1]);
248 my $me = shift;
249  
250 #Stringify
251 local $_ = join('', @_);
252  
253 #Terminated?
254 my $LF = do{ chomp(local $_=$_) };
255  
256 #Squeeze #XXX handle with logical lines display?
257 s/\n{2,}/\n\n/g if $me->{squeeze};
258  
259 #Split on new lines, preserving internal blanks
260 my @F = split(/\n/, $_, -1);
261  
262 if( $me->{fold} ){
263 #Two expressions to avoid lame single-use warning
264 local $Text::Wrap::columns;
265 $Text::Wrap::columns = $me->{cols} -
266 ( $me->{_statCols} = ($me->{lineNo} ? 9 : $me->{statusCol} ? 1 : 0) );
267  
268 my $lines = scalar(@F);
269 my $extraSum=0;
270 for( my $i=0; $i<$lines; $i++ ){
271 $me->{_lineNo}->[$i+$me->{_txtN}] = $me->{_txtN}+$i+1-$extraSum;
272  
273 #Automark multi-file
274 $me->{_mark}->{$1} = $i+$me->{_txtN} if
275 defined($F[$i]) && $F[$i] =~ m%\cF\c]\cL\cE \[(\d+)/%;
276  
277 if( defined($F[$i]) && length($F[$i]) > $me->{cols} ){
278 my @G = split/\n/, wrap('', '', $F[$i]);
279 my $extras = scalar(@G);
280 splice(@F, $i, 1, @G);
281 #Repeat real line number for logical folded lines
282 $me->{_lineNo}->[$i+$me->{_txtN}+$_] =
283 $me->{_txtN}+$i+1-$extraSum foreach 1..$extras-1;
284  
285 $i += $extras-1;
286 $lines += $extras;
287 $extraSum += $extras-1;
288 }
289 }
290 }
291 #Remove the extra record from the trailing new line
292 pop @F if $LF;
293  
294 #Handle partial lines in case sysread is used further up the stack
295 push(@F, undef) unless $LF;
296 if( $me->{_txtN} && !defined($me->{_text}->[-1]) ){
297 pop @{$me->{_text}};
298 $me->{_text}->[-1] .= shift @F;
299 }
300  
301 #Store text, and refresh screen if content would fit in window
302 my $shown = $me->{_txtN};
303 push @{$me->{_text}}, @F;
304 $me->{_txtN} = @{ $me->{_text} }; #-1;
305  
306 $me->refresh(); #XXX if $shown <= $me->{rows}; # + $me->{_cursor};
307 }
308  
309 sub reflow {
310 my $me = shift;
311 my($prevLine, @text) = 0;
312 while( scalar @{$me->{_text}} ){
313 my $curLine = shift @{$me->{_lineNo}};
314 if( $curLine == $prevLine ){
315 $text[-1] .= ' ' . (shift @{$me->{_text}}||''); }
316 else{
317 push @text, shift @{$me->{_text}}; }
318 $prevLine = $curLine;
319 }
320 $me->{_lineNo}=[];
321 $me->{_txtN}=0;
322 $me->add_text( join($/, @text) );
323 }
324  
325 #Capture errant method calls
326 sub AUTOLOAD{
327 eval "use Carp";
328 my $me = shift;
329 our $AUTOLOAD =~ s/.*:://;
330 return if $AUTOLOAD eq 'DESTROY';
331  
332 local $Text::Wrap::columns=int(.75*$me->{cols});
333 my $msg = wrap('', '', "$AUTOLOAD\n\n". Carp::longmess());
334 $me->beep();
335 $me->dialog("Unknown method $msg", 1);
336 }
337  
338 #$input is pulled outside the subroutine to allow for Esc+x entry of M-x
339 #after the deferring to host loop instead of using a TIGHT input loop
340 my $input;
341 sub more {
342 my $me = shift;
343 my %param = @_;
344 $RT = $me->{RT} = $param{RT};
345
346 ReadMode 3; #cbreak
347 $| = 1;
348  
349 if( $me->{_dumb} ){
350 $me->dumb_mode();
351 }
352 else{
353 print $me->{NOR};
354 $DB::single = 1;
355  
356  
357 #INPUT LOOP, revised with inspiration from Term::Screen::getch()
358 #my $input=''; #TIGHT
359 while( 1 ){
360 $me->status(); # status line
361 my $exit = undef;
362  
363 my $char = ReadKey($param{RT});
364 #Defer to host loop, obviating need for callbacks to implement tail
365 #functionality and for cleaner startup (no preload on piped input)
366 #next unless defined($char); #TIGHT
367 return 1 unless defined($char);
368 $me->{_I18N}{prompt} = $input .= $char;
369 $me->status();
370
371 unless( ($input=~ /^\e/ and index($me->{_fncRE}, $input)>0 )
372 || $input =~ /^\d+/
373 || $input =~ /:+/
374 || defined($me->{_fnc}->{$input}) ){
375 $me->beep($input);
376 $input ='';
377 next;
378 }
379  
380 if( $me->{_fnc}->{$input} ){
381 #Get mapped sub name
382 # use B 'svref_2object';
383 # my $n = $me->{_fnc}->{$input};
384 # $n = svref_2object($n)->GV->NAME;
385  
386 $exit = $me->{_fnc}->{$input}->($me);
387 $me->{_I18N}{prompt} = $input = '';
388 }
389 #vi-style input
390 elsif( $input =~ /^:/ ){
391 if( ($char eq "\cG") or ($input eq '::') ){
392 $me->{_I18N}{prompt} = $input = '';
393 $me->status();
394 return 1; }
395 }
396 #Line-number input; would love to use getln, but does not mix w/ status
397 elsif( $me->{_fnc}->{'/(\d+)/'} and $input =~ /^\d+/ ){
398 if( $char eq "\cH" or ord($char)==127 ){
399 $input = substr($input, 0, -2, ''); }
400 elsif( $char eq "\cG" ){
401 $input = '';
402 $exit = 1; }
403 elsif( $char eq "\n" ){
404 #Remove extraneous characters that could cause infinite error loop
405 #XXX this prevents goofy RPN-like repeated commands
406 $input =~ y/0-9//cd;# chomp($input);
407 $exit = $input < $me->{_txtN} ? $me->jump($input) : $me->to_bott();
408 $input = ''; }
409  
410 $me->{_I18N}{prompt} = $input;
411 $me->status();
412 }
413  
414 return 1 if $param{RT} && defined($exit);
415 }
416 }
417 $me->close();
418 }
419 *less = \&more; *page = \&more;
420 #Avoid lame single-use warning
421 my $foo = \&less; $foo = \&page;
422  
423  
424 #ACCESSORS
425 sub I18N {
426 my($me, $msg, $text) = @_;
427 $me->{_I18N}{$msg} = $text if defined($text);
428 $me->{_I18N}{$msg};
429 }
430  
431 BEGIN{
432 #Install generic accessors
433 no strict 'refs';
434 foreach my $method ( qw(eof lineNo pause raw statusCol visualBell) ){
435 *{$method} = sub{ $_[0]->{$method}=$_[1] if defined($_[1]);
436 $_[0]->{$method} }
437 }
438 foreach my $method ( qw(rows cols speed fold squeeze) ){
439 *{$method} = sub{ $_[0]->{$method}}
440 }
441 }
442  
443 #HELPERS
444 sub add_keys{
445 our %config;
446 my $sub = shift;
447 $config{$_} = $sub foreach @_;
448 }
449  
450 sub add_func{
451 my $me = shift;
452 my %param = @_;
453 while( my($k, $v) = each %param ){
454 $me->{_fnc}{$k} = $v;
455 }
456 #XXX RegExp::Trie, List::RegExp? #quotemeta?
457 $me->{_fncRE} = join '|', sort keys %{ $me->{_fnc} };
458 #$me->{_fncRE} = qr/^($me->{_fncRE})$/;
459 }
460  
461 sub beep{
462 print "\a";
463 print $_[0]->{_term}->Tputs('vb') if $_[0]->{visualBell};
464  
465 if( defined($_[1]) ){
466 $_[1] =~ s/\e/^[/;
467 $_[1] =~ s/([^[:print:]])/sprintf("\\%03o", ord($1))/ge; #Cook
468 $_[0]->dialog("Unrecognized command: $_[1]", 1);
469  
470 $_[0]->{_I18N}{prompt} = '';
471 $_[0]->status();
472 }
473 }
474  
475 sub getln{
476 my $input;
477 while(1){
478 my $l = ReadKey();
479 last if $l eq "\n" || $l eq "\r";
480  
481 if( !defined($l)| $l eq "\e" || $l eq "\cG" ){
482 $input = '';
483 last; }
484 elsif( $l eq "\b" || $l eq "\177" ){
485 print "\b \b" if $input ne '';
486 substr($input, -1, 1, '');
487 next;
488 }
489  
490 print $l;
491 $input .= $l;
492 }
493 return $input;
494 }
495  
496  
497 # display a minihelp, etc
498 sub status{
499 my $me = shift;
500 $me->{_txtN} ||= 0;
501  
502 my $end= $me->{_cursor} + $me->{rows};
503  
504 my $pct = $me->{_txtN} > $end ? $end/($me->{_txtN}) : 1;
505 #XXX unify with scrollbar: consistency and as private property
506 my $pos = $me->{_cursor} ?
507 ($pct==1 ? $me->{_I18N}{bottom} : 'L'.$me->{_cursor}) :
508 $me->{_I18N}{top};
509 $pos .= 'C'.$me->{_left} if $me->{_left};
510 my $p = sprintf "[tp] %d%% %s %s", 100*$pct, $pos, $me->{_I18N}{prompt};
511  
512 print $me->{_term}->Tgoto('cm', 0, $me->{rows}); # bottom left
513 print $me->{_term}->Tputs('ce'); # clear line
514 my $minihelp = $me->{_I18N}{minihelp};
515 (my $pSansCodes = $p) =~ s/\e\[[\d;]*[a-zA-Z]//g;
516 my $pN = $me->{cols} -1 -length($pSansCodes) -length($me->{_I18N}{minihelp});
517 $p .= ' ' x ($pN > 1 ? $pN : 1);
518 $minihelp = $pN>2 ? $minihelp : do {$minihelp =~ s/\000.+//; $minihelp };
519 print $me->{REV}; # reverse video
520 print $p," ", $minihelp; # status line
521 print $me->{NOR}; # normal video
522 }
523  
524 sub close{
525 ReadMode 0;
526 print "\n\e[?1000l";
527 $| = $SP || 0;
528 #Did we exit via signal or user?
529 $RT ? die : return \"foo";
530 }
531  
532 {
533 no warnings 'once';
534 *done = \&close;
535 }
536  
537  
538 # provide help to user
539 sub help{
540 my $me = shift;
541 my $help = $me->{_I18N}{help};
542 my $cont = $me->{_I18N}{continue};
543  
544 if( $me->max_width( split/\n/, $help ) > $me->{cols} ){
545 #Split help in half horizontally for narrow dispays
546 my $help2 = $help;
547 $help2 =~ s/\000.*//mg;
548 $help =~ s/.*\000//mg;
549 my $padding = $me->max_width($cont) / 2;
550 $me->dialog( $help2 . "\n" . (' 'x$padding) . $cont );
551 }
552 else{
553 $help =~ y/\000//d;
554 }
555 my $padding = $me->max_width($cont) / 2;
556 $me->dialog( $help . "\n" . (' 'x$padding) . $cont );
557 }
558  
559 sub max_width{
560 my $me = shift;
561 my $width = 0;
562 foreach (@_){ $width = length($_) if length($_) > $width };
563 return $width;
564 }
565  
566 sub dialog{
567 my($me, $msg, $timeout) = @_;
568 my @txt = defined($msg) ? split(/\n/, $msg) : ();
569 my $w = $me->max_width(@txt);
570  
571 #Prepare dialog
572 my $h = '+' . '='x($w+2) . '+';
573 my $d = join('', map { sprintf("%s| %- @{[$w+4]}s |\n",
574 $me->{_term}->Tgoto('RI',0,4),
575 $_) } $h, @txt, $h);
576  
577 print $me->{_term}->Tgoto('cm',0, 2), # move
578 $me->{MENU}, # set color
579 $d, # dialog
580 $me->{NOR}; # normal color
581  
582 defined($timeout) ? sleep($timeout) : getc();
583  
584 #Allow wipe of incomplete/paused output.
585 local($me->{pause});
586  
587 #XXX Use full refresh if _grep for simple accurate solution?
588 # Fractional restoration instead of full refresh
589 foreach my $n (2 .. scalar(@txt)+3){
590 print $me->{_term}->Tgoto('cm', 0, $n); # move
591 print $me->{_term}->Tputs('ce'); # clear line
592 $me->line($n);
593 }
594 }
595  
596 sub flush_buffer{
597 my $me = shift;
598 $me->{_text} = [];
599 $me->{_txtN} = 0;
600 $me->{_lineNo}=[];
601 $me->refresh();
602 }
603  
604 # refresh screen
605 sub refresh{
606 my $me = shift;
607  
608 print $me->{_term}->Tputs('cl'); # home, clear
609 for my $n (0 .. $me->{rows} -1){
610 print $me->{_term}->Tgoto('cm', 0, $n); # move
611 print $me->{_term}->Tputs('ce'); # clear line
612  
613 #Skip cursor ahead to matching line if in grep mode
614 if( $me->{_grep} && defined($me->{_text}->[$me->{_cursor}+$n]) ){
615 until( $me->{_text}->[$me->{_cursor}+$n] =~
616 m%$me->{_search}|\cF\c]\cL\cE \[\d+/% ){
617 $me->{_cursor}++;
618 last if $me->{_cursor}+$me->{rows}+$n >= $me->{_txtN};
619 }
620 }
621  
622 $me->line($n+$me->{_cursor}) if # XXX w/o cursor messy
623 $me->{_cursor}+$me->{rows}+$n <= $me->{_txtN} # after menu & refresh
624 }
625 $me->scrollBar() if $me->{scrollBar};
626 }
627  
628 sub scrollBar{
629 my $me = shift;
630 $me->{_pages} = $me->{_txtN}/$me->{rows};
631 $me->{_thumbW} = $me->{rows}/$me->{_pages};
632 $me->{_thumbT} = sprintf("%i", ($me->{_cursor} / $me->{_pages}) )+($me->{_cursor}>$me->{_txtN}/2);
633 $me->{_thumbB} = sprintf("%i", $me->{_thumbT}+$me->{_thumbW});
634  
635 #$me->dialog("cursor $me->{_cursor} top $me->{_thumbT} + width $me->{_thumbW}");
636  
637 for my $n (0 .. $me->{rows} -1){
638 print $me->{_term}->Tgoto('cm', $me->{cols}+1, $n);
639 print $n>=$me->{_thumbT} && $n<$me->{_thumbB} ? ' ' : "$me->{REV} $me->{NOR}";
640 }
641 }
642  
643 sub mouse{
644 my $me = shift;
645 my $input ='';
646 $input .= ReadKey(0) until $input =~ /M$/i;
647  
648 my @args = split /;/, $input;
649  
650 if( $args[0] == 65 ){
651 $me->downhalf(); }
652 elsif( $args[0] == 64 ){
653 $me->uphalf(); }
654 elsif( $me->{scrollBar} && $args[1] == $me->{cols}+1 ){
655 if( chop $args[2] eq 'm'){ #mouse-up
656 if( $me->{_thumbDrag} ){
657 $me->{_thumbDrag} = 0;
658 my $pos;
659 if( $args[2]==1 ){
660 $pos=0 }
661 elsif( $args[2]==$me->{rows} ){
662 $pos= $me->{_txtN} - 2*$me->{rows}-1 }
663 else{
664 $pos = sprintf("%i", $args[2] / $me->{rows} * $me->{_txtN}) }
665 $me->jump($pos);
666 }
667 $me->uppage() if $args[2] < $me->{_thumbT};
668 $me->downpage() if $args[2] > $me->{_thumbB};
669 }
670 elsif( $args[2]>=$me->{_thumbT} &&
671 $args[2]<=$me->{_thumbB} ){ #automagically M (mouse-down)
672 $me->{_thumbDrag}=1;
673 }
674 }
675 }
676  
677  
678 sub line{
679 my $me = shift;
680 my $n = shift;
681 local $_ = $me->{_text}[$n]||'';
682 # my $prev = $me->{_text}[$n-1]||'';
683  
684 #!! ORDER OF OPERATIONS ON OUTPUT PROCESSING AND DECORATION MATTERS
685  
686 # #Squeeze... this identifies lines, but just gives a blank line, still
687 # code elsewhere iterates over rows and advances down screen...
688 # we need to intervene in each of those instances and:
689 # not progress another line of display then add another iteration
690 # return if $me->{squeeze} && $_ eq '' && $prev eq '';
691  
692 $me->{_curFile} = $1 if m%\cF\c]\cL\cE \[(\d+)/%;
693  
694 #Breaks?
695 my $pausey = 1 if length($me->{pause}) && defined && /$me->{pause}/;
696  
697 #Crop if no folding
698 my $len = length();
699 unless( $me->{fold} ){
700 $_ = ($len-$me->{_statCols}) < $me->{_left} ? '' :
701 substr($_, $me->{_left}, $me->{cols}-$me->{_statCols});
702 if( $len - $me->{_left} > $me->{cols} ){
703 substr($_, -1, 1, "\$");
704 }
705 }
706  
707 #Cook control characters
708 unless( $me->{raw} ){
709 s/([\000-\010\013-\037])/$me->{REV}^$me->{_raw}->{$1}$me->{NOR}/g;
710 }
711  
712 #Search
713 my $matched = (s/($me->{_search})/$me->{SRCH}$1$me->{NOR}/g) if
714 $me->{_search} ne '';
715  
716 #Line numbering & search status
717 my $info = $me->{statusCol} && !$me->{lineNo} ? ($matched ? '*' : ' ') : '';
718 $info = sprintf("% 8s",
719 $me->{fold} ? ($me->{_lineNo}->[$n]||-1) :
720 (defined($me->{_text}[$n]) ? $n+1 : '')
721 ) if $me->{lineNo};
722 $_ = ($me->{Statuscol} && $matched ? $me->{REV} : ''). $info.
723 ($me->{statusCol} && $matched ? $me->{NOR} : '').
724 ($me->{lineNo} ? ' ' : ''). $_;
725 print;
726  
727 if( $pausey ){
728 $me->{_end} = $n; #Advance past pause
729 no warnings 'exiting'; last;
730 }
731 }
732  
733 sub down_lines{
734 my $me = shift;
735 my $n = shift;
736 my $t = $me->{_term};
737  
738 LINE: for(1..$n){
739 if( $me->{_end} >= $me->{_txtN}-1 ){
740 $me->close() if $me->{eof} && ref($me->{text}) ne 'CODE';
741 if( ref($me->{text}) eq 'CODE' ){
742 $me->add_text( $me->{text}->() ); }
743 else{
744 &beep; last; }
745 }
746 #Two blocks instead of an else to allow input callback
747 if( $me->{_end} < $me->{_txtN}-1 ){
748 if( length($me->{pause}) && $me->{_end} < $me->{rows}-1 ){
749 print $t->Tgoto('cm', 0, $me->{_end}+1 ); } # move
750 else{
751 # why? because some terminals have bugs...
752 print $t->Tgoto('cm', 0, $me->{rows} ); # move
753 print $t->Tputs('sf'); # scroll
754 print $t->Tgoto('cm', 0, $me->{rows} - 1); # move
755 }
756 print $t->Tputs('ce'); # clear line
757  
758 #Skip cursor ahead to matching line if in grep mode
759 if( $me->{_grep} && $me->{_end} < $me->{_txtN} ){
760 until( $me->{_text}->[$me->{_end}] =~
761 m%$me->{_search}|\cF\c]\cL\cE \[\d+/% ){
762 $me->dialog(#"$me->{_end} >= $me->{_txtN} #$me->{_cursor}\n".
763 'Pagination in grep mode does not work at this time.', 1);
764 last LINE;
765 # $me->{_end}++;
766 $me->{_cursor}++;
767 if( $me->{_end} >= $me->{_txtN} ){
768 $me->{cursor} = $me->{_end} = $me->{_txtN};
769 last;
770 }
771 }
772 }
773 $me->line( ++$me->{_end} ) if $me->{_end} <= $me->{_txtN};
774 $me->{_cursor}++;
775 }
776 }
777 $me->scrollBar() if $me->{scrollBar};
778 }
779 sub downhalf { $_[0]->down_lines( $_[0]->{rows} / 2 ); }
780 sub downpage { $_[0]->down_lines( $_[0]->{rows} );
781 #WTF?! add_text in tp's while-loop cannot be reached if there's
782 #no delay here until something other than downpage is called?!
783 select(undef, undef, undef, .1); #XXX WTF?!
784 # warn "\n\n", map{$_[0]->{$_}."\n"} qw/rows _cursor _end/;
785 }
786 sub downline { $_[0]->down_lines( 1 ); }
787 #Term::ReadKey doesn't offer sufficiently fine control; we want CS8 but -OCRNL
788 sub downline_raw { $_[0]->down_lines( 1 ); $_[0]->refresh(); }
789  
790 sub up_lines{
791 my $me = shift;
792 my $n = shift;
793  
794 for (1 .. $n){
795 if( $me->{_cursor} <= 0 ){
796 &beep; last; }
797 else{
798 print $me->{_term}->Tgoto('cm',0,0); # move
799 print $me->{_term}->Tputs('sr'); # scroll back
800  
801 #XXX Skip cursor back to matching line if in grep mode
802 #Skip cursor back to matching line if in grep mode
803 # if( $me->{_grep} && $me->{_cursor} > 0 ){
804 # until( $me->{_text}->[$me->{_end}] =~
805 # m%$me->{_search}|\cF\c]\cL\cE \[\d+/% ){
806 # $me->{_cursor}--;
807 # if( $me->{_cursor} <= 0 ){
808 # $me->{cursor} = 0;
809 # last;
810 # }
811 # }
812 # }
813  
814 $me->line( --$me->{_cursor} );
815 $me->{_end}--;
816 }
817 }
818  
819 print $me->{_term}->Tgoto('cm',0,$me->{rows}); # goto bottom
820 $me->scrollBar() if $me->{scrollBar};
821 }
822 sub uppage { $_[0]->up_lines( $_[0]->{rows} ); }
823 sub upline { $_[0]->up_lines( 1 ); }
824 sub uphalf { $_[0]->up_lines( $_[0]->{rows} / 2 ); }
825  
826 sub to_top { $_[0]->jump(0); }
827  
828 sub to_bott{
829 my $me = shift;
830 if( $me->{rows}>$me->{_txtN} ){
831 $me->jump( 0 ) }
832 else{
833 $me->jump( $me->{_txtN}-1 );
834 $me->uppage() }
835 }
836  
837 sub save_mark{
838 my $me = shift;
839  
840 $me->I18N('status', $me->{BLD}.'*Mark name?*'.$me->{NOR}.$me->{REV});
841 $me->status();
842 $me->{_term}->Tgoto('cm',
843 #XXX I18N
844 length('[tp] 100% Bottom Mark name?')+1,
845 $me->{rows});
846 my $mark = ReadKey();
847 return if $mark eq "\cG";
848 next if $mark eq "'";
849 $me->{_mark}->{$mark} = $me->{_cursor};
850 $me->I18N('status', '');
851 $me->status();
852 }
853  
854 sub goto_mark{
855 my $me = shift;
856  
857 my $mark = ReadKey();
858 return if $mark eq "\cG" or not exists($me->{_mark}->{$mark});
859  
860 my $jump = $me->{_mark}->{$mark};
861 if( $mark eq '^' ){
862 $jump = 0;
863 }
864 elsif( $mark eq '$' ){
865 $jump = $me->{_txtN} - $me->{rows};
866 }
867 elsif( $mark eq '"' ){
868 my $marks = join("\n", map {"$_ = $me->{_mark}->{$_}"}
869 sort keys %{ $me->{_mark} } );
870 $me->dialog($marks);
871 return;
872 }
873 $me->{_mark}->{"'"} = $me->{_cursor};
874 $me->jump( $jump );
875 }
876  
877 sub prev_file{ $_[0]->next_file('anti') }
878 sub next_file{
879 my $me = shift;
880 my $mode = shift || '';
881 my $mark = $me->{_curFile} + ( $mode eq 'anti' ? -1 : 1 );
882 if( exists($me->{_mark}->{$mark}) ){
883 $me->{_mark}->{"'"} = $me->{_cursor};
884 $me->jump( $me->{_mark}->{$mark} ); }
885 else{
886 $me->beep()
887 }
888 }
889  
890 sub jump{
891 my $me = shift;
892 $me->{_cursor} = shift;
893 $me->{_end} = $me->{_cursor} + $me->{rows}; # - 1;
894 $me->refresh();
895 }
896  
897 sub tab_right{
898 my $me = shift;
899 $me->{_left} += 8;
900 $me->refresh();
901 }
902  
903 sub tab_left{
904 my $me = shift;
905 $me->{_left} = 0 if ($me->{_left} -= 8) < 0;
906 $me->refresh();
907 }
908  
909 sub shift_right{
910 my $me = shift;
911 $me->{_left} += int($me->{cols}/2);
912 $me->refresh();
913 }
914  
915 sub shift_left{
916 my $me = shift;
917 $me->{_left} = 0 if ( $me->{_left} -= int($me->{cols}/2) ) < 0;
918 $me->refresh();
919 }
920  
921  
922 sub grep{ $_[0]->search(-1); }
923 sub hcraes{ $_[0]->search(1); }
924 sub search{
925 my $me = shift;
926 my $mode = shift || 0;
927 $me->{_hcraes} = $mode == 1;
928 $me->{_grep} = $mode == -1;
929 $me->{_searchWrap} = 0 unless $me->{_grep};
930  
931 # get pattern
932 (my($prev), $me->{_search}) = ($me->{_search}, '');
933  
934 print $me->{_term}->Tgoto('cm', 0, $me->{rows}); # move bottom
935 print $me->{_term}->Tputs('ce'); # clear line
936 print $me->{HILT}; # set color
937 print $mode ? ( $mode > 0 ? '?' : '&' ) : '/';
938  
939 $me->{_search} = $me->getln() || '';
940 print $me->{NOR}; # normal color
941 print $me->{_term}->Tgoto('cm', 0, $me->{rows}); # move bottom
942 print $me->{_term}->Tputs('ce'); # clear line
943 if( $me->{_search} eq '' ){
944 $me->refresh();
945 return;
946 }
947  
948 $me->{_search} = '(?i)'.$me->{_search} unless
949 $me->{_search} ne lc($me->{_search});
950  
951 $me->{_search} = $prev if $me->{_search} eq '/' && $prev;
952  
953 #Jump to first match
954 for my $n ( $me->{_cursor} .. $me->{_txtN} -1){ #XXX why offset needed?
955 next unless $me->{_text}[$n] =~ /$me->{_search}/i;
956
957 $me->{_cursor} = $n;
958 $me->{_cursor} = 0 if $me->{_txtN} < $me->{rows}; # - 1;
959 $me->{_end} = $me->{_cursor} + $me->{rows}; # - 1;
960  
961 #Special jump if match is on last screen
962 if( $me->{_cursor} + $me->{rows} > $me->{_txtN} - 1 && $me->{_cursor} ){
963 my $x = $me->{_cursor} + $me->{rows} - $me->{_txtN};
964 $x = $me->{_cursor} if $x > $me->{_cursor};
965 $me->{_cursor} -= $x;
966 $me->{_end} -= $x;
967 }
968  
969 $me->refresh();
970 return;
971 }
972  
973 # not found
974 &beep;
975 $me->dialog($me->{_I18N}{404}, 1);
976 return;
977 }
978  
979 sub prev_match{ $_[0]->next_match('anti'); }
980 sub next_match{
981 my $me = shift;
982 return unless defined($me->{_txtN}) and defined($me->{_search});
983  
984 my $mode=shift;
985 if( defined($mode) and $mode ='anti' ){
986 $mode = not $me->{_hcraes}; }
987 else{
988 $mode = $me->{_hcraes};
989 }
990  
991 if( $me->{_searchWrap} ){
992 $me->{_searchWrap} = 0;
993 $me->jump( $mode ? $me->{_txtN} : 0 );
994 }
995  
996  
997 my $i = $mode ? ($me->{_cursor}||0)-1 : ($me->{_cursor})+1;
998 my $matched=0;
999 for( ;
1000 $mode ? $i>0 : $i< $me->{_txtN};
1001 $mode ? $i-- : $i++ ){
1002 $matched = $me->{_text}[$i] =~ /$me->{_search}/;
1003 last if $matched;
1004 }
1005 if( ($i == ($mode ? 0 : $me->{_txtN} )) && ($me->{_searchWrap} == 0) ){
1006 $me->dialog($me->I18N('searchwrap'), 1);
1007 $me->{_searchWrap} = 1;
1008 return;
1009 }
1010 $matched ? $me->jump($i) : &beep;
1011 }
1012  
1013 sub toggle_num{
1014 my $me = shift;
1015 $me->{lineNo} = not $me->{lineNo};
1016 # $me->reflow();
1017 $me->refresh();
1018 }
1019  
1020 sub toggle_raw{
1021 my $me = shift;
1022 $me->{raw} = not $me->{raw};
1023 $me->reflow();
1024 }
1025  
1026 sub toggle_fold{
1027 my $me = shift;
1028 $me->{fold} = not $me->{fold};
1029 $me->{_lineNo} = [1 .. $me->{_txtN}] if $me->{fold};
1030 $me->reflow();
1031 }
1032  
1033  
1034 sub write_buffer{
1035 my $me = shift;
1036  
1037 print $me->{_term}->Tgoto('cm', 0, $me->{rows}); # move bottom
1038 print $me->{_term}->Tputs('ce'); # clear line
1039 print "Save to: ";
1040  
1041 my $out = $me->{_search} = $me->getln();
1042 if( ! -e $out && open(OUT, '>', $out) ){
1043 print OUT join($/, @{$me->{_text}});
1044 CORE::close(OUT);
1045 }
1046 else{
1047 $me->dialog("ERROR: " . -e $out ? "File exists" : $!)
1048 }
1049 }
1050  
1051 sub open_file{
1052 my $me = shift;
1053  
1054 print $me->{_term}->Tgoto('cm', 0, $me->{rows}); # move bottom
1055 print $me->{_term}->Tputs('ce'); # clear line
1056 print "Examine: ";
1057  
1058 my $file = $me->getln();
1059 unless( -e $file ){
1060 $me->dialog( sprintf("%s: $file", $me->{_I18N}{404}) );
1061 return;
1062 }
1063 unless( open(IN, '<', $file) ){
1064 $me->dialog($!);
1065 return;
1066 }
1067 my $N = $me->get_fileN();
1068 $me->set_fileN($N+1);
1069 $me->add_text(sprintf("======== \cF\c]\cL\cE [%i/..] %s ========\n",
1070 $N, $file), <IN>);
1071 }
1072  
1073 sub get_fileN{ $_[0]->{_fileN} }
1074 sub set_fileN{ $_[0]->{_fileN} = $_[1] }
1075  
1076  
1077 sub dumb_mode{
1078 my $me = shift;
1079 my $end = 0;
1080  
1081 while(1){
1082 for my $i (1 .. $me->{rows} ){
1083 last if $end >= $me->{_txtN};
1084 print $me->{_text}[$end++], "\n";
1085 }
1086
1087 print "--more [dumb]-- <q> quit";
1088 my $a = getc();
1089 print "\b \b"x15;
1090  
1091 return if $a eq 'q';
1092 return if $end >= $me->{_txtN};
1093 }
1094 }
1095  
1096 1;
1097 __END__