Skip to content

Commit ee9214b

Browse files
committed
xy_to_offset, offset_to_xy tweaks and tests
Note that the "one past the last byte" tests need JuliaLang/JuliaSyntax.jl#552 to pass
1 parent 074d6df commit ee9214b

File tree

3 files changed

+44
-4
lines changed

3 files changed

+44
-4
lines changed

src/utils.jl

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ get_fileinfo(s::ServerState, t::TextDocumentIdentifier) = get_fileinfo(s, URI(t.
5151
"""
5252
Convert 0-based `(;line = y, character = x)` to a 1-based byte offset
5353
"""
54-
function xy_to_offset(fi::FileInfo, pos::Position)
55-
code = fi.parsed_stream.textbuf
54+
function xy_to_offset(code::Vector{UInt8}, pos::Position)
5655
b = 0
5756
for z in 1:pos.line
5857
b = findnext(isequal(UInt8('\n')), code, b + 1)
@@ -66,12 +65,16 @@ function xy_to_offset(fi::FileInfo, pos::Position)
6665
end
6766
return b + line_b
6867
end
68+
xy_to_offset(fi::FileInfo, pos::Position) = xy_to_offset(fi.parsed_stream.textbuf, pos)
6969

7070
"""
7171
Convert a 1-based byte offset to a 0-based line and character number
7272
"""
73-
function offset_to_xy(fi::FileInfo, b::Integer)
74-
sf = JuliaSyntax.SourceFile(fi.parsed_stream)
73+
function offset_to_xy(ps::Union{AbstractString, JuliaSyntax.ParseStream}, b::Integer)
74+
sf = JuliaSyntax.SourceFile(ps)
75+
@assert b in JS.first_byte(ps):JS.last_byte(ps) + 1
7576
l, c = JuliaSyntax.source_location(sf, b)
7677
return Position(;line = l-1, character = c-1)
7778
end
79+
offset_to_xy(code::Vector{UInt8}, b::Integer) = offset_to_xy(String(copy(code)), b)
80+
offset_to_xy(fi::FileInfo, b::Integer) = offset_to_xy(fi.parsed_stream, b)

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ using Test
22

33
@testset "JETLS" begin
44
@testset "basic" include("basic.jl")
5+
@testset "utils" include("utils.jl")
56
end

test/utils.jl

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using Test
2+
using JETLS
3+
4+
fake_files = [
5+
"",
6+
"1",
7+
"\n\n\n",
8+
"""
9+
aaa
10+
b
11+
ccc
12+
Αα,Ββ,Γγ,Δδ,Εε,Ζζ,Ηη,Θθ,Ιι,Κκ,Λλ,Μμ,Νν,Ξξ,Οο,Ππ,Ρρ,Σσς,Ττ,Υυ,Φφ,Χχ,Ψψ,Ωω
13+
""",
14+
]
15+
16+
function test_string_positions(s)
17+
v = Vector{UInt8}(s)
18+
for b in eachindex(s)
19+
pos = JETLS.offset_to_xy(v, b)
20+
b2 = JETLS.xy_to_offset(v, pos)
21+
@test b === b2
22+
end
23+
# One past the last byte is a valid position in an editor
24+
b = length(v) + 1
25+
pos = JETLS.offset_to_xy(v, b)
26+
b2 = JETLS.xy_to_offset(v, pos)
27+
@test b === b2
28+
end
29+
30+
@testset "Cursor file position <-> byte" begin
31+
for i in eachindex(fake_files)
32+
@testset "fake_files[$i]" begin
33+
test_string_positions(fake_files[i])
34+
end
35+
end
36+
end

0 commit comments

Comments
 (0)