Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 87 lines (72 sloc) 2.539 kb
#!/usr/bin/env ruby
#
# Vertically aligns multiple columns, which are
# delimited by a user-defined regular expression,
# that are present in the input given on STDIN.
#
# For example, the following input:
#
# short text = foo = hello
# really long text = bar = world
# wide operator <=> moz <=> again
#
# yields the following output:
#
# short text = foo
# really long text = bar
# wide operator <=> moz
#
# Written in 2007 by Suraj N. Kurapati <https://github.com/sunaku>
def align_table lines, delimiter, selector, rejector, justifier
delim_regexp = /#{delimiter}/
# determine columns widths
widths = []
rows = lines.map do |line|
if line =~ selector and line !~ rejector and line =~ delim_regexp
delims = line.scan(delim_regexp).map(&:squeeze)
fields = line.split(delim_regexp).map(&:strip)
result = fields.zip(delims).flatten(1)
result.pop if result.last.nil?
# update the widths for the entire table by inspecting this row
result.map(&:size).each_with_index do |new_width, column|
widths[column] = [new_width, (widths[column] || 0)].max
end
result
else
line
end
end
# equalize column widths
rows.map do |row|
if row.respond_to? :zip and not row.empty?
row.zip(widths).map do |column, width|
column.send(justifier, width)
end.join
else
row
end
end
end
if $0 == __FILE__
require 'optparse'
parser = OptionParser.new
parser.on '-h', '--help', 'show this help message' do
puts File.read(__FILE__).split(/^$/).first, nil, parser
exit
end
parser.on '-d', '--delimiter REGEXP', 'input column delimiter',
"(default: #{(delimiter = /[[:punct:]]*=[[:punct:]]*/).inspect})\n",
String do |arg| delimiter = arg end
parser.on '-j', '--justify METHOD', 'justify text inside columns',
'(choices: ljust, rjust, or center)',
"(default: #{justifier = 'center'})",
String do |arg| justifier = arg end
parser.on '-m', '--select REGEXP', 'only wrap lines that match REGEXP',
"(default: #{(selector = //).inspect})",
Regexp do |arg| selector = arg end
parser.on '-M', '--reject REGEXP', 'do not wrap lines that match REGEXP',
"(default: #{(rejector = nil).inspect})",
Regexp do |arg| rejector = arg end
parser.parse ARGV
puts align_table(STDIN.readlines, delimiter, selector, rejector, justifier)
end
Jump to Line
Something went wrong with that request. Please try again.