aboutsummaryrefslogtreecommitdiff
path: root/data/core/doc/search.lua
blob: fe57523e3686b6118bc6b551df965c973c49a2fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
local search = {}

local default_opt = {}


local function pattern_lower(str)
  if str:sub(1, 1) == "%" then
    return str
  end
  return str:lower()
end


local function init_args(doc, line, col, text, opt)
  opt = opt or default_opt
  line, col = doc:sanitize_position(line, col)

  if opt.no_case then
    if opt.pattern then
      text = text:gsub("%%?.", pattern_lower)
    else
      text = text:lower()
    end
  end

  return doc, line, col, text, opt
end


function search.find(doc, line, col, text, opt)
  doc, line, col, text, opt = init_args(doc, line, col, text, opt)

  for line = line, #doc.lines do
    local line_text = doc.lines[line]
    if opt.no_case then
      line_text = line_text:lower()
    end
    local s, e = line_text:find(text, col, not opt.pattern)
    if s then
      return line, s, line, e + 1
    end
    col = 1
  end

  if opt.wrap then
    opt = { no_case = opt.no_case, pattern = opt.pattern }
    return search.find(doc, 1, 1, text, opt)
  end
end


return search