-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathgetNodeMatcher.ts
More file actions
90 lines (81 loc) · 2.21 KB
/
Copy pathgetNodeMatcher.ts
File metadata and controls
90 lines (81 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { UnsupportedLanguageError } from "@cursorless/common";
import type { Node } from "web-tree-sitter";
import type { SimpleScopeTypeType } from "@cursorless/common";
import type {
NodeMatcher,
NodeMatcherValue,
SelectionWithEditor,
} from "../typings/Types";
import { notSupported } from "../util/nodeMatchers";
import { selectionWithEditorFromRange } from "../util/selectionUtils";
import clojure from "./clojure";
import type { LegacyLanguageId } from "./LegacyLanguageId";
import latex from "./latex";
import { patternMatchers as ruby } from "./ruby";
import rust from "./rust";
export function getNodeMatcher(
languageId: string,
scopeTypeType: SimpleScopeTypeType,
includeSiblings: boolean,
): NodeMatcher {
const matchers = languageMatchers[languageId as LegacyLanguageId];
if (matchers == null) {
throw new UnsupportedLanguageError(languageId);
}
const matcher = matchers[scopeTypeType];
if (matcher == null) {
return notSupported(scopeTypeType);
}
if (includeSiblings) {
return matcherIncludeSiblings(matcher);
}
return matcher;
}
export const languageMatchers: Record<
LegacyLanguageId,
Partial<Record<SimpleScopeTypeType, NodeMatcher>>
> = {
clojure,
latex,
ruby,
rust,
};
function matcherIncludeSiblings(matcher: NodeMatcher): NodeMatcher {
return (
selection: SelectionWithEditor,
node: Node,
): NodeMatcherValue[] | null => {
let matches = matcher(selection, node);
if (matches == null) {
return null;
}
matches = matches.flatMap((match) =>
iterateNearestIterableAncestor(
match.node,
selectionWithEditorFromRange(selection, match.selection.selection),
matcher,
),
);
if (matches.length > 0) {
return matches;
}
return null;
};
}
function iterateNearestIterableAncestor(
node: Node,
selection: SelectionWithEditor,
nodeMatcher: NodeMatcher,
) {
let parent: Node | null = node.parent;
while (parent != null) {
const matches = parent.namedChildren
.flatMap((sibling) => nodeMatcher(selection, sibling))
.filter((match) => match != null) as NodeMatcherValue[];
if (matches.length > 0) {
return matches;
}
parent = parent.parent;
}
return [];
}