Silliness of the day: digit-by-digit tab completion for ints/floats

I was hacking on Perinci::Sub::Complete these past two days and I thought I'd add a (silly) feature that most other completion libraries don't (bother to) have.

# high-low
use strict;
use Perinci::CmdLine;

our %SPEC;

$SPEC{high_low} = {
v => 1.1,
args => {
first => {
schema => [int => req=>1, min=>1, max=>6],
req => 1,
pos => 0,
},
second => {
schema => [int => req=>1, min=>1, max=>6],
req => 1,
pos => 1,
},
},
result_naked => 1,
};
sub high_low {
my %args = @_;
my $first = $args{first};
my $second = $args{second};
my $total = $first + $second;
$total > 7 ? "high" : $total < 7 ? "low" : "seven";
}

Perinci::CmdLine->new(url => '/main/high_low')->run;

Rinci metadata can give enough information for us to complete argument value. For example, in the above program, we know from the min and max schema clauses that the first and second arguments can only contain integers between 1 and 6. So when we run the program on the command-line:

% complete -C ./high-low high-low
% ./high-low --first [TAB]
1 2 3 4 5 6

By default, the limit for completion is 100. So if you have schemas like these:

[int => between => [-100, 100]] # schema 1
[int => min=>1, max=>2000] # schema 2
['int'] # schema 3

The completion library won't return any completion alternatives, fearing the list is too long (or infinite).

But today I thought, how about adding completion alternatives for the next digit only? So for schema #1:

% prog --int [TAB]
-1 -2 -3 -4 -5 -6 -7 -8 -9 0 1 2 3 4 5 6 7 8 9

% prog --int -1[TAB]
-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19

% prog --int 9[TAB]
9 90 91 92 93 94 95 96 97 98 99

% ./high-low --int 100[TAB]
100

The same is done for float, e.g. for schema [float => min => 2, xmax=>5]:

% prog --float [TAB]
2 3 4

% prog --float 2[TAB]
2 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9

% prog --float 2.4[TAB]
2.4 2.40 2.41 2.42 2.43 2.44 2.45 2.46 2.47 2.48 2.49

% prog --float 2.42[TAB]
2.42 2.420 2.421 2.422 2.423 2.424 2.425 2.426 2.427 2.428 2.429

I don't know when I'll ever find this feature nifty, but anyway it's fun to add ;-)

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.