Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --- Detects the word under the cursor and its position within the line.
- --- Walks left/right from cursor to find word boundaries, so it correctly
- --- handles lines with repeated words (e.g. "foo abc foo").
- --- @return table|nil { word: string, start: number, offset: number }
- function M.word_position_at_cursor()
- local line = vim.api.nvim_get_current_line()
- local col = vim.fn.col('.') - 1 -- 0-indexed
- if not line:sub(col + 1, col + 1):match('[%w_]') then return nil end
- local start_col = col
- while start_col > 0 and line:sub(start_col, start_col):match('[%w_]') do
- start_col = start_col - 1
- end
- local end_col = col
- while end_col < #line and line:sub(end_col + 1, end_col + 1):match('[%w_]') do
- end_col = end_col + 1
- end
- local word = line:sub(start_col + 1, end_col)
- return {
- word = word,
- start = start_col,
- offset = col - start_col,
- }
- end
Advertisement
Add Comment
Please, Sign In to add comment