| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
"""A compatibility wrapper reimplementing the 'readline' standard module |
| 25 |
on top of pyrepl. Not all functionalities are supported. Contains |
| 26 |
extensions for multiline input. |
| 27 |
""" |
| 28 |
|
| 29 |
from __future__ import annotations |
| 30 |
|
| 31 |
import warnings |
| 32 |
from dataclasses import dataclass, field |
| 33 |
|
| 34 |
import os |
| 35 |
from site import gethistoryfile |
| 36 |
import sys |
| 37 |
|
| 38 |
from . import commands, historical_reader |
| 39 |
from .completing_reader import CompletingReader |
| 40 |
from .console import Console as ConsoleType |
| 41 |
|
| 42 |
Console: type[ConsoleType] |
| 43 |
_error: tuple[type[Exception], ...] | type[Exception] |
| 44 |
try: |
| 45 |
from .unix_console import UnixConsole as Console, _error |
| 46 |
except ImportError: |
| 47 |
from .windows_console import WindowsConsole as Console, _error |
| 48 |
|
| 49 |
ENCODING = sys.getdefaultencoding() or "latin1" |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
Command = commands.Command |
| 54 |
from collections.abc import Callable, Collection |
| 55 |
from .types import Callback, Completer, KeySpec, CommandName |
| 56 |
|
| 57 |
TYPE_CHECKING = False |
| 58 |
|
| 59 |
if TYPE_CHECKING: |
| 60 |
from typing import Any, Mapping |
| 61 |
|
| 62 |
|
| 63 |
MoreLinesCallable = Callable[[str], bool] |
| 64 |
|
| 65 |
|
| 66 |
__all__ = [ |
| 67 |
"add_history", |
| 68 |
"clear_history", |
| 69 |
"get_begidx", |
| 70 |
"get_completer", |
| 71 |
"get_completer_delims", |
| 72 |
"get_current_history_length", |
| 73 |
"get_endidx", |
| 74 |
"get_history_item", |
| 75 |
"get_history_length", |
| 76 |
"get_line_buffer", |
| 77 |
"insert_text", |
| 78 |
"parse_and_bind", |
| 79 |
"read_history_file", |
| 80 |
|
| 81 |
"redisplay", |
| 82 |
"remove_history_item", |
| 83 |
"replace_history_item", |
| 84 |
"set_auto_history", |
| 85 |
"set_completer", |
| 86 |
"set_completer_delims", |
| 87 |
"set_completion_display_matches_hook", |
| 88 |
"set_history_length", |
| 89 |
"set_pre_input_hook", |
| 90 |
"set_startup_hook", |
| 91 |
"write_history_file", |
| 92 |
|
| 93 |
"multiline_input", |
| 94 |
] |
| 95 |
|
| 96 |
|
| 97 |
_RL_CMD_TO_PYREPL: dict[str, str] = { |
| 98 |
'backward-char': 'left', |
| 99 |
'forward-char': 'right', |
| 100 |
'backward-word': 'backward-word', |
| 101 |
'forward-word': 'forward-word', |
| 102 |
'beginning-of-line': 'beginning-of-line', |
| 103 |
'end-of-line': 'end-of-line', |
| 104 |
'kill-line': 'kill-line', |
| 105 |
'backward-kill-word': 'backward-kill-word', |
| 106 |
'kill-word': 'kill-word', |
| 107 |
'unix-line-discard': 'unix-line-discard', |
| 108 |
'unix-word-rubout': 'unix-word-rubout', |
| 109 |
'yank': 'yank', |
| 110 |
'complete': 'complete', |
| 111 |
'accept-line': 'accept', |
| 112 |
'clear-screen': 'clear-screen', |
| 113 |
'transpose-chars': 'transpose-characters', |
| 114 |
} |
| 115 |
|
| 116 |
|
| 117 |
def _rl_keyspec_to_pyrepl(keyspec: str) -> str: |
| 118 |
"""Convert a GNU readline key name (from parse_and_bind) to pyrepl keyspec.""" |
| 119 |
if keyspec.startswith('"') and keyspec.endswith('"'): |
| 120 |
|
| 121 |
return keyspec[1:-1] |
| 122 |
lower = keyspec.lower() |
| 123 |
if lower.startswith('control-'): |
| 124 |
return r'\C-' + keyspec[8:] |
| 125 |
if lower.startswith('meta-'): |
| 126 |
return r'\M-' + keyspec[5:] |
| 127 |
_named = { |
| 128 |
'tab': r'\t', 'return': r'\r', 'escape': r'\033', |
| 129 |
'space': ' ', 'del': r'\x7f', 'delete': r'\x7f', 'rubout': r'\x7f', |
| 130 |
} |
| 131 |
if lower in _named: |
| 132 |
return _named[lower] |
| 133 |
if len(keyspec) == 1: |
| 134 |
return keyspec |
| 135 |
raise ValueError("unrecognized readline key spec: %r" % keyspec) |
| 136 |
|
| 137 |
|
| 138 |
def _decode_readline_macro(text: str) -> str: |
| 139 |
"""Decode backslash escapes inside a readline macro string value.""" |
| 140 |
result = [] |
| 141 |
i = 0 |
| 142 |
while i < len(text): |
| 143 |
if text[i] != '\\' or i + 1 >= len(text): |
| 144 |
result.append(text[i]) |
| 145 |
i += 1 |
| 146 |
continue |
| 147 |
c = text[i + 1] |
| 148 |
if c in ('x', 'X'): |
| 149 |
result.append(chr(int(text[i + 2:i + 4], 16))) |
| 150 |
i += 4 |
| 151 |
elif c.isdigit(): |
| 152 |
result.append(chr(int(text[i + 1:i + 4], 8))) |
| 153 |
i += 4 |
| 154 |
elif c in _MACRO_ESCAPES: |
| 155 |
result.append(_MACRO_ESCAPES[c]) |
| 156 |
i += 2 |
| 157 |
else: |
| 158 |
result.append('\\') |
| 159 |
result.append(c) |
| 160 |
i += 2 |
| 161 |
return ''.join(result) |
| 162 |
|
| 163 |
_MACRO_ESCAPES = { |
| 164 |
'n': '\n', 'r': '\r', 't': '\t', 'a': '\a', |
| 165 |
'b': '\b', 'f': '\f', 'v': '\v', 'e': '\033', |
| 166 |
'\\': '\\', '"': '"', "'": "'", |
| 167 |
} |
| 168 |
|
| 169 |
|
| 170 |
def _make_macro_command(text: str) -> type: |
| 171 |
"""Return a new Command subclass that inserts 'text' when invoked.""" |
| 172 |
class macro_insert(commands.Command): |
| 173 |
_text = text |
| 174 |
def do(self) -> None: |
| 175 |
self.reader.insert(self._text) |
| 176 |
return macro_insert |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
@dataclass |
| 182 |
class ReadlineConfig: |
| 183 |
readline_completer: Completer | None = None |
| 184 |
completer_delims: frozenset[str] = frozenset(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?") |
| 185 |
completion_display_matches_hook: Callable | None = None |
| 186 |
|
| 187 |
|
| 188 |
@dataclass(kw_only=True) |
| 189 |
class ReadlineAlikeReader(historical_reader.HistoricalReader, CompletingReader): |
| 190 |
|
| 191 |
assume_immutable_completions = False |
| 192 |
use_brackets = False |
| 193 |
sort_in_column = True |
| 194 |
|
| 195 |
|
| 196 |
config: ReadlineConfig |
| 197 |
more_lines: MoreLinesCallable | None = None |
| 198 |
last_used_indentation: str | None = None |
| 199 |
|
| 200 |
def __post_init__(self) -> None: |
| 201 |
super().__post_init__() |
| 202 |
self.commands["maybe_accept"] = maybe_accept |
| 203 |
self.commands["maybe-accept"] = maybe_accept |
| 204 |
self.commands["backspace_dedent"] = backspace_dedent |
| 205 |
self.commands["backspace-dedent"] = backspace_dedent |
| 206 |
|
| 207 |
def error(self, msg: str = "none") -> None: |
| 208 |
pass |
| 209 |
|
| 210 |
def get_completion_display_matches_hook(self) -> Callable | None: |
| 211 |
return self.config.completion_display_matches_hook |
| 212 |
|
| 213 |
def get_stem(self) -> str: |
| 214 |
b = self.buffer |
| 215 |
p = self.pos - 1 |
| 216 |
completer_delims = self.config.completer_delims |
| 217 |
while p >= 0 and b[p] not in completer_delims: |
| 218 |
p -= 1 |
| 219 |
return "".join(b[p + 1 : self.pos]) |
| 220 |
|
| 221 |
def get_completions(self, stem: str) -> list[str]: |
| 222 |
if len(stem) == 0 and self.more_lines is not None: |
| 223 |
b = self.buffer |
| 224 |
p = self.pos |
| 225 |
while p > 0 and b[p - 1] != "\n": |
| 226 |
p -= 1 |
| 227 |
num_spaces = 4 - ((self.pos - p) % 4) |
| 228 |
return [" " * num_spaces] |
| 229 |
result = [] |
| 230 |
function = self.config.readline_completer |
| 231 |
if function is not None: |
| 232 |
try: |
| 233 |
stem = str(stem) |
| 234 |
except UnicodeEncodeError: |
| 235 |
pass |
| 236 |
state = 0 |
| 237 |
self.console.restore_output() |
| 238 |
try: |
| 239 |
while True: |
| 240 |
try: |
| 241 |
next = function(stem, state) |
| 242 |
except Exception: |
| 243 |
break |
| 244 |
if not isinstance(next, str): |
| 245 |
break |
| 246 |
result.append(next) |
| 247 |
state += 1 |
| 248 |
finally: |
| 249 |
self.console.prepare_output() |
| 250 |
|
| 251 |
|
| 252 |
result.sort() |
| 253 |
return result |
| 254 |
|
| 255 |
def get_trimmed_history(self, maxlength: int) -> list[str]: |
| 256 |
if maxlength >= 0: |
| 257 |
cut = len(self.history) - maxlength |
| 258 |
if cut < 0: |
| 259 |
cut = 0 |
| 260 |
else: |
| 261 |
cut = 0 |
| 262 |
return self.history[cut:] |
| 263 |
|
| 264 |
def update_last_used_indentation(self) -> None: |
| 265 |
indentation = _get_first_indentation(self.buffer) |
| 266 |
if indentation is not None: |
| 267 |
self.last_used_indentation = indentation |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
def collect_keymap(self) -> tuple[tuple[KeySpec, CommandName], ...]: |
| 272 |
return super().collect_keymap() + ( |
| 273 |
(r"\n", "maybe-accept"), |
| 274 |
(r"\<backspace>", "backspace-dedent"), |
| 275 |
) |
| 276 |
|
| 277 |
def after_command(self, cmd: Command) -> None: |
| 278 |
super().after_command(cmd) |
| 279 |
if self.more_lines is None: |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
try: |
| 285 |
index = self.buffer.index("\n") |
| 286 |
except ValueError: |
| 287 |
pass |
| 288 |
else: |
| 289 |
self.buffer = self.buffer[:index] |
| 290 |
if self.pos > len(self.buffer): |
| 291 |
self.pos = len(self.buffer) |
| 292 |
|
| 293 |
|
| 294 |
def set_auto_history(_should_auto_add_history: bool) -> None: |
| 295 |
"""Enable or disable automatic history""" |
| 296 |
historical_reader.should_auto_add_history = bool(_should_auto_add_history) |
| 297 |
|
| 298 |
|
| 299 |
def _get_this_line_indent(buffer: list[str], pos: int) -> int: |
| 300 |
indent = 0 |
| 301 |
while pos > 0 and buffer[pos - 1] in " \t": |
| 302 |
indent += 1 |
| 303 |
pos -= 1 |
| 304 |
if pos > 0 and buffer[pos - 1] == "\n": |
| 305 |
return indent |
| 306 |
return 0 |
| 307 |
|
| 308 |
|
| 309 |
def _get_previous_line_indent(buffer: list[str], pos: int) -> tuple[int, int | None]: |
| 310 |
prevlinestart = pos |
| 311 |
while prevlinestart > 0 and buffer[prevlinestart - 1] != "\n": |
| 312 |
prevlinestart -= 1 |
| 313 |
prevlinetext = prevlinestart |
| 314 |
while prevlinetext < pos and buffer[prevlinetext] in " \t": |
| 315 |
prevlinetext += 1 |
| 316 |
if prevlinetext == pos: |
| 317 |
indent = None |
| 318 |
else: |
| 319 |
indent = prevlinetext - prevlinestart |
| 320 |
return prevlinestart, indent |
| 321 |
|
| 322 |
|
| 323 |
def _get_first_indentation(buffer: list[str]) -> str | None: |
| 324 |
indented_line_start = None |
| 325 |
for i in range(len(buffer)): |
| 326 |
if (i < len(buffer) - 1 |
| 327 |
and buffer[i] == "\n" |
| 328 |
and buffer[i + 1] in " \t" |
| 329 |
): |
| 330 |
indented_line_start = i + 1 |
| 331 |
elif indented_line_start is not None and buffer[i] not in " \t\n": |
| 332 |
return ''.join(buffer[indented_line_start : i]) |
| 333 |
return None |
| 334 |
|
| 335 |
|
| 336 |
def _should_auto_indent(buffer: list[str], pos: int) -> bool: |
| 337 |
|
| 338 |
|
| 339 |
last_char = None |
| 340 |
while pos > 0: |
| 341 |
pos -= 1 |
| 342 |
if last_char is None: |
| 343 |
if buffer[pos] not in " \t\n#": |
| 344 |
last_char = buffer[pos] |
| 345 |
else: |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
if buffer[pos] == "\n": |
| 350 |
break |
| 351 |
if buffer[pos] == "#": |
| 352 |
last_char = None |
| 353 |
return last_char == ":" |
| 354 |
|
| 355 |
|
| 356 |
class maybe_accept(commands.Command): |
| 357 |
def do(self) -> None: |
| 358 |
r: ReadlineAlikeReader |
| 359 |
r = self.reader |
| 360 |
r.dirty = True |
| 361 |
|
| 362 |
if self.reader.in_bracketed_paste: |
| 363 |
r.insert("\n") |
| 364 |
return |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
text = r.get_unicode() |
| 369 |
|
| 370 |
if "\n" in r.buffer[r.pos :] or ( |
| 371 |
r.more_lines is not None and r.more_lines(text) |
| 372 |
): |
| 373 |
def _newline_before_pos(): |
| 374 |
before_idx = r.pos - 1 |
| 375 |
while before_idx > 0 and text[before_idx].isspace(): |
| 376 |
before_idx -= 1 |
| 377 |
return text[before_idx : r.pos].count("\n") > 0 |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
if _newline_before_pos() and text[r.pos:].isspace(): |
| 383 |
self.finish = True |
| 384 |
return |
| 385 |
|
| 386 |
|
| 387 |
prevlinestart, indent = _get_previous_line_indent(r.buffer, r.pos) |
| 388 |
r.insert("\n") |
| 389 |
if not self.reader.paste_mode: |
| 390 |
if indent: |
| 391 |
for i in range(prevlinestart, prevlinestart + indent): |
| 392 |
r.insert(r.buffer[i]) |
| 393 |
r.update_last_used_indentation() |
| 394 |
if _should_auto_indent(r.buffer, r.pos): |
| 395 |
if r.last_used_indentation is not None: |
| 396 |
indentation = r.last_used_indentation |
| 397 |
else: |
| 398 |
|
| 399 |
indentation = " " * 4 |
| 400 |
r.insert(indentation) |
| 401 |
elif not self.reader.paste_mode: |
| 402 |
self.finish = True |
| 403 |
else: |
| 404 |
r.insert("\n") |
| 405 |
|
| 406 |
|
| 407 |
class backspace_dedent(commands.Command): |
| 408 |
def do(self) -> None: |
| 409 |
r = self.reader |
| 410 |
b = r.buffer |
| 411 |
if r.pos > 0: |
| 412 |
repeat = 1 |
| 413 |
if b[r.pos - 1] != "\n": |
| 414 |
indent = _get_this_line_indent(b, r.pos) |
| 415 |
if indent > 0: |
| 416 |
ls = r.pos - indent |
| 417 |
while ls > 0: |
| 418 |
ls, pi = _get_previous_line_indent(b, ls - 1) |
| 419 |
if pi is not None and pi < indent: |
| 420 |
repeat = indent - pi |
| 421 |
break |
| 422 |
r.pos -= repeat |
| 423 |
del b[r.pos : r.pos + repeat] |
| 424 |
r.dirty = True |
| 425 |
else: |
| 426 |
self.reader.error("can't backspace at start") |
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
@dataclass(slots=True) |
| 433 |
class _ReadlineWrapper: |
| 434 |
f_in: int = -1 |
| 435 |
f_out: int = -1 |
| 436 |
reader: ReadlineAlikeReader | None = field(default=None, repr=False) |
| 437 |
saved_history_length: int = -1 |
| 438 |
startup_hook: Callback | None = None |
| 439 |
pre_input_hook: Callback | None = None |
| 440 |
config: ReadlineConfig = field(default_factory=ReadlineConfig, repr=False) |
| 441 |
_pending_bindings: list = field(default_factory=list, repr=False) |
| 442 |
_pending_macro_commands: dict = field(default_factory=dict, repr=False) |
| 443 |
|
| 444 |
def __post_init__(self) -> None: |
| 445 |
if self.f_in == -1: |
| 446 |
self.f_in = os.dup(0) |
| 447 |
if self.f_out == -1: |
| 448 |
self.f_out = os.dup(1) |
| 449 |
|
| 450 |
def get_reader(self) -> ReadlineAlikeReader: |
| 451 |
if self.reader is None: |
| 452 |
console = Console(self.f_in, self.f_out, encoding=ENCODING) |
| 453 |
self.reader = ReadlineAlikeReader(console=console, config=self.config) |
| 454 |
for name, cls in self._pending_macro_commands.items(): |
| 455 |
self.reader.commands[name] = cls |
| 456 |
for keyspec, cmd_name in self._pending_bindings: |
| 457 |
self.reader.bind(keyspec, cmd_name) |
| 458 |
return self.reader |
| 459 |
|
| 460 |
def input(self, prompt: object = "") -> str: |
| 461 |
try: |
| 462 |
reader = self.get_reader() |
| 463 |
except _error: |
| 464 |
assert raw_input is not None |
| 465 |
return raw_input(prompt) |
| 466 |
reader.ps1 = str(prompt) |
| 467 |
hooks = [h for h in (self.startup_hook, self.pre_input_hook) if h is not None] |
| 468 |
def combined_hook() -> None: |
| 469 |
for h in hooks: |
| 470 |
h() |
| 471 |
return reader.readline(startup_hook=combined_hook if hooks else None) |
| 472 |
|
| 473 |
def multiline_input(self, more_lines: MoreLinesCallable, ps1: str, ps2: str) -> str: |
| 474 |
"""Read an input on possibly multiple lines, asking for more |
| 475 |
lines as long as 'more_lines(unicodetext)' returns an object whose |
| 476 |
boolean value is true. |
| 477 |
""" |
| 478 |
reader = self.get_reader() |
| 479 |
saved = reader.more_lines |
| 480 |
try: |
| 481 |
reader.more_lines = more_lines |
| 482 |
reader.ps1 = ps1 |
| 483 |
reader.ps2 = ps1 |
| 484 |
reader.ps3 = ps2 |
| 485 |
reader.ps4 = "" |
| 486 |
with warnings.catch_warnings(action="ignore"): |
| 487 |
return reader.readline() |
| 488 |
finally: |
| 489 |
reader.more_lines = saved |
| 490 |
reader.paste_mode = False |
| 491 |
|
| 492 |
def parse_and_bind(self, string: str) -> None: |
| 493 |
string = string.strip() |
| 494 |
if string.startswith('set '): |
| 495 |
return |
| 496 |
colon = string.find(':') |
| 497 |
if colon == -1: |
| 498 |
return |
| 499 |
key_part = string[:colon].strip() |
| 500 |
val_part = string[colon + 1:].strip() |
| 501 |
try: |
| 502 |
pyrepl_spec = _rl_keyspec_to_pyrepl(key_part) |
| 503 |
except ValueError: |
| 504 |
return |
| 505 |
if val_part.startswith('"') and val_part.endswith('"') and len(val_part) >= 2: |
| 506 |
text = _decode_readline_macro(val_part[1:-1]) |
| 507 |
cmd_name = 'macro_' + text.encode('unicode_escape').decode('ascii') |
| 508 |
if cmd_name not in self._pending_macro_commands: |
| 509 |
self._pending_macro_commands[cmd_name] = _make_macro_command(text) |
| 510 |
else: |
| 511 |
cmd_name = _RL_CMD_TO_PYREPL.get(val_part, val_part) |
| 512 |
if self.reader is not None: |
| 513 |
for name, cls in self._pending_macro_commands.items(): |
| 514 |
if name not in self.reader.commands: |
| 515 |
self.reader.commands[name] = cls |
| 516 |
self.reader.bind(pyrepl_spec, cmd_name) |
| 517 |
else: |
| 518 |
self._pending_bindings.append((pyrepl_spec, cmd_name)) |
| 519 |
|
| 520 |
def set_completer(self, function: Completer | None = None) -> None: |
| 521 |
self.config.readline_completer = function |
| 522 |
|
| 523 |
def get_completer(self) -> Completer | None: |
| 524 |
return self.config.readline_completer |
| 525 |
|
| 526 |
def set_completer_delims(self, delimiters: Collection[str]) -> None: |
| 527 |
self.config.completer_delims = frozenset(delimiters) |
| 528 |
|
| 529 |
def get_completer_delims(self) -> str: |
| 530 |
return "".join(sorted(self.config.completer_delims)) |
| 531 |
|
| 532 |
def _histline(self, line: str) -> str: |
| 533 |
line = line.rstrip("\n") |
| 534 |
return line |
| 535 |
|
| 536 |
def get_history_length(self) -> int: |
| 537 |
return self.saved_history_length |
| 538 |
|
| 539 |
def set_history_length(self, length: int) -> None: |
| 540 |
self.saved_history_length = length |
| 541 |
|
| 542 |
def get_current_history_length(self) -> int: |
| 543 |
return len(self.get_reader().history) |
| 544 |
|
| 545 |
def read_history_file(self, filename: str = gethistoryfile()) -> None: |
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
history = self.get_reader().history |
| 551 |
|
| 552 |
with open(os.path.expanduser(filename), 'rb') as f: |
| 553 |
lines = [line.decode('utf-8', errors='replace') for line in f.read().split(b'\n')] |
| 554 |
buffer = [] |
| 555 |
for line in lines: |
| 556 |
|
| 557 |
if line.startswith("_HiStOrY_V2_"): |
| 558 |
continue |
| 559 |
if line.endswith("\r"): |
| 560 |
buffer.append(line+'\n') |
| 561 |
else: |
| 562 |
line = self._histline(line) |
| 563 |
if buffer: |
| 564 |
line = "".join(buffer).replace("\r", "") + line |
| 565 |
del buffer[:] |
| 566 |
if line: |
| 567 |
history.append(line) |
| 568 |
|
| 569 |
def write_history_file(self, filename: str = gethistoryfile()) -> None: |
| 570 |
maxlength = self.saved_history_length |
| 571 |
history = self.get_reader().get_trimmed_history(maxlength) |
| 572 |
with open(os.path.expanduser(filename), "w", encoding="utf-8") as f: |
| 573 |
for entry in history: |
| 574 |
entry = entry.replace("\n", "\r\n") |
| 575 |
f.write(entry + "\n") |
| 576 |
|
| 577 |
def clear_history(self) -> None: |
| 578 |
del self.get_reader().history[:] |
| 579 |
|
| 580 |
def get_history_item(self, index: int) -> str | None: |
| 581 |
history = self.get_reader().history |
| 582 |
if 1 <= index <= len(history): |
| 583 |
return history[index - 1] |
| 584 |
else: |
| 585 |
return None |
| 586 |
|
| 587 |
def remove_history_item(self, index: int) -> None: |
| 588 |
history = self.get_reader().history |
| 589 |
if 0 <= index < len(history): |
| 590 |
del history[index] |
| 591 |
else: |
| 592 |
raise ValueError("No history item at position %d" % index) |
| 593 |
|
| 594 |
|
| 595 |
def replace_history_item(self, index: int, line: str) -> None: |
| 596 |
history = self.get_reader().history |
| 597 |
if 0 <= index < len(history): |
| 598 |
history[index] = self._histline(line) |
| 599 |
else: |
| 600 |
raise ValueError("No history item at position %d" % index) |
| 601 |
|
| 602 |
|
| 603 |
def add_history(self, line: str) -> None: |
| 604 |
self.get_reader().history.append(self._histline(line)) |
| 605 |
|
| 606 |
def set_completion_display_matches_hook(self, function: Callable | None = None) -> None: |
| 607 |
self.config.completion_display_matches_hook = function |
| 608 |
|
| 609 |
def set_pre_input_hook(self, function: Callback | None = None) -> None: |
| 610 |
self.pre_input_hook = function |
| 611 |
|
| 612 |
def set_startup_hook(self, function: Callback | None = None) -> None: |
| 613 |
self.startup_hook = function |
| 614 |
|
| 615 |
def get_line_buffer(self) -> str: |
| 616 |
return self.get_reader().get_unicode() |
| 617 |
|
| 618 |
def _get_idxs(self) -> tuple[int, int]: |
| 619 |
start = cursor = self.get_reader().pos |
| 620 |
buf = self.get_line_buffer() |
| 621 |
for i in range(cursor - 1, -1, -1): |
| 622 |
if str(buf[i]) in self.get_completer_delims(): |
| 623 |
break |
| 624 |
start = i |
| 625 |
return start, cursor |
| 626 |
|
| 627 |
def get_begidx(self) -> int: |
| 628 |
return self._get_idxs()[0] |
| 629 |
|
| 630 |
def get_endidx(self) -> int: |
| 631 |
return self._get_idxs()[1] |
| 632 |
|
| 633 |
def insert_text(self, text: str) -> None: |
| 634 |
self.get_reader().insert(text) |
| 635 |
|
| 636 |
|
| 637 |
_wrapper = _ReadlineWrapper() |
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
parse_and_bind = _wrapper.parse_and_bind |
| 643 |
set_completer = _wrapper.set_completer |
| 644 |
get_completer = _wrapper.get_completer |
| 645 |
set_completer_delims = _wrapper.set_completer_delims |
| 646 |
get_completer_delims = _wrapper.get_completer_delims |
| 647 |
get_history_length = _wrapper.get_history_length |
| 648 |
set_history_length = _wrapper.set_history_length |
| 649 |
get_current_history_length = _wrapper.get_current_history_length |
| 650 |
read_history_file = _wrapper.read_history_file |
| 651 |
write_history_file = _wrapper.write_history_file |
| 652 |
clear_history = _wrapper.clear_history |
| 653 |
get_history_item = _wrapper.get_history_item |
| 654 |
remove_history_item = _wrapper.remove_history_item |
| 655 |
replace_history_item = _wrapper.replace_history_item |
| 656 |
add_history = _wrapper.add_history |
| 657 |
set_completion_display_matches_hook = _wrapper.set_completion_display_matches_hook |
| 658 |
set_pre_input_hook = _wrapper.set_pre_input_hook |
| 659 |
set_startup_hook = _wrapper.set_startup_hook |
| 660 |
get_line_buffer = _wrapper.get_line_buffer |
| 661 |
get_begidx = _wrapper.get_begidx |
| 662 |
get_endidx = _wrapper.get_endidx |
| 663 |
insert_text = _wrapper.insert_text |
| 664 |
|
| 665 |
|
| 666 |
multiline_input = _wrapper.multiline_input |
| 667 |
|
| 668 |
|
| 669 |
_get_reader = _wrapper.get_reader |
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
def _make_stub(_name: str, _ret: object) -> None: |
| 676 |
def stub(*args: object, **kwds: object) -> None: |
| 677 |
import warnings |
| 678 |
|
| 679 |
warnings.warn("readline.%s() not implemented" % _name, stacklevel=2) |
| 680 |
|
| 681 |
stub.__name__ = _name |
| 682 |
globals()[_name] = stub |
| 683 |
|
| 684 |
|
| 685 |
for _name, _ret in [ |
| 686 |
("read_init_file", None), |
| 687 |
("redisplay", None), |
| 688 |
]: |
| 689 |
assert _name not in globals(), _name |
| 690 |
_make_stub(_name, _ret) |
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
def _setup(namespace: Mapping[str, Any] | None = None) -> None: |
| 696 |
from rlcompleter import Completer as RLCompleter |
| 697 |
import builtins |
| 698 |
global raw_input |
| 699 |
if raw_input is not None: |
| 700 |
return |
| 701 |
|
| 702 |
try: |
| 703 |
f_in = sys.stdin.fileno() |
| 704 |
f_out = sys.stdout.fileno() |
| 705 |
except (AttributeError, ValueError): |
| 706 |
return |
| 707 |
if not os.isatty(f_in) or not os.isatty(f_out): |
| 708 |
return |
| 709 |
|
| 710 |
_wrapper.f_in = f_in |
| 711 |
_wrapper.f_out = f_out |
| 712 |
|
| 713 |
if namespace is None: |
| 714 |
import builtins |
| 715 |
namespace = builtins.__dict__ |
| 716 |
if not isinstance(namespace, dict): |
| 717 |
namespace = dict(namespace) |
| 718 |
if namespace is None: |
| 719 |
pass |
| 720 |
elif not isinstance(namespace, dict): |
| 721 |
|
| 722 |
namespace = dict(namespace) |
| 723 |
_wrapper.config.readline_completer = RLCompleter(namespace).complete |
| 724 |
|
| 725 |
if '__pypy__' in sys.builtin_module_names: |
| 726 |
|
| 727 |
def raw_input(prompt=''): |
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
try: |
| 734 |
del sys.__raw_input__ |
| 735 |
except AttributeError: |
| 736 |
pass |
| 737 |
return input(prompt) |
| 738 |
sys.__raw_input__ = _wrapper.input |
| 739 |
else: |
| 740 |
raw_input = builtins.input |
| 741 |
builtins.input = _wrapper.input |
| 742 |
|
| 743 |
|
| 744 |
raw_input: Callable[[object], str] | None = None |