dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
4.72k stars 191 forks source link

Get node at (line, col) #891

Open HoldYourWaffle opened 3 years ago

HoldYourWaffle commented 3 years ago

Is your feature request related to a problem? Please describe. I get line & column coordinates from an external source, I want to get the node(s) at this coordinate.

Describe the solution you'd like The obvious solution would be sourceFile.getChildAtPos, but this takes a 1D coordinate. I can convert from "pos" to line+col using sourceFile.getLineAndColumnAtPos (#801) but I can't find anything for the reverse.

Describe alternatives you've considered I bodged together this:

for (const node of source.getDescendants()) {
    if (line === node.getStartLineNumber() && col === node.getStart() - node.getStartLinePos()) {
        // We have our node!
    }
}

But that doesn't seem like an efficient solution.

dsherret commented 3 years ago

I think probably the inverse of getLineAndColumnAtPos would be nice, so sourceFile.getPosAtLineAndColumn({ line, column }) and then that could be used with node.getChildAtPos or node.getDescendantAtPos.

HoldYourWaffle commented 3 years ago

Yeah that would probably be the best solution. I'll see if I can create a PR for this later today 😄

cubenoy22 commented 3 years ago

Hi. I had encountered this problem too and I saw #893. Finally I could solve this with below code:

const source: SourceFile = ...;
const pos = source.compilerNode.getPositionOfLineAndCharacter(line, col);

~So, I think we can close this issue with no changes.~

HoldYourWaffle commented 3 years ago

Interesting, that function must've been added in a more recent version. I'd still argue that a "convenience" function in ts-morph would be nice as well, but that's @dsherret's call.