Skip to content

Commit f4f813b

Browse files
committed
Fix that cursor position is not correctly computed when /r/n is the line ending
1 parent 84d5d65 commit f4f813b

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

Tool/Sources/XcodeInspector/SourceEditor.swift

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class SourceEditor {
1818
let lineAnnotations = lineAnnotationElements.map(\.description)
1919

2020
if let selectionRange = element.selectedTextRange {
21-
let range = Self.convertRangeToCursorRange(selectionRange, in: content)
21+
let range = Self.convertRangeToCursorRange(selectionRange, in: split)
2222
return .init(
2323
content: content,
2424
lines: split,
@@ -104,15 +104,21 @@ public extension SourceEditor {
104104
var countE = 0
105105
var cursorRange = CursorRange(start: .zero, end: .outOfScope)
106106
for (i, line) in lines.enumerated() {
107-
if countS <= range.lowerBound, range.lowerBound < countS + line.count {
107+
// The range is counted in UTF8, which causes line endings like \r\n to be of length 2.
108+
let lineEndingAddition = (line.lineEnding?.utf8.count ?? 1) - 1
109+
if countS <= range.lowerBound,
110+
range.lowerBound < countS + line.count + lineEndingAddition
111+
{
108112
cursorRange.start = .init(line: i, character: range.lowerBound - countS)
109113
}
110-
if countE <= range.upperBound, range.upperBound < countE + line.count {
114+
if countE <= range.upperBound,
115+
range.upperBound < countE + line.count + lineEndingAddition
116+
{
111117
cursorRange.end = .init(line: i, character: range.upperBound - countE)
112118
break
113119
}
114-
countS += line.count
115-
countE += line.count
120+
countS += line.count + lineEndingAddition
121+
countE += line.count + lineEndingAddition
116122
}
117123
if cursorRange.end == .outOfScope {
118124
cursorRange.end = .init(line: lines.endIndex - 1, character: lines.last?.count ?? 0)

0 commit comments

Comments
 (0)