在 urxvt 终端里左键选取一个单词,右键即刻翻译。


#! perl

sub on_start {
    my ($self) = @_;
    $self->grab_button (3);
    ()
}

sub on_button_press {
    my ($self, $event) = @_;

    if ($event->{button} == 3) {
        my $popup = $self->popup ($event)
            or return 1;

        my $word = $self->selection;

        my $title = $word;
        $title =~ s/[\x00-\x1f\x80-\x9f]/·/g;
        $title =~ s/\W//g; # 删除所有非英文字母

        my @dict = `export LANG=zh_CN.UTF-8; /usr/bin/sdcv -n --utf8-output -u 'XDICT英汉辞典' "$title"`
            or return 2;

        splice(@dict, 0, 4); # 删除前四行
        splice(@dict, -1);   # 删除末尾行
        splice(@dict, 10);   # 只保留十行
        for my $eachline (@dict) {
            chomp $eachline;
            $eachline = $self->locale_decode($eachline);
            $popup->add_title ($eachline);
        }

        $popup->show;

        return 1;
    }

    ()
}

下载保存在 /tmp/blabla/selection-dict,修改 ~/.Xresources 后执行 xrdb ~/.Xresources 再新开一个 urxvt 即可。

URxvt.perl-lib:          /tmp/blabla/  
URxvt.perl-ext-common:   selection-dict