|
2 | 2 | # Copyright 2021- Python Language Server Contributors.
|
3 | 3 | import logging
|
4 | 4 | import os
|
| 5 | +from typing import Any |
5 | 6 |
|
6 |
| -from rope.contrib.findit import find_implementations |
| 7 | +from rope.base.project import Project |
| 8 | +from rope.base.resources import Resource |
| 9 | +from rope.contrib.findit import Location, find_implementations |
7 | 10 |
|
8 | 11 | from pylsp import hookimpl, uris
|
9 | 12 |
|
@@ -31,13 +34,37 @@ def pylsp_implementations(config, workspace, document, position):
|
31 | 34 | document.uri,
|
32 | 35 | path=os.path.join(workspace.root_path, impl.resource.path),
|
33 | 36 | ),
|
34 |
| - "range": { |
35 |
| - # TODO: `impl.region` seems to be from the start of the file |
36 |
| - # and offsets from the start of the line difficult to obtain, |
37 |
| - # so we just return the whole line for now: |
38 |
| - "start": {"line": impl.lineno - 1, "character": 0}, |
39 |
| - "end": {"line": impl.lineno - 1, "character": 999}, |
40 |
| - }, |
| 37 | + "range": _rope_location_to_range(impl, rope_project), |
41 | 38 | }
|
42 | 39 | for impl in impls
|
43 | 40 | ]
|
| 41 | + |
| 42 | + |
| 43 | +def _rope_location_to_range( |
| 44 | + location: Location, rope_project: Project |
| 45 | +) -> dict[str, Any]: |
| 46 | + # NOTE: This assumes the result is confined to a single line, which should |
| 47 | + # always be the case here because Python doesn't allow splitting up |
| 48 | + # identifiers across more than one line. |
| 49 | + start_column, end_column = _rope_region_to_columns( |
| 50 | + location.region, location.lineno, location.resource, rope_project |
| 51 | + ) |
| 52 | + return { |
| 53 | + "start": {"line": location.lineno - 1, "character": start_column}, |
| 54 | + "end": {"line": location.lineno - 1, "character": end_column}, |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | +def _rope_region_to_columns( |
| 59 | + offsets: tuple[int, int], line: int, rope_resource: Resource, rope_project: Project |
| 60 | +) -> tuple[int, int]: |
| 61 | + """ |
| 62 | + Convert pair of offsets from start of file to columns within line. |
| 63 | +
|
| 64 | + Assumes both offsets reside within the same line and will return nonsense |
| 65 | + for the end offset if this isn't the case. |
| 66 | + """ |
| 67 | + line_start_offset = rope_project.get_pymodule(rope_resource).lines.get_line_start( |
| 68 | + line |
| 69 | + ) |
| 70 | + return offsets[0] - line_start_offset, offsets[1] - line_start_offset |
0 commit comments