class IRB::Pager

def page

def page
  if STDIN.tty? && pager = setup_pager
    begin
      pid = pager.pid
      yield pager
    ensure
      pager.close
    end
  else
    yield $stdout
  end
# When user presses Ctrl-C, IRB would raise `IRB::Abort`
# But since Pager is implemented by running paging commands like `less` in another process with `IO.popen`,
# the `IRB::Abort` exception only interrupts IRB's execution but doesn't affect the pager
# So to properly terminate the pager with Ctrl-C, we need to catch `IRB::Abort` and kill the pager process
rescue IRB::Abort
  Process.kill("TERM", pid) if pid
  nil
rescue Errno::EPIPE
end