rlmain.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. # -*- coding: utf-8 -*-
  2. # *****************************************************************************
  3. # Copyright (C) 2003-2006 Gary Bishop.
  4. # Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
  5. # Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
  6. #
  7. # Distributed under the terms of the BSD License. The full license is in
  8. # the file COPYING, distributed as part of this software.
  9. # *****************************************************************************
  10. import os
  11. import re
  12. import sys
  13. import time
  14. from glob import glob
  15. import pyreadline3
  16. import pyreadline3.clipboard as clipboard
  17. import pyreadline3.console as console
  18. import pyreadline3.lineeditor.history as history
  19. import pyreadline3.lineeditor.lineobj as lineobj
  20. import pyreadline3.logger as logger
  21. from pyreadline3.keysyms.common import make_KeyPress_from_keydescr
  22. from pyreadline3.py3k_compat import is_ironpython
  23. from pyreadline3.unicode_helper import ensure_str, ensure_unicode
  24. from .error import GetSetError, ReadlineError
  25. from .logger import log
  26. from .modes import editingmodes
  27. from .py3k_compat import execfile, is_callable
  28. # an attempt to implement readline for Python in Python using ctypes
  29. if is_ironpython: # ironpython does not provide a prompt string to readline
  30. import System
  31. default_prompt = ">>> "
  32. else:
  33. default_prompt = ""
  34. class MockConsoleError(Exception):
  35. pass
  36. class MockConsole(object):
  37. """object used during refactoring. Should raise errors when someone tries
  38. to use it.
  39. """
  40. def __setattr__(self, _name, _value):
  41. raise MockConsoleError("Should not try to get attributes from MockConsole")
  42. def cursor(self, size=50):
  43. pass
  44. class BaseReadline(object):
  45. def __init__(self):
  46. self.allow_ctrl_c = False
  47. self.ctrl_c_tap_time_interval = 0.3
  48. self.debug = False
  49. self.bell_style = "none"
  50. self.mark = -1
  51. self.console = MockConsole()
  52. self.disable_readline = False
  53. # this code needs to follow l_buffer and history creation
  54. self.editingmodes = [mode(self) for mode in editingmodes]
  55. for mode in self.editingmodes:
  56. mode.init_editing_mode(None)
  57. self.mode = self.editingmodes[0]
  58. self.read_inputrc()
  59. log("\n".join(self.mode.rl_settings_to_string()))
  60. self.callback = None
  61. def parse_and_bind(self, string):
  62. """Parse and execute single line of a readline init file."""
  63. try:
  64. log('parse_and_bind("%s")' % string)
  65. if string.startswith("#"):
  66. return
  67. if string.startswith("set"):
  68. m = re.compile(r"set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$").match(string)
  69. if m:
  70. var_name = m.group(1)
  71. val = m.group(2)
  72. try:
  73. setattr(self.mode, var_name.replace("-", "_"), val)
  74. except AttributeError:
  75. log('unknown var="%s" val="%s"' % (var_name, val))
  76. else:
  77. log('bad set "%s"' % string)
  78. return
  79. m = re.compile(r"\s*(\S+)\s*:\s*([-a-zA-Z]+)\s*$").match(string)
  80. if m:
  81. key = m.group(1)
  82. func_name = m.group(2)
  83. py_name = func_name.replace("-", "_")
  84. try:
  85. func = getattr(self.mode, py_name)
  86. except AttributeError:
  87. log('unknown func key="%s" func="%s"' % (key, func_name))
  88. if self.debug:
  89. print(
  90. "pyreadline3 parse_and_bind error, unknown "
  91. 'function to bind: "%s"' % func_name
  92. )
  93. return
  94. self.mode._bind_key(key, func)
  95. except BaseException:
  96. log("error")
  97. raise
  98. def _set_prompt(self, prompt):
  99. self.mode.prompt = prompt
  100. def _get_prompt(self):
  101. return self.mode.prompt
  102. prompt = property(_get_prompt, _set_prompt)
  103. def get_line_buffer(self):
  104. """Return the current contents of the line buffer."""
  105. return self.mode.l_buffer.get_line_text()
  106. def insert_text(self, string):
  107. """Insert text into the command line."""
  108. self.mode.insert_text(string)
  109. def read_init_file(self, filename=None):
  110. """Parse a readline initialization file. The default filename is the last filename used."""
  111. log('read_init_file("%s")' % filename)
  112. # History file book keeping methods (non-bindable)
  113. def add_history(self, line):
  114. """Append a line to the history buffer, as if it was the last line typed."""
  115. self.mode._history.add_history(line)
  116. def get_current_history_length(self):
  117. """Return the number of lines currently in the history.
  118. (This is different from get_history_length(), which returns
  119. the maximum number of lines that will be written to a history file.)"""
  120. return self.mode._history.get_current_history_length()
  121. def get_history_length(self):
  122. """Return the desired length of the history file.
  123. Negative values imply unlimited history file size."""
  124. return self.mode._history.get_history_length()
  125. def set_history_length(self, length):
  126. """Set the number of lines to save in the history file.
  127. write_history_file() uses this value to truncate the history file
  128. when saving. Negative values imply unlimited history file size.
  129. """
  130. self.mode._history.set_history_length(length)
  131. def get_history_item(self, index):
  132. """Return the current contents of history item at index."""
  133. return self.mode._history.get_history_item(index)
  134. def clear_history(self):
  135. """Clear readline history"""
  136. self.mode._history.clear_history()
  137. def read_history_file(self, filename=None):
  138. """Load a readline history file. The default filename is ~/.history."""
  139. if filename is None:
  140. filename = self.mode._history.history_filename
  141. log("read_history_file from %s" % ensure_unicode(filename))
  142. self.mode._history.read_history_file(filename)
  143. def write_history_file(self, filename=None):
  144. """Save a readline history file. The default filename is ~/.history."""
  145. self.mode._history.write_history_file(filename)
  146. # Completer functions
  147. def set_completer(self, function=None):
  148. """Set or remove the completer function.
  149. If function is specified, it will be used as the new completer
  150. function; if omitted or None, any completer function already
  151. installed is removed. The completer function is called as
  152. function(text, state), for state in 0, 1, 2, ..., until it returns a
  153. non-string value. It should return the next possible completion
  154. starting with text.
  155. """
  156. log("set_completer")
  157. self.mode.completer = function
  158. def get_completer(self):
  159. """Get the completer function."""
  160. log("get_completer")
  161. return self.mode.completer
  162. def get_begidx(self):
  163. """Get the beginning index of the readline tab-completion scope."""
  164. return self.mode.begidx
  165. def get_endidx(self):
  166. """Get the ending index of the readline tab-completion scope."""
  167. return self.mode.endidx
  168. def set_completer_delims(self, string):
  169. """Set the readline word delimiters for tab-completion."""
  170. self.mode.completer_delims = string
  171. def get_completer_delims(self):
  172. """Get the readline word delimiters for tab-completion."""
  173. return self.mode.completer_delims
  174. def set_startup_hook(self, function=None):
  175. """Set or remove the startup_hook function.
  176. If function is specified, it will be used as the new startup_hook
  177. function; if omitted or None, any hook function already installed is
  178. removed. The startup_hook function is called with no arguments just
  179. before readline prints the first prompt.
  180. """
  181. self.mode.startup_hook = function
  182. def set_pre_input_hook(self, function=None):
  183. """Set or remove the pre_input_hook function.
  184. If function is specified, it will be used as the new pre_input_hook
  185. function; if omitted or None, any hook function already installed is
  186. removed. The pre_input_hook function is called with no arguments
  187. after the first prompt has been printed and just before readline
  188. starts reading input characters.
  189. """
  190. self.mode.pre_input_hook = function
  191. # Functions that are not relevant for all Readlines but should at least
  192. # have a NOP
  193. def _bell(self):
  194. pass
  195. #
  196. # Standard call, not available for all implementations
  197. #
  198. def readline(self, prompt=""):
  199. raise NotImplementedError
  200. #
  201. # Callback interface
  202. #
  203. def process_keyevent(self, keyinfo):
  204. return self.mode.process_keyevent(keyinfo)
  205. def readline_setup(self, prompt=""):
  206. return self.mode.readline_setup(prompt)
  207. def keyboard_poll(self):
  208. return self.mode._readline_from_keyboard_poll()
  209. def callback_handler_install(self, prompt, callback):
  210. """bool readline_callback_handler_install ( string prompt, callback callback)
  211. Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  212. """
  213. self.callback = callback
  214. self.readline_setup(prompt)
  215. def callback_handler_remove(self):
  216. """Removes a previously installed callback handler and restores terminal settings"""
  217. self.callback = None
  218. def callback_read_char(self):
  219. """Reads a character and informs the readline callback interface when a line is received"""
  220. if self.keyboard_poll():
  221. line = self.get_line_buffer() + "\n"
  222. # however there is another newline added by
  223. # self.mode.readline_setup(prompt) which is called by callback_handler_install
  224. # this differs from GNU readline
  225. self.add_history(self.mode.l_buffer)
  226. # TADA:
  227. self.callback(line)
  228. def read_inputrc(
  229. self, # in 2.4 we cannot call expanduser with unicode string
  230. inputrcpath=os.path.expanduser(ensure_str("~/pyreadlineconfig.ini")),
  231. ):
  232. modes = dict([(x.mode, x) for x in self.editingmodes])
  233. mode = self.editingmodes[0].mode
  234. def setmode(name):
  235. self.mode = modes[name]
  236. def bind_key(key, name):
  237. import types
  238. if is_callable(name):
  239. modes[mode]._bind_key(key, types.MethodType(name, modes[mode]))
  240. elif hasattr(modes[mode], name):
  241. modes[mode]._bind_key(key, getattr(modes[mode], name))
  242. else:
  243. print("Trying to bind unknown command '%s' to key '%s'" % (name, key))
  244. def un_bind_key(key):
  245. keyinfo = make_KeyPress_from_keydescr(key).tuple()
  246. if keyinfo in modes[mode].key_dispatch:
  247. del modes[mode].key_dispatch[keyinfo]
  248. def bind_exit_key(key):
  249. modes[mode]._bind_exit_key(key)
  250. def un_bind_exit_key(key):
  251. keyinfo = make_KeyPress_from_keydescr(key).tuple()
  252. if keyinfo in modes[mode].exit_dispatch:
  253. del modes[mode].exit_dispatch[keyinfo]
  254. def setkill_ring_to_clipboard(killring):
  255. import pyreadline3.lineeditor.lineobj
  256. pyreadline3.lineeditor.lineobj.kill_ring_to_clipboard = killring
  257. def sethistoryfilename(filename):
  258. self.mode._history.history_filename = os.path.expanduser(
  259. ensure_str(filename)
  260. )
  261. def setbellstyle(mode):
  262. self.bell_style = mode
  263. def disable_readline(mode):
  264. self.disable_readline = mode
  265. def sethistorylength(length):
  266. self.mode._history.history_length = int(length)
  267. def allow_ctrl_c(mode):
  268. log("allow_ctrl_c:%s:%s" % (self.allow_ctrl_c, mode))
  269. self.allow_ctrl_c = mode
  270. def setbellstyle(mode):
  271. self.bell_style = mode
  272. def show_all_if_ambiguous(mode):
  273. self.mode.show_all_if_ambiguous = mode
  274. def ctrl_c_tap_time_interval(mode):
  275. self.ctrl_c_tap_time_interval = mode
  276. def mark_directories(mode):
  277. self.mode.mark_directories = mode
  278. def completer_delims(delims):
  279. self.mode.completer_delims = delims
  280. def complete_filesystem(delims):
  281. self.mode.complete_filesystem = delims.lower()
  282. def enable_ipython_paste_for_paths(boolean):
  283. self.mode.enable_ipython_paste_for_paths = boolean
  284. def debug_output(
  285. on, filename="pyreadline_debug_log.txt"
  286. ): # Not implemented yet
  287. if on in ["on", "on_nologfile"]:
  288. self.debug = True
  289. if on == "on":
  290. logger.start_file_log(filename)
  291. logger.start_socket_log()
  292. logger.log("STARTING LOG")
  293. elif on == "on_nologfile":
  294. logger.start_socket_log()
  295. logger.log("STARTING LOG")
  296. else:
  297. logger.log("STOPING LOG")
  298. logger.stop_file_log()
  299. logger.stop_socket_log()
  300. _color_trtable = {
  301. "black": 0,
  302. "darkred": 4,
  303. "darkgreen": 2,
  304. "darkyellow": 6,
  305. "darkblue": 1,
  306. "darkmagenta": 5,
  307. "darkcyan": 3,
  308. "gray": 7,
  309. "red": 4 + 8,
  310. "green": 2 + 8,
  311. "yellow": 6 + 8,
  312. "blue": 1 + 8,
  313. "magenta": 5 + 8,
  314. "cyan": 3 + 8,
  315. "white": 7 + 8,
  316. }
  317. def set_prompt_color(color):
  318. self.prompt_color = self._color_trtable.get(color.lower(), 7)
  319. def set_input_color(color):
  320. self.command_color = self._color_trtable.get(color.lower(), 7)
  321. loc = {
  322. "version": pyreadline3.__version__,
  323. "mode": mode,
  324. "modes": modes,
  325. "set_mode": setmode,
  326. "bind_key": bind_key,
  327. "disable_readline": disable_readline,
  328. "bind_exit_key": bind_exit_key,
  329. "un_bind_key": un_bind_key,
  330. "un_bind_exit_key": un_bind_exit_key,
  331. "bell_style": setbellstyle,
  332. "mark_directories": mark_directories,
  333. "show_all_if_ambiguous": show_all_if_ambiguous,
  334. "completer_delims": completer_delims,
  335. "complete_filesystem": complete_filesystem,
  336. "debug_output": debug_output,
  337. "history_filename": sethistoryfilename,
  338. "history_length": sethistorylength,
  339. "set_prompt_color": set_prompt_color,
  340. "set_input_color": set_input_color,
  341. "allow_ctrl_c": allow_ctrl_c,
  342. "ctrl_c_tap_time_interval": ctrl_c_tap_time_interval,
  343. "kill_ring_to_clipboard": setkill_ring_to_clipboard,
  344. "enable_ipython_paste_for_paths": enable_ipython_paste_for_paths,
  345. }
  346. if os.path.isfile(inputrcpath):
  347. try:
  348. execfile(inputrcpath, loc, loc)
  349. except Exception as x:
  350. raise
  351. import traceback
  352. print("Error reading .pyinputrc", file=sys.stderr)
  353. filepath, lineno = traceback.extract_tb(sys.exc_info()[2])[1][:2]
  354. print("Line: %s in file %s" % (lineno, filepath), file=sys.stderr)
  355. print(x, file=sys.stderr)
  356. raise ReadlineError("Error reading .pyinputrc")
  357. def redisplay(self):
  358. pass
  359. class Readline(BaseReadline):
  360. """Baseclass for readline based on a console"""
  361. def __init__(self):
  362. super().__init__()
  363. self.console = console.Console()
  364. self.selection_color = self.console.saveattr << 4
  365. self.command_color = None
  366. self.prompt_color = None
  367. self.size = self.console.size()
  368. # variables you can control with parse_and_bind
  369. # To export as readline interface
  370. # Internal functions
  371. def _bell(self):
  372. """ring the bell if requested."""
  373. if self.bell_style == "none":
  374. pass
  375. elif self.bell_style == "visible":
  376. raise NotImplementedError("Bellstyle visible is not implemented yet.")
  377. elif self.bell_style == "audible":
  378. self.console.bell()
  379. else:
  380. raise ReadlineError("Bellstyle %s unknown." % self.bell_style)
  381. def _clear_after(self):
  382. c = self.console
  383. x, y = c.pos()
  384. w, h = c.size()
  385. c.rectangle((x, y, w + 1, y + 1))
  386. c.rectangle((0, y + 1, w, min(y + 3, h)))
  387. def _set_cursor(self):
  388. c = self.console
  389. xc, yc = self.prompt_end_pos
  390. w, h = c.size()
  391. xc += self.mode.l_buffer.visible_line_width()
  392. while xc >= w:
  393. xc -= w
  394. yc += 1
  395. c.pos(xc, yc)
  396. def _print_prompt(self):
  397. c = self.console
  398. x, y = c.pos()
  399. n = c.write_scrolling(self.prompt, self.prompt_color)
  400. self.prompt_begin_pos = (x, y - n)
  401. self.prompt_end_pos = c.pos()
  402. self.size = c.size()
  403. def _update_prompt_pos(self, n):
  404. if n != 0:
  405. bx, by = self.prompt_begin_pos
  406. ex, ey = self.prompt_end_pos
  407. self.prompt_begin_pos = (bx, by - n)
  408. self.prompt_end_pos = (ex, ey - n)
  409. def _update_line(self):
  410. c = self.console
  411. l_buffer = self.mode.l_buffer
  412. c.cursor(0) # Hide cursor avoiding flicking
  413. c.pos(*self.prompt_begin_pos)
  414. self._print_prompt()
  415. ltext = l_buffer.quoted_text()
  416. if l_buffer.enable_selection and (l_buffer.selection_mark >= 0):
  417. start = len(l_buffer[: l_buffer.selection_mark].quoted_text())
  418. stop = len(l_buffer[: l_buffer.point].quoted_text())
  419. if start > stop:
  420. stop, start = start, stop
  421. n = c.write_scrolling(ltext[:start], self.command_color)
  422. n = c.write_scrolling(ltext[start:stop], self.selection_color)
  423. n = c.write_scrolling(ltext[stop:], self.command_color)
  424. else:
  425. n = c.write_scrolling(ltext, self.command_color)
  426. x, y = c.pos() # Preserve one line for Asian IME(Input Method Editor) statusbar
  427. w, h = c.size()
  428. if (y >= h - 1) or (n > 0):
  429. c.scroll_window(-1)
  430. c.scroll((0, 0, w, h), 0, -1)
  431. n += 1
  432. self._update_prompt_pos(n)
  433. if hasattr(
  434. c, "clear_to_end_of_window"
  435. ): # Work around function for ironpython due
  436. c.clear_to_end_of_window() # to System.Console's lack of FillFunction
  437. else:
  438. self._clear_after()
  439. # Show cursor, set size vi mode changes size in insert/overwrite mode
  440. c.cursor(1, size=self.mode.cursor_size)
  441. self._set_cursor()
  442. def callback_read_char(self):
  443. # Override base to get automatic newline
  444. """Reads a character and informs the readline callback interface when a line is received"""
  445. if self.keyboard_poll():
  446. line = self.get_line_buffer() + "\n"
  447. self.console.write("\r\n")
  448. # however there is another newline added by
  449. # self.mode.readline_setup(prompt) which is called by callback_handler_install
  450. # this differs from GNU readline
  451. self.add_history(self.mode.l_buffer)
  452. # TADA:
  453. self.callback(line)
  454. def event_available(self):
  455. return self.console.peek() or (len(self.paste_line_buffer) > 0)
  456. def _readline_from_keyboard(self):
  457. while True:
  458. if self._readline_from_keyboard_poll():
  459. break
  460. def _readline_from_keyboard_poll(self):
  461. pastebuffer = self.mode.paste_line_buffer
  462. if len(pastebuffer) > 0:
  463. # paste first line in multiline paste buffer
  464. self.l_buffer = lineobj.ReadLineTextBuffer(pastebuffer[0])
  465. self._update_line()
  466. self.mode.paste_line_buffer = pastebuffer[1:]
  467. return True
  468. c = self.console
  469. def nop(e):
  470. pass
  471. try:
  472. event = c.getkeypress()
  473. except KeyboardInterrupt:
  474. event = self.handle_ctrl_c()
  475. try:
  476. result = self.mode.process_keyevent(event.keyinfo)
  477. except EOFError:
  478. logger.stop_logging()
  479. raise
  480. self._update_line()
  481. return result
  482. def readline_setup(self, prompt=""):
  483. BaseReadline.readline_setup(self, prompt)
  484. self._print_prompt()
  485. self._update_line()
  486. def readline(self, prompt=""):
  487. self.readline_setup(prompt)
  488. self.ctrl_c_timeout = time.time()
  489. self._readline_from_keyboard()
  490. self.console.write("\r\n")
  491. log("returning(%s)" % self.get_line_buffer())
  492. return self.get_line_buffer() + "\n"
  493. def handle_ctrl_c(self):
  494. from pyreadline3.console.event import Event
  495. from pyreadline3.keysyms.common import KeyPress
  496. log("KBDIRQ")
  497. event = Event(0, 0)
  498. event.char = "c"
  499. event.keyinfo = KeyPress(
  500. "c", shift=False, control=True, meta=False, keyname=None
  501. )
  502. if self.allow_ctrl_c:
  503. now = time.time()
  504. if (now - self.ctrl_c_timeout) < self.ctrl_c_tap_time_interval:
  505. log("Raise KeyboardInterrupt")
  506. raise KeyboardInterrupt
  507. else:
  508. self.ctrl_c_timeout = now
  509. else:
  510. raise KeyboardInterrupt
  511. return event
  512. def redisplay(self):
  513. BaseReadline.redisplay(self)