-
Notifications
You must be signed in to change notification settings - Fork 2
/
regex_find.lua
77 lines (63 loc) · 2.12 KB
/
regex_find.lua
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
-- Copyright (C) 2014 Chris Emerson <[email protected]>
-- See LICENSE for details (MIT license).
local M = {}
local ta_regex = require 'ta-regex.pegex'
-- Replace textadept's events.FIND handler with one implementing better regex.
function M.install()
events.connect(events.FIND, M.find, 1)
end
-- Find expression forwards from the current point.
function M.find(regex, forward)
local pat = ta_regex.compile(regex)
-- Search a subset of the buffer, and adjust the match to set the
-- start/end pointers correctly.
local function search(startpos, endpos)
local m = pat:match(buffer:text_range(startpos, endpos))
if m then
-- Adjust result to take account of startpos
m._start = m._start + startpos - 1
m._end = m._end + startpos
end
return m
end
-- As search(), but search backwards.
-- This isn't as efficient, as it searches forward and waits for the
-- last match.
local function search_rev(startpos, endpos)
local res = nil
while true do
local m = search(startpos, endpos)
if m then
-- a later match than we'd previously had
res = m
-- Start searching from this point (non-overlapping)
startpos = m._end
else
-- no other matches - return the last we got.
break
end
end
return res
end
local m = nil
if forward then
local startpos = buffer.current_pos + 1
local endpos = buffer.length
-- If we're at the end of the buffer, then start from
-- the beginning.
if startpos >= endpos then startpos = 0 end
m = search(startpos, endpos) or search(0, endpos)
else
local startpos = 0
local endpos = buffer.current_pos
m = search_rev(startpos, endpos) or search_rev(0, buffer.length)
end
if m then
local s, e = m._start, m._end
buffer:set_sel(e, s)
else
ui.statusbar_text = "Not found"
end
return false
end
return M