Ignore:
Timestamp:
Jul 27, 2009, 11:23:57 PM (12 years ago)
Author:
Nelson Elhage <nelhage@mit.edu>
Branches:
master, release-1.4, release-1.5, release-1.6, release-1.7, release-1.8, release-1.9
Children:
5368d75
Parents:
d7bcff8
git-author:
Nelson Elhage <nelhage@mit.edu> (07/27/09 20:24:21)
git-committer:
Nelson Elhage <nelhage@mit.edu> (07/27/09 23:23:57)
Message:
Implement tab completion for command names.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • perl/lib/BarnOwl/Completion.pm

    r8eac1a5 r6e48560  
    1515
    1616use BarnOwl::Completion::Context;
     17use BarnOwl::Editwin qw(text_before_point text_after_point);
    1718
     19use List::Util qw(max first);
    1820
     21sub do_complete {
     22    my $cmd = shift;
     23    my $before = text_before_point();
     24    my $after  = text_after_point();
     25    BarnOwl::debug("Completing: $before-|-$after");
     26    my $ctx = BarnOwl::Completion::Context->new($before, $after);
     27
     28    my @words = get_completions($ctx);
     29    return unless @words;
     30    my $prefix = common_prefix(@words);
     31
     32    my $word = $ctx->words->[$ctx->word];
     33
     34    if($prefix && $prefix ne $word) {
     35        if(scalar @words == 1) {
     36            $prefix .= ' ';
     37        }
     38       
     39        BarnOwl::Editwin::insert_text(substr($prefix, length($word)));
     40    }
     41
     42    if(scalar @words > 1) {
     43        show_completions(@words);
     44    }
     45}
     46
     47sub get_completions {
     48    my $ctx = shift;
     49    if($ctx->word == 0) {
     50        return complete_command($ctx->words->[0]);
     51    } else {
     52        return;
     53    }
     54}
     55
     56sub complete_command {
     57    my $cmd = shift;
     58    return grep {$_ =~ m{^\Q$cmd\E}} @BarnOwl::all_commands;
     59}
     60
     61sub show_completions {
     62    my @words = @_;
     63    my $all = join(" ", map {BarnOwl::quote($_)} @words);
     64    my $width = BarnOwl::getnumcols();
     65    if (length($all) > $width-1) {
     66        $all = substr($all, 0, $width-4) . "...";
     67    }
     68    BarnOwl::message($all);
     69}
     70
     71sub common_prefix {
     72    my @words = @_;
     73    my $len   = max(map {length($_)} @words);
     74    my $pfx = '';
     75    for my $i (1..$len) {
     76        $pfx = substr($words[0], 0, $i);
     77        if(first {substr($_, 0, $i) ne $pfx} @words) {
     78            $pfx = substr($pfx, 0, $i-1);
     79            last;
     80        }
     81    }
     82
     83    return $pfx;
     84}
    1985
    20861;
Note: See TracChangeset for help on using the changeset viewer.