basemode.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 glob
  11. import math
  12. import os
  13. import re
  14. import sys
  15. import pyreadline3.clipboard as clipboard
  16. import pyreadline3.lineeditor.history as history
  17. import pyreadline3.lineeditor.lineobj as lineobj
  18. from pyreadline3.error import ReadlineError
  19. from pyreadline3.keysyms.common import make_KeyPress_from_keydescr
  20. from pyreadline3.logger import log
  21. from pyreadline3.py3k_compat import is_callable, is_ironpython
  22. from pyreadline3.unicode_helper import ensure_str, ensure_unicode
  23. class BaseMode(object):
  24. mode = "base"
  25. def __init__(self, rlobj):
  26. self.argument = 0
  27. self.rlobj = rlobj
  28. self.exit_dispatch = {}
  29. self.key_dispatch = {}
  30. self.argument = 1
  31. self.prevargument = None
  32. self.l_buffer = lineobj.ReadLineTextBuffer("")
  33. self._history = history.LineHistory()
  34. self.completer_delims = " \t\n\"\\'`@$><=;|&{("
  35. self.show_all_if_ambiguous = "on"
  36. self.mark_directories = "on"
  37. self.complete_filesystem = "off"
  38. self.completer = None
  39. self.begidx = 0
  40. self.endidx = 0
  41. self.tabstop = 4
  42. self.startup_hook = None
  43. self.pre_input_hook = None
  44. self.first_prompt = True
  45. self.cursor_size = 25
  46. self.prompt = ">>> "
  47. # Paste settings
  48. # assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n
  49. # and replace \ with / for easier use in ipython
  50. self.enable_ipython_paste_for_paths = True
  51. # automatically convert tabseparated data to list of lists or array
  52. # constructors
  53. self.enable_ipython_paste_list_of_lists = True
  54. self.enable_win32_clipboard = True
  55. self.paste_line_buffer = []
  56. self._sub_modes = []
  57. def __repr__(self):
  58. return "<BaseMode>"
  59. def _gs(x):
  60. def g(self):
  61. return getattr(self.rlobj, x)
  62. def s(self, q):
  63. setattr(self.rlobj, x, q)
  64. return g, s
  65. def _g(x):
  66. def g(self):
  67. return getattr(self.rlobj, x)
  68. return g
  69. def _argreset(self):
  70. val = self.argument
  71. self.argument = 0
  72. if val == 0:
  73. val = 1
  74. return val
  75. argument_reset = property(_argreset)
  76. # used in readline
  77. ctrl_c_tap_time_interval = property(*_gs("ctrl_c_tap_time_interval"))
  78. allow_ctrl_c = property(*_gs("allow_ctrl_c"))
  79. _print_prompt = property(_g("_print_prompt"))
  80. _update_line = property(_g("_update_line"))
  81. console = property(_g("console"))
  82. prompt_begin_pos = property(_g("prompt_begin_pos"))
  83. prompt_end_pos = property(_g("prompt_end_pos"))
  84. # used in completer _completions
  85. # completer_delims=property(*_gs("completer_delims"))
  86. _bell = property(_g("_bell"))
  87. bell_style = property(_g("bell_style"))
  88. # used in emacs
  89. _clear_after = property(_g("_clear_after"))
  90. _update_prompt_pos = property(_g("_update_prompt_pos"))
  91. # not used in basemode or emacs
  92. def process_keyevent(self, keyinfo):
  93. raise NotImplementedError
  94. def readline_setup(self, prompt=""):
  95. self.l_buffer.selection_mark = -1
  96. if self.first_prompt:
  97. self.first_prompt = False
  98. if self.startup_hook:
  99. try:
  100. self.startup_hook()
  101. except BaseException:
  102. print("startup hook failed")
  103. traceback.print_exc()
  104. self.l_buffer.reset_line()
  105. self.prompt = prompt
  106. if self.pre_input_hook:
  107. try:
  108. self.pre_input_hook()
  109. except BaseException:
  110. print("pre_input_hook failed")
  111. traceback.print_exc()
  112. self.pre_input_hook = None
  113. # ###################################
  114. def finalize(self):
  115. """Every bindable command should call this function for cleanup.
  116. Except those that want to set argument to a non-zero value.
  117. """
  118. self.argument = 0
  119. def add_history(self, text):
  120. self._history.add_history(lineobj.ReadLineTextBuffer(text))
  121. # Create key bindings:
  122. def rl_settings_to_string(self):
  123. out = ["%-20s: %s" % ("show all if ambigous", self.show_all_if_ambiguous)]
  124. out.append("%-20s: %s" % ("mark_directories", self.mark_directories))
  125. out.append("%-20s: %s" % ("bell_style", self.bell_style))
  126. out.append("------------- key bindings ------------")
  127. tablepat = "%-7s %-7s %-7s %-15s %-15s "
  128. out.append(tablepat % ("Control", "Meta", "Shift", "Keycode/char", "Function"))
  129. bindings = sorted(
  130. [(k[0], k[1], k[2], k[3], v.__name__) for k, v in self.key_dispatch.items()]
  131. )
  132. for key in bindings:
  133. out.append(tablepat % (key))
  134. return out
  135. def _bind_key(self, key, func):
  136. """setup the mapping from key to call the function."""
  137. if not is_callable(func):
  138. print("Trying to bind non method to keystroke:%s,%s" % (key, func))
  139. raise ReadlineError(
  140. "Trying to bind non method to keystroke:%s,%s,%s,%s"
  141. % (key, func, type(func), type(self._bind_key))
  142. )
  143. keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
  144. log(">>>%s -> %s<<<" % (keyinfo, func.__name__))
  145. self.key_dispatch[keyinfo] = func
  146. def _bind_exit_key(self, key):
  147. """setup the mapping from key to call the function."""
  148. keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
  149. self.exit_dispatch[keyinfo] = None
  150. def init_editing_mode(self, e): # (C-e)
  151. """When in vi command mode, this causes a switch to emacs editing
  152. mode."""
  153. raise NotImplementedError
  154. # completion commands
  155. def _get_completions(self):
  156. """Return a list of possible completions for the string ending at the point.
  157. Also set begidx and endidx in the process."""
  158. completions = []
  159. self.begidx = self.l_buffer.point
  160. self.endidx = self.l_buffer.point
  161. buf = self.l_buffer.line_buffer
  162. if self.completer:
  163. # get the string to complete
  164. while self.begidx > 0:
  165. self.begidx -= 1
  166. if buf[self.begidx] in self.completer_delims:
  167. self.begidx += 1
  168. break
  169. text = ensure_str("".join(buf[self.begidx : self.endidx]))
  170. log('complete text="%s"' % ensure_unicode(text))
  171. i = 0
  172. while True:
  173. try:
  174. r = self.completer(ensure_unicode(text), i)
  175. except IndexError:
  176. break
  177. i += 1
  178. if r is None:
  179. break
  180. elif r and r not in completions:
  181. completions.append(r)
  182. else:
  183. pass
  184. log("text completions=<%s>" % list(map(ensure_unicode, completions)))
  185. if (self.complete_filesystem == "on") and not completions:
  186. # get the filename to complete
  187. while self.begidx > 0:
  188. self.begidx -= 1
  189. if buf[self.begidx] in " \t\n":
  190. self.begidx += 1
  191. break
  192. text = ensure_str("".join(buf[self.begidx : self.endidx]))
  193. log('file complete text="%s"' % ensure_unicode(text))
  194. completions = list(
  195. map(
  196. ensure_unicode,
  197. glob.glob(os.path.expanduser(text) + "*".encode("ascii")),
  198. )
  199. )
  200. if self.mark_directories == "on":
  201. mc = []
  202. for f in completions:
  203. if os.path.isdir(f):
  204. mc.append(f + os.sep)
  205. else:
  206. mc.append(f)
  207. completions = mc
  208. log("fnames=<%s>" % list(map(ensure_unicode, completions)))
  209. return completions
  210. def _display_completions(self, completions):
  211. if not completions:
  212. return
  213. self.console.write("\n")
  214. wmax = max(map(len, completions))
  215. w, h = self.console.size()
  216. cols = max(1, int((w - 1) / (wmax + 1)))
  217. rows = int(math.ceil(float(len(completions)) / cols))
  218. for row in range(rows):
  219. s = ""
  220. for col in range(cols):
  221. i = col * rows + row
  222. if i < len(completions):
  223. self.console.write(completions[i].ljust(wmax + 1))
  224. self.console.write("\n")
  225. if is_ironpython:
  226. self.prompt = sys.ps1
  227. self._print_prompt()
  228. def complete(self, e): # (TAB)
  229. """Attempt to perform completion on the text before point. The
  230. actual completion performed is application-specific. The default is
  231. filename completion."""
  232. completions = self._get_completions()
  233. if completions:
  234. cprefix = commonprefix(completions)
  235. if len(cprefix) > 0:
  236. rep = [c for c in cprefix]
  237. point = self.l_buffer.point
  238. self.l_buffer[self.begidx : self.endidx] = rep
  239. self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx)
  240. if len(completions) > 1:
  241. if self.show_all_if_ambiguous == "on":
  242. self._display_completions(completions)
  243. else:
  244. self._bell()
  245. else:
  246. self._bell()
  247. self.finalize()
  248. def possible_completions(self, e): # (M-?)
  249. """List the possible completions of the text before point."""
  250. completions = self._get_completions()
  251. self._display_completions(completions)
  252. self.finalize()
  253. def insert_completions(self, e): # (M-*)
  254. """Insert all completions of the text before point that would have
  255. been generated by possible-completions."""
  256. completions = self._get_completions()
  257. b = self.begidx
  258. e = self.endidx
  259. for comp in completions:
  260. rep = [c for c in comp]
  261. rep.append(" ")
  262. self.l_buffer[b:e] = rep
  263. b += len(rep)
  264. e = b
  265. self.line_cursor = b
  266. self.finalize()
  267. def menu_complete(self, e): # ()
  268. """Similar to complete, but replaces the word to be completed with a
  269. single match from the list of possible completions. Repeated
  270. execution of menu-complete steps through the list of possible
  271. completions, inserting each match in turn. At the end of the list of
  272. completions, the bell is rung (subject to the setting of bell-style)
  273. and the original text is restored. An argument of n moves n
  274. positions forward in the list of matches; a negative argument may be
  275. used to move backward through the list. This command is intended to
  276. be bound to TAB, but is unbound by default."""
  277. self.finalize()
  278. # Methods below here are bindable emacs functions
  279. def insert_text(self, string):
  280. """Insert text into the command line."""
  281. self.l_buffer.insert_text(string, self.argument_reset)
  282. self.finalize()
  283. def beginning_of_line(self, e): # (C-a)
  284. """Move to the start of the current line."""
  285. self.l_buffer.beginning_of_line()
  286. self.finalize()
  287. def end_of_line(self, e): # (C-e)
  288. """Move to the end of the line."""
  289. self.l_buffer.end_of_line()
  290. self.finalize()
  291. def forward_char(self, e): # (C-f)
  292. """Move forward a character."""
  293. self.l_buffer.forward_char(self.argument_reset)
  294. self.finalize()
  295. def backward_char(self, e): # (C-b)
  296. """Move back a character."""
  297. self.l_buffer.backward_char(self.argument_reset)
  298. self.finalize()
  299. def forward_word(self, e): # (M-f)
  300. """Move forward to the end of the next word. Words are composed of
  301. letters and digits."""
  302. self.l_buffer.forward_word(self.argument_reset)
  303. self.finalize()
  304. def backward_word(self, e): # (M-b)
  305. """Move back to the start of the current or previous word. Words are
  306. composed of letters and digits."""
  307. self.l_buffer.backward_word(self.argument_reset)
  308. self.finalize()
  309. def forward_word_end(self, e): # ()
  310. """Move forward to the end of the next word. Words are composed of
  311. letters and digits."""
  312. self.l_buffer.forward_word_end(self.argument_reset)
  313. self.finalize()
  314. def backward_word_end(self, e): # ()
  315. """Move forward to the end of the next word. Words are composed of
  316. letters and digits."""
  317. self.l_buffer.backward_word_end(self.argument_reset)
  318. self.finalize()
  319. # Movement with extend selection
  320. def beginning_of_line_extend_selection(self, e):
  321. """Move to the start of the current line."""
  322. self.l_buffer.beginning_of_line_extend_selection()
  323. self.finalize()
  324. def end_of_line_extend_selection(self, e):
  325. """Move to the end of the line."""
  326. self.l_buffer.end_of_line_extend_selection()
  327. self.finalize()
  328. def forward_char_extend_selection(self, e):
  329. """Move forward a character."""
  330. self.l_buffer.forward_char_extend_selection(self.argument_reset)
  331. self.finalize()
  332. def backward_char_extend_selection(self, e):
  333. """Move back a character."""
  334. self.l_buffer.backward_char_extend_selection(self.argument_reset)
  335. self.finalize()
  336. def forward_word_extend_selection(self, e):
  337. """Move forward to the end of the next word. Words are composed of
  338. letters and digits."""
  339. self.l_buffer.forward_word_extend_selection(self.argument_reset)
  340. self.finalize()
  341. def backward_word_extend_selection(self, e):
  342. """Move back to the start of the current or previous word. Words are
  343. composed of letters and digits."""
  344. self.l_buffer.backward_word_extend_selection(self.argument_reset)
  345. self.finalize()
  346. def forward_word_end_extend_selection(self, e):
  347. """Move forward to the end of the next word. Words are composed of
  348. letters and digits."""
  349. self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
  350. self.finalize()
  351. def backward_word_end_extend_selection(self, e):
  352. """Move forward to the end of the next word. Words are composed of
  353. letters and digits."""
  354. self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
  355. self.finalize()
  356. # Change case
  357. def upcase_word(self, e): # (M-u)
  358. """Uppercase the current (or following) word. With a negative
  359. argument, uppercase the previous word, but do not move the cursor."""
  360. self.l_buffer.upcase_word()
  361. self.finalize()
  362. def downcase_word(self, e): # (M-l)
  363. """Lowercase the current (or following) word. With a negative
  364. argument, lowercase the previous word, but do not move the cursor."""
  365. self.l_buffer.downcase_word()
  366. self.finalize()
  367. def capitalize_word(self, e): # (M-c)
  368. """Capitalize the current (or following) word. With a negative
  369. argument, capitalize the previous word, but do not move the cursor."""
  370. self.l_buffer.capitalize_word()
  371. self.finalize()
  372. # #######
  373. def clear_screen(self, e): # (C-l)
  374. """Clear the screen and redraw the current line, leaving the current
  375. line at the top of the screen."""
  376. self.console.page()
  377. self.finalize()
  378. def redraw_current_line(self, e): # ()
  379. """Refresh the current line. By default, this is unbound."""
  380. self.finalize()
  381. def accept_line(self, e): # (Newline or Return)
  382. """Accept the line regardless of where the cursor is. If this line
  383. is non-empty, it may be added to the history list for future recall
  384. with add_history(). If this line is a modified history line, the
  385. history line is restored to its original state."""
  386. self.finalize()
  387. return True
  388. def delete_char(self, e): # (C-d)
  389. """Delete the character at point. If point is at the beginning of
  390. the line, there are no characters in the line, and the last
  391. character typed was not bound to delete-char, then return EOF."""
  392. self.l_buffer.delete_char(self.argument_reset)
  393. self.finalize()
  394. def backward_delete_char(self, e): # (Rubout)
  395. """Delete the character behind the cursor. A numeric argument means
  396. to kill the characters instead of deleting them."""
  397. self.l_buffer.backward_delete_char(self.argument_reset)
  398. self.finalize()
  399. def backward_delete_word(self, e): # (Control-Rubout)
  400. """Delete the character behind the cursor. A numeric argument means
  401. to kill the characters instead of deleting them."""
  402. self.l_buffer.backward_delete_word(self.argument_reset)
  403. self.finalize()
  404. def forward_delete_word(self, e): # (Control-Delete)
  405. """Delete the character behind the cursor. A numeric argument means
  406. to kill the characters instead of deleting them."""
  407. self.l_buffer.forward_delete_word(self.argument_reset)
  408. self.finalize()
  409. def delete_horizontal_space(self, e): # ()
  410. """Delete all spaces and tabs around point. By default, this is unbound."""
  411. self.l_buffer.delete_horizontal_space()
  412. self.finalize()
  413. def self_insert(self, e): # (a, b, A, 1, !, ...)
  414. """Insert yourself."""
  415. if (
  416. e.char and ord(e.char) != 0
  417. ): # don't insert null character in buffer, can happen with dead keys.
  418. self.insert_text(e.char)
  419. self.finalize()
  420. # Paste from clipboard
  421. def paste(self, e):
  422. """Paste windows clipboard.
  423. Assume single line strip other lines and end of line markers and trailing spaces
  424. """ # (Control-v)
  425. if self.enable_win32_clipboard:
  426. txt = clipboard.get_clipboard_text_and_convert(False)
  427. txt = txt.split("\n")[0].strip("\r").strip("\n")
  428. log("paste: >%s<" % list(map(ord, txt)))
  429. self.insert_text(txt)
  430. self.finalize()
  431. def paste_mulitline_code(self, e):
  432. """Paste windows clipboard as multiline code.
  433. Removes any empty lines in the code"""
  434. reg = re.compile("\r?\n")
  435. if self.enable_win32_clipboard:
  436. txt = clipboard.get_clipboard_text_and_convert(False)
  437. t = reg.split(txt)
  438. t = [row for row in t if row.strip() != ""] # remove empty lines
  439. if t != [""]:
  440. self.insert_text(t[0])
  441. self.add_history(self.l_buffer.copy())
  442. self.paste_line_buffer = t[1:]
  443. log("multi: >%s<" % self.paste_line_buffer)
  444. return True
  445. else:
  446. return False
  447. self.finalize()
  448. def ipython_paste(self, e):
  449. """Paste windows clipboard. If enable_ipython_paste_list_of_lists is
  450. True then try to convert tabseparated data to repr of list of lists or
  451. repr of array.
  452. If enable_ipython_paste_for_paths==True then change \\ to / and spaces
  453. to \\space"""
  454. if self.enable_win32_clipboard:
  455. txt = clipboard.get_clipboard_text_and_convert(
  456. self.enable_ipython_paste_list_of_lists
  457. )
  458. if self.enable_ipython_paste_for_paths:
  459. if len(txt) < 300 and ("\t" not in txt) and ("\n" not in txt):
  460. txt = txt.replace("\\", "/").replace(" ", r"\ ")
  461. self.insert_text(txt)
  462. self.finalize()
  463. def copy_region_to_clipboard(self, e): # ()
  464. """Copy the text in the region to the windows clipboard."""
  465. self.l_buffer.copy_region_to_clipboard()
  466. self.finalize()
  467. def copy_selection_to_clipboard(self, e): # ()
  468. """Copy the text in the region to the windows clipboard."""
  469. self.l_buffer.copy_selection_to_clipboard()
  470. self.finalize()
  471. def cut_selection_to_clipboard(self, e): # ()
  472. """Copy the text in the region to the windows clipboard."""
  473. self.l_buffer.cut_selection_to_clipboard()
  474. self.finalize()
  475. def dump_functions(self, e): # ()
  476. """Print all of the functions and their key bindings to the Readline
  477. output stream. If a numeric argument is supplied, the output is
  478. formatted in such a way that it can be made part of an inputrc
  479. file. This command is unbound by default."""
  480. print()
  481. txt = "\n".join(self.rl_settings_to_string())
  482. print(txt)
  483. self._print_prompt()
  484. self.finalize()
  485. def commonprefix(m):
  486. "Given a list of pathnames, returns the longest common leading component"
  487. if not m:
  488. return ""
  489. prefix = m[0]
  490. for item in m:
  491. for i in range(len(prefix)):
  492. if prefix[: i + 1].lower() != item[: i + 1].lower():
  493. prefix = prefix[:i]
  494. if i == 0:
  495. return ""
  496. break
  497. return prefix