Debian Codegraph @

lib_pypy/pyrepl/pager.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import io
4 import os
5 import re
6 import sys
7
8
9 # types
10 if False:
11 from typing import Protocol
12 class Pager(Protocol):
13 def __call__(self, text: str, title: str = "") -> None:
14 ...
15
16
17 def get_pager() -> Pager:
18 """Decide what method to use for paging through text."""
19 if not hasattr(sys.stdin, "isatty"):
20 return plain_pager
21 if not hasattr(sys.stdout, "isatty"):
22 return plain_pager
23 if not sys.stdin.isatty() or not sys.stdout.isatty():
24 return plain_pager
25 if sys.platform == "emscripten":
26 return plain_pager
27 use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
28 if use_pager:
29 if sys.platform == 'win32': # pipes completely broken in Windows
30 return lambda text, title='': tempfile_pager(plain(text), use_pager)
31 elif os.environ.get('TERM') in ('dumb', 'emacs'):
32 return lambda text, title='': pipe_pager(plain(text), use_pager, title)
33 else:
34 return lambda text, title='': pipe_pager(text, use_pager, title)
35 if os.environ.get('TERM') in ('dumb', 'emacs'):
36 return plain_pager
37 if sys.platform == 'win32':
38 return lambda text, title='': tempfile_pager(plain(text), 'more <')
39 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
40 return lambda text, title='': pipe_pager(text, 'less', title)
41
42 import tempfile
43 (fd, filename) = tempfile.mkstemp()
44 os.close(fd)
45 try:
46 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
47 return lambda text, title='': pipe_pager(text, 'more', title)
48 else:
49 return tty_pager
50 finally:
51 os.unlink(filename)
52
53
54 def escape_stdout(text: str) -> str:
55 # Escape non-encodable characters to avoid encoding errors later
56 encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8'
57 return text.encode(encoding, 'backslashreplace').decode(encoding)
58
59
60 def escape_less(s: str) -> str:
61 return re.sub(r'([?:.%\\])', r'\\\1', s)
62
63
64 def plain(text: str) -> str:
65 """Remove boldface formatting from text."""
66 return re.sub('.\b', '', text)
67
68
69 def tty_pager(text: str, title: str = '') -> None:
70 """Page through text on a text terminal."""
71 lines = plain(escape_stdout(text)).split('\n')
72 has_tty = False
73 try:
74 import tty
75 import termios
76 fd = sys.stdin.fileno()
77 old = termios.tcgetattr(fd)
78 tty.setcbreak(fd)
79 has_tty = True
80
81 def getchar() -> str:
82 return sys.stdin.read(1)
83
84 except (ImportError, AttributeError, io.UnsupportedOperation):
85 def getchar() -> str:
86 return sys.stdin.readline()[:-1][:1]
87
88 try:
89 try:
90 h = int(os.environ.get('LINES', 0))
91 except ValueError:
92 h = 0
93 if h <= 1:
94 h = 25
95 r = inc = h - 1
96 sys.stdout.write('\n'.join(lines[:inc]) + '\n')
97 while lines[r:]:
98 sys.stdout.write('-- more --')
99 sys.stdout.flush()
100 c = getchar()
101
102 if c in ('q', 'Q'):
103 sys.stdout.write('\r \r')
104 break
105 elif c in ('\r', '\n'):
106 sys.stdout.write('\r \r' + lines[r] + '\n')
107 r = r + 1
108 continue
109 if c in ('b', 'B', '\x1b'):
110 r = r - inc - inc
111 if r < 0: r = 0
112 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
113 r = r + inc
114
115 finally:
116 if has_tty:
117 termios.tcsetattr(fd, termios.TCSAFLUSH, old)
118
119
120 def plain_pager(text: str, title: str = '') -> None:
121 """Simply print unformatted text. This is the ultimate fallback."""
122 sys.stdout.write(plain(escape_stdout(text)))
123
124
125 def pipe_pager(text: str, cmd: str, title: str = '') -> None:
126 """Page through text by feeding it to another program."""
127 import subprocess
128 env = os.environ.copy()
129 if title:
130 title += ' '
131 esc_title = escape_less(title)
132 prompt_string = (
133 f' {esc_title}' +
134 '?ltline %lt?L/%L.'
135 ':byte %bB?s/%s.'
136 '.'
137 '?e (END):?pB %pB\\%..'
138 ' (press h for help or q to quit)')
139 env['LESS'] = '-RmPm{0}$PM{0}$'.format(prompt_string)
140 proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
141 errors='backslashreplace', env=env)
142 assert proc.stdin is not None
143 try:
144 with proc.stdin as pipe:
145 try:
146 pipe.write(text)
147 except KeyboardInterrupt:
148 # We've hereby abandoned whatever text hasn't been written,
149 # but the pager is still in control of the terminal.
150 pass
151 except OSError:
152 pass # Ignore broken pipes caused by quitting the pager program.
153 while True:
154 try:
155 proc.wait()
156 break
157 except KeyboardInterrupt:
158 # Ignore ctl-c like the pager itself does. Otherwise the pager is
159 # left running and the terminal is in raw mode and unusable.
160 pass
161
162
163 def tempfile_pager(text: str, cmd: str, title: str = '') -> None:
164 """Page through text by invoking a program on a temporary file."""
165 import tempfile
166 with tempfile.TemporaryDirectory() as tempdir:
167 filename = os.path.join(tempdir, 'pydoc.out')
168 with open(filename, 'w', errors='backslashreplace',
169 encoding=os.device_encoding(0) if
170 sys.platform == 'win32' else None
171 ) as file:
172 file.write(text)
173 os.system(cmd + ' "' + filename + '"')