2016-11-26 14:10:16 +09:00
|
|
|
#!/usr/bin/env ruby
|
|
|
|
#
|
|
|
|
# usage: ./preview.rb [-v] FILENAME[:LINE][:IGNORED]
|
|
|
|
|
|
|
|
require 'shellwords'
|
|
|
|
|
2017-03-18 02:07:06 +09:00
|
|
|
COMMAND = %[(highlight -O ansi -l {} || coderay {} || rougify {} || cat {}) 2> /dev/null]
|
2016-11-26 14:10:16 +09:00
|
|
|
ANSI = /\x1b\[[0-9;]*m/
|
|
|
|
REVERSE = "\x1b[7m"
|
|
|
|
RESET = "\x1b[m"
|
|
|
|
|
|
|
|
split = ARGV.delete('-v')
|
|
|
|
|
2016-12-08 13:30:06 +09:00
|
|
|
def usage
|
2016-11-26 14:10:16 +09:00
|
|
|
puts "usage: #$0 [-v] FILENAME[:LINENO][:IGNORED]"
|
|
|
|
exit 1
|
|
|
|
end
|
|
|
|
|
2016-12-08 13:30:06 +09:00
|
|
|
usage if ARGV.empty?
|
|
|
|
|
2017-10-22 09:50:12 -04:00
|
|
|
file, center, extra = ARGV.first.split(':')
|
|
|
|
if ARGV.first =~ /^[A-Z]:\\/
|
|
|
|
file << ':' + center
|
|
|
|
center = extra
|
|
|
|
end
|
2016-12-08 13:30:06 +09:00
|
|
|
usage unless file
|
2016-11-26 14:10:16 +09:00
|
|
|
|
2016-12-08 13:30:06 +09:00
|
|
|
path = File.expand_path(file)
|
|
|
|
unless File.readable? path
|
2016-11-26 14:10:16 +09:00
|
|
|
puts "File not found: #{file}"
|
|
|
|
exit 1
|
|
|
|
end
|
|
|
|
|
2017-01-23 10:28:08 +09:00
|
|
|
if `file --mime "#{file}"` =~ /binary/
|
|
|
|
puts "#{file} is a binary file"
|
|
|
|
exit 0
|
|
|
|
end
|
|
|
|
|
2016-11-26 14:10:16 +09:00
|
|
|
center = (center || 0).to_i
|
2017-12-09 23:21:26 +09:00
|
|
|
if ENV['LINES']
|
|
|
|
height = ENV['LINES'].to_i
|
2017-04-30 12:06:41 +09:00
|
|
|
else
|
|
|
|
height = File.readable?('/dev/tty') ? `stty size < /dev/tty`.split.first.to_i : 40
|
|
|
|
height /= 2 if split
|
|
|
|
height -= 2 # preview border
|
|
|
|
end
|
2016-11-26 14:10:16 +09:00
|
|
|
offset = [1, center - height / 3].max
|
|
|
|
|
2016-12-08 13:30:06 +09:00
|
|
|
IO.popen(['sh', '-c', COMMAND.gsub('{}', Shellwords.shellescape(path))]) do |io|
|
2016-11-26 14:10:16 +09:00
|
|
|
io.each_line.drop(offset - 1).take(height).each_with_index do |line, lno|
|
|
|
|
if lno + offset == center
|
|
|
|
puts REVERSE + line.chomp.gsub(ANSI) { |m| m + REVERSE } + RESET
|
|
|
|
else
|
|
|
|
puts line
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|