voyeg3r

word_position_at_cursor

Sep 4th, 2026
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.89 KB | None | 0 0
  1. --- Detects the word under the cursor and its position within the line.
  2. --- Walks left/right from cursor to find word boundaries, so it correctly
  3. --- handles lines with repeated words (e.g. "foo abc foo").
  4. --- @return table|nil { word: string, start: number, offset: number }
  5. function M.word_position_at_cursor()
  6.   local line = vim.api.nvim_get_current_line()
  7.   local col = vim.fn.col('.') - 1 -- 0-indexed
  8.  
  9.   if not line:sub(col + 1, col + 1):match('[%w_]') then return nil end
  10.  
  11.   local start_col = col
  12.   while start_col > 0 and line:sub(start_col, start_col):match('[%w_]') do
  13.     start_col = start_col - 1
  14.   end
  15.  
  16.   local end_col = col
  17.   while end_col < #line and line:sub(end_col + 1, end_col + 1):match('[%w_]') do
  18.     end_col = end_col + 1
  19.   end
  20.  
  21.   local word = line:sub(start_col + 1, end_col)
  22.  
  23.   return {
  24.     word = word,
  25.     start = start_col,
  26.     offset = col - start_col,
  27.   }
  28. end
Tags: lua neovim nvim
Advertisement
Add Comment
Please, Sign In to add comment