- my $trim = 1;
- my $before = $offset > $context ? $self->[$offset - $context] : '';
- for my $match (split //, $before) {
- scalar $link =~ /\G\Q$match/g or last;
- $trim++;
+ my $penalty = 0;
+ # take a value slightly before the current offset
+ if ((my $before = $offset + $lookbehind) > 0) {
+ # see how much of it matches the current link
+ my $trim = 1;
+ for my $match (split //, $self->[$before - 1]) {
+ scalar $link =~ /\G\Q$match/g or last;
+ $trim++;
+ }
+ # truncate link upto where the earlier value starts to differ
+ if ($trim < length $link) {
+ substr($link, $trim) = '';
+ for (reverse $before .. $offset) {
+ $self->[$offset - $penalty] =~ /^\Q$link/ or last;
+ $penalty++;
+ }
+ }
+ }
+
+ $lookbehind = -$context;
+
+ # take a value after the current offset
+ if ((my $after = $offset + $lookahead) < $#$self) {
+ # see how much of it matches the current link
+ my $trim = 1;
+ for my $match (split //, $self->[$after]) {
+ scalar $link =~ /\G\Q$match/g or last;
+ $trim++;
+ }
+ # use this link if it's shorter
+ if ($trim < length $link) {
+ $link = substr $self->[$after], 0, $trim;
+ # advance lookbehind offset on the next page
+ $penalty = 0;
+ for ($offset .. $after) {
+ last if $self->[$_] =~ /^\Q$link/;
+ $lookbehind++;
+ }
+ }