39 lines
1.2 KiB
Swift
39 lines
1.2 KiB
Swift
// EditorPositionMapping.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdUI/LiveCompile
|
|
//
|
|
// Maps an `NSTextView` UTF-16 insertion offset to a zero-based (line, character)
|
|
// position. LSP positions are UTF-16-based, matching `NSTextView`'s own offsets,
|
|
// so no re-encoding is needed — only newline counting.
|
|
|
|
#if os(macOS)
|
|
|
|
/// Convert a UTF-16 offset into `text` to a zero-based `(line, character)`
|
|
/// where `character` is a UTF-16 code-unit column — the coordinate space
|
|
/// `sourcekit-lsp` expects. An offset past the end clamps to the final position.
|
|
func editorLineAndUTF16Char(in text: String, utf16Offset: Int) -> (line: Int, character: Int) {
|
|
let units: String.UTF16View = text.utf16
|
|
var idx: String.UTF16View.Index = units.startIndex
|
|
var consumed: Int = 0
|
|
var line: Int = 0
|
|
var character: Int = 0
|
|
let newline: UInt16 = 10
|
|
while consumed < utf16Offset, idx < units.endIndex {
|
|
if units[idx] == newline {
|
|
line += 1
|
|
character = 0
|
|
} else {
|
|
character += 1
|
|
}
|
|
idx = units.index(after: idx)
|
|
consumed += 1
|
|
}
|
|
return (line, character)
|
|
}
|
|
|
|
#endif
|