ui:util:pager: document Nathan Weizenbaum as author of Ruby inspiration
[be.git] / libbe / ui / util / pager.py
1 # Copyright (C) 2009-2012 Chris Ball <cjb@laptop.org>
2 #                         W. Trevor King <wking@tremily.us>
3 #
4 # This file is part of Bugs Everywhere.
5 #
6 # Bugs Everywhere is free software: you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation, either version 2 of the License, or (at your option) any
9 # later version.
10 #
11 # Bugs Everywhere is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14 # more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
18
19 """
20 Automatic pager for terminal output (a la Git).
21 """
22
23 import sys, os, select
24
25 # Inspired by Nathan Weizenbaum's
26 #   http://nex-3.com/posts/73-git-style-automatic-paging-in-ruby
27 def run_pager(paginate='auto'):
28     """
29     paginate should be one of 'never', 'auto', or 'always'.
30
31     usage: just call this function and continue using sys.stdout like
32     you normally would.
33     """
34     if paginate == 'never' \
35             or sys.platform == 'win32' \
36             or not hasattr(sys.stdout, 'isatty') \
37             or sys.stdout.isatty() == False:
38         return
39
40     if paginate == 'auto':
41         if 'LESS' not in os.environ:
42             os.environ['LESS'] = '' # += doesn't work on undefined var
43         # don't page if the input is short enough
44         os.environ['LESS'] += ' -FRX'
45     if 'PAGER' in os.environ:
46         pager = os.environ['PAGER']
47     else:
48         pager = 'less'
49
50     read_fd, write_fd = os.pipe()
51     if os.fork() == 0:
52         # child process
53         os.close(read_fd)
54         os.dup2(write_fd, 1)
55         os.close(write_fd)
56         if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty() == True:
57             os.dup2(1, 2)
58         return
59
60     # parent process, become pager
61     os.close(write_fd)
62     os.dup2(read_fd, 0)
63     os.close(read_fd)
64
65     # Wait until we have input before we start the pager
66     select.select([0], [], [])
67     os.execlp(pager, pager)