source: perl/lib/BarnOwl/Completion.pm @ 0fee298

release-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 0fee298 was 0fee298, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Completion.pm: Remove a dead variable.
  • Property mode set to 100644
File size: 2.2 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Completion
7
8=head1 DESCRIPTION
9
10Hooks for tab-completion support in BarnOwl.
11
12=cut
13
14package BarnOwl::Completion;
15
16use BarnOwl::Completion::Context;
17use BarnOwl::Editwin qw(save_excursion text_before_point text_after_point
18                        point_move replace_region);
19
20use List::Util qw(max first);
21
22sub do_complete {
23    my $cmd = shift;
24    my $before = text_before_point();
25    my $after  = text_after_point();
26    BarnOwl::debug("Completing: $before-|-$after");
27    my $ctx = BarnOwl::Completion::Context->new($before, $after);
28
29    my @words = get_completions($ctx);
30    return unless @words;
31    my $prefix = common_prefix(@words);
32
33    if($prefix) {
34        insert_completion($ctx, $prefix, scalar @words == 1);
35    }
36
37    if(scalar @words > 1) {
38        show_completions(@words);
39    } else {
40        BarnOwl::message('');
41    }
42}
43
44sub insert_completion {
45    my $ctx = shift;
46    my $completion = shift;
47    my $unique = shift;
48
49    save_excursion {
50        point_move($ctx->word_start - $ctx->point);
51        BarnOwl::Editwin::set_mark();
52        point_move($ctx->word_end - $ctx->word_start);
53        replace_region(BarnOwl::quote($completion));
54    };
55    if($unique && $ctx->word == (scalar @{$ctx->words} - 1)) {
56        save_excursion {
57            BarnOwl::Editwin::set_mark();
58            replace_region(' ');
59        };
60        point_move(1);
61    }
62}
63
64sub get_completions {
65    my $ctx = shift;
66    if($ctx->word == 0) {
67        return complete_command($ctx->words->[0]);
68    } else {
69        return;
70    }
71}
72
73sub complete_command {
74    my $cmd = shift;
75    return grep {$_ =~ m{^\Q$cmd\E}} @BarnOwl::all_commands;
76}
77
78sub show_completions {
79    my @words = @_;
80    my $all = join(" ", map {BarnOwl::quote($_)} @words);
81    my $width = BarnOwl::getnumcols();
82    if (length($all) > $width-1) {
83        $all = substr($all, 0, $width-4) . "...";
84    }
85    BarnOwl::message($all);
86}
87
88sub common_prefix {
89    my @words = @_;
90    my $len   = max(map {length($_)} @words);
91    my $pfx = '';
92    for my $i (1..$len) {
93        $pfx = substr($words[0], 0, $i);
94        if(first {substr($_, 0, $i) ne $pfx} @words) {
95            $pfx = substr($pfx, 0, $i-1);
96            last;
97        }
98    }
99
100    return $pfx;
101}
102
1031;
Note: See TracBrowser for help on using the repository browser.