Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get node at (line, col) #891

Open
HoldYourWaffle opened this issue Dec 3, 2020 · 4 comments · May be fixed by #893
Open

Get node at (line, col) #891

HoldYourWaffle opened this issue Dec 3, 2020 · 4 comments · May be fixed by #893

Comments

@HoldYourWaffle
Copy link
Contributor

HoldYourWaffle commented Dec 3, 2020

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
Copy link
Owner

dsherret commented Dec 4, 2020

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
Copy link
Contributor Author

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

HoldYourWaffle added a commit to HoldYourWaffle2/ts-morph that referenced this issue Dec 5, 2020
@HoldYourWaffle HoldYourWaffle linked a pull request Dec 5, 2020 that will close this issue
@cubenoy22
Copy link

cubenoy22 commented May 25, 2021

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
Copy link
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants