Skip to content

Commit 2ff384a

Browse files
gselzerclaude
andcommitted
code-lsp: clamp positions to a line's content, without overflow
Positions.offset clamped a character past a line's end to its \n, so on a line ending in \r\n, it pointed between the \r and the \n. And it added the character to the line's start before clamping, so a huge one (as some clients send, for the end of the line) overflowed to a negative offset. Now a line ends before its line break, \r\n included, and the character is clamped before it is added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c72e2f8 commit 2ff384a

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

‎scijava-code-lsp/src/main/java/org/scijava/code/lsp/Positions.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,11 @@ public static int offset(final String text, final Position position) {
6767
}
6868
int end = text.indexOf('\n', start);
6969
if (end < 0) end = text.length();
70-
return Math.min(start + position.getCharacter(), end);
70+
// NB: The line ends before its line break, a \r\n included.
71+
else if (end > start && text.charAt(end - 1) == '\r') end--;
72+
// NB: Clamped before adding the line's start, lest a huge character (as
73+
// some clients send, for the end of the line) overflow.
74+
return start + Math.min(position.getCharacter(), end - start);
7175
}
7276

7377
/**

‎scijava-code-lsp/src/test/java/org/scijava/code/lsp/PositionsTest.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,26 @@ public void testCrlf() {
6868
assertEquals(new Position(1, 1), Positions.position(text, 5));
6969
}
7070

71+
/**
72+
* Tests that a position past the end of a line ending in \r\n is clamped
73+
* to before the \r: the end of the line's content, not within its line
74+
* break.
75+
*/
76+
@Test
77+
public void testCrlfClamped() {
78+
assertEquals(2, Positions.offset("ab\r\ncd", new Position(0, 99)));
79+
}
80+
81+
/**
82+
* Tests that a huge character (as some clients send, for the end of the
83+
* line) is clamped to the line, rather than overflowing.
84+
*/
85+
@Test
86+
public void testHugeCharacter() {
87+
assertEquals(5, Positions.offset("ab\ncd", new Position(1,
88+
Integer.MAX_VALUE)));
89+
}
90+
7191
@Test
7292
public void testCallStart() {
7393
// The call around the caret: its opening parenthesis.

0 commit comments

Comments
 (0)