- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathpager.py
175 lines (150 loc) · 5.68 KB
/
pager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from __future__ importannotations
importio
importos
importre
importsys
# types
ifFalse:
fromtypingimportProtocol
classPager(Protocol):
def__call__(self, text: str, title: str="") ->None:
...
defget_pager() ->Pager:
"""Decide what method to use for paging through text."""
ifnothasattr(sys.stdin, "isatty"):
returnplain_pager
ifnothasattr(sys.stdout, "isatty"):
returnplain_pager
ifnotsys.stdin.isatty() ornotsys.stdout.isatty():
returnplain_pager
ifsys.platform=="emscripten":
returnplain_pager
use_pager=os.environ.get('MANPAGER') oros.environ.get('PAGER')
ifuse_pager:
ifsys.platform=='win32': # pipes completely broken in Windows
returnlambdatext, title='': tempfile_pager(plain(text), use_pager)
elifos.environ.get('TERM') in ('dumb', 'emacs'):
returnlambdatext, title='': pipe_pager(plain(text), use_pager, title)
else:
returnlambdatext, title='': pipe_pager(text, use_pager, title)
ifos.environ.get('TERM') in ('dumb', 'emacs'):
returnplain_pager
ifsys.platform=='win32':
returnlambdatext, title='': tempfile_pager(plain(text), 'more <')
ifhasattr(os, 'system') andos.system('(pager) 2>/dev/null') ==0:
returnlambdatext, title='': pipe_pager(text, 'pager', title)
ifhasattr(os, 'system') andos.system('(less) 2>/dev/null') ==0:
returnlambdatext, title='': pipe_pager(text, 'less', title)
importtempfile
(fd, filename) =tempfile.mkstemp()
os.close(fd)
try:
ifhasattr(os, 'system') andos.system('more "%s"'%filename) ==0:
returnlambdatext, title='': pipe_pager(text, 'more', title)
else:
returntty_pager
finally:
os.unlink(filename)
defescape_stdout(text: str) ->str:
# Escape non-encodable characters to avoid encoding errors later
encoding=getattr(sys.stdout, 'encoding', None) or'utf-8'
returntext.encode(encoding, 'backslashreplace').decode(encoding)
defescape_less(s: str) ->str:
returnre.sub(r'([?:.%\\])', r'\\\1', s)
defplain(text: str) ->str:
"""Remove boldface formatting from text."""
returnre.sub('.\b', '', text)
deftty_pager(text: str, title: str='') ->None:
"""Page through text on a text terminal."""
lines=plain(escape_stdout(text)).split('\n')
has_tty=False
try:
importtty
importtermios
fd=sys.stdin.fileno()
old=termios.tcgetattr(fd)
tty.setcbreak(fd)
has_tty=True
defgetchar() ->str:
returnsys.stdin.read(1)
except (ImportError, AttributeError, io.UnsupportedOperation):
defgetchar() ->str:
returnsys.stdin.readline()[:-1][:1]
try:
try:
h=int(os.environ.get('LINES', 0))
exceptValueError:
h=0
ifh<=1:
h=25
r=inc=h-1
sys.stdout.write('\n'.join(lines[:inc]) +'\n')
whilelines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c=getchar()
ifcin ('q', 'Q'):
sys.stdout.write('\r\r')
break
elifcin ('\r', '\n'):
sys.stdout.write('\r\r'+lines[r] +'\n')
r=r+1
continue
ifcin ('b', 'B', '\x1b'):
r=r-inc-inc
ifr<0: r=0
sys.stdout.write('\n'+'\n'.join(lines[r:r+inc]) +'\n')
r=r+inc
finally:
ifhas_tty:
termios.tcsetattr(fd, termios.TCSAFLUSH, old)
defplain_pager(text: str, title: str='') ->None:
"""Simply print unformatted text. This is the ultimate fallback."""
sys.stdout.write(plain(escape_stdout(text)))
defpipe_pager(text: str, cmd: str, title: str='') ->None:
"""Page through text by feeding it to another program."""
importsubprocess
env=os.environ.copy()
iftitle:
title+=' '
esc_title=escape_less(title)
prompt_string= (
f' {esc_title}'+
'?ltline %lt?L/%L.'
':byte %bB?s/%s.'
'.'
'?e (END):?pB %pB\\%..'
' (press h for help or q to quit)')
env['LESS'] ='-RmPm{0}$PM{0}$'.format(prompt_string)
proc=subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
errors='backslashreplace', env=env)
assertproc.stdinisnotNone
try:
withproc.stdinaspipe:
try:
pipe.write(text)
exceptKeyboardInterrupt:
# We've hereby abandoned whatever text hasn't been written,
# but the pager is still in control of the terminal.
pass
exceptOSError:
pass# Ignore broken pipes caused by quitting the pager program.
whileTrue:
try:
proc.wait()
break
exceptKeyboardInterrupt:
# Ignore ctl-c like the pager itself does. Otherwise the pager is
# left running and the terminal is in raw mode and unusable.
pass
deftempfile_pager(text: str, cmd: str, title: str='') ->None:
"""Page through text by invoking a program on a temporary file."""
importtempfile
withtempfile.TemporaryDirectory() astempdir:
filename=os.path.join(tempdir, 'pydoc.out')
withopen(filename, 'w', errors='backslashreplace',
encoding=os.device_encoding(0) if
sys.platform=='win32'elseNone
) asfile:
file.write(text)
os.system(cmd+' "'+filename+'"')