Skip to content

Instantly share code, notes, and snippets.

@MrSimbax
Created April 5, 2025 21:37
Show Gist options
  • Select an option

  • Save MrSimbax/2d61e953eb94916a7dbc33dd32edaa36 to your computer and use it in GitHub Desktop.

Select an option

Save MrSimbax/2d61e953eb94916a7dbc33dd32edaa36 to your computer and use it in GitHub Desktop.
Align Markdown table
#!/bin/python
import sys
import re
table: list[list[str]] = []
for line in sys.stdin.readlines():
line = line.strip()
if len(line) == 0:
continue
assert(line[0] == '|')
row: list[str] = []
i = 1
while i < len(line):
j = line.find('|', i)
assert(j != -1)
row.append(line[i:j].strip())
i = j + 1
table.append(row)
cols_count = len(table[0])
col_sizes = []
for col_idx in range(cols_count):
col_size = 0
for row in table:
assert(len(row) == cols_count)
col_size = max(col_size, len(row[col_idx]))
col_sizes.append(col_size)
out = sys.stdout
for row in table:
out.write("| ")
for col_idx, col in enumerate(row):
col_size = col_sizes[col_idx]
align = col_size - len(col)
fill_char = ' '
left_align = ''
right_align = ''
separator = re.match(r"^\:?\-+(\:?)$", col)
if separator:
fill_char = '-'
if separator.group(1) == ':':
right_align = ':'
col = col[:-1]
out.write(col + fill_char * align + right_align + " |")
if col_idx < len(row) - 1:
out.write(' ')
out.write('\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment