Getting the start of line where cursor is?

For now, I solved the original issue of this post with the following script:

function searchBackwards(pattern)
  local pos = editor.getCursor  ()
  
  -- get only the text before the cursor
  local pageText = editor.getText():sub(1, pos) 
  
  -- set some defaults to initialize the search
  -- if they are still both 0 by the end, we know no newline was found.
  local matchStart, matchEnd = 0, 0
  
  local searchPos = pos
  while matchStart < 1 and searchPos > 0 do
    -- move the virtual cursor one space to the front
    searchPos = searchPos - 1
  
     -- starting from the new position, check if we can find a newline
    matchStart, matchEnd = pageText:find(pattern, searchPos)
  end

  return matchStart, matchEnd
end

local closestPreviousNewline = searchBackwards("\n")

This iteratively checks for a newline between the start of the page and the current cursor position by slowly moving a virtual cursor to the left and checking if it can find a newline from there.

1 Like