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) {|output, pid| ... } ⇒ String?

The pager method manages terminal output paging functionality

This method 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.

Parameters:

  • command (String) (defaults to: nil)

    the pager command to use when paging is needed

  • lines (Integer) (defaults to: nil)

    the number of lines to compare against terminal height

Yields:

  • (output, pid)

    when a block is provided, yields the output stream and child’s process ID

Yield Parameters:

  • output (IO)

    the IO stream to write output to

  • pid (Integer)

    the process ID of the pager subprocess

Returns:

  • (String, nil)

    the pager command string if paging was used, nil otherwise



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

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, output.pid
      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.



65
66
67
68
# File 'lib/kramdown/ansi/pager.rb', line 65

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