summaryrefslogtreecommitdiff
path: root/script/core/command/removeSpace.lua
blob: ba1ee8ebe6bde7ab45fe18541ba495ad38e0dba5 (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
local files    = require 'files'
local searcher = require 'core.searcher'
local proto    = require 'proto'
local lang     = require 'language'

local function isInString(ast, offset)
    return searcher.eachSourceContain(ast.ast, offset, function (source)
        if source.type == 'string' then
            return true
        end
    end) or false
end

return function (data)
    local uri   = data.uri
    local lines = files.getLines(uri)
    local text  = files.getText(uri)
    local ast   = files.getAst(uri)
    if not lines then
        return
    end

    local textEdit = {}
    for i = 1, #lines do
        local line = searcher.lineContent(lines, text, i, true)
        local pos  = line:find '[ \t]+$'
        if pos then
            local start, finish = searcher.lineRange(lines, i, true)
            start = start + pos - 1
            if isInString(ast, start) then
                goto NEXT_LINE
            end
            textEdit[#textEdit+1] = {
                range = files.range(uri, start, finish),
                newText = '',
            }
            goto NEXT_LINE
        end

        ::NEXT_LINE::
    end

    if #textEdit == 0 then
        return
    end

    proto.awaitRequest('workspace/applyEdit', {
        label = lang.script.COMMAND_REMOVE_SPACE,
        edit = {
            changes = {
                [uri] = textEdit,
            }
        },
    })
end