Skip to content

Instantly share code, notes, and snippets.

@jeremyf
Created August 27, 2014 23:22
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/50bd89f38b649da56214 to your computer and use it in GitHub Desktop.
Save jeremyf/50bd89f38b649da56214 to your computer and use it in GitHub Desktop.
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