Skip to content

Instantly share code, notes, and snippets.

@robmiller
Created February 6, 2024 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmiller/8d4f03a6a5beff1370b9201660453b0d to your computer and use it in GitHub Desktop.
Save robmiller/8d4f03a6a5beff1370b9201660453b0d to your computer and use it in GitHub Desktop.
Script for aligning a Markdown table neatly. Put in your PATH as mdtable then use in Vim visual mode: !mdtable
#!/usr/bin/env ruby
table = ARGF.read.chomp
parse_row = ->(row) { row.gsub(/^\||\|$/, "").split("|").map(&:strip) }
rows = table.each_line.map(&parse_row)
# Normalise column count
column_count = rows.map(&:length).max
rows = rows.map { |row| (row + ([""] * column_count)).take(column_count) }
# Find longest value for each column
columns = 1.upto(column_count).map { |n| rows.map { |row| row[n - 1] } }
column_widths = columns.map { |cells| cells.map(&:length).max }
# Expand each cell to the right size for its column
rows = rows.map do |row|
row.zip(column_widths).map do |value, length|
# If it's a header row, expand the dashes all the way across the cell
if value =~ /^[\s\-]{2,}$/
"-" * (length + 2)
# Otherwise, pad the string to the correct length with spaces around
else
" #{value.ljust(length)} "
end
end
end
# Display the table
rows.each do |row|
puts "|#{row.join("|")}|"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment