functions.lua (2677B)
1 local vim = vim 2 3 local X = {} 4 5 ---@param on_attach fun(client, buffer) 6 function X.on_attach(on_attach) 7 vim.api.nvim_create_autocmd("LspAttach", { 8 callback = function(args) 9 local buffer = args.buf 10 local client = vim.lsp.get_client_by_id(args.data.client_id) 11 on_attach(client, buffer) 12 end, 13 }) 14 end 15 16 function X.starts_with(str, start) 17 return str:sub(1, #start) == start 18 end 19 20 function X.is_table(to_check) 21 return type(to_check) == "table" 22 end 23 24 function X.has_key(t, key) 25 for t_key, _ in pairs(t) do 26 if t_key == key then 27 return true 28 end 29 end 30 return false 31 end 32 33 function X.has_value(t, val) 34 for _, value in ipairs(t) do 35 if value == val then 36 return true 37 end 38 end 39 return false 40 end 41 42 function X.tprint(table) 43 print(vim.inspect(table)) 44 end 45 46 function X.tprint_keys(table) 47 for k in pairs(table) do 48 print(k) 49 end 50 end 51 52 X.reload = function() 53 local presentReload, reload = pcall(require, "plenary.reload") 54 if presentReload then 55 local counter = 0 56 57 for moduleName in pairs(package.loaded) do 58 if X.starts_with(moduleName, "lt.") then 59 reload.reload_module(moduleName) 60 counter = counter + 1 61 end 62 end 63 -- clear nvim-mapper keys 64 vim.g.mapper_records = nil 65 vim.notify("Reloaded " .. counter .. " modules!") 66 end 67 end 68 69 function X.is_macunix() 70 return vim.fn.has("macunix") 71 end 72 73 function X.link_highlight(from, to, override) 74 local hl_exists, _ = pcall(vim.api.nvim_get_hl_by_name, from, false) 75 if override or not hl_exists then 76 -- vim.cmd(("highlight link %s %s"):format(from, to)) 77 vim.api.nvim_set_hl(0, from, { link = to }) 78 end 79 end 80 81 X.highlight = function(group, opts) 82 vim.api.nvim_set_hl(0, group, opts) 83 end 84 85 X.highlight_bg = function(group, col) 86 vim.api.nvim_set_hl(0, group, { bg = col }) 87 end 88 89 -- Define fg color 90 -- @param group Group 91 -- @param color Color 92 X.highlight_fg = function(group, col) 93 vim.api.nvim_set_hl(0, group, { fg = col }) 94 end 95 96 -- Define bg and fg color 97 -- @param group Group 98 -- @param fgcol Fg Color 99 -- @param bgcol Bg Color 100 X.highlight_fg_bg = function(group, fgcol, bgcol) 101 vim.api.nvim_set_hl(0, group, { bg = bgcol, fg = fgcol }) 102 end 103 104 X.from_highlight = function(hl) 105 local result = {} 106 local list = vim.api.nvim_get_hl_by_name(hl, true) 107 for k, v in pairs(list) do 108 local name = k == "background" and "bg" or "fg" 109 result[name] = string.format("#%06x", v) 110 end 111 return result 112 end 113 114 X.get_color_from_terminal = function(num, default) 115 local key = "terminal_color_" .. num 116 return vim.g[key] and vim.g[key] or default 117 end 118 119 X.cmd = function(name, command, desc) 120 vim.api.nvim_create_user_command(name, command, desc) 121 end 122 123 X.autocmd = function(evt, opts) 124 vim.api.nvim_create_autocmd(evt, opts) 125 end 126 return X