text.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. --- Left 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_left(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_right(lines, indent_amount)
  20. end
  21. --- Center align lines relatively to the parent container
  22. -- @param container The container where lines will be displayed
  23. -- @param lines The text to align
  24. -- @param alignment The alignment value, range: [0-1]
  25. function M.align_center(container, lines, alignment)
  26. local output = {}
  27. local max_len = max_len_line(lines)
  28. for _, line in ipairs(lines) do
  29. local padding = string.rep(" ", (math.max(container.width, max_len) - line:len()) * alignment)
  30. table.insert(output, padding .. line)
  31. end
  32. return output
  33. end
  34. --- Shift lines by a given amount
  35. -- @params lines The lines the shift
  36. -- @param amount The amount of spaces to add
  37. function M.shift_right(lines, amount)
  38. local output = {}
  39. local padding = string.rep(" ", amount)
  40. for _, line in ipairs(lines) do
  41. table.insert(output, padding .. line)
  42. end
  43. return output
  44. end
  45. --- Pretty format tables
  46. -- @param entries The table to format
  47. -- @param col_count The number of column to span the table on
  48. -- @param col_sep The separator between each column, default: " "
  49. function M.format_table(entries, col_count, col_sep)
  50. col_sep = col_sep or " "
  51. local col_rows = math.ceil(vim.tbl_count(entries) / col_count)
  52. local cols = {}
  53. local count = 0
  54. for i, entry in ipairs(entries) do
  55. if ((i - 1) % col_rows) == 0 then
  56. table.insert(cols, {})
  57. count = count + 1
  58. end
  59. table.insert(cols[count], entry)
  60. end
  61. local col_max_len = {}
  62. for _, col in ipairs(cols) do
  63. table.insert(col_max_len, max_len_line(col))
  64. end
  65. local output = {}
  66. for i, col in ipairs(cols) do
  67. for j, entry in ipairs(col) do
  68. if not output[j] then
  69. output[j] = entry
  70. else
  71. local padding = string.rep(" ", col_max_len[i - 1] - cols[i - 1][j]:len())
  72. output[j] = output[j] .. padding .. col_sep .. entry
  73. end
  74. end
  75. end
  76. return output
  77. end
  78. return M