aboutsummaryrefslogtreecommitdiff
path: root/plugins/gofmt.lua
blob: 2f0aeced96cff88ce8a633a74731886a7a8b8907 (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
-- mod-version:3 --lite-xl 2.1
local core = require "core"
local command = require "core.command"
local keymap = require "core.keymap"

local function exec(cmd)
  local fp = io.popen(cmd, "r")
  local res = fp:read("*a")
  local success = fp:close()
  return res:gsub("%\n$", ""), success
end

local function get_cmd_text(cmd, doc)
  local active_filename = doc and system.absolute_path(doc.filename or "")
  return exec(string.format("%s %s", cmd, active_filename))
end

local function update_doc(cmd, doc)
  local text, success = get_cmd_text(cmd, doc)
  if success == nil then
    local err_text = "Command '%s' not found in the system"
    core.error(string.format(err_text, cmd))
    return
  end

  local sel = { doc:get_selection() }
  doc:remove(1, 1, math.huge, math.huge)
  doc:insert(1, 1, text)
  doc:set_selection(table.unpack(sel))
end

command.add("core.docview", {
  ["gofmt:gofmt"] = function()
    update_doc("gofmt", core.active_view.doc)
  end,

  ["gofmt:goimports"] = function()
    update_doc("goimports", core.active_view.doc)
  end,

  ["gofmt:goreturns"] = function()
    update_doc("goreturns", core.active_view.doc)
  end,
})

keymap.add {
  ["ctrl+i"] = "gofmt:gofmt",
  ["ctrl+h"] = "gofmt:goimports",
  ["ctrl+u"] = "gofmt:goreturns",
}