Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply pretty padding to markdown table
#!/usr/bin/env ruby -wU
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].strip =~ /\A-+\Z/
size = columns[i].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
puts resulting_lines.join("\n")
# columns = content.split("|")
# puts colum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.