Skip to content

Instantly share code, notes, and snippets.

@jeremyf
Created August 28, 2014 02:24
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 jeremyf/a6793fe01f28af72631f to your computer and use it in GitHub Desktop.
Save jeremyf/a6793fe01f28af72631f to your computer and use it in GitHub Desktop.
Make a markdown table pretty by creating uniform column spacing
#!/usr/bin/env ruby -wU
# Takes your paste buffer and outputs a markdown table with pretty spacing
content = `pbpaste`.strip
def columnize(line)
line.sub(/\A\s*\|?(.*)\|?\Z/, '\1').split("|")
end
lines = content.split("\n")
column_count = columnize(lines.first).size
widths = (0...column_count).collect {|a| 0 }
lines.each do |line|
columns = columnize(line)
(0...column_count).each do |i|
next if columns[i].to_s.strip =~ /\A-+\Z/
size = columns[i].to_s.strip.size
widths[i] = size if size > widths[i]
end
end
resulting_lines = lines.collect do |line|
columns = columnize(line)
row = []
(0...column_count).each do |i|
if columns[i].to_s.strip =~ /\A-+\Z/
row << ('-' * (widths[i] + 2))
else
row << sprintf(" % -#{widths[i]}s ", columns[i].to_s.strip)
end
end
"|" + row.join("|") + "|"
end
STDOUT.puts resulting_lines.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment