025d62e23e3a96f5e92b1c5b050344071ca5a3ea
[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 # see http://nex-3.com/posts/73-git-style-automatic-paging-in-ruby
26 def run_pager(paginate='auto'):
27     """
28     paginate should be one of 'never', 'auto', or 'always'.
29
30     usage: just call this function and continue using sys.stdout like
31     you normally would.
32     """
33     if paginate == 'never' \
34             or sys.platform == 'win32' \
35             or not hasattr(sys.stdout, 'isatty') \
36             or sys.stdout.isatty() == False:
37         return
38
39     if paginate == 'auto':
40         if 'LESS' not in os.environ:
41             os.environ['LESS'] = '' # += doesn't work on undefined var
42         # don't page if the input is short enough
43         os.environ['LESS'] += ' -FRX'
44     if 'PAGER' in os.environ:
45         pager = os.environ['PAGER']
46     else:
47         pager = 'less'
48
49     read_fd, write_fd = os.pipe()
50     if os.fork() == 0:
51         # child process
52         os.close(read_fd)
53         os.dup2(write_fd, 1)
54         os.close(write_fd)
55         if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty() == True:
56             os.dup2(1, 2)
57         return
58
59     # parent process, become pager
60     os.close(write_fd)
61     os.dup2(read_fd, 0)
62     os.close(read_fd)
63
64     # Wait until we have input before we start the pager
65     select.select([0], [], [])
66     os.execlp(pager, pager)