Pager/Perl.pm untested

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