From 02c656e0eed5864b90967a83949b8f18fa130ef2 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Mon, 11 Sep 2023 18:49:28 -0700 Subject: [PATCH] add #trim-end predicate The same thing can be accomplished with #shrink-to-match!, but this is considerably simpler to use, and meets a common need. Suggested by Pokey during review of #1854. --- .../queryPredicateOperators.ts | 20 +++++++++++++++++++ queries/talon.scm | 4 ++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/cursorless-engine/src/languages/TreeSitterQuery/queryPredicateOperators.ts b/packages/cursorless-engine/src/languages/TreeSitterQuery/queryPredicateOperators.ts index e1647f5f1e..46fb97f705 100644 --- a/packages/cursorless-engine/src/languages/TreeSitterQuery/queryPredicateOperators.ts +++ b/packages/cursorless-engine/src/languages/TreeSitterQuery/queryPredicateOperators.ts @@ -150,6 +150,25 @@ class ShrinkToMatch extends QueryPredicateOperator { } } +/** + * A predicate operator that modifies the range of the match by trimming trailing whitespace, + * similar to the javascript trimEnd function. + */ +class TrimEnd extends QueryPredicateOperator { + name = "trim-end!" as const; + schema = z.tuple([q.node]); + + run(nodeInfo: MutableQueryCapture) { + const { document, range } = nodeInfo; + const text = document.getText(range); + const trimmed = text.trimEnd(); + const endOffset = + document.offsetAt(range.end) + trimmed.length - text.length; + nodeInfo.range = new Range(range.start, document.positionAt(endOffset)); + return true; + } +} + class AllowMultiple extends QueryPredicateOperator { name = "allow-multiple!" as const; schema = z.tuple([q.node]); @@ -179,6 +198,7 @@ class InsertionDelimiter extends QueryPredicateOperator { export const queryPredicateOperators = [ new NotType(), + new TrimEnd(), new NotEmpty(), new NotParentType(), new IsNthChild(), diff --git a/queries/talon.scm b/queries/talon.scm index 4275407c7b..8eb3b4b2e7 100644 --- a/queries/talon.scm +++ b/queries/talon.scm @@ -113,8 +113,8 @@ ) @_.domain (#not-empty? @condition) (#not-empty? @_.trailing) - (#shrink-to-match! @condition "^(?.*)(\s|\n|\r)+-$") - (#shrink-to-match! @_.trailing "^.*(?(\s|\n|\r)+-)$") + (#trim-end! @condition) + (#trim-end! @_.trailing) ) ;;!! slap: key(enter)