m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

603 lines
24 KiB

6 months ago
  1. # -*- coding: utf-8 -*-
  2. #*****************************************************************************
  3. # Copyright (C) 2003-2006 Gary Bishop.
  4. # Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
  5. #
  6. # Distributed under the terms of the BSD License. The full license is in
  7. # the file COPYING, distributed as part of this software.
  8. #*****************************************************************************
  9. from __future__ import print_function, unicode_literals, absolute_import
  10. import os
  11. import pyreadline.logger as logger
  12. from pyreadline.logger import log
  13. import pyreadline.lineeditor.lineobj as lineobj
  14. import pyreadline.lineeditor.history as history
  15. from . import basemode
  16. class NotEmacsMode(basemode.BaseMode):
  17. mode="notemacs"
  18. def __init__(self,rlobj):
  19. super(NotEmacsMode,self).__init__(rlobj)
  20. def __repr__(self):
  21. return "<NotEmacsMode>"
  22. def _readline_from_keyboard(self):
  23. c=self.console
  24. while 1:
  25. self._update_line()
  26. event = c.getkeypress()
  27. if self.next_meta:
  28. self.next_meta = False
  29. control, meta, shift, code = event.keyinfo
  30. event.keyinfo = (control, True, shift, code)
  31. #Process exit keys. Only exit on empty line
  32. if event.keyinfo in self.exit_dispatch:
  33. if lineobj.EndOfLine(self.l_buffer) == 0:
  34. raise EOFError
  35. dispatch_func = self.key_dispatch.get(event.keyinfo,self.self_insert)
  36. log("readline from keyboard:%s"%(event.keyinfo,))
  37. r = None
  38. if dispatch_func:
  39. r = dispatch_func(event)
  40. self.l_buffer.push_undo()
  41. self.previous_func = dispatch_func
  42. if r:
  43. self._update_line()
  44. break
  45. def readline(self, prompt=''):
  46. '''Try to act like GNU readline.'''
  47. # handle startup_hook
  48. if self.first_prompt:
  49. self.first_prompt = False
  50. if self.startup_hook:
  51. try:
  52. self.startup_hook()
  53. except:
  54. print('startup hook failed')
  55. traceback.print_exc()
  56. c = self.console
  57. self.l_buffer.reset_line()
  58. self.prompt = prompt
  59. self._print_prompt()
  60. if self.pre_input_hook:
  61. try:
  62. self.pre_input_hook()
  63. except:
  64. print('pre_input_hook failed')
  65. traceback.print_exc()
  66. self.pre_input_hook = None
  67. log("in readline: %s"%self.paste_line_buffer)
  68. if len(self.paste_line_buffer)>0:
  69. self.l_buffer=lineobj.ReadlineTextBuffer(self.paste_line_buffer[0])
  70. self._update_line()
  71. self.paste_line_buffer=self.paste_line_buffer[1:]
  72. c.write('\r\n')
  73. else:
  74. self._readline_from_keyboard()
  75. c.write('\r\n')
  76. self.add_history(self.l_buffer.copy())
  77. log('returning(%s)' % self.l_buffer.get_line_text())
  78. return self.l_buffer.get_line_text() + '\n'
  79. ### Methods below here are bindable emacs functions
  80. def beginning_of_line(self, e): # (C-a)
  81. '''Move to the start of the current line. '''
  82. self.l_buffer.beginning_of_line()
  83. def end_of_line(self, e): # (C-e)
  84. '''Move to the end of the line. '''
  85. self.l_buffer.end_of_line()
  86. def forward_char(self, e): # (C-f)
  87. '''Move forward a character. '''
  88. self.l_buffer.forward_char()
  89. def backward_char(self, e): # (C-b)
  90. '''Move back a character. '''
  91. self.l_buffer.backward_char()
  92. def forward_word(self, e): # (M-f)
  93. '''Move forward to the end of the next word. Words are composed of
  94. letters and digits.'''
  95. self.l_buffer.forward_word()
  96. def backward_word(self, e): # (M-b)
  97. '''Move back to the start of the current or previous word. Words are
  98. composed of letters and digits.'''
  99. self.l_buffer.backward_word()
  100. def clear_screen(self, e): # (C-l)
  101. '''Clear the screen and redraw the current line, leaving the current
  102. line at the top of the screen.'''
  103. self.console.page()
  104. def redraw_current_line(self, e): # ()
  105. '''Refresh the current line. By default, this is unbound.'''
  106. pass
  107. def accept_line(self, e): # (Newline or Return)
  108. '''Accept the line regardless of where the cursor is. If this line
  109. is non-empty, it may be added to the history list for future recall
  110. with add_history(). If this line is a modified history line, the
  111. history line is restored to its original state.'''
  112. return True
  113. ######### History commands
  114. def previous_history(self, e): # (C-p)
  115. '''Move back through the history list, fetching the previous command. '''
  116. self._history.previous_history(self.l_buffer)
  117. def next_history(self, e): # (C-n)
  118. '''Move forward through the history list, fetching the next command. '''
  119. self._history.next_history(self.l_buffer)
  120. def beginning_of_history(self, e): # (M-<)
  121. '''Move to the first line in the history.'''
  122. self._history.beginning_of_history()
  123. def end_of_history(self, e): # (M->)
  124. '''Move to the end of the input history, i.e., the line currently
  125. being entered.'''
  126. self._history.end_of_history(self.l_buffer)
  127. def _i_search(self, searchfun, direction, init_event):
  128. c = self.console
  129. line = self.get_line_buffer()
  130. query = ''
  131. hc_start = self._history.history_cursor #+ direction
  132. while 1:
  133. x, y = self.prompt_end_pos
  134. c.pos(0, y)
  135. if direction < 0:
  136. prompt = 'reverse-i-search'
  137. else:
  138. prompt = 'forward-i-search'
  139. scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line))
  140. self._update_prompt_pos(scroll)
  141. self._clear_after()
  142. event = c.getkeypress()
  143. if event.keysym == 'BackSpace':
  144. if len(query) > 0:
  145. query = query[:-1]
  146. self._history.history_cursor = hc_start
  147. else:
  148. self._bell()
  149. elif event.char in string.letters + string.digits + string.punctuation + ' ':
  150. self._history.history_cursor = hc_start
  151. query += event.char
  152. elif event.keyinfo == init_event.keyinfo:
  153. self._history.history_cursor += direction
  154. line=searchfun(query)
  155. pass
  156. else:
  157. if event.keysym != 'Return':
  158. self._bell()
  159. break
  160. line=searchfun(query)
  161. px, py = self.prompt_begin_pos
  162. c.pos(0, py)
  163. self.l_buffer.set_line(line)
  164. self._print_prompt()
  165. self._history.history_cursor=len(self._history.history)
  166. def reverse_search_history(self, e): # (C-r)
  167. '''Search backward starting at the current line and moving up
  168. through the history as necessary. This is an incremental search.'''
  169. # print("HEJ")
  170. # self.console.bell()
  171. self._i_search(self._history.reverse_search_history, -1, e)
  172. def forward_search_history(self, e): # (C-s)
  173. '''Search forward starting at the current line and moving down
  174. through the the history as necessary. This is an incremental search.'''
  175. # print("HEJ")
  176. # self.console.bell()
  177. self._i_search(self._history.forward_search_history, 1, e)
  178. def non_incremental_reverse_search_history(self, e): # (M-p)
  179. '''Search backward starting at the current line and moving up
  180. through the history as necessary using a non-incremental search for
  181. a string supplied by the user.'''
  182. self._history.non_incremental_reverse_search_history(self.l_buffer)
  183. def non_incremental_forward_search_history(self, e): # (M-n)
  184. '''Search forward starting at the current line and moving down
  185. through the the history as necessary using a non-incremental search
  186. for a string supplied by the user.'''
  187. self._history.non_incremental_reverse_search_history(self.l_buffer)
  188. def history_search_forward(self, e): # ()
  189. '''Search forward through the history for the string of characters
  190. between the start of the current line and the point. This is a
  191. non-incremental search. By default, this command is unbound.'''
  192. self.l_buffer=self._history.history_search_forward(self.l_buffer)
  193. def history_search_backward(self, e): # ()
  194. '''Search backward through the history for the string of characters
  195. between the start of the current line and the point. This is a
  196. non-incremental search. By default, this command is unbound.'''
  197. self.l_buffer=self._history.history_search_backward(self.l_buffer)
  198. def yank_nth_arg(self, e): # (M-C-y)
  199. '''Insert the first argument to the previous command (usually the
  200. second word on the previous line) at point. With an argument n,
  201. insert the nth word from the previous command (the words in the
  202. previous command begin with word 0). A negative argument inserts the
  203. nth word from the end of the previous command.'''
  204. pass
  205. def yank_last_arg(self, e): # (M-. or M-_)
  206. '''Insert last argument to the previous command (the last word of
  207. the previous history entry). With an argument, behave exactly like
  208. yank-nth-arg. Successive calls to yank-last-arg move back through
  209. the history list, inserting the last argument of each line in turn.'''
  210. pass
  211. def delete_char(self, e): # (C-d)
  212. '''Delete the character at point. If point is at the beginning of
  213. the line, there are no characters in the line, and the last
  214. character typed was not bound to delete-char, then return EOF.'''
  215. self.l_buffer.delete_char()
  216. def backward_delete_char(self, e): # (Rubout)
  217. '''Delete the character behind the cursor. A numeric argument means
  218. to kill the characters instead of deleting them.'''
  219. self.l_buffer.backward_delete_char()
  220. def forward_backward_delete_char(self, e): # ()
  221. '''Delete the character under the cursor, unless the cursor is at
  222. the end of the line, in which case the character behind the cursor
  223. is deleted. By default, this is not bound to a key.'''
  224. pass
  225. def quoted_insert(self, e): # (C-q or C-v)
  226. '''Add the next character typed to the line verbatim. This is how to
  227. insert key sequences like C-q, for example.'''
  228. e = self.console.getkeypress()
  229. self.insert_text(e.char)
  230. def tab_insert(self, e): # (M-TAB)
  231. '''Insert a tab character. '''
  232. cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
  233. ws = ' ' * (self.tabstop - (cursor % self.tabstop))
  234. self.insert_text(ws)
  235. def self_insert(self, e): # (a, b, A, 1, !, ...)
  236. '''Insert yourself. '''
  237. if ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys.
  238. self.insert_text(e.char)
  239. def transpose_chars(self, e): # (C-t)
  240. '''Drag the character before the cursor forward over the character
  241. at the cursor, moving the cursor forward as well. If the insertion
  242. point is at the end of the line, then this transposes the last two
  243. characters of the line. Negative arguments have no effect.'''
  244. self.l_buffer.transpose_chars()
  245. def transpose_words(self, e): # (M-t)
  246. '''Drag the word before point past the word after point, moving
  247. point past that word as well. If the insertion point is at the end
  248. of the line, this transposes the last two words on the line.'''
  249. self.l_buffer.transpose_words()
  250. def upcase_word(self, e): # (M-u)
  251. '''Uppercase the current (or following) word. With a negative
  252. argument, uppercase the previous word, but do not move the cursor.'''
  253. self.l_buffer.upcase_word()
  254. def downcase_word(self, e): # (M-l)
  255. '''Lowercase the current (or following) word. With a negative
  256. argument, lowercase the previous word, but do not move the cursor.'''
  257. self.l_buffer.downcase_word()
  258. def capitalize_word(self, e): # (M-c)
  259. '''Capitalize the current (or following) word. With a negative
  260. argument, capitalize the previous word, but do not move the cursor.'''
  261. self.l_buffer.capitalize_word()
  262. def overwrite_mode(self, e): # ()
  263. '''Toggle overwrite mode. With an explicit positive numeric
  264. argument, switches to overwrite mode. With an explicit non-positive
  265. numeric argument, switches to insert mode. This command affects only
  266. emacs mode; vi mode does overwrite differently. Each call to
  267. readline() starts in insert mode. In overwrite mode, characters
  268. bound to self-insert replace the text at point rather than pushing
  269. the text to the right. Characters bound to backward-delete-char
  270. replace the character before point with a space.'''
  271. pass
  272. def kill_line(self, e): # (C-k)
  273. '''Kill the text from point to the end of the line. '''
  274. self.l_buffer.kill_line()
  275. def backward_kill_line(self, e): # (C-x Rubout)
  276. '''Kill backward to the beginning of the line. '''
  277. self.l_buffer.backward_kill_line()
  278. def unix_line_discard(self, e): # (C-u)
  279. '''Kill backward from the cursor to the beginning of the current line. '''
  280. # how is this different from backward_kill_line?
  281. self.l_buffer.unix_line_discard()
  282. def kill_whole_line(self, e): # ()
  283. '''Kill all characters on the current line, no matter where point
  284. is. By default, this is unbound.'''
  285. self.l_buffer.kill_whole_line()
  286. def kill_word(self, e): # (M-d)
  287. '''Kill from point to the end of the current word, or if between
  288. words, to the end of the next word. Word boundaries are the same as
  289. forward-word.'''
  290. self.l_buffer.kill_word()
  291. def backward_kill_word(self, e): # (M-DEL)
  292. '''Kill the word behind point. Word boundaries are the same as
  293. backward-word. '''
  294. self.l_buffer.backward_kill_word()
  295. def unix_word_rubout(self, e): # (C-w)
  296. '''Kill the word behind point, using white space as a word
  297. boundary. The killed text is saved on the kill-ring.'''
  298. self.l_buffer.unix_word_rubout()
  299. def delete_horizontal_space(self, e): # ()
  300. '''Delete all spaces and tabs around point. By default, this is unbound. '''
  301. pass
  302. def kill_region(self, e): # ()
  303. '''Kill the text in the current region. By default, this command is unbound. '''
  304. pass
  305. def copy_region_as_kill(self, e): # ()
  306. '''Copy the text in the region to the kill buffer, so it can be
  307. yanked right away. By default, this command is unbound.'''
  308. pass
  309. def copy_region_to_clipboard(self, e): # ()
  310. '''Copy the text in the region to the windows clipboard.'''
  311. if self.enable_win32_clipboard:
  312. mark=min(self.l_buffer.mark,len(self.l_buffer.line_buffer))
  313. cursor=min(self.l_buffer.point,len(self.l_buffer.line_buffer))
  314. if self.l_buffer.mark==-1:
  315. return
  316. begin=min(cursor,mark)
  317. end=max(cursor,mark)
  318. toclipboard="".join(self.l_buffer.line_buffer[begin:end])
  319. clipboard.SetClipboardText(str(toclipboard))
  320. def copy_backward_word(self, e): # ()
  321. '''Copy the word before point to the kill buffer. The word
  322. boundaries are the same as backward-word. By default, this command
  323. is unbound.'''
  324. pass
  325. def copy_forward_word(self, e): # ()
  326. '''Copy the word following point to the kill buffer. The word
  327. boundaries are the same as forward-word. By default, this command is
  328. unbound.'''
  329. pass
  330. def paste(self,e):
  331. '''Paste windows clipboard'''
  332. if self.enable_win32_clipboard:
  333. txt=clipboard.get_clipboard_text_and_convert(False)
  334. self.insert_text(txt)
  335. def paste_mulitline_code(self,e):
  336. '''Paste windows clipboard'''
  337. reg=re.compile("\r?\n")
  338. if self.enable_win32_clipboard:
  339. txt=clipboard.get_clipboard_text_and_convert(False)
  340. t=reg.split(txt)
  341. t=[row for row in t if row.strip()!=""] #remove empty lines
  342. if t!=[""]:
  343. self.insert_text(t[0])
  344. self.add_history(self.l_buffer.copy())
  345. self.paste_line_buffer=t[1:]
  346. log("multi: %s"%self.paste_line_buffer)
  347. return True
  348. else:
  349. return False
  350. def ipython_paste(self,e):
  351. '''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
  352. True then try to convert tabseparated data to repr of list of lists or
  353. repr of array'''
  354. if self.enable_win32_clipboard:
  355. txt=clipboard.get_clipboard_text_and_convert(
  356. self.enable_ipython_paste_list_of_lists)
  357. if self.enable_ipython_paste_for_paths:
  358. if len(txt)<300 and ("\t" not in txt) and ("\n" not in txt):
  359. txt=txt.replace("\\", "/").replace(" ", r"\ ")
  360. self.insert_text(txt)
  361. def yank(self, e): # (C-y)
  362. '''Yank the top of the kill ring into the buffer at point. '''
  363. pass
  364. def yank_pop(self, e): # (M-y)
  365. '''Rotate the kill-ring, and yank the new top. You can only do this
  366. if the prior command is yank or yank-pop.'''
  367. pass
  368. def digit_argument(self, e): # (M-0, M-1, ... M--)
  369. '''Add this digit to the argument already accumulating, or start a
  370. new argument. M-- starts a negative argument.'''
  371. pass
  372. def universal_argument(self, e): # ()
  373. '''This is another way to specify an argument. If this command is
  374. followed by one or more digits, optionally with a leading minus
  375. sign, those digits define the argument. If the command is followed
  376. by digits, executing universal-argument again ends the numeric
  377. argument, but is otherwise ignored. As a special case, if this
  378. command is immediately followed by a character that is neither a
  379. digit or minus sign, the argument count for the next command is
  380. multiplied by four. The argument count is initially one, so
  381. executing this function the first time makes the argument count
  382. four, a second time makes the argument count sixteen, and so on. By
  383. default, this is not bound to a key.'''
  384. pass
  385. def delete_char_or_list(self, e): # ()
  386. '''Deletes the character under the cursor if not at the beginning or
  387. end of the line (like delete-char). If at the end of the line,
  388. behaves identically to possible-completions. This command is unbound
  389. by default.'''
  390. pass
  391. def start_kbd_macro(self, e): # (C-x ()
  392. '''Begin saving the characters typed into the current keyboard macro. '''
  393. pass
  394. def end_kbd_macro(self, e): # (C-x ))
  395. '''Stop saving the characters typed into the current keyboard macro
  396. and save the definition.'''
  397. pass
  398. def call_last_kbd_macro(self, e): # (C-x e)
  399. '''Re-execute the last keyboard macro defined, by making the
  400. characters in the macro appear as if typed at the keyboard.'''
  401. pass
  402. def re_read_init_file(self, e): # (C-x C-r)
  403. '''Read in the contents of the inputrc file, and incorporate any
  404. bindings or variable assignments found there.'''
  405. pass
  406. def abort(self, e): # (C-g)
  407. '''Abort the current editing command and ring the terminals bell
  408. (subject to the setting of bell-style).'''
  409. self._bell()
  410. def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
  411. '''If the metafied character x is lowercase, run the command that is
  412. bound to the corresponding uppercase character.'''
  413. pass
  414. def prefix_meta(self, e): # (ESC)
  415. '''Metafy the next character typed. This is for keyboards without a
  416. meta key. Typing ESC f is equivalent to typing M-f. '''
  417. self.next_meta = True
  418. def undo(self, e): # (C-_ or C-x C-u)
  419. '''Incremental undo, separately remembered for each line.'''
  420. self.l_buffer.pop_undo()
  421. def revert_line(self, e): # (M-r)
  422. '''Undo all changes made to this line. This is like executing the
  423. undo command enough times to get back to the beginning.'''
  424. pass
  425. def tilde_expand(self, e): # (M-~)
  426. '''Perform tilde expansion on the current word.'''
  427. pass
  428. def set_mark(self, e): # (C-@)
  429. '''Set the mark to the point. If a numeric argument is supplied, the
  430. mark is set to that position.'''
  431. self.l_buffer.set_mark()
  432. def exchange_point_and_mark(self, e): # (C-x C-x)
  433. '''Swap the point with the mark. The current cursor position is set
  434. to the saved position, and the old cursor position is saved as the
  435. mark.'''
  436. pass
  437. def character_search(self, e): # (C-])
  438. '''A character is read and point is moved to the next occurrence of
  439. that character. A negative count searches for previous occurrences.'''
  440. pass
  441. def character_search_backward(self, e): # (M-C-])
  442. '''A character is read and point is moved to the previous occurrence
  443. of that character. A negative count searches for subsequent
  444. occurrences.'''
  445. pass
  446. def insert_comment(self, e): # (M-#)
  447. '''Without a numeric argument, the value of the comment-begin
  448. variable is inserted at the beginning of the current line. If a
  449. numeric argument is supplied, this command acts as a toggle: if the
  450. characters at the beginning of the line do not match the value of
  451. comment-begin, the value is inserted, otherwise the characters in
  452. comment-begin are deleted from the beginning of the line. In either
  453. case, the line is accepted as if a newline had been typed.'''
  454. pass
  455. def dump_functions(self, e): # ()
  456. '''Print all of the functions and their key bindings to the Readline
  457. output stream. If a numeric argument is supplied, the output is
  458. formatted in such a way that it can be made part of an inputrc
  459. file. This command is unbound by default.'''
  460. pass
  461. def dump_variables(self, e): # ()
  462. '''Print all of the settable variables and their values to the
  463. Readline output stream. If a numeric argument is supplied, the
  464. output is formatted in such a way that it can be made part of an
  465. inputrc file. This command is unbound by default.'''
  466. pass
  467. def dump_macros(self, e): # ()
  468. '''Print all of the Readline key sequences bound to macros and the
  469. strings they output. If a numeric argument is supplied, the output
  470. is formatted in such a way that it can be made part of an inputrc
  471. file. This command is unbound by default.'''
  472. pass
  473. #Create key bindings:
  474. def init_editing_mode(self, e): # (C-e)
  475. '''When in vi command mode, this causes a switch to emacs editing
  476. mode.'''
  477. self._bind_exit_key('Control-d')
  478. self._bind_exit_key('Control-z')
  479. # I often accidentally hold the shift or control while typing space
  480. self._bind_key('Shift-space', self.self_insert)
  481. self._bind_key('Control-space', self.self_insert)
  482. self._bind_key('Return', self.accept_line)
  483. self._bind_key('Left', self.backward_char)
  484. self._bind_key('Control-b', self.backward_char)
  485. self._bind_key('Right', self.forward_char)
  486. self._bind_key('Control-f', self.forward_char)
  487. self._bind_key('BackSpace', self.backward_delete_char)
  488. self._bind_key('Home', self.beginning_of_line)
  489. self._bind_key('End', self.end_of_line)
  490. self._bind_key('Delete', self.delete_char)
  491. self._bind_key('Control-d', self.delete_char)
  492. self._bind_key('Clear', self.clear_screen)
  493. # make it case insensitive
  494. def commonprefix(m):
  495. "Given a list of pathnames, returns the longest common leading component"
  496. if not m: return ''
  497. prefix = m[0]
  498. for item in m:
  499. for i in range(len(prefix)):
  500. if prefix[:i+1].lower() != item[:i+1].lower():
  501. prefix = prefix[:i]
  502. if i == 0: return ''
  503. break
  504. return prefix