|
| 1 | +local macro = require("gp.macro") |
| 2 | +local gp = require("gp") |
| 3 | + |
| 4 | +local M = {} |
| 5 | + |
| 6 | +---@type gp.Macro |
| 7 | +M = { |
| 8 | + name = "context_file`", |
| 9 | + description = "replaces the macro with the content of the specified file", |
| 10 | + default = nil, |
| 11 | + max_occurrences = 100, |
| 12 | + |
| 13 | + triggered = function(params) |
| 14 | + local cropped_line = params.cropped_line |
| 15 | + return cropped_line:match("@context_file`[^`]*$") |
| 16 | + end, |
| 17 | + |
| 18 | + completion = function(params) |
| 19 | + local root_dir = params.state.context_dir or vim.fn.getcwd() |
| 20 | + local files = vim.fn.globpath(root_dir, "**", false, true) |
| 21 | + local root_dir_length = #root_dir + 2 |
| 22 | + files = vim.tbl_map(function(file) |
| 23 | + return file:sub(root_dir_length) .. " `" |
| 24 | + end, files) |
| 25 | + return files |
| 26 | + end, |
| 27 | + |
| 28 | + parser = function(result) |
| 29 | + local template = result.template |
| 30 | + local macro_pattern = "@context_file`([^`]*)`" |
| 31 | + |
| 32 | + for _ = 1, M.max_occurrences do |
| 33 | + local s, e, value = template:find(macro_pattern) |
| 34 | + if not value then |
| 35 | + break |
| 36 | + end |
| 37 | + |
| 38 | + value = value:match("^%s*(.-)%s*$") |
| 39 | + local placeholder = macro.generate_placeholder(M.name, value) |
| 40 | + |
| 41 | + local full_path = value |
| 42 | + if vim.fn.fnamemodify(full_path, ":p") ~= value then |
| 43 | + full_path = vim.fn.fnamemodify(result.state.context_dir .. "/" .. value, ":p") |
| 44 | + end |
| 45 | + |
| 46 | + if vim.fn.filereadable(full_path) == 0 then |
| 47 | + result.artifacts[placeholder] = "" |
| 48 | + gp.logger.error("Context file not found: " .. full_path) |
| 49 | + else |
| 50 | + local content = table.concat(vim.fn.readfile(full_path), "\n") |
| 51 | + content = gp.render.template(gp.config.template_context_file, { |
| 52 | + ["{{content}}"] = content, |
| 53 | + ["{{filename}}"] = full_path, |
| 54 | + }) |
| 55 | + result.artifacts[placeholder] = content |
| 56 | + end |
| 57 | + |
| 58 | + template = template:sub(1, s - 1) .. placeholder .. template:sub(e + 1) |
| 59 | + end |
| 60 | + |
| 61 | + result.template = template |
| 62 | + return result |
| 63 | + end, |
| 64 | +} |
| 65 | + |
| 66 | +return M |
0 commit comments