MCPcopy
hub / github.com/prettier/prettier / getCursorLocation

Function getCursorLocation

src/main/get-cursor-node.js:19–81  ·  view source on GitHub ↗

* Find the location of the cursor in the AST, represented in one of the * following ways: * * { "cursorNode": } - the cursor is WITHIN * * { "nodeBeforeCursor": | undefined, * "nodeAfterCursor": | undefined } * - the cursor is BETWEEN and <node2

(ast, options)

Source from the content-addressed store, hash-verified

17 * the other possibilities otherwise.
18 */
19function getCursorLocation(ast, options) {
20 const { cursorOffset, locStart, locEnd, getVisitorKeys } = options;
21
22 const nodeContainsCursor = (node) =>
23 locStart(node) <= cursorOffset && locEnd(node) >= cursorOffset;
24
25 let cursorNode = ast;
26 const nodesContainingCursor = [ast];
27
28 for (const node of getDescendants(ast, {
29 getVisitorKeys,
30 filter: nodeContainsCursor,
31 })) {
32 nodesContainingCursor.push(node);
33 cursorNode = node;
34 }
35
36 if (isLeaf(cursorNode, { getVisitorKeys })) {
37 return { cursorNode };
38 }
39
40 // We've established that the cursor is NOT contained in a leaf node of the
41 // AST. We instead need to find two nodes (which needn't necessarily be
42 // leaves) of the AST that the cursor lies *between*.
43
44 let nodeBeforeCursor;
45 let nodeAfterCursor;
46 let nodeBeforeCursorEndIndex = -1;
47 let nodeAfterCursorStartIndex = Number.POSITIVE_INFINITY;
48
49 while (
50 nodesContainingCursor.length > 0 &&
51 (nodeBeforeCursor === undefined || nodeAfterCursor === undefined)
52 ) {
53 cursorNode = nodesContainingCursor.pop();
54 const foundBeforeNode = nodeBeforeCursor !== undefined;
55 const foundAfterNode = nodeAfterCursor !== undefined;
56 for (const node of getChildren(cursorNode, { getVisitorKeys })) {
57 if (!foundBeforeNode) {
58 const nodeEnd = locEnd(node);
59 if (nodeEnd <= cursorOffset && nodeEnd > nodeBeforeCursorEndIndex) {
60 nodeBeforeCursor = node;
61 nodeBeforeCursorEndIndex = nodeEnd;
62 }
63 }
64 if (!foundAfterNode) {
65 const nodeStart = locStart(node);
66 if (
67 nodeStart >= cursorOffset &&
68 nodeStart < nodeAfterCursorStartIndex
69 ) {
70 nodeAfterCursor = node;
71 nodeAfterCursorStartIndex = nodeStart;
72 }
73 }
74 }
75 }
76

Callers 2

coreFormatFunction · 0.85
printToDocFunction · 0.85

Calls 5

getDescendantsFunction · 0.90
isLeafFunction · 0.90
getChildrenFunction · 0.90
locEndFunction · 0.50
locStartFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…