feat: Add basic export support

This commit is contained in:
Myzel394 2023-10-06 21:41:43 +02:00
parent 67a2a9e86b
commit f5a9a3cdcf
3 changed files with 92 additions and 0 deletions

61
lua/easytables/export.lua Normal file
View File

@ -0,0 +1,61 @@
local M = {}
---comment
---@param content string
---@param width number
---@return table
function M:export_cell(content, width)
return "| " .. content .. string.rep(" ", width - #content) .. " "
end
---Exports a line to a string
---@param line table Cells divided into columns
---@param widths table Width of each column
---@return string
function M:export_line(line, widths)
local str = ""
for i, cell in ipairs(line) do
local width = widths[i]
str = str .. self:export_cell(cell, width)
end
return str .. "|"
end
---comment
---@param widths table
---@return string
function M:create_header_line(widths)
local str = ""
-- No idea why, but "ipairs" is required otherwise lua complains
for _, width in ipairs(widths) do
str = str .. "|" .. string.rep("-", width + 2)
end
return str .. "|"
end
---comment
---@return table
function M:export_table(
table
)
local representation = {}
local widths = table:get_widths_for_columns(1)
for i, line in ipairs(table.table) do
representation[#representation + 1] = self:export_line(line, widths)
if i == 1 and table.header_enabled then
representation[#representation + 1] = self:create_header_line(widths)
end
end
return representation
end
return M

View File

@ -1,4 +1,5 @@
local table_builder = require("easytables.tablebuilder")
local export = require("easytables.export")
local math = require("math")
local M = {}
@ -20,6 +21,7 @@ function M:create(table, options)
self.height = options.height or DEFAULT_OPTIONS.height
self.min_value_width = options.min_value_width or DEFAULT_OPTIONS.min_value_width
self.table = table
self.previous_buffer = vim.api.nvim_get_current_buf()
return self
end
@ -142,6 +144,14 @@ function M:draw_table()
self:_draw_highlight()
end
function M:close()
vim.api.nvim_win_close(self.preview_window, true)
vim.api.nvim_win_close(self.prompt_window, true)
self.preview_window = nil
self.prompt_window = nil
end
function M:register_listeners()
vim.api.nvim_buf_attach(self.prompt_buffer, false, {
on_lines = function(_, handle)
@ -303,6 +313,27 @@ function M:register_listeners()
end,
{}
)
vim.api.nvim_buf_create_user_command(
self.prompt_buffer,
"ExportTable",
function()
local markdown_table = export:export_table(self.table)
self:close()
vim.schedule(function()
vim.api.nvim_buf_set_text(
self.previous_buffer,
0,
0,
0,
0,
markdown_table
)
end)
end,
{}
)
end
return M

0
test.txt Normal file
View File