Created
August 28, 2014 02:24
-
-
Save jeremyf/a6793fe01f28af72631f to your computer and use it in GitHub Desktop.
Make a markdown table pretty by creating uniform column spacing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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