Skip to content

Instantly share code, notes, and snippets.

@eduardoarandah
Created April 26, 2026 20:24
Show Gist options
  • Select an option

  • Save eduardoarandah/b8d8c3f89c2c2d872c2c1c3f49ccdf21 to your computer and use it in GitHub Desktop.

Select an option

Save eduardoarandah/b8d8c3f89c2c2d872c2c1c3f49ccdf21 to your computer and use it in GitHub Desktop.
neovim generate an ascii table around text
-- use:
--
-- require("ascii_box").setup()
local M = {}
--- Genera una tabla ASCII alrededor del texto dado
--- @param lines string[] Lista de líneas de texto
--- @return string[] Líneas con la caja ASCII
function M.make_box(lines)
-- Encontrar el ancho máximo para que todas las líneas encajen
local max_width = 0
for _, line in ipairs(lines) do
-- vim.fn.strdisplaywidth maneja correctamente caracteres unicode/acentos
local w = vim.fn.strdisplaywidth(line)
if w > max_width then
max_width = w
end
end
-- El borde horizontal: +---...---+ (con padding de 1 espacio a cada lado)
local border = "+" .. string.rep("-", max_width + 2) .. "+"
local result = { border }
for _, line in ipairs(lines) do
-- Calcular el padding derecho según el ancho real mostrado
local padding = max_width - vim.fn.strdisplaywidth(line)
table.insert(result, "| " .. line .. string.rep(" ", padding) .. " |")
end
table.insert(result, border)
return result
end
--- Reemplaza la selección visual con el texto enmarcado
function M.box_visual_selection()
-- getpos("'<") y getpos("'>") devuelven las marcas del último rango visual
-- Formato: { bufnum, lnum, col, off }
local start_pos = vim.fn.getpos("'<")
local end_pos = vim.fn.getpos("'>")
local start_line = start_pos[2]
local end_line = end_pos[2]
-- nvim_buf_get_lines usa índices 0-based y exclusive end, por eso restamos 1 al inicio
local lines = vim.api.nvim_buf_get_lines(0, start_line - 1, end_line, false)
local boxed = M.make_box(lines)
-- Reemplazar las líneas originales con la versión enmarcada
vim.api.nvim_buf_set_lines(0, start_line - 1, end_line, false, boxed)
end
-- Registrar comando
M.setup = function()
vim.api.nvim_create_user_command("Box", M.box_visual_selection, { range = true })
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment