Psh/Completion.pm untested

filter: Statementstmt 0.0% 0 / 280 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 72 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 575 CC 69 SCAR 53.9
CC
69
Cov
0%
completion
650.0
cmpl_filenames
210.0
cmpl_executable
42.0
CRAP 218.2
1 package Psh::Completion;
2  
3 use strict;
4 require Psh::Util;
5 require Psh::OS;
6  
7 my $APPEND="not_implemented";
8  
9 @Psh::Completion::bookmarks= ();
10 @Psh::Completion::autoload=();
11  
12 my %module_loaded=();
13  
14 sub init
15 {
16 my $attribs=$Psh::term->Attribs;
17  
18 # The following is ridiculous, but....
19 if( $Psh::term->ReadLine eq 'Term::ReadLine::Perl') {
20 $APPEND='completer_terminator_character';
21 } elsif( $Psh::term->ReadLine eq 'Term::ReadLine::Gnu') {
22 $APPEND='completion_append_character';
23 }
24  
25 # Only ::Gnu understand it, and ::Perl ignores it silently.
26 $attribs->{completion_display_matches_hook}
27 = \&display_match_list;
28 }
29  
30 sub start_module {
31 my $command= shift;
32 my $file= $Psh::Completion::modules{$command};
33 return unless $file;
34 return if $module_loaded{$file};
35 open(FILE, "< $file");
36 my @lines= <FILE>;
37 close(FILE);
38 if (@lines) {
39 my $text= join('',@lines);
40 Psh::process_variable($text);
41 $module_loaded{$file}=1;
42 }
43 }
44  
45 {
46 my $kh_loaded=0;
47 sub bookmarks {
48 return @Psh::Completion::bookmarks if $kh_loaded;
49 push @Psh::Completion::bookmarks, Psh::OS::get_known_hosts();
50 $kh_loaded=1;
51 return @Psh::Completion::bookmarks;
52 }
53 }
54  
55 # Returns a list of possible file completions
56 sub cmpl_filenames
57 {
58 my $text= shift;
59 my $executable_only= shift||0;
60  
61 my $exclam=0;
62  
63 # HACK HACK HACK - this needs to be fixed some other way -
64 # the completion code is severly messed I fear
65 $text= Psh::Parser::unquote($text);
66 $text=~ s/\\//g;
67 # HACK END
68  
69 if ( $executable_only) {
70 if ($text=~s/^\!//) {
71 $exclam=1;
72 }
73 }
74  
75 my $globtext= $text;
76 my $prepend= '';
77  
78 if( substr($text,0,1) eq '"') {
79 $prepend='"';
80 $globtext= substr($text,1);
81 }
82  
83 my @result;
84  
85 if (substr($globtext,0,1) eq '~' and !($globtext=~/\//)) {
86 # after ~ try username completion
87 @result= cmpl_usernames($globtext);
88 $Psh::Completion::ac="/" if @result;
89 return @result;
90 }
91  
92 @result= Psh::OS::glob("$globtext*");
93  
94 if( Psh::Options::has_option('fignore')) {
95 my @ignore= Psh::Options::get_option('fignore');
96 @result= grep {
97 my $item= $_;
98 my $result= ! grep { Psh::Util::ends_with($item,$_) } @ignore;
99 $result;
100 } @result;
101 }
102  
103 if ( $executable_only) {
104 @result= grep { -x $_ || -d _ } @result;
105 }
106  
107 @result= map { -d $_ ? "$_/" : $_ } @result;
108  
109 # HACK: This won't help much if user tries to do another completion
110 # on the same item afterwards
111 @result= map { s/([ \'\"\ยด\`])/\\$1/g; $_ } @result unless $prepend eq '"';
112  
113 if(@result==1) {
114 if (substr($result[0],-1) eq '/') {
115 $Psh::Completion::ac='';
116 }
117 $Psh::Completion::ac=$prepend.$Psh::Completion::ac if $prepend;
118 }
119  
120 foreach (@result) {
121 if( m|/([^/]+\/?)$| ) {
122 $_=$1;
123 }
124 }
125  
126 return @result;
127 }
128  
129  
130 # Returns a list of possible directory completions
131 sub cmpl_directories
132 {
133 my $text= shift;
134 my $globtext= $text;
135 my $prepend= '';
136  
137 if( substr($text,0,1) eq '"') {
138 $prepend='"';
139 $globtext= substr($text,1);
140 }
141  
142 my @result;
143 if (substr($globtext,0,1) eq '~' and !($globtext=~/\//)) {
144 # after ~ try username completion
145 @result= cmpl_usernames($globtext);
146 $Psh::Completion::ac="/" if @result;
147 return @result;
148 }
149  
150 @result= grep { -d $_ } Psh::OS::glob("$globtext*");
151  
152 $Psh::Completion::ac=$prepend||'';
153  
154 @result= map { $_.'/' } @result;
155  
156 foreach (@result) {
157 if( m|/([^/]+/?)$| ) {
158 $_=$1;
159 }
160 }
161  
162 return @result;
163 }
164  
165  
166 # Returns an array with possible username completions
167 sub cmpl_usernames
168 {
169 my $text= shift;
170 my @result= grep { Psh::Util::starts_with($_,$text) } Psh::OS::get_all_users();
171 return @result;
172 }
173  
174  
175 #
176 # Tries to find executables for possible completions
177 sub cmpl_executable
178 {
179 my $cmd= shift;
180 my @result = ();
181 my $exclam=0;
182  
183 if ($cmd=~s/^\!//) {
184 $exclam=1;
185 }
186  
187 if (Psh::Strategy::active('built_in')) {
188 if ($Psh::Support::Alias::loaded) {
189 push @result, grep { Psh::Util::starts_with($_,$cmd) } Psh::Support::Alias::get_alias_commands();
190 }
191 push @result, grep { Psh::Util::starts_with($_,$cmd) } Psh::Support::Builtins::get_builtin_commands();
192 }
193 push @result, cmpl_directories($cmd) if $Psh::Completion::complete_first_word_dirs;
194
195 local $^W= 0;
196  
197 Psh::Util::which($cmd);
198 # set up absed_path if not already set and check
199
200 foreach my $dir (@Psh::absed_path) {
201 push( @result, map { $exclam?'!'.$_:$_ }
202 grep { -x $dir.'/'.$_ && ! -d _ } Psh::OS::glob("$cmd*",$dir) );
203 }
204 return @result;
205 }
206  
207  
208 #
209 # Completes perl symbols
210  
211 {
212 my %type;
213  
214 BEGIN {
215 %type = ('$' => 'SCALAR', '*' => 'SCALAR',
216 '@' => 'ARRAY', '$#' => 'ARRAY',
217 '%' => 'HASH',
218 '&' => 'CODE');
219 }
220  
221 sub cmpl_symbol {
222 my ($text, $line, $start) = @_;
223
224 my ($prefix, $pre, $pkg, $sym);
225 no strict qw(refs);
226 ($prefix, $pre, $pkg) = ($text =~ m/^((\$#|[\@\$%&])(.*::)?)/);
227 my @packages = grep /::$/, $pkg ? keys %$pkg : keys %::;
228 $pkg = ($Psh::PerlEval::current_package eq 'main' ? '::' : $Psh::PerlEval::current_package . '::') unless $pkg;
229
230 my @symbols;
231 if ($pre eq '$') {
232 no strict 'vars'; # make `eval' quiet
233 # I cannot use `defined *$sym{SCALAR}',
234 # since it is always true.
235 @symbols = grep (/^\w+$/
236 && (eval "defined $prefix$_"
237 || ($sym = $pkg . $_,
238 defined *$sym{ARRAY}
239 || defined *$sym{HASH})),
240 keys %$pkg);
241 } else {
242 @symbols = grep (/^\w+$/
243 && ($sym = $pkg . $_,
244 defined *$sym{$type{$pre}}),
245 keys %$pkg);
246 }
247 # Do we need a user customizable variable to ignore @packages?
248 return grep(/^\Q$text/,
249 map($prefix . $_, @packages, @symbols));
250 }
251 }
252  
253 #
254 # Completes key names for Perl hashes
255 #
256 sub cmpl_hashkeys {
257 my ($text, $line, $start) = @_;
258  
259 my $tmp= substr($line, 0, $start + 1);
260 my ($var,$arrow) = ($tmp =~ m/^[\$\%]([\w:]+)\s*(->)?\s*\{\s*['"]?/);
261 return () unless $var;
262  
263 no strict 'refs';
264 $var = "$Psh::PerlEval::current_package::$var" unless ($var =~ m/::/);
265 return () unless $var;
266 if ($arrow) {
267 my $hashref = eval "\$$var";
268 return grep(/^\Q$text/, keys %$hashref);
269 } else {
270 return grep(/^\Q$text/, keys %$var);
271 }
272 }
273  
274 sub _search_ISA {
275 my ($mypkg) = @_;
276 no strict qw(refs);
277 my $isa = "${mypkg}::ISA";
278 return $mypkg, map _search_ISA($_), @$isa;
279 }
280  
281 sub cmpl_method {
282 my ($text, $line, $start) = @_;
283
284 my ($var, $pkg, $sym, $pk);
285 $var = (substr($line, 0, $start + 1)
286 =~ m/\$([\w:]+)\s*->\s*$/)[0];
287 $pkg = ref eval (($var =~ m/::/) ? "\$$var" : "\$$Psh::PerlEval::current_package::$var");
288 no strict qw(refs);
289 return grep(/^\Q$text/,
290 map { $pk = $_ . '::';
291 grep (/^\w+$/
292 && ($sym = "${pk}$_", defined *$sym{CODE}),
293 keys %$pk);
294 } _search_ISA($pkg));
295 }
296  
297 {
298  
299 # complete perl bare words (Perl function, subroutines, filehandle)
300 sub cmpl_perl_function {
301 my ($text) = @_;
302  
303 my ($prefix, $pkg, $sym);
304 no strict qw(refs);
305 ($prefix, $pkg) = ($text =~ m/^((.*::)?)/);
306 my @packages = grep /::$/, $pkg ? keys %$pkg : keys %::;
307 $pkg = ($Psh::PerlEval::current_package eq 'main' ? '::' : $Psh::PerlEval::current_package . '::') unless $pkg;
308
309 my @subs = grep (/^\w+$/
310 && ($sym = $pkg . $_,
311 defined *$sym{CODE}
312 || defined *$sym{FILEHANDLE}),
313 keys %$pkg);
314 # Do we need a user customizable variable to ignore @packages?
315 my @result= grep(/^\Q$text/,
316 !$prefix && @Psh::Completion::keyword,
317 map($prefix . $_, @packages, @subs));
318 if (@result==1) {
319 $Psh::Completion::ac='';
320 }
321 return @result;
322 }
323  
324 BEGIN {
325 # from perl5.004_02 perlfunc
326 @Psh::Completion::keyword = qw(
327 chomp chop chr crypt hex index lc lcfirst
328 length oct ord pack q qq
329 reverse rindex sprintf substr tr uc ucfirst
330 y
331
332 m pos quotemeta s split study qr
333  
334 abs atan2 cos exp hex int log oct rand sin
335 sqrt srand
336  
337 pop push shift splice unshift
338  
339 grep join map qw reverse sort unpack
340
341 delete each exists keys values
342
343 binmode close closedir dbmclose dbmopen die
344 eof fileno flock format getc print printf
345 read readdir rewinddir seek seekdir select
346 syscall sysread sysseek syswrite tell telldir
347 truncate warn write
348
349 pack read syscall sysread syswrite unpack vec
350
351 chdir chmod chown chroot fcntl glob ioctl
352 link lstat mkdir open opendir readlink rename
353 rmdir stat symlink umask unlink utime
354
355 caller continue die do dump eval exit goto
356 last next redo return sub wantarray
357
358 caller import local my package use
359
360 defined dump eval formline local my reset
361 scalar undef wantarray
362
363 alarm exec fork getpgrp getppid getpriority
364 kill pipe qx setpgrp setpriority sleep
365 system times wait waitpid
366
367 do import no package require use
368
369 bless dbmclose dbmopen package ref tie tied
370 untie use
371
372 accept bind connect getpeername getsockname
373 getsockopt listen recv send setsockopt shutdown
374 socket socketpair
375
376 msgctl msgget msgrcv msgsnd semctl semget
377 semop shmctl shmget shmread shmwrite
378
379 endgrent endhostent endnetent endpwent getgrent
380 getgrgid getgrnam getlogin getpwent getpwnam
381 getpwuid setgrent setpwent
382
383 endprotoent endservent gethostbyaddr
384 gethostbyname gethostent getnetbyaddr
385 getnetbyname getnetent getprotobyname
386 getprotobynumber getprotoent getservbyname
387 getservbyport getservent sethostent setnetent
388 setprotoent setservent
389
390 gmtime localtime time times
391
392 abs bless chomp chr exists formline glob
393 import lc lcfirst map my no prototype qx qw
394 readline readpipe ref sub sysopen tie tied
395 uc ucfirst untie use
396
397 dbmclose dbmopen
398 );
399 }
400 }
401  
402 #
403 # completion(text,line,start,end)
404 #
405 # Main Completion function
406 #
407  
408 sub completion
409 {
410 my ($text, $line, $start) = @_;
411 my $attribs = $Psh::term->Attribs;
412  
413  
414 my @tmp=();
415 my $cut= 0;
416 my $starttext= substr($line, 0, $start);
417  
418 if ($starttext =~ /((?:\S|\\\s)+\\\s)$/) {
419 $text= $1.$text;
420 $cut= length($1);
421 $start-= $cut;
422 $starttext= substr($line, 0, $start);
423 }
424  
425  
426 my $startchar= substr($line, $start, 1);
427  
428 $starttext =~ /^\s*(\S+)\s+/;
429 my $command= $1 || '';
430  
431 my $pretext= '';
432 if( $starttext =~ /--\w+=(\S*)$/) {
433 $pretext= $1;
434 } elsif ( $starttext =~ /\s(\S*)$/) {
435 $pretext= $1;
436 } elsif( $starttext =~ /^(\S*)$/) {
437 $pretext= $1;
438 }
439  
440 # are we in backticks or after a pipe ?
441 if( $starttext =~ /.*[\|\`]\s*(\S+)\s+/) {
442 $command= $1;
443 }
444  
445 my $firstflag= $starttext !~/\s/ || 0;
446  
447 $Psh::Completion::ac=' ';
448  
449 $command =~ m|^\s*(\S*/)?(\S*)|;
450  
451 if ($Psh::debugging and
452 ($Psh::debugging eq '1' or
453 $Psh::debugging =~ /c/)) {
454 Psh::Util::print_debug_class('c',"\n");
455 Psh::Util::print_debug_class('c',"Completion: text=$text, line=$line, start=$start, starttext=$starttext, command=$command, first=$firstflag\n");
456 }
457  
458  
459 my $dir=$1||'';
460 my $base=$2||'';
461 my $cmd;
462  
463 if ($Psh::Completion::modules{$cmd= $dir.$base} or
464 $Psh::Completion::modules{$cmd= $base}) {
465 start_module($cmd);
466 }
467  
468 if ($Psh::PCompletion::LOADED) {
469 # Check completion-spec is defined or not.
470 my $cmd;
471 my $cs = $Psh::PCompletion::COMPSPEC{$cmd = $dir . $base}
472 || $Psh::PCompletion::COMPSPEC{$cmd = $base};
473 my $universal=0;
474 unless (defined $cs) {
475 $cs= $Psh::PCompletion::COMPSPEC{'*'};
476 $cmd= $dir.$base;
477 $universal=1;
478 }
479  
480 # Do programmable completion if completion-spec is defined.
481 # This is done here to keep the compatibility with bash.
482 if (defined $cs) {
483 # remove prefix string if it is already prefixed.
484 $text =~ s/^\Q$cs->{prefix}//
485 if (defined $cs->{prefix});
486 @tmp = Psh::PCompletion::pcomp_list($cs, $text, $line, $start, $cmd);
487 if (!@tmp) {
488 if ($cs->{option} and $cs->{option} eq 'default') {
489 } elsif ($universal) {
490 # ignore both cases
491 } else {
492 return ();
493 }
494 } else {
495 $attribs->{$APPEND}=$Psh::Completion::ac;
496 return @tmp;
497 }
498 }
499 }
500  
501 if ($starttext =~ m/\$([\w:]+)\s*(->)?\s*{\s*['"]?$/) {
502 # $foo{key, $foo->{key
503 @tmp= cmpl_hashkeys($text, $line, $start);
504 $Psh::Completion::ac = '}';
505 } elsif ($starttext =~ m/\$([\w:]+)\s*->\s*['"]?$/) {
506 # $foo->method
507 @tmp= cmpl_method($text, $line, $start);
508 $Psh::Completion::ac = ' ';
509 } elsif ( $text =~ /^\$#|[\@\$%&]/) {
510 # $foo, @foo, $#foo, %foo, &foo
511 @tmp= cmpl_symbol($text, $line, $start);
512 $Psh::Completion::ac = '';
513 } elsif( $firstflag || $starttext =~ /[\|\`]\s*$/) {
514 # we have the first word in the line or a pipe sign/backtick in front
515 # of the current item, so we try to complete executables
516
517 if ($pretext=~m/\//) {
518 @tmp = cmpl_filenames($pretext.$text,1)
519 } else {
520 @tmp= cmpl_executable($text);
521 }
522 unless ($pretext) {
523 # Afterwards we add possible matches for perl barewords
524 push @tmp, cmpl_perl_function($text);
525 }
526 } else {
527 @tmp = cmpl_filenames($pretext.$text);
528 }
529  
530 if (Psh::Strategy::active('built_in') and
531 grep { $_ eq $command } Psh::Support::Builtins::get_builtin_commands() ) {
532 my $pkg= ucfirst($command);
533 eval "require Psh::Builtins::$pkg";
534 Psh::Util::print_debug_class('e',"Error: $@") if $@;
535 my @tmp2= eval 'Psh::Builtins::'.$pkg.'::cmpl_'."$command('$text','$pretext','$starttext','$line')";
536 if( @tmp2 && $tmp2[0]) {
537 shift(@tmp2);
538 @tmp= @tmp2;
539 } else {
540 shift(@tmp2);
541 push @tmp, @tmp2;
542 }
543 }
544  
545 $attribs->{$APPEND}=$Psh::Completion::ac;
546  
547 if ($cut) {
548 @tmp= map { substr($_, $cut)} @tmp;
549 }
550 return @tmp;
551 }
552  
553 sub display_match_list {
554 my($matches, $num_matches, $max_length) = @_;
555 my @matches= @$matches; # make a copy, otherwise there's memory managment trouble
556 shift @matches;
557  
558 map { $_ =~ s/^((\$#|[\@\$%&])?).*::(.+)/$3/; }(@matches);
559 my $col='01;34';
560 if ($ENV{LS_COLORS}) {
561 my @tmp= split /:/, $ENV{LS_COLORS};
562 foreach (@tmp) {
563 if (substr($_,0,3) eq 'di=') {
564 $col= substr($_,3);
565 last;
566 }
567 }
568 }
569 map { $_ =~ s/^([^\/]+)\/$/\001\e[${col}m\002$1\001\e[00m\002\//; } (@matches);
570 print STDOUT "\n";
571 Psh::Util::print_list(\@matches,$max_length);
572 # eval {
573 # local $^W=0;
574 # $Psh::term->display_match_list($matches);
575 # };
576 eval {
577 local $^W=0;
578 $Psh::term->forced_update_display if defined $Psh::term;
579 };
580 }
581  
582 1;
583 __END__