0

I want to find a line number and a column for a particular byte number in a buffer in Neovim. I can get it (sort of) with

local b = 444
local line = vim.fn.byte2line(b)
local line_start = vim.fn.line2byte(line)
local col = b - line_start + 1

But the result will not be correct for multibyte charactes.

How to calculate line and column correctly for a given byte in a buffer?

2

You can use the charidx() function to convert the byte index to the character index. For example:

    chidx = vim.fn.charidx(vim.fn.getline(line), col)
2

Use :goto to go to a specific byte. Then can use line() & col()

:goto 444
:echo [line('.'), col('.')]

For more help see:

:h :goto
:h line()
:h col()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.