anyas-utilittys/maam.rb

68 lines
1.5 KiB
Ruby
Executable file

#!/usr/bin/env ruby
def dorun(args)
if args.length == 0
args = ['-']
end
files = []
args.each do |arg|
if arg == '--help'
dohelp;exit
elsif arg == '—help'
dohelp;exit
elsif arg == '-h'
dohelp;exit
end
files << arg
end
files.each do |filename|
if filename == '-'
puts convert(STDIN.read)
next
end
File.open(filename, 'r') do |f|
puts convert(f.read)
end
end
end
def dohelp
puts "Maam - Merry Anya's ANSI woMan page printer"
puts "Pass files to maam and get output of the files"
puts " using ansi escapes rather than itty escapes."
end
def convert(file)
file = file.gsub( /\x11\[s(?<style>[0-9a-fA-F]{4})\]/ ) do
out = "\x1b["
hexes = $~[:style].chars.map { |char| char.hex }
if hexes[0] == 7
# nothing; this is itty's default foreground
elsif hexes[0] < 8
out += ";3#{hexes[0]}"
else
out += ";9#{hexes[0]-8}"
end
if hexes[1] == 0
# nothing; this is itty's default background
elsif hexes[1] < 8
out += ";4#{hexes[1]}"
else
out += ";10#{hexes[1]-8}"
end
out += (hexes[2] & 1 != 0) ? ";1" : "" # bold
out += (hexes[2] & 2 != 0) ? ";3" : "" # italic
out += (hexes[2] & 4 != 0) ? ";4" : "" # underline
out += (hexes[2] & 8 != 0) ? "" : "" # show/hide cursor (ignored)
out += 'm' # end of escape
next out #<< implicit return
end
file = file.gsub("\x11", "") # remove invalid escapes
file += "\x1b[m" # reset at the end
file
end
dorun ARGV