Module: Kramdown::ANSI::Pager

Defined in:
lib/kramdown/ansi/pager.rb

Overview

A module that provides paging functionality for terminal output.

The Pager module handles the logic for determining when to use a pager command like ‘less’ or ‘more’ when the output exceeds the terminal’s line capacity. It also manages the execution of these pagers and ensures proper terminal state restoration when paging is used.

Examples:

Using the pager with a block

Kramdown::ANSI::Pager.pager(command: 'less', lines: 50) do |output|
  output.puts "Content to display"
end

Checking if a pager is needed

pager_command = Kramdown::ANSI::Pager.pager(command: 'more', lines: 100)

Class Method Summary collapse

Class Method Details

.pager(command: nil, lines: nil) {|IO| ... } ⇒ NilClass

If called without a block returns either the provided command for paging if the given number of lines are exceeding the available number of terminal lines or nil. If a block was provided it yields to an IO handle for the pager command in the latter case or STDOUT in the former.

Parameters:

  • command (String) (defaults to: nil)

    the pager command (optional)

  • lines (Integer) (defaults to: nil)

    the number of lines in the output (optional)

Yields:

  • (IO)

    yields the output IO handle for further processing

Returns:

  • (NilClass)

    returns nil if STDOUT is used or STDOUT is not a TTY.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kramdown/ansi/pager.rb', line 30

def pager(command: nil, lines: nil, &block)
  if block
    if my_pager = pager(command:, lines:)
      IO.popen(my_pager, 'w') do |output|
        output.sync = true
        yield output
      rescue Interrupt, Errno::EPIPE
        pager_reset_screen
        return nil
      ensure
        output.close
      end
      my_pager
    else
      yield STDOUT
      nil
    end
  else
    return unless STDOUT.tty?
    if lines
      if lines >= Tins::Terminal.lines
        pager(command:)
      end
    else
      command
    end
  end
end

.pager_reset_screenObject

Resets the terminal screen by printing ANSI escape codes for reset, clear screen, move home and show cursor.



61
62
63
64
# File 'lib/kramdown/ansi/pager.rb', line 61

def pager_reset_screen
  c = Term::ANSIColor
  STDOUT.print c.reset, c.clear_screen, c.move_home, c.show_cursor
end