Skip to content

Commit

Permalink
Subtokens support reversed order ordinals (#121)
Browse files Browse the repository at this point in the history
* fixed small offset error on the negative end index

* Handle reverse order sub token

* excluding end index for negative index

* use anchor and active instead of start and end
  • Loading branch information
AndreasArvidsson authored Jul 21, 2021
1 parent 477681d commit 0e307f4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 28 deletions.
4 changes: 2 additions & 2 deletions src/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ export interface ContainingScopeModifier {
export interface SubpieceModifier {
type: "subpiece";
pieceType: PieceType;
startIndex: number;
endIndex: number | null;
anchor: number;
active: number;
}
export interface MatchingPairSymbolModifier {
type: "matchingPairSymbol";
Expand Down
40 changes: 14 additions & 26 deletions src/processTargets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,49 +206,37 @@ function transformSelection(
let pieces: { start: number; end: number }[] = [];

if (modifier.pieceType === "word") {
const matches = token.matchAll(SUBWORD_MATCHER);
for (const match of matches) {
pieces.push({
start: match.index!,
end: match.index! + match[0].length,
});
}
pieces = [...token.matchAll(SUBWORD_MATCHER)].map((match) => ({
start: match.index!,
end: match.index! + match[0].length,
}));
} else if (modifier.pieceType === "character") {
pieces = range(token.length).map((index) => ({
start: index,
end: index + 1,
}));
}

// NB: We use the modulo here to handle negative offsets
const endIndex =
modifier.endIndex == null
? pieces.length
: modifier.endIndex <= 0
? modifier.endIndex + pieces.length
: modifier.endIndex;
const anchorIndex =
modifier.anchor < 0 ? modifier.anchor + pieces.length : modifier.anchor;
const activeIndex =
modifier.active < 0 ? modifier.active + pieces.length : modifier.active;

const startIndex =
modifier.startIndex < 0
? modifier.startIndex + pieces.length
: modifier.startIndex;
const isReversed = activeIndex < anchorIndex;

const start = selection.selection.start.translate(
const anchor = selection.selection.start.translate(
undefined,
pieces[startIndex].start
isReversed ? pieces[anchorIndex].end : pieces[anchorIndex].start
);
const end = selection.selection.start.translate(
const active = selection.selection.start.translate(
undefined,
pieces[endIndex - 1].end
isReversed ? pieces[activeIndex].start : pieces[activeIndex].end
);

return [
{
selection: update(selection, {
selection: (s) =>
s.isReversed
? new Selection(end, start)
: new Selection(start, end),
selection: () => new Selection(anchor, active),
}),
context: {},
},
Expand Down

0 comments on commit 0e307f4

Please sign in to comment.