Sha256: a9e69afb8171cbe45f5b553e37526cea3964b8ff9eeb371460ced00805820d33

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

require 'rib'

module Rib; module Paging
  extend Plugin
  Shell.use(self)

  # --------------- Rib API ---------------

  # Print if the it fits one screen, paging it through a pager otherwise.
  def puts str=''
    return super if Paging.disabled?
    if one_screen?(str)
      super
    else
      page_result(str)
    end
  end

  # `less -F` can't cat the output, so we need to detect by ourselves.
  # `less -X` would mess up the buffers, so it's not desired, either.
  def one_screen? str
    cols, lines = `tput cols`.to_i, `tput lines`.to_i
    (str.count("\n") + 2) <= lines && # count last line and prompt
      str.gsub(/\e\[[^m]*m/, '').size <= cols * lines
  end

  def page_result str
    less = IO.popen(pager, 'w')
    less.write(str)
    less.close_write
  rescue Errno::EPIPE
    # less quit without consuming all the input
  end

  def pager
    ENV['PAGER'] || 'less -R'
  end
end; end

pager = ENV['PAGER'] || 'less'

if `which #{pager}`.empty?
  Rib.warn("#{pager} is not available, disabling Rib::Paging")
  Rib::Paging.disable
elsif `which tput`.empty?
  Rib.warn("tput is not available, disabling Rib::Paging")
  Rib::Paging.disable
elsif ENV['TERM'] == 'dumb' || ENV['TERM'].nil?
  Rib.warn("Your terminal is dumb, disabling Rib::Paging")
  Rib::Paging.disable
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rib-1.6.1 lib/rib/extra/paging.rb
rib-1.6.0 lib/rib/extra/paging.rb
rib-1.5.4 lib/rib/extra/paging.rb
rib-1.5.3 lib/rib/extra/paging.rb
rib-1.5.2 lib/rib/extra/paging.rb