Skip to content

Commit

Permalink
lua: add file:match_at method to match LPeg pattern around a position
Browse files Browse the repository at this point in the history
  • Loading branch information
martanne committed Feb 22, 2017
1 parent 065f819 commit 0cbd1b8
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lua/vis.lua
Original file line number Diff line number Diff line change
Expand Up @@ -190,4 +190,35 @@ end

vis.events = events

---
-- @type File

--- Check whether LPeg pattern matches at a given file position.
-- @function match_at
-- @param pattern the LPeg pattern
-- @tparam int the absolute position in bytes to test for a match
-- @tparam[opt] int horizon the number of bytes around `pos` to consider (defaults to 1K)
-- @treturn int start,end the range of the matched region or `nil`
vis.types['vis.file'].match_at = function(file, pattern, pos, horizon)
horizon = horizon or 1024
local lpeg = vis.lpeg
if not lpeg then return nil end
local before, after = pos - horizon, pos + horizon
if before < 0 then before = 0 end
local data = file:content(before, after - before)
local string_pos = pos - before + 1

local I = lpeg.Cp()
local p = lpeg.P{ I * pattern * I + 1 * lpeg.V(1) }
local s, e = 1
while true do
s, e = p:match(data, s)
if not s then return nil end
if s <= string_pos and string_pos < e then
return before + s - 1, before + e - 1
end
s = e
end
end

require('vis-std')

0 comments on commit 0cbd1b8

Please sign in to comment.