text.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. local M = {}
  2. local function max_len_line(lines)
  3. local max_len = 0
  4. for _, line in ipairs(lines) do
  5. local line_len = line:len()
  6. if line_len > max_len then
  7. max_len = line_len
  8. end
  9. end
  10. return max_len
  11. end
  12. --- Center align lines relatively to the parent container
  13. -- @param container The container where lines will be displayed
  14. -- @param lines The text to align
  15. -- @param alignment The alignment value, range: [0-1]
  16. function M.align(container, lines, alignment)
  17. local max_len = max_len_line(lines)
  18. local indent_amount = math.ceil(math.max(container.width - max_len, 0) * alignment)
  19. return M.shift_left(lines, indent_amount)
  20. end
  21. --- Shift lines by a given amount
  22. -- @params lines The lines the shift
  23. -- @param amount The amount of spaces to add
  24. function M.shift_left(lines, amount)
  25. local output = {}
  26. local padding = string.rep(" ", amount)
  27. for _, line in ipairs(lines) do
  28. table.insert(output, padding .. line)
  29. end
  30. return output
  31. end
  32. --- Pretty format tables
  33. -- @param entries The table to format
  34. -- @param col_count The number of column to span the table on
  35. -- @param col_sep The separator between each colummn, default: " "
  36. function M.format_table(entries, col_count, col_sep)
  37. col_sep = col_sep or " "
  38. local col_rows = math.ceil(vim.tbl_count(entries) / col_count)
  39. local cols = {}
  40. local count = 0
  41. for i, entry in ipairs(entries) do
  42. if ((i - 1) % col_rows) == 0 then
  43. table.insert(cols, {})
  44. count = count + 1
  45. end
  46. table.insert(cols[count], entry)
  47. end
  48. local col_max_len = {}
  49. for _, col in ipairs(cols) do
  50. table.insert(col_max_len, max_len_line(col))
  51. end
  52. local output = {}
  53. for i, col in ipairs(cols) do
  54. for j, entry in ipairs(col) do
  55. if not output[j] then
  56. output[j] = entry
  57. else
  58. local padding = string.rep(" ", col_max_len[i - 1] - cols[i - 1][j]:len())
  59. output[j] = output[j] .. padding .. col_sep .. entry
  60. end
  61. end
  62. end
  63. return output
  64. end
  65. return M