Skip to content

Commit

Permalink
Narrow text edits
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Feb 1, 2024
1 parent 2e67c8e commit b22db34
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions ruff_lsp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from pathlib import Path
from typing import Any, List, NamedTuple, Sequence, Union, cast

from lsprotocol import validators
from lsprotocol.types import (
CODE_ACTION_RESOLVE,
INITIALIZE,
Expand Down Expand Up @@ -1376,16 +1375,44 @@ def _fixed_source_to_edits(
fixed_source = "".join(fixed_source)

new_source = _match_line_endings(original_source, fixed_source)

if new_source == original_source:
return []

# Reduce the exit by finding the common suffix and postfix (lines) and omitting them from the text position.
# We could use a more sophisticated to reduce the edit sizes more but it has the downside that they
# require additional dependencies or risk to be very slow.
# This gives us a simple `O(n)` diffing that's sufficient to avoid transmitting the entire source document
# for each range formatting call.
new_lines = new_source.splitlines(True)
original_lines = original_source.splitlines(True)

start_offset = 0
end_offset = 0

for new_line, original_line in zip(new_lines, original_lines):
if new_line == original_line:
start_offset += 1
else:
break

for new_line, original_line in zip(
reversed(new_lines[start_offset:]), reversed(original_lines[start_offset:])
):
if new_line == original_line:
end_offset += 1
else:
break

trimmed_new_source = "".join(new_lines[start_offset : len(new_lines) - end_offset])

return [
TextEdit(
range=Range(
start=Position(line=0, character=0),
end=Position(line=validators.UINTEGER_MAX_VALUE, character=0),
start=Position(line=start_offset, character=0),
end=Position(line=len(original_lines) - end_offset, character=0),
),
new_text=new_source,
new_text=trimmed_new_source,
)
]

Expand Down

0 comments on commit b22db34

Please sign in to comment.