summaryrefslogtreecommitdiff
path: root/script/method/textDocument/foldingRange.lua
blob: 6395c90897738bd2a96aa9184eaa297b1848f427 (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
local core = require 'core'

local timerCache = {}

local function convertRange(lines, range)
    local start_row,  start_col  = lines:rowcol(range.start)
    local finish_row, finish_col = lines:rowcol(range.finish)
    local result = {
        startLine      = start_row - 1,
        endLine        = finish_row - 2,
        kind           = range.kind,
    }
    if result.startLine >= result.endLine then
        return nil
    end
    return result
end

--- @param lsp LSP
--- @param params table
--- @return function
return function (lsp, params)
    local uri = params.textDocument.uri
    if timerCache[uri] then
        timerCache[uri]:remove()
        timerCache[uri] = nil
    end

    return function (response)
        local clock = os.clock()
        timerCache[uri] = ac.loop(0.1, function (t)
            local vm, lines = lsp:getVM(uri)
            if not vm then
                if os.clock() - clock > 10 then
                    t:remove()
                    timerCache[uri] = nil
                    response(nil)
                end
                return
            end

            t:remove()
            timerCache[uri] = nil

            local comments = lsp:getComments(uri)
            local ranges = core.foldingRange(vm, comments)
            if not ranges then
                response(nil)
                return
            end

            local results = {}
            for _, range in ipairs(ranges) do
                results[#results+1] = convertRange(lines, range)
            end

            response(results)
        end)
    end
end