summaryrefslogtreecommitdiff
path: root/script/core/look-backward.lua
blob: 82f2ea1f9effe1b9b09cf20358503593b85ea751 (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
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
78
79
80
81
82
83
84
85
86
87
88
89
---@class lookForward
local m = {}

--- 是否是空白符
---@param inline boolean # 必须在同一行中(排除换行符)
function m.isSpace(char, inline)
    if inline then
        if char == ' '
        or char == '\t' then
            return true
        end
    else
        if char == ' '
        or char == '\n'
        or char == '\r'
        or char == '\t' then
            return true
        end
    end
    return false
end

--- 跳过空白符
---@param inline boolean # 必须在同一行中(排除换行符)
function m.skipSpace(text, offset, inline)
    for i = offset, 1, -1 do
        local char = text:sub(i, i)
        if not m.isSpace(char, inline) then
            return i
        end
    end
    return 0
end

function m.findWord(text, offset)
    for i = offset, 1, -1 do
        if not text:sub(i, i):match '[%w_]' then
            if i == offset then
                return nil
            end
            return text:sub(i + 1, offset), i + 1
        end
    end
    return text:sub(1, offset), 1
end

function m.findSymbol(text, offset)
    for i = offset, 1, -1 do
        local char = text:sub(i, i)
        if m.isSpace(char) then
            goto CONTINUE
        end
        if char == '.'
        or char == ':'
        or char == '('
        or char == ','
        or char == '=' then
            return char, i
        else
            return nil
        end
        ::CONTINUE::
    end
    return nil
end

function m.findTargetSymbol(text, offset, symbol)
    offset = m.skipSpace(text, offset)
    for i = offset, 1, -1 do
        local char = text:sub(i - #symbol + 1, i)
        if char == symbol then
            return i - #symbol + 1
        else
            return nil
        end
    end
    return nil
end

function m.findAnyOffset(text, offset)
    for i = offset, 1, -1 do
        if not m.isSpace(text:sub(i, i)) then
            return i
        end
    end
    return nil
end

return m