all repos

gopher.nvim @ d1a21bffabd7e74b241bfea1016cf78befb3b122

Minimalistic plugin for Go development

gopher.nvim/lua/gopher/comment.lua(view raw)

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
---@toc_entry Generate comments
---@tag gopher.nvim-comments
---@usage Execute `:GoCmt` to generate a comment for the current function/method/struct/etc on this line.
---@text This module provides a way to generate comments for Go code.

local log = require "gopher._utils.log"

local function generate(row, col)
  local ts_utils = require "gopher._utils.ts"
  local comment, ns = nil, nil

  ns = ts_utils.get_package_node_at_pos(row, col, nil, false)
  if ns ~= nil then
    comment = "// Package " .. ns.name .. " provides " .. ns.name
    return comment, ns
  end

  ns = ts_utils.get_struct_node_at_pos(row, col, nil, false)
  if ns ~= nil then
    comment = "// " .. ns.name .. " " .. ns.type .. " "
    return comment, ns
  end

  ns = ts_utils.get_func_method_node_at_pos(row, col, nil, false)
  if ns ~= nil then
    comment = "// " .. ns.name .. " " .. ns.type .. " "
    return comment, ns
  end

  ns = ts_utils.get_interface_node_at_pos(row, col, nil, false)
  if ns ~= nil then
    comment = "// " .. ns.name .. " " .. ns.type .. " "
    return comment, ns
  end

  return "// ", {}
end

return function()
  local row, col = unpack(vim.api.nvim_win_get_cursor(0))
  local comment, ns = generate(row + 1, col + 1)

  log.debug("generated comment: " .. comment)

  vim.api.nvim_win_set_cursor(0, {
    ns.dim.s.r,
    ns.dim.s.c,
  })

  ---@diagnostic disable-next-line: param-type-mismatch
  vim.fn.append(row - 1, comment)

  vim.api.nvim_win_set_cursor(0, {
    ns.dim.s.r,
    #comment + 1,
  })

  vim.cmd [[startinsert!]]
end