go.nvim/lua/go/reftool.lua

85 lines
2.1 KiB
Lua
Raw Normal View History

2021-04-23 06:31:00 +00:00
local reftool = {}
2022-04-24 10:30:41 +00:00
local utils = require("go.utils")
local log = utils.log
2022-06-01 11:29:13 +00:00
local vfn = vim.fn
2021-04-23 06:31:00 +00:00
local function insert_result(result)
2022-06-01 11:29:13 +00:00
local curpos = vfn.getcurpos()
2022-04-24 10:30:41 +00:00
local goto_l = string.format("goto %d", result["start"] + 1)
vim.cmd(goto_l)
local inserts = result.code
2022-04-24 10:30:41 +00:00
inserts = vim.split(inserts, "\n")
local change = string.format("normal! %ds%s", result["end"] - result.start, inserts[1])
vim.cmd(change)
2022-04-24 10:30:41 +00:00
vim.cmd("startinsert!")
log(change)
local curline = curpos[2]
for i = 2, #inserts do
log("append ", curline, inserts[i])
2022-06-01 11:29:13 +00:00
vfn.append(curline, inserts[i])
curline = curline + 1
2021-04-23 06:31:00 +00:00
end
2022-04-24 10:30:41 +00:00
vim.cmd("stopinsert!")
vim.cmd("write")
-- format(#inserts, curpos)
2022-06-01 11:29:13 +00:00
vfn.setpos(".", curpos)
require('go.format').gofmt()
2021-04-23 06:31:00 +00:00
end
-- can only be fillstruct and fillswitch
local function fill(cmd)
2022-04-24 10:30:41 +00:00
if cmd ~= "fillstruct" and cmd ~= "fillswitch" then
log(cmd, "not found")
2022-04-24 10:30:41 +00:00
error("cmd not supported by go.nvim", cmd)
end
require("go.install").install(cmd)
2021-04-23 06:31:00 +00:00
2021-09-30 12:23:36 +00:00
log(cmd)
2022-06-01 11:29:13 +00:00
local file = vfn.expand("%:p")
local line = vfn.line(".")
-- local run = string.format("%s -file=%s -line=%d 2>/dev/null", cmd, file, line)
2022-04-24 10:30:41 +00:00
local farg = string.format("-file=%s", file)
local larg = string.format("-line=%d", line)
local args = { cmd, farg, larg, "2>/dev/null" }
log(args)
2022-06-01 11:29:13 +00:00
vfn.jobstart(args, {
on_stdout = function(_, str, _)
log(str)
if #str < 2 then
2022-04-24 10:30:41 +00:00
log("reftools", cmd, "finished with no result")
return
end
2022-06-01 11:29:13 +00:00
local json = vfn.json_decode(str)
if #json == 0 then
vim.notify("reftools " .. cmd .. " finished with no result", vim.log.levels.DEBUG)
2021-04-23 06:31:00 +00:00
end
local result = json[1]
insert_result(result)
2022-04-24 10:30:41 +00:00
end,
})
end
local function gopls_fillstruct(timeout_ms)
2022-04-24 10:30:41 +00:00
log("fill struct with gopls")
local codeaction = require("go.lsp").codeaction
codeaction("fill_struct", "refactor.rewrite", timeout_ms)
end
function reftool.fillstruct()
2022-04-24 10:30:41 +00:00
if _GO_NVIM_CFG.fillstruct == "gopls" then
gopls_fillstruct(1000)
else
2022-04-24 10:30:41 +00:00
log("fillstruct")
fill("fillstruct")
2021-04-23 06:31:00 +00:00
end
end
2021-09-30 12:23:36 +00:00
reftool.fillswitch = function()
2022-04-24 10:30:41 +00:00
fill("fillswitch")
2021-09-30 12:23:36 +00:00
end
2021-04-23 06:31:00 +00:00
return reftool