This might not be exactly what you want but it was fun anyways :)
Done without looking at hints or other code.
Runs in xterm on ArchLinux, don't know about other systems...
#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11150326 use warnings; use List::Util qw( uniq ); use Term::ReadKey; # dummy items to play with my @animals = (qw( cow camel dog cat )); my @foods = (qw( fish pasture meat )); my @places = (qw( wood sea desert )); # commands my $commands = { select => { completion_list => \@animals, commands => { give => { completion_list => \@foods, }, take_to => { completion_list => \@places, }, }, }, kill => { completion_list => \@animals, } }; my $completed = autocomplete( $commands, 'test autocomplete> ' ); print $completed ? "\nThe user entered: $completed\n" : "\nEscape\n"; exit; ###################################################################### sub autocomplete { my ($commands, $prompt) = @_; my $lines = join "\n", lines($commands), ''; $prompt //= '> '; my $input = ''; my $clearline = "\e[G\e[K"; my $skip; $| = 1; ReadMode 'raw'; eval { while() { $skip or print $clearline, $prompt, $input; $skip = 0; my $char = ReadKey; $char =~ tr/\e\cc// and $input = '', last; $char =~ tr/\n\r// and $lines =~ /^$input$/m ? last : next; $char eq "\b" and chop($input), next; if( $char eq "\t" ) { my ($new, $letters) = extend($input, $lines); if( not defined $new ) { # shorten to longest legal string $input = "$input\n$lines" =~ /^(.*).*\n(?:.*\n)*\1/ ? $1 : ' +'; next; } $input = $new; my $info = (extend($input, $lines))[1] || '***Complete!'; my $len = 2 + length $info; print $clearline, $prompt, $input, " \e[92m$info\e[m\e[${len} +D"; $skip = 1; next; } $input .= $char; } }; ReadMode 'restore'; print "\n"; return $input; } sub extend { my ($in, $lines) = @_; my $match = join '', $lines =~ /^\Q$in\E.*\n/gm; my $extend = $match =~ /^(.*).*\n(?:\1.*\n)*\z/? $1 : undef; my $letters = join ' ', sort + uniq $lines =~ /^\Q$in\E(\S+)/gm; return $extend, $letters; } sub lines { my $cmd = shift or return ''; map s/ +$//r, map { my $key = $_; # fun triple map nesting map { my $prev = $_; map "$key $_ $prev", @{ $cmd->{$key}{completion_list} }; } lines( $cmd->{$key}{commands} ) } keys %$cmd; }
In reply to Re: [challenge] Nested autocompletion
by tybalt89
in thread [challenge] Nested autocompletion
by Discipulus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |