Run update_copyright.py.
[be.git] / libbe / ui / util / pager.py
1 # Copyright (C) 2009-2011 Chris Ball <cjb@laptop.org>
2 #                         W. Trevor King <wking@drexel.edu>
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
8 # Free Software Foundation, either version 2 of the License, or (at your
9 # option) any 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
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with 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.close(0)
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)