Created
May 15, 2012 18:06
-
-
Save hawx/2703807 to your computer and use it in GitHub Desktop.
Script to reformat ascii tabs to a given maximum width
This file contains hidden or 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 | |
# | |
# Usage: tab-format <max-width> <input-file> | |
# eg. tab-format 120 tango.txt > out.txt | |
# | |
# Reformats ascii tabs to different widths. Will complain if tab contains any | |
# other text. So <file> will look like (obviously with numbers in): | |
# | |
# E |---------- ... | |
# B |---------- ... | |
# G |---------- ... | |
# D |---------- ... | |
# A |---------- ... | |
# E |---------- ... | |
# | |
# |------------ ... | |
# |------------ ... | |
# |------------ ... | |
# |------------ ... | |
# |------------ ... | |
# |------------ ... | |
# | |
# And output will be in the same format but with the correct line widths. | |
# | |
class Bar | |
attr_reader :strings | |
def initialize(strings) | |
@strings = strings | |
end | |
def size | |
@strings.first.size + 1 | |
end | |
def <<(other) | |
0.upto(5) {|i| @strings[i] += '|' + other.strings[i] } | |
self | |
end | |
def to_s | |
@strings.map {|i| i + "|" }.join("\n") | |
end | |
end | |
class Score | |
def initialize(width, bars) | |
@width = width | |
@bars = bars | |
end | |
def build | |
final = [] | |
temp = @bars[0] | |
@bars[1..-1].each do |bar| | |
if temp.size + bar.size > @width | |
final << temp | |
temp = bar | |
else | |
temp << bar | |
end | |
end | |
final << temp | |
end | |
def to_s | |
build.map(&:to_s).join("\n\n") | |
end | |
end | |
width = ARGV[0].to_i | |
text = File.read(ARGV[1]) | |
lines = text.split /\n\s*\n/ | |
bars = lines.map {|line| line.split("\n").map {|i| i.split("|") }.transpose }. | |
flatten(1).map {|i| Bar.new(i) } | |
score = Score.new(width, bars) | |
puts score.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment