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