From 5ff848f7ec0ccba1aaa62f1c7af6fa52a1528a08 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 20:19:06 +0200 Subject: [PATCH 01/26] started refactor to reduce coupling between classes to enable easier reuse in GUIs. moved readline from modes.emacs to modes.basemode created process_keyevent in modes.emacs to process each keypress from a keyevent --- pyreadline/modes/basemode.py | 72 ++++++++++++++++++- pyreadline/modes/emacs.py | 130 ++++++++++------------------------- 2 files changed, 105 insertions(+), 97 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 1d4ff64..3d4e857 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -6,7 +6,7 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -import os,re,math,glob,sys +import os,re,math,glob,sys,time import pyreadline.logger as logger from pyreadline.logger import log,log_sock from pyreadline.keysyms.common import make_KeyPress_from_keydescr @@ -87,7 +87,75 @@ class BaseMode(object): raise NotImplementedError def readline(self, prompt=''): - raise NotImplementedError + '''Try to act like GNU readline.''' + # handle startup_hook + self.ctrl_c_timeout=time.time() + self.l_buffer.selection_mark=-1 + if self.first_prompt: + self.first_prompt = False + if self.startup_hook: + try: + self.startup_hook() + except: + print 'startup hook failed' + traceback.print_exc() + + c = self.console + self.l_buffer.reset_line() + self.prompt = prompt + self._print_prompt() + + if self.pre_input_hook: + try: + self.pre_input_hook() + except: + print 'pre_input_hook failed' + traceback.print_exc() + self.pre_input_hook = None + + log("in readline: %s"%self.paste_line_buffer) + if len(self.paste_line_buffer)>0: + self.l_buffer=lineobj.ReadLineTextBuffer(self.paste_line_buffer[0]) + self._update_line() + self.paste_line_buffer=self.paste_line_buffer[1:] + c.write('\r\n') + else: + while 1: + self._update_line() + lbuf=self.l_buffer + log_sock("point:%d mark:%d selection_mark:%d"%(lbuf.point,lbuf.mark,lbuf.selection_mark)) + try: + event = c.getkeypress() + log_sock(u">>%s"%event) + except KeyboardInterrupt: + from pyreadline.keysyms.common import KeyPress + from pyreadline.console.event import Event + event=Event(0,0) + event.char="c" + event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) + log_sock("KBDIRQ") + if self.allow_ctrl_c: + now=time.time() + if (now-self.ctrl_c_timeout)" def add_key_logger(self,logfun): """logfun should be function that takes disp_fun and line_buffer object """ self._keylog=logfun - - def _readline_from_keyboard(self): - c=self.console + + def _process_keyevent(self, keyinfo): + """return True when line is final + """ + #Process exit keys. Only exit on empty line def nop(e): pass - while 1: - self._update_line() - lbuf=self.l_buffer - log_sock("point:%d mark:%d selection_mark:%d"%(lbuf.point,lbuf.mark,lbuf.selection_mark)) - try: - event = c.getkeypress() - log_sock(u">>%s"%event) - except KeyboardInterrupt: - from pyreadline.keysyms.common import KeyPress - from pyreadline.console.event import Event - event=Event(0,0) - event.char="c" - event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) - log_sock("KBDIRQ") - if self.allow_ctrl_c: - now=time.time() - if (now-self.ctrl_c_timeout)1: - default=nop - else: - default=self.self_insert - dispatch_func = self.key_dispatch.get(keyinfo,default) - - log("readline from keyboard:%s,%s"%(keyinfo,dispatch_func)) - log_sock((u"%s|%s"%(ensure_unicode(format(keyinfo)),dispatch_func.__name__)),"bound_function") - r = None - if dispatch_func: - r = dispatch_func(event) - self._keylog(dispatch_func,self.l_buffer) - self.l_buffer.push_undo() - - self.previous_func = dispatch_func - if r: - self._update_line() - break - - def readline(self, prompt=''): - '''Try to act like GNU readline.''' - # handle startup_hook - self.ctrl_c_timeout=time.time() - self.l_buffer.selection_mark=-1 - if self.first_prompt: - self.first_prompt = False - if self.startup_hook: - try: - self.startup_hook() - except: - print 'startup hook failed' - traceback.print_exc() - - c = self.console - self.l_buffer.reset_line() - self.prompt = prompt - self._print_prompt() - - if self.pre_input_hook: - try: - self.pre_input_hook() - except: - print 'pre_input_hook failed' - traceback.print_exc() - self.pre_input_hook = None - - log("in readline: %s"%self.paste_line_buffer) - if len(self.paste_line_buffer)>0: - self.l_buffer=lineobj.ReadLineTextBuffer(self.paste_line_buffer[0]) - self._update_line() - self.paste_line_buffer=self.paste_line_buffer[1:] - c.write('\r\n') + keytuple=keyinfo.tuple() + + if self._insert_verbatim: + self.insert_text(keyinfo) + self._insert_verbatim=False + return False + + if keytuple in self.exit_dispatch: + if lineobj.EndOfLine(self.l_buffer) == 0: + raise EOFError + if keyinfo.keyname: + default=nop else: - self._readline_from_keyboard() - c.write('\r\n') + default=self.self_insert + dispatch_func = self.key_dispatch.get(keytuple, default) - self.add_history(self.l_buffer.copy()) + log("readline from keyboard:%s,%s"%(keytuple, dispatch_func)) + log_sock((u"%s|%s"%(ensure_unicode(format(keytuple)),dispatch_func.__name__)),"bound_function") + r = None + if dispatch_func: + r = dispatch_func(keyinfo) + self._keylog(dispatch_func,self.l_buffer) + self.l_buffer.push_undo() + + self.previous_func = dispatch_func + if r: + self._update_line() + return True + return False - log('returning(%s)' % self.l_buffer.get_line_text()) - return self.l_buffer.get_line_text() + '\n' ######### History commands def previous_history(self, e): # (C-p) @@ -278,8 +219,7 @@ class EmacsMode(basemode.BaseMode): def quoted_insert(self, e): # (C-q or C-v) '''Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example.''' - e = self.console.getkeypress() - self.insert_text(e.char) + self._insert_verbatim=True def tab_insert(self, e): # (M-TAB) '''Insert a tab character. ''' From cc1073613b94251d596fedba5588a9e8b69b9923 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 20:22:36 +0200 Subject: [PATCH 02/26] made changes after starting last commit --- pyreadline/modes/basemode.py | 2 +- pyreadline/modes/emacs.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 3d4e857..4257624 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -147,7 +147,7 @@ class BaseMode(object): self.next_meta = False control, meta, shift, code = event.keyinfo event.keyinfo = (control, True, shift, code) - if self._process_keyevent(event.keyinfo): + if self.process_keyevent(event.keyinfo): break c.write('\r\n') diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index f9ac178..f34d784 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -42,7 +42,7 @@ class EmacsMode(basemode.BaseMode): """logfun should be function that takes disp_fun and line_buffer object """ self._keylog=logfun - def _process_keyevent(self, keyinfo): + def process_keyevent(self, keyinfo): """return True when line is final """ #Process exit keys. Only exit on empty line From 114163c2c2a7a1869e104dd65865ec6fad99363f Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 20:41:22 +0200 Subject: [PATCH 03/26] change vi mode to use process_keyevent and the default readline method from modes.basemode --- pyreadline/modes/emacs.py | 4 +- pyreadline/modes/vi.py | 88 ++++++++++----------------------------- 2 files changed, 24 insertions(+), 68 deletions(-) diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index f34d784..a153d80 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -34,7 +34,7 @@ class EmacsMode(basemode.BaseMode): self.previous_func=None self.prompt=">>>" self._insert_verbatim=False - + def __repr__(self): return "" @@ -56,6 +56,7 @@ class EmacsMode(basemode.BaseMode): return False if keytuple in self.exit_dispatch: + log_sock("exit_dispatch:%s, %s"%(self.l_buffer,lineobj.EndOfLine(self.l_buffer))) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError if keyinfo.keyname: @@ -78,7 +79,6 @@ class EmacsMode(basemode.BaseMode): return True return False - ######### History commands def previous_history(self, e): # (C-p) '''Move back through the history list, fetching the previous command. ''' diff --git a/pyreadline/modes/vi.py b/pyreadline/modes/vi.py index 5542fda..a8102ba 100644 --- a/pyreadline/modes/vi.py +++ b/pyreadline/modes/vi.py @@ -23,73 +23,29 @@ class ViMode(basemode.BaseMode): def __repr__(self): return "" - def _readline_from_keyboard(self): - c=self.console - while 1: + def process_keyevent(self, keyinfo): + def nop(e): + pass + keytuple=keyinfo.tuple() + + #Process exit keys. Only exit on empty line + if keytuple in self.exit_dispatch: + if lineobj.EndOfLine(self.l_buffer) == 0: + raise EOFError + + dispatch_func = self.key_dispatch.get(keytuple,self.vi_key) + log("readline from keyboard:%s->%s"%(keytuple,dispatch_func)) + r = None + if dispatch_func: + r = dispatch_func(keyinfo) + self.l_buffer.push_undo() + + self.previous_func = dispatch_func + if r: self._update_line() - event = c.getkeypress() - if self.next_meta: - self.next_meta = False - control, meta, shift, code = event.keyinfo - event.keyinfo = (control, True, shift, code) - - #Process exit keys. Only exit on empty line - if event.keyinfo in self.exit_dispatch: - if lineobj.EndOfLine(self.l_buffer) == 0: - raise EOFError - - dispatch_func = self.key_dispatch.get(event.keyinfo.tuple(),self.vi_key) - log("readline from keyboard:%s->%s"%(event.keyinfo.tuple(),dispatch_func)) - r = None - if dispatch_func: - r = dispatch_func(event) - self.l_buffer.push_undo() - - self.previous_func = dispatch_func - if r: - self._update_line() - break - - def readline(self, prompt=''): - '''Try to act like GNU readline.''' - # handle startup_hook - if self.first_prompt: - self.first_prompt = False - if self.startup_hook: - try: - self.startup_hook() - except: - print 'startup hook failed' - traceback.print_exc() - - c = self.console - self.l_buffer.reset_line() - self.prompt = prompt - self._print_prompt() - - if self.pre_input_hook: - try: - self.pre_input_hook() - except: - print 'pre_input_hook failed' - traceback.print_exc() - self.pre_input_hook = None - - log("in readline: %s"%self.paste_line_buffer) - if len(self.paste_line_buffer)>0: - self.l_buffer=lineobj.ReadlineTextBuffer(self.paste_line_buffer[0]) - self._update_line() - self.paste_line_buffer=self.paste_line_buffer[1:] - c.write('\r\n') - else: - self._readline_from_keyboard() - c.write('\r\n') - - self.add_history(self.l_buffer.copy()) - - log('returning(%s)' % self.l_buffer.get_line_text()) - return self.l_buffer.get_line_text() + '\n' - + return True + return False + ### Methods below here are bindable emacs functions def init_editing_mode(self, e): # (M-C-j) From 9adf8f44931674a5038e885a9fc5b97a3ba33e4d Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 20:55:59 +0200 Subject: [PATCH 04/26] moved l_buffer and _history from ReadLine to modes.basemode --- pyreadline/modes/basemode.py | 7 +++++-- pyreadline/rlmain.py | 36 +++++++++++++++++++----------------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 4257624..1eb8e9e 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -25,6 +25,8 @@ class BaseMode(object): self.key_dispatch = {} self.argument=1 self.prevargument=None + self.l_buffer=lineobj.ReadLineTextBuffer("") + self._history=history.LineHistory() def __repr__(self): return "" @@ -47,9 +49,11 @@ class BaseMode(object): return val argument_reset=property(_argreset) +# _history=property(_g("_history")) +# l_buffer=property(*_gs("l_buffer")) + ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval")) allow_ctrl_c=property(*_gs("allow_ctrl_c")) - l_buffer=property(*_gs("l_buffer")) next_meta=property(*_gs("next_meta")) first_prompt=property(*_gs("first_prompt")) prompt=property(*_gs("prompt")) @@ -77,7 +81,6 @@ class BaseMode(object): enable_ipython_paste_list_of_lists=property(_g("enable_ipython_paste_list_of_lists")) enable_ipython_paste_for_paths=property(_g("enable_ipython_paste_for_paths")) _bell=property(_g("_bell")) - _history=property(_g("_history")) prompt_end_pos=property(_g("prompt_end_pos")) prompt_begin_pos=property(_g("prompt_begin_pos")) diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 7ca5705..54e43f8 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -66,8 +66,6 @@ class Readline(object): self.mark_directories = 'on' self.bell_style = 'none' self.mark=-1 - self.l_buffer=lineobj.ReadLineTextBuffer("") - self._history=history.LineHistory() # this code needs to follow l_buffer and history creation self.editingmodes=[mode(self) for mode in editingmodes] @@ -144,11 +142,11 @@ class Readline(object): def get_line_buffer(self): '''Return the current contents of the line buffer.''' - return self.l_buffer.get_line_text() + return self.l_buffer.mode.get_line_text() def insert_text(self, string): '''Insert text into the command line.''' - self.l_buffer.insert_text(string) + self.mode.l_buffer.insert_text(string) def read_init_file(self, filename=None): '''Parse a readline initialization file. The default filename is the last filename used.''' @@ -158,13 +156,13 @@ class Readline(object): def add_history(self, line): '''Append a line to the history buffer, as if it was the last line typed.''' - self._history.add_history(line) + self.mode._history.add_history(line) def get_history_length(self ): '''Return the desired length of the history file. Negative values imply unlimited history file size.''' - return self._history.get_history_length() + return self.mode._history.get_history_length() def set_history_length(self, length): '''Set the number of lines to save in the history file. @@ -172,19 +170,22 @@ class Readline(object): write_history_file() uses this value to truncate the history file when saving. Negative values imply unlimited history file size. ''' - self._history.set_history_length(length) + self.mode._history.set_history_length(length) def clear_history(self): '''Clear readline history''' - self._history.clear_history() + self.mode._history.clear_history() def read_history_file(self, filename=None): '''Load a readline history file. The default filename is ~/.history.''' - self._history.read_history_file(filename) + if filename is None: + filename=self.mode._history.history_filename + log_sock("read_history_file from %s"%filename) + self.mode._history.read_history_file(filename) def write_history_file(self, filename=None): '''Save a readline history file. The default filename is ~/.history.''' - self._history.write_history_file(filename) + self.mode._history.write_history_file(filename) #Completer functions @@ -285,7 +286,7 @@ class Readline(object): c = self.console xc, yc = self.prompt_end_pos w, h = c.size() - xc += self.l_buffer.visible_line_width() + xc += self.mode.l_buffer.visible_line_width() while(xc >= w): xc -= w yc += 1 @@ -309,12 +310,13 @@ class Readline(object): def _update_line(self): c=self.console + l_buffer=self.mode.l_buffer c.cursor(0) #Hide cursor avoiding flicking c.pos(*self.prompt_end_pos) - ltext = self.l_buffer.quoted_text() - if self.l_buffer.enable_selection and self.l_buffer.selection_mark>=0: - start=len(self.l_buffer[:self.l_buffer.selection_mark].quoted_text()) - stop=len(self.l_buffer[:self.l_buffer.point].quoted_text()) + ltext = l_buffer.quoted_text() + if l_buffer.enable_selection and l_buffer.selection_mark>=0: + start=len(l_buffer[:l_buffer.selection_mark].quoted_text()) + stop=len(l_buffer[:l_buffer.point].quoted_text()) if start>stop: stop,start=start,stop n = c.write_scrolling(ltext[:start], self.command_color) @@ -368,11 +370,11 @@ class Readline(object): import pyreadline.lineeditor.lineobj pyreadline.lineeditor.lineobj.kill_ring_to_clipboard=killring def sethistoryfilename(filename): - self._history.history_filename=os.path.expanduser(filename) + self.mode._history.history_filename=os.path.expanduser(filename) def setbellstyle(mode): self.bell_style=mode def sethistorylength(length): - self._history.history_length=int(length) + self.mode._history.history_length=int(length) def allow_ctrl_c(mode): log_sock("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) self.allow_ctrl_c=mode From 81e5edd031f494534186f85e9fa7d4c0be262cee Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 21:25:55 +0200 Subject: [PATCH 05/26] moving insert_text, add_history to basemode rearranging properties in basemode to sort them according to where they are used --- pyreadline/modes/basemode.py | 44 ++++++++++++++++++++++++------------ pyreadline/modes/emacs.py | 2 +- pyreadline/rlmain.py | 2 +- 3 files changed, 32 insertions(+), 16 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 1eb8e9e..e535c1f 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -52,39 +52,44 @@ class BaseMode(object): # _history=property(_g("_history")) # l_buffer=property(*_gs("l_buffer")) + +#used in readline ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval")) allow_ctrl_c=property(*_gs("allow_ctrl_c")) next_meta=property(*_gs("next_meta")) first_prompt=property(*_gs("first_prompt")) prompt=property(*_gs("prompt")) paste_line_buffer=property(*_gs("paste_line_buffer")) + startup_hook=property(*_gs("startup_hook")) + pre_input_hook=property(*_gs("pre_input_hook")) + _print_prompt=property(_g("_print_prompt")) + _update_line=property(_g("_update_line")) + console=property(_g("console")) + +#used in completer _completions completer_delims=property(*_gs("completer_delims")) show_all_if_ambiguous=property(*_gs("show_all_if_ambiguous")) mark_directories=property(*_gs("mark_directories")) completer=property(*_gs("completer")) begidx=property(*_gs("begidx")) - startup_hook=property(*_gs("startup_hook")) - pre_input_hook=property(*_gs("pre_input_hook")) endidx=property(*_gs("endidx")) - - console=property(_g("console")) - insert_text=property(_g("insert_text")) - _print_prompt=property(_g("_print_prompt")) - _update_line=property(_g("_update_line")) - add_history=property(_g("add_history")) _bell=property(_g("_bell")) + + rl_settings_to_string=property(_g("rl_settings_to_string")) + +#used in emacs _clear_after=property(_g("_clear_after")) - _set_cursor=property(_g("_set_cursor")) _update_prompt_pos=property(_g("_update_prompt_pos")) - _update_line=property(_g("_update_line")) + + enable_win32_clipboard=property(_g("enable_win32_clipboard")) enable_ipython_paste_list_of_lists=property(_g("enable_ipython_paste_list_of_lists")) enable_ipython_paste_for_paths=property(_g("enable_ipython_paste_for_paths")) - _bell=property(_g("_bell")) - prompt_end_pos=property(_g("prompt_end_pos")) - prompt_begin_pos=property(_g("prompt_begin_pos")) - rl_settings_to_string=property(_g("rl_settings_to_string")) + +#not used in basemode or emacs + + def _readline_from_keyboard(self): raise NotImplementedError @@ -160,6 +165,11 @@ class BaseMode(object): return self.l_buffer.get_line_text() + '\n' + + def add_history(self, text): + self._history.add_history(text) + + #Create key bindings: def _bind_key(self, key, func): @@ -306,6 +316,12 @@ class BaseMode(object): ### Methods below here are bindable emacs functions + + def insert_text(self, string): + '''Insert text into the command line.''' + self.l_buffer.insert_text(string) + + def beginning_of_line(self, e): # (C-a) '''Move to the start of the current line. ''' self.l_buffer.beginning_of_line() diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index a153d80..61be412 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -56,7 +56,7 @@ class EmacsMode(basemode.BaseMode): return False if keytuple in self.exit_dispatch: - log_sock("exit_dispatch:%s, %s"%(self.l_buffer,lineobj.EndOfLine(self.l_buffer))) + log_sock("exit_dispatch:%s, %s"%(self.l_buffer, lineobj.EndOfLine(self.l_buffer))) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError if keyinfo.keyname: diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 54e43f8..e05456a 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -146,7 +146,7 @@ class Readline(object): def insert_text(self, string): '''Insert text into the command line.''' - self.mode.l_buffer.insert_text(string) + self.mode.insert_text(string) def read_init_file(self, filename=None): '''Parse a readline initialization file. The default filename is the last filename used.''' From c5ce530293829feac50075f0e0f0743bbb786480 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 23 Jun 2008 21:40:30 +0200 Subject: [PATCH 06/26] move properties associated with completer from rlmain to basemode --- pyreadline/modes/basemode.py | 37 ++++++++++++++++++++----------- pyreadline/rlmain.py | 43 +++++++++--------------------------- 2 files changed, 35 insertions(+), 45 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index e535c1f..524861b 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -27,7 +27,13 @@ class BaseMode(object): self.prevargument=None self.l_buffer=lineobj.ReadLineTextBuffer("") self._history=history.LineHistory() - + self.completer_delims = " \t\n\"\\'`@$><=;|&{(" + self.show_all_if_ambiguous = 'off' + self.mark_directories = 'on' + self.completer = None + self.begidx = 0 + self.endidx = 0 + def __repr__(self): return "" @@ -67,13 +73,9 @@ class BaseMode(object): console=property(_g("console")) #used in completer _completions - completer_delims=property(*_gs("completer_delims")) - show_all_if_ambiguous=property(*_gs("show_all_if_ambiguous")) - mark_directories=property(*_gs("mark_directories")) - completer=property(*_gs("completer")) - begidx=property(*_gs("begidx")) - endidx=property(*_gs("endidx")) +# completer_delims=property(*_gs("completer_delims")) _bell=property(_g("_bell")) + bell_style=property(_g("bell_style")) rl_settings_to_string=property(_g("rl_settings_to_string")) @@ -89,8 +91,6 @@ class BaseMode(object): #not used in basemode or emacs - - def _readline_from_keyboard(self): raise NotImplementedError @@ -171,6 +171,19 @@ class BaseMode(object): #Create key bindings: + def rl_settings_to_string(self): + out=["%-20s: %s"%("show all if ambigous",self.show_all_if_ambiguous)] + out.append("%-20s: %s"%("mark_directories",self.mark_directories)) + out.append("%-20s: %s"%("bell_style",self.bell_style)) + out.append("------------- key bindings ------------") + tablepat="%-7s %-7s %-7s %-15s %-15s " + out.append(tablepat%("Control","Meta","Shift","Keycode/char","Function")) + bindings=[(k[0],k[1],k[2],k[3],v.__name__) for k,v in self.key_dispatch.iteritems()] + bindings.sort() + for key in bindings: + out.append(tablepat%(key)) + return out + def _bind_key(self, key, func): '''setup the mapping from key to call the function.''' @@ -194,9 +207,7 @@ class BaseMode(object): #completion commands def _get_completions(self): - '''Return a list of possible completions for the string ending at the point. - Also set begidx and endidx in the process.''' completions = [] self.begidx = self.l_buffer.point @@ -244,7 +255,7 @@ class BaseMode(object): log('fnames=%s' % completions) return completions - + def _display_completions(self, completions): if not completions: return @@ -264,6 +275,7 @@ class BaseMode(object): self.prompt=sys.ps1 self._print_prompt() + def complete(self, e): # (TAB) '''Attempt to perform completion on the text before point. The actual completion performed is application-specific. The default is @@ -321,7 +333,6 @@ class BaseMode(object): '''Insert text into the command line.''' self.l_buffer.insert_text(string) - def beginning_of_line(self, e): # (C-a) '''Move to the start of the current line. ''' self.l_buffer.beginning_of_line() diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index e05456a..ceb9f05 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -42,8 +42,6 @@ class Readline(object): def __init__(self): self.startup_hook = None self.pre_input_hook = None - self.completer = None - self.completer_delims = " \t\n\"\\'`@$><=;|&{(" self.console = console.Console() self.size = self.console.size() self.prompt_color = None @@ -58,12 +56,7 @@ class Readline(object): self.ctrl_c_tap_time_interval=0.3 self.debug=False - self.begidx = 0 - self.endidx = 0 - # variables you can control with parse_and_bind - self.show_all_if_ambiguous = 'off' - self.mark_directories = 'on' self.bell_style = 'none' self.mark=-1 @@ -74,7 +67,7 @@ class Readline(object): self.mode=self.editingmodes[0] self.read_inputrc() - log("\n".join(self.rl_settings_to_string())) + log("\n".join(self.mode.rl_settings_to_string())) #Paste settings #assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n @@ -200,30 +193,30 @@ class Readline(object): starting with text. ''' log('set_completer') - self.completer = function + self.mode.completer = function def get_completer(self): '''Get the completer function. ''' log('get_completer') - return self.completer + return self.mode.completer def get_begidx(self): '''Get the beginning index of the readline tab-completion scope.''' - return self.begidx + return self.mode.begidx def get_endidx(self): '''Get the ending index of the readline tab-completion scope.''' - return self.endidx + return self.mode.endidx def set_completer_delims(self, string): '''Set the readline word delimiters for tab-completion.''' - self.completer_delims = string + self.mode.completer_delims = string def get_completer_delims(self): '''Get the readline word delimiters for tab-completion.''' - return self.completer_delims + return self.mode.completer_delims def set_startup_hook(self, function=None): '''Set or remove the startup_hook function. @@ -250,20 +243,6 @@ class Readline(object): ## Internal functions - def rl_settings_to_string(self): - out=["%-20s: %s"%("show all if ambigous",self.show_all_if_ambiguous)] - out.append("%-20s: %s"%("mark_directories",self.mark_directories)) - out.append("%-20s: %s"%("bell_style",self.bell_style)) - out.append("%-20s: %s"%("mark_directories",self.mark_directories)) - out.append("------------- key bindings ------------") - tablepat="%-7s %-7s %-7s %-15s %-15s " - out.append(tablepat%("Control","Meta","Shift","Keycode/char","Function")) - bindings=[(k[0],k[1],k[2],k[3],v.__name__) for k,v in self.mode.key_dispatch.iteritems()] - bindings.sort() - for key in bindings: - out.append(tablepat%(key)) - return out - def _bell(self): '''ring the bell if requested.''' if self.bell_style == 'none': @@ -381,13 +360,13 @@ class Readline(object): def setbellstyle(mode): self.bell_style=mode def show_all_if_ambiguous(mode): - self.show_all_if_ambiguous=mode + self.mode.show_all_if_ambiguous=mode def ctrl_c_tap_time_interval(mode): self.ctrl_c_tap_time_interval=mode def mark_directories(mode): - self.mark_directories=mode - def completer_delims(mode): - self.completer_delims=mode + self.mode.mark_directories=mode + def completer_delims(delims): + self.mode.completer_delims=delims def debug_output(on,filename="pyreadline_debug_log.txt"): #Not implemented yet if on in ["on","on_nologfile"]: self.debug=True From 776d2141a8fd4aa1887c3159bdd1e25b54eed4f4 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 24 Jun 2008 20:08:32 +0200 Subject: [PATCH 07/26] Added the callback interface from the callback branch. --- pyreadline/__init__.py | 3 + pyreadline/examples/callback_example.py | 53 +++++++++++ pyreadline/modes/basemode.py | 112 ++++++++++++------------ pyreadline/modes/emacs.py | 1 + pyreadline/rlmain.py | 46 +++++++++- 5 files changed, 160 insertions(+), 55 deletions(-) create mode 100644 pyreadline/examples/callback_example.py diff --git a/pyreadline/__init__.py b/pyreadline/__init__.py index 02da956..c0845c5 100644 --- a/pyreadline/__init__.py +++ b/pyreadline/__init__.py @@ -27,6 +27,9 @@ __all__ = [ 'parse_and_bind', 'set_completer_delims', 'get_completer_delims', 'add_history', + 'callback_handler_install', + 'callback_handler_remove', + 'callback_read_char', 'GetOutputFile', 'rl', 'rlmain'] diff --git a/pyreadline/examples/callback_example.py b/pyreadline/examples/callback_example.py new file mode 100644 index 0000000..d7fdc44 --- /dev/null +++ b/pyreadline/examples/callback_example.py @@ -0,0 +1,53 @@ +''' +Example script using the callback interface of readline. + +:author: strank +''' + +__docformat__ = "restructuredtext en" + +import sys +import os +import time + +import readline + +import msvcrt +from pyreadline.rlmain import rl + +prompting = True +count = 0 +maxlines = 10 + + +def main(): + readline.callback_handler_install('Starting test, please do type:' + os.linesep, lineReceived) + index = 0 + start = int(time.time()) + while prompting: + # demonstrate that async stuff is possible: + if start + index < time.time(): + rl.console.title("NON-BLOCKING: %d" % index) + index += 1 + # ugly busy waiting/polling on windows, using 'select' on Unix: (or use twisted) + if msvcrt.kbhit(): + readline.callback_read_char() + print "Done, index =", index + + +def lineReceived(line): + global count, prompting + count += 1 + print "Got line: %s" % line + if count > maxlines: + prompting = False + readline.callback_handler_remove() + else: + readline.callback_handler_install('Got %s of %s, more typing please:' % (count, maxlines) + + os.linesep, lineReceived) + + + + +if __name__ == '__main__': + main() diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 524861b..7eb58b5 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -55,10 +55,6 @@ class BaseMode(object): return val argument_reset=property(_argreset) -# _history=property(_g("_history")) -# l_buffer=property(*_gs("l_buffer")) - - #used in readline ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval")) allow_ctrl_c=property(*_gs("allow_ctrl_c")) @@ -77,8 +73,6 @@ class BaseMode(object): _bell=property(_g("_bell")) bell_style=property(_g("bell_style")) - rl_settings_to_string=property(_g("rl_settings_to_string")) - #used in emacs _clear_after=property(_g("_clear_after")) _update_prompt_pos=property(_g("_update_prompt_pos")) @@ -91,12 +85,65 @@ class BaseMode(object): #not used in basemode or emacs + def readline_event_available(self): + return self.console.peek() or (len(self.paste_line_buffer)>0) + def _readline_from_keyboard(self): - raise NotImplementedError + while 1: + if self._readline_from_keyboard_poll(): + break + + def _readline_from_keyboard_poll(self): + if len(self.paste_line_buffer)>0: + #paste first line in multiline paste buffer + self.l_buffer=lineobj.ReadLineTextBuffer(self.paste_line_buffer[0]) + self._update_line() + self.paste_line_buffer=self.paste_line_buffer[1:] + return True + + c=self.console + def nop(e): + pass + try: + event = c.getkeypress() + except KeyboardInterrupt: + event=self.handle_ctrl_c() + + if self.next_meta: + self.next_meta = False + control, meta, shift, code = event.keyinfo + event.keyinfo = (control, True, shift, code) + result=self.process_keyevent(event.keyinfo) + self._update_line() + return result def readline(self, prompt=''): - '''Try to act like GNU readline.''' - # handle startup_hook + self.readline_setup(prompt) + self._readline_from_keyboard() + self.console.write('\r\n') + log('returning(%s)' % self.l_buffer.get_line_text()) + return self.l_buffer.get_line_text() + '\n' + + def handle_ctrl_c(self): + from pyreadline.keysyms.common import KeyPress + from pyreadline.console.event import Event + log_sock("KBDIRQ") + event=Event(0,0) + event.char="c" + event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) + if self.allow_ctrl_c: + now=time.time() + if (now-self.ctrl_c_timeout)0: - self.l_buffer=lineobj.ReadLineTextBuffer(self.paste_line_buffer[0]) - self._update_line() - self.paste_line_buffer=self.paste_line_buffer[1:] - c.write('\r\n') - else: - while 1: - self._update_line() - lbuf=self.l_buffer - log_sock("point:%d mark:%d selection_mark:%d"%(lbuf.point,lbuf.mark,lbuf.selection_mark)) - try: - event = c.getkeypress() - log_sock(u">>%s"%event) - except KeyboardInterrupt: - from pyreadline.keysyms.common import KeyPress - from pyreadline.console.event import Event - event=Event(0,0) - event.char="c" - event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) - log_sock("KBDIRQ") - if self.allow_ctrl_c: - now=time.time() - if (now-self.ctrl_c_timeout) Date: Tue, 24 Jun 2008 21:11:41 +0200 Subject: [PATCH 08/26] continue to move properties between basemode and rlmain * Added a no_clipboard module in the clipboard package. Contains an implementation that emulates the clipboard incase we cannot import the clipboard. * Removed uncommented imports in history. * moved from rlmain to basemode: tabstop, startup_hook, pre_input_hook, first_prompt, prompt, enable_ipython_paste_list_of_lists enable_ipython_paste_for_paths, enable_win32_clipboard,paste_line_buffer * moved next_meta to emacs.py * fixed tabstop using code in emacs.py * removed old unsused properties from Readline in rlmain --- pyreadline/clipboard/__init__.py | 9 +++---- pyreadline/lineeditor/history.py | 2 -- pyreadline/modes/basemode.py | 33 +++++++++++------------ pyreadline/modes/emacs.py | 6 ++++- pyreadline/modes/vi.py | 4 +-- pyreadline/rlmain.py | 45 +++++++++----------------------- 6 files changed, 39 insertions(+), 60 deletions(-) diff --git a/pyreadline/clipboard/__init__.py b/pyreadline/clipboard/__init__.py index 2852618..b3112bc 100644 --- a/pyreadline/clipboard/__init__.py +++ b/pyreadline/clipboard/__init__.py @@ -1,18 +1,17 @@ import sys -success=False +success=True in_ironpython="IronPython" in sys.version if in_ironpython: try: from ironpython_clipboard import GetClipboardText,SetClipboardText - success=True except ImportError: - pass + from no_clipboard import GetClipboardText,SetClipboardText + else: try: from win32_clipboard import GetClipboardText,SetClipboardText - success=True except ImportError: - raise + from no_clipboard import GetClipboardText,SetClipboardText def send_data(lists): diff --git a/pyreadline/lineeditor/history.py b/pyreadline/lineeditor/history.py index 761a8aa..10012a5 100644 --- a/pyreadline/lineeditor/history.py +++ b/pyreadline/lineeditor/history.py @@ -7,8 +7,6 @@ #***************************************************************************** import re,operator,string,sys,os -#import wordmatcher -#import pyreadline.clipboard as clipboard from pyreadline.unicode_helper import ensure_unicode,ensure_str if "pyreadline" in sys.modules: pyreadline= sys.modules["pyreadline"] diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 7eb58b5..d16de4c 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -33,6 +33,23 @@ class BaseMode(object): self.completer = None self.begidx = 0 self.endidx = 0 + self.tabstop = 4 + self.startup_hook = None + self.pre_input_hook = None + self.first_prompt = True + + self.prompt = ">>>" + + #Paste settings + #assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n + #and replace \ with / for easier use in ipython + self.enable_ipython_paste_for_paths=True + + #automatically convert tabseparated data to list of lists or array constructors + self.enable_ipython_paste_list_of_lists=True + self.enable_win32_clipboard=True + + self.paste_line_buffer=[] def __repr__(self): return "" @@ -58,12 +75,6 @@ class BaseMode(object): #used in readline ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval")) allow_ctrl_c=property(*_gs("allow_ctrl_c")) - next_meta=property(*_gs("next_meta")) - first_prompt=property(*_gs("first_prompt")) - prompt=property(*_gs("prompt")) - paste_line_buffer=property(*_gs("paste_line_buffer")) - startup_hook=property(*_gs("startup_hook")) - pre_input_hook=property(*_gs("pre_input_hook")) _print_prompt=property(_g("_print_prompt")) _update_line=property(_g("_update_line")) console=property(_g("console")) @@ -77,12 +88,6 @@ class BaseMode(object): _clear_after=property(_g("_clear_after")) _update_prompt_pos=property(_g("_update_prompt_pos")) - - enable_win32_clipboard=property(_g("enable_win32_clipboard")) - enable_ipython_paste_list_of_lists=property(_g("enable_ipython_paste_list_of_lists")) - enable_ipython_paste_for_paths=property(_g("enable_ipython_paste_for_paths")) - - #not used in basemode or emacs def readline_event_available(self): @@ -109,10 +114,6 @@ class BaseMode(object): except KeyboardInterrupt: event=self.handle_ctrl_c() - if self.next_meta: - self.next_meta = False - control, meta, shift, code = event.keyinfo - event.keyinfo = (control, True, shift, code) result=self.process_keyevent(event.keyinfo) self._update_line() return result diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 116c9df..9a407e1 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -34,6 +34,7 @@ class EmacsMode(basemode.BaseMode): self.previous_func=None self.prompt=">>>" self._insert_verbatim=False + self.next_meta = False # True to force meta on next character def __repr__(self): return "" @@ -48,6 +49,9 @@ class EmacsMode(basemode.BaseMode): #Process exit keys. Only exit on empty line def nop(e): pass + if self.next_meta: + self.next_meta = False + keyinfo.meta=True keytuple=keyinfo.tuple() if self._insert_verbatim: @@ -224,7 +228,7 @@ class EmacsMode(basemode.BaseMode): def tab_insert(self, e): # (M-TAB) '''Insert a tab character. ''' - ws = ' ' * (self.tabstop - (self.line_cursor%self.tabstop)) + ws = ' ' * (self.tabstop - (self.l_buffer.point%self.tabstop)) self.insert_text(ws) def transpose_chars(self, e): # (C-t) diff --git a/pyreadline/modes/vi.py b/pyreadline/modes/vi.py index a8102ba..d6710ac 100644 --- a/pyreadline/modes/vi.py +++ b/pyreadline/modes/vi.py @@ -112,8 +112,6 @@ class ViMode(basemode.BaseMode): else: self._vi_command = ViCommand (self) self.vi_set_insert_mode (False) -# if self.line_cursor > 0: -# self.line_cursor -= 1 self.l_buffer.point=lineobj.PrevChar elif self._vi_command and self._vi_command.is_replace_one: self._vi_command.add_char (e.char) @@ -358,7 +356,7 @@ class ViCommand: if char == '\x1b': # escape self.escape (char) elif char == '\x09': # tab - ts = self.readline.tabstop + ts = self.tabstop ws = ' ' * (ts - (self.readline.l_buffer.point%ts)) self.set_text (ws) elif char == '\x08': # backspace diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 44a59c4..58cec4c 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -40,8 +40,6 @@ def inword(buffer,point): class Readline(object): def __init__(self): - self.startup_hook = None - self.pre_input_hook = None self.console = console.Console() self.size = self.console.size() self.prompt_color = None @@ -49,9 +47,7 @@ class Readline(object): self.selection_color = self.console.saveattr<<4 self.key_dispatch = {} self.previous_func = None - self.first_prompt = True - self.next_meta = False # True to force meta on next character - self.tabstop = 4 + self.allow_ctrl_c=False self.ctrl_c_tap_time_interval=0.3 self.debug=False @@ -69,34 +65,8 @@ class Readline(object): self.read_inputrc() log("\n".join(self.mode.rl_settings_to_string())) - #Paste settings - #assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n - #and replace \ with / for easier use in ipython - self.enable_ipython_paste_for_paths=True - - #automatically convert tabseparated data to list of lists or array constructors - self.enable_ipython_paste_list_of_lists=True - self.enable_win32_clipboard=True - - self.paste_line_buffer=[] self.callback = None - #Below is for refactoring, raise errors when using old style attributes - #that should be refactored out - def _g(x): - def g(self): - raise GetSetError("GET %s"%x) - def s(self,q): - raise GetSetError("SET %s"%x) - return g,s - line_buffer=property(*_g("line_buffer")) - line_cursor=property(*_g("line_buffer")) - undo_stack =property(*_g("undo_stack")) # each entry is a tuple with cursor_position and line_text - history_length =property(*_g("history_length")) # each entry is a tuple with cursor_position and line_text - history =property(*_g("history")) # each entry is a tuple with cursor_position and line_text - history_cursor =property(*_g("history_cursor")) # each entry is a tuple with cursor_position and line_text - - # To export as readline interface def parse_and_bind(self, string): @@ -134,6 +104,15 @@ class Readline(object): log('error') raise + def _set_prompt(self, prompt): + self.mode.prompt=prompt + + def _get_prompt(self): + return self.mode.prompt + + prompt=property(_get_prompt, _set_prompt) + + def get_line_buffer(self): '''Return the current contents of the line buffer.''' return self.mode.l_buffer.get_line_text() @@ -228,7 +207,7 @@ class Readline(object): before readline prints the first prompt. ''' - self.startup_hook = function + self.mode.startup_hook = function def set_pre_input_hook(self, function=None): '''Set or remove the pre_input_hook function. @@ -240,7 +219,7 @@ class Readline(object): starts reading input characters. ''' - self.pre_input_hook = function + self.mode.pre_input_hook = function ## Internal functions From b736f6397f6b6615f48cb27f814ba2f1118b8a83 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Thu, 26 Jun 2008 19:24:56 +0200 Subject: [PATCH 09/26] added mockup for gui-use of pyreadline --- pyreadline/clipboard/no_clipboard.py | 18 +++++++ pyreadline/examples/tk_gui.py | 77 ++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 pyreadline/clipboard/no_clipboard.py create mode 100644 pyreadline/examples/tk_gui.py diff --git a/pyreadline/clipboard/no_clipboard.py b/pyreadline/clipboard/no_clipboard.py new file mode 100644 index 0000000..b1c4664 --- /dev/null +++ b/pyreadline/clipboard/no_clipboard.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +#***************************************************************************** +# Copyright (C) 2006 Jorgen Stenarson. +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#***************************************************************************** + + +mybuffer="" + +def GetClipboardText(): + return mybuffer + +def SetClipboardText(text): + global mybuffer + mybuffer=text + diff --git a/pyreadline/examples/tk_gui.py b/pyreadline/examples/tk_gui.py new file mode 100644 index 0000000..f539814 --- /dev/null +++ b/pyreadline/examples/tk_gui.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +#***************************************************************************** +# Copyright (C) 2006 Jorgen Stenarson. +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#***************************************************************************** + +""" Mockup of gui-use of pyreadline + + +""" + +import Tkinter + +class KeyEvent(object): + def __init__(self, char, shift, control, meta, keyname): + self.char=char + self.shift=shift + self.control=control + self.meta=meta + self.keyname=keyname + + +class DumbReadLine(object): + def __init__(self): + self._text=[] + + + def ProcKeyEvent(self, event): + char=event.char + if event.keyname=="backspace": + self._text=self._text[:-1] + elif event.keyname=="return": + return True + elif len(event.char)==1: + self._text.append(event.char) + return False + + def get_line(self): + return "".join(self._text) + + def new_line(self): + self._text=[] + +class App: + def __init__(self, master): + self.lines=["Hello"] + self.RL=DumbReadLine() + self.textvar = Tkinter.StringVar() + self._update_line() + self.text=Tkinter.Label(master, textvariable=self.textvar,width=50,height=40,justify=Tkinter.LEFT,anchor=Tkinter.NW) + self.text.pack(side=Tkinter.LEFT) + master.bind("",self.handler) + + def handler(self, event): + if len(event.keysym)>1: + keysym=event.keysym.lower() + else: + keysym="" + keyevent=KeyEvent(event.char, False, False, False, keysym) + result=self.RL.ProcKeyEvent(keyevent) + if result: + self.lines.append(self.RL.get_line()) + self.RL.new_line() + self._update_line() + + + def _update_line(self): + self.textvar.set("\n".join(self.lines+[self.RL.get_line()])) + + + +root=Tkinter.Tk() + +display=App(root) +root.mainloop() \ No newline at end of file From ddeaa854ddb9315e300727886771e557a9abbc33 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Thu, 26 Jun 2008 22:11:53 +0200 Subject: [PATCH 10/26] Extracted a BaseReadLine class without console stuff from ReadLine. tk_gui.py example of using the BaseReadLine class from a gui continued to refactor to remove all console related stuff from modes, there are still some console related stuff in the history search commands --- pyreadline/examples/tk_gui.py | 70 ++++---- pyreadline/modes/basemode.py | 65 +------- pyreadline/modes/emacs.py | 9 +- pyreadline/rlmain.py | 306 ++++++++++++++++++++++------------ 4 files changed, 239 insertions(+), 211 deletions(-) diff --git a/pyreadline/examples/tk_gui.py b/pyreadline/examples/tk_gui.py index f539814..f4950b8 100644 --- a/pyreadline/examples/tk_gui.py +++ b/pyreadline/examples/tk_gui.py @@ -10,64 +10,56 @@ """ - -import Tkinter - -class KeyEvent(object): - def __init__(self, char, shift, control, meta, keyname): - self.char=char - self.shift=shift - self.control=control - self.meta=meta - self.keyname=keyname +from pyreadline.rlmain import BaseReadline +from pyreadline.keysyms.common import KeyPress +import pyreadline.logger as log +log.sock_silent=False +import Tkinter,sys -class DumbReadLine(object): - def __init__(self): - self._text=[] - - - def ProcKeyEvent(self, event): +def KeyPress_from_event(event): + if len(event.keysym)>1: + keysym=event.keysym.lower() char=event.char - if event.keyname=="backspace": - self._text=self._text[:-1] - elif event.keyname=="return": - return True - elif len(event.char)==1: - self._text.append(event.char) - return False + else: + keysym="" + char=event.keysym + return KeyPress(char, event.state&1!=0, event.state&4!=0, event.state&(131072)!=0, keysym) - def get_line(self): - return "".join(self._text) - - def new_line(self): - self._text=[] class App: def __init__(self, master): + self.frame=frame=Tkinter.Frame(master) + frame.pack() self.lines=["Hello"] - self.RL=DumbReadLine() + self.RL=BaseReadline() + self.RL.read_inputrc() + self.prompt=">>>" + self.readline_setup(self.prompt) self.textvar = Tkinter.StringVar() self._update_line() - self.text=Tkinter.Label(master, textvariable=self.textvar,width=50,height=40,justify=Tkinter.LEFT,anchor=Tkinter.NW) + self.text=Tkinter.Label(frame, textvariable=self.textvar,width=50,height=40,justify=Tkinter.LEFT,anchor=Tkinter.NW) self.text.pack(side=Tkinter.LEFT) master.bind("",self.handler) def handler(self, event): - if len(event.keysym)>1: - keysym=event.keysym.lower() - else: - keysym="" - keyevent=KeyEvent(event.char, False, False, False, keysym) - result=self.RL.ProcKeyEvent(keyevent) + keyevent=KeyPress_from_event(event) + try: + result=self.RL.process_keyevent(keyevent) + except EOFError: + self.frame.quit() + return if result: - self.lines.append(self.RL.get_line()) - self.RL.new_line() + self.lines.append(self.RL.get_line_buffer()) + self.readline_setup(self.prompt) self._update_line() + + def readline_setup(self, prompt=''): + self.RL.readline_setup(prompt) def _update_line(self): - self.textvar.set("\n".join(self.lines+[self.RL.get_line()])) + self.textvar.set("\n".join(self.lines+[self.prompt+" "+self.RL.get_line_buffer()])) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index d16de4c..dfaa449 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -78,6 +78,8 @@ class BaseMode(object): _print_prompt=property(_g("_print_prompt")) _update_line=property(_g("_update_line")) console=property(_g("console")) + prompt_begin_pos=property(_g("prompt_begin_pos")) + prompt_end_pos=property(_g("prompt_end_pos")) #used in completer _completions # completer_delims=property(*_gs("completer_delims")) @@ -90,62 +92,10 @@ class BaseMode(object): #not used in basemode or emacs - def readline_event_available(self): - return self.console.peek() or (len(self.paste_line_buffer)>0) - - def _readline_from_keyboard(self): - while 1: - if self._readline_from_keyboard_poll(): - break - - def _readline_from_keyboard_poll(self): - if len(self.paste_line_buffer)>0: - #paste first line in multiline paste buffer - self.l_buffer=lineobj.ReadLineTextBuffer(self.paste_line_buffer[0]) - self._update_line() - self.paste_line_buffer=self.paste_line_buffer[1:] - return True - - c=self.console - def nop(e): - pass - try: - event = c.getkeypress() - except KeyboardInterrupt: - event=self.handle_ctrl_c() - - result=self.process_keyevent(event.keyinfo) - self._update_line() - return result - - def readline(self, prompt=''): - self.readline_setup(prompt) - self._readline_from_keyboard() - self.console.write('\r\n') - log('returning(%s)' % self.l_buffer.get_line_text()) - return self.l_buffer.get_line_text() + '\n' - - def handle_ctrl_c(self): - from pyreadline.keysyms.common import KeyPress - from pyreadline.console.event import Event - log_sock("KBDIRQ") - event=Event(0,0) - event.char="c" - event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) - if self.allow_ctrl_c: - now=time.time() - if (now-self.ctrl_c_timeout) 0: #self._history.history_cursor = hc_start #forces search to restart when search empty @@ -136,11 +135,11 @@ class EmacsMode(basemode.BaseMode): #self._history.history_cursor = hc_start query += event.char line=searchfun(query) - elif event.keyinfo == init_event.keyinfo: + elif event== init_event: self._history.history_cursor += direction line=searchfun(query) else: - if event.keyinfo.keyname != 'return': + if event.keyname != 'return': self._bell() break diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 58cec4c..cf2bcd6 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -7,7 +7,7 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** ''' an attempt to implement readline for Python in Python using ctypes''' -import sys,os,re +import sys,os,re,time from glob import glob import clipboard,logger,console @@ -30,32 +30,26 @@ else: import pdb -def quote_char(c): - if ord(c)>0: - return c +class MockConsoleError(Exception): + pass +class MockConsole(object): + """object used during refactoring. Should raise errors when someone tries to use it. + """ + def __setattr__(self,x): + raise MockConsoleError("Should not try to get attributes from MockConsole") -def inword(buffer,point): - return buffer[point:point+1] in [A-Za-z0-9] + def cursor(self,size=50): + pass - -class Readline(object): +class BaseReadline(object): def __init__(self): - self.console = console.Console() - self.size = self.console.size() - self.prompt_color = None - self.command_color = None - self.selection_color = self.console.saveattr<<4 - self.key_dispatch = {} - self.previous_func = None - self.allow_ctrl_c=False self.ctrl_c_tap_time_interval=0.3 - self.debug=False - # variables you can control with parse_and_bind + self.debug=False self.bell_style = 'none' self.mark=-1 - + self.console=MockConsole() # this code needs to follow l_buffer and history creation self.editingmodes=[mode(self) for mode in editingmodes] for mode in self.editingmodes: @@ -67,7 +61,6 @@ class Readline(object): self.callback = None -# To export as readline interface def parse_and_bind(self, string): '''Parse and execute single line of a readline init file.''' @@ -221,99 +214,25 @@ class Readline(object): ''' self.mode.pre_input_hook = function -## Internal functions +#Functions that are not relevant for all Readlines but should at least have a NOP def _bell(self): - '''ring the bell if requested.''' - if self.bell_style == 'none': - pass - elif self.bell_style == 'visible': - raise NotImplementedError("Bellstyle visible is not implemented yet.") - elif self.bell_style == 'audible': - self.console.bell() - else: - raise ReadlineError("Bellstyle %s unknown."%self.bell_style) - - def _clear_after(self): - c = self.console - x, y = c.pos() - w, h = c.size() - c.rectangle((x, y, w+1, y+1)) - c.rectangle((0, y+1, w, min(y+3,h))) - - def _set_cursor(self): - c = self.console - xc, yc = self.prompt_end_pos - w, h = c.size() - xc += self.mode.l_buffer.visible_line_width() - while(xc >= w): - xc -= w - yc += 1 - c.pos(xc, yc) - - def _print_prompt(self): - c = self.console - x, y = c.pos() - - n = c.write_scrolling(self.prompt, self.prompt_color) - self.prompt_begin_pos = (x, y - n) - self.prompt_end_pos = c.pos() - self.size = c.size() - - def _update_prompt_pos(self, n): - if n != 0: - bx, by = self.prompt_begin_pos - ex, ey = self.prompt_end_pos - self.prompt_begin_pos = (bx, by - n) - self.prompt_end_pos = (ex, ey - n) - - def _update_line(self): - c=self.console - l_buffer=self.mode.l_buffer - c.cursor(0) #Hide cursor avoiding flicking - c.pos(*self.prompt_end_pos) - ltext = l_buffer.quoted_text() - if l_buffer.enable_selection and l_buffer.selection_mark>=0: - start=len(l_buffer[:l_buffer.selection_mark].quoted_text()) - stop=len(l_buffer[:l_buffer.point].quoted_text()) - if start>stop: - stop,start=start,stop - n = c.write_scrolling(ltext[:start], self.command_color) - n = c.write_scrolling(ltext[start:stop], self.selection_color) - n = c.write_scrolling(ltext[stop:], self.command_color) - else: - n = c.write_scrolling(ltext, self.command_color) - - x,y = c.pos() #Preserve one line for Asian IME(Input Method Editor) statusbar - w,h = c.size() - if y >= h - 1 or n > 0: - c.scroll_window(-1) - c.scroll((0,0,w,h),0,-1) - n += 1 - - self._update_prompt_pos(n) - if hasattr(c,"clear_to_end_of_window"): #Work around function for ironpython due - c.clear_to_end_of_window() #to System.Console's lack of FillFunction - else: - self._clear_after() - c.cursor(1) #Show cursor - self._set_cursor() + pass # -# Standard call +# Standard call, not available for all implementations # def readline(self, prompt=''): - return self.mode.readline(prompt) + raise NotImplementedError # # Callback interface # - - def event_available(self): - return self.mode.readline_event_available() - - def setup(self,prompt=""): + def process_keyevent(self, keyinfo): + return self.mode.process_keyevent(keyinfo) + + def readline_setup(self,prompt=""): return self.mode.readline_setup(prompt) def keyboard_poll(self): @@ -324,7 +243,7 @@ class Readline(object): Initializes the readline callback interface and terminal, prints the prompt and returns immediately ''' self.callback = callback - self.mode.readline_setup(prompt) + self.readline_setup(prompt) def callback_handler_remove(self): '''Removes a previously installed callback handler and restores terminal settings''' @@ -334,7 +253,6 @@ class Readline(object): '''Reads a character and informs the readline callback interface when a line is received''' if self.keyboard_poll(): line = self.get_line_buffer() + '\n' - self.console.write('\r\n') # this is the newline terminating input # however there is another newline added by # self.mode.readline_setup(prompt) which is called by callback_handler_install # this differs from GNU readline @@ -438,16 +356,186 @@ class Readline(object): +class Readline(BaseReadline): + """Baseclass for readline based on a console + """ + def __init__(self): + BaseReadline.__init__(self) + self.console = console.Console() + self.size = self.console.size() + self.prompt_color = None + self.command_color = None + self.selection_color = self.console.saveattr<<4 + + # variables you can control with parse_and_bind + +# To export as readline interface + + +## Internal functions + + def _bell(self): + '''ring the bell if requested.''' + if self.bell_style == 'none': + pass + elif self.bell_style == 'visible': + raise NotImplementedError("Bellstyle visible is not implemented yet.") + elif self.bell_style == 'audible': + self.console.bell() + else: + raise ReadlineError("Bellstyle %s unknown."%self.bell_style) + + def _clear_after(self): + c = self.console + x, y = c.pos() + w, h = c.size() + c.rectangle((x, y, w+1, y+1)) + c.rectangle((0, y+1, w, min(y+3,h))) + + def _set_cursor(self): + c = self.console + xc, yc = self.prompt_end_pos + w, h = c.size() + xc += self.mode.l_buffer.visible_line_width() + while(xc >= w): + xc -= w + yc += 1 + c.pos(xc, yc) + + def _print_prompt(self): + c = self.console + x, y = c.pos() + + n = c.write_scrolling(self.prompt, self.prompt_color) + self.prompt_begin_pos = (x, y - n) + self.prompt_end_pos = c.pos() + self.size = c.size() + + def _update_prompt_pos(self, n): + if n != 0: + bx, by = self.prompt_begin_pos + ex, ey = self.prompt_end_pos + self.prompt_begin_pos = (bx, by - n) + self.prompt_end_pos = (ex, ey - n) + + def _update_line(self): + c=self.console + l_buffer=self.mode.l_buffer + c.cursor(0) #Hide cursor avoiding flicking + c.pos(*self.prompt_end_pos) + ltext = l_buffer.quoted_text() + if l_buffer.enable_selection and l_buffer.selection_mark>=0: + start=len(l_buffer[:l_buffer.selection_mark].quoted_text()) + stop=len(l_buffer[:l_buffer.point].quoted_text()) + if start>stop: + stop,start=start,stop + n = c.write_scrolling(ltext[:start], self.command_color) + n = c.write_scrolling(ltext[start:stop], self.selection_color) + n = c.write_scrolling(ltext[stop:], self.command_color) + else: + n = c.write_scrolling(ltext, self.command_color) + + x,y = c.pos() #Preserve one line for Asian IME(Input Method Editor) statusbar + w,h = c.size() + if y >= h - 1 or n > 0: + c.scroll_window(-1) + c.scroll((0,0,w,h),0,-1) + n += 1 + + self._update_prompt_pos(n) + if hasattr(c,"clear_to_end_of_window"): #Work around function for ironpython due + c.clear_to_end_of_window() #to System.Console's lack of FillFunction + else: + self._clear_after() + c.cursor(1) #Show cursor + self._set_cursor() + + + def callback_read_char(self): + #Override base to get automatic newline + '''Reads a character and informs the readline callback interface when a line is received''' + if self.keyboard_poll(): + line = self.get_line_buffer() + '\n' + self.console.write("\r\n") + # however there is another newline added by + # self.mode.readline_setup(prompt) which is called by callback_handler_install + # this differs from GNU readline + self.add_history(self.mode.l_buffer) + # TADA: + self.callback(line) + + + def event_available(self): + return self.console.peek() or (len(self.paste_line_buffer)>0) + + + def _readline_from_keyboard(self): + while 1: + if self._readline_from_keyboard_poll(): + break + + def _readline_from_keyboard_poll(self): + pastebuffer=self.mode.paste_line_buffer + if len(pastebuffer)>0: + #paste first line in multiline paste buffer + self.l_buffer=lineobj.ReadLineTextBuffer(pastebuffer[0]) + self._update_line() + self.mode.paste_line_buffer=pastebuffer[1:] + return True + + c=self.console + def nop(e): + pass + try: + event = c.getkeypress() + except KeyboardInterrupt: + event=self.handle_ctrl_c() + + result=self.mode.process_keyevent(event.keyinfo) + self._update_line() + return result + + def readline_setup(self, prompt=''): + BaseReadline.readline_setup(self, prompt) + self._print_prompt() + self._update_line() + + def readline(self, prompt=''): + self.readline_setup(prompt) + self.ctrl_c_timeout=time.time() + self._readline_from_keyboard() + self.console.write('\r\n') + log('returning(%s)' % self.get_line_buffer()) + return self.get_line_buffer() + '\n' + + def handle_ctrl_c(self): + from pyreadline.keysyms.common import KeyPress + from pyreadline.console.event import Event + log_sock("KBDIRQ") + event=Event(0,0) + event.char="c" + event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) + if self.allow_ctrl_c: + now=time.time() + if (now-self.ctrl_c_timeout) Date: Fri, 27 Jun 2008 19:27:55 +0200 Subject: [PATCH 11/26] Fixed bug with alt gr inserting wrong character --- pyreadline/keysyms/keysyms.py | 2 + pyreadline/modes/basemode.py | 141 +++++++++++++++++----------------- pyreadline/rlmain.py | 5 -- 3 files changed, 72 insertions(+), 76 deletions(-) diff --git a/pyreadline/keysyms/keysyms.py b/pyreadline/keysyms/keysyms.py index 6d62de7..f07e1f5 100644 --- a/pyreadline/keysyms/keysyms.py +++ b/pyreadline/keysyms/keysyms.py @@ -117,6 +117,8 @@ def make_KeyPress(char,state,keycode): shift = (state & 0x10) != 0 if control and char !="\x00": char = chr(VkKeyScan(ord(char)) & 0xff) + elif control and meta and char !="\x00": + char = chr(VkKeyScan(ord(char)) & 0xff) elif control: char=chr(keycode) try: diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index dfaa449..3767acf 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -144,7 +144,7 @@ class BaseMode(object): def _bind_key(self, key, func): - '''setup the mapping from key to call the function.''' + """setup the mapping from key to call the function.""" if type(func) != type(self._bind_key): print "Trying to bind non method to keystroke:%s,%s"%(key,func) raise PyreadlineError("Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(self._bind_key))) @@ -153,20 +153,20 @@ class BaseMode(object): self.key_dispatch[keyinfo] = func def _bind_exit_key(self, key): - '''setup the mapping from key to call the function.''' + """setup the mapping from key to call the function.""" keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple() self.exit_dispatch[keyinfo] = None def init_editing_mode(self, e): # (C-e) - '''When in vi command mode, this causes a switch to emacs editing - mode.''' + """When in vi command mode, this causes a switch to emacs editing + mode.""" raise NotImplementedError #completion commands def _get_completions(self): - '''Return a list of possible completions for the string ending at the point. - Also set begidx and endidx in the process.''' + """Return a list of possible completions for the string ending at the point. + Also set begidx and endidx in the process.""" completions = [] self.begidx = self.l_buffer.point self.endidx = self.l_buffer.point @@ -235,9 +235,9 @@ class BaseMode(object): def complete(self, e): # (TAB) - '''Attempt to perform completion on the text before point. The + """Attempt to perform completion on the text before point. The actual completion performed is application-specific. The default is - filename completion.''' + filename completion.""" completions = self._get_completions() if completions: cprefix = commonprefix(completions) @@ -254,13 +254,13 @@ class BaseMode(object): self._bell() def possible_completions(self, e): # (M-?) - '''List the possible completions of the text before point. ''' + """List the possible completions of the text before point. """ completions = self._get_completions() self._display_completions(completions) def insert_completions(self, e): # (M-*) - '''Insert all completions of the text before point that would have - been generated by possible-completions.''' + """Insert all completions of the text before point that would have + been generated by possible-completions.""" completions = self._get_completions() b = self.begidx e = self.endidx @@ -273,7 +273,7 @@ class BaseMode(object): self.line_cursor = b def menu_complete(self, e): # () - '''Similar to complete, but replaces the word to be completed with a + """Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of @@ -281,154 +281,153 @@ class BaseMode(object): and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to - be bound to TAB, but is unbound by default.''' + be bound to TAB, but is unbound by default.""" pass ### Methods below here are bindable emacs functions def insert_text(self, string): - '''Insert text into the command line.''' + """Insert text into the command line.""" self.l_buffer.insert_text(string) def beginning_of_line(self, e): # (C-a) - '''Move to the start of the current line. ''' + """Move to the start of the current line. """ self.l_buffer.beginning_of_line() def end_of_line(self, e): # (C-e) - '''Move to the end of the line. ''' + """Move to the end of the line. """ self.l_buffer.end_of_line() def forward_char(self, e): # (C-f) - '''Move forward a character. ''' + """Move forward a character. """ self.l_buffer.forward_char(self.argument_reset) def backward_char(self, e): # (C-b) - '''Move back a character. ''' + """Move back a character. """ self.l_buffer.backward_char(self.argument_reset) def forward_word(self, e): # (M-f) - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.forward_word(self.argument_reset) def backward_word(self, e): # (M-b) - '''Move back to the start of the current or previous word. Words are - composed of letters and digits.''' + """Move back to the start of the current or previous word. Words are + composed of letters and digits.""" self.l_buffer.backward_word(self.argument_reset) def forward_word_end(self, e): # () - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.forward_word_end(self.argument_reset) def backward_word_end(self, e): # () - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.backward_word_end(self.argument_reset) ### Movement with extend selection def beginning_of_line_extend_selection(self, e): # - '''Move to the start of the current line. ''' + """Move to the start of the current line. """ self.l_buffer.beginning_of_line_extend_selection() def end_of_line_extend_selection(self, e): # - '''Move to the end of the line. ''' + """Move to the end of the line. """ self.l_buffer.end_of_line_extend_selection() def forward_char_extend_selection(self, e): # - '''Move forward a character. ''' + """Move forward a character. """ self.l_buffer.forward_char_extend_selection(self.argument_reset) def backward_char_extend_selection(self, e): # - '''Move back a character. ''' + """Move back a character. """ self.l_buffer.backward_char_extend_selection(self.argument_reset) def forward_word_extend_selection(self, e): # - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.forward_word_extend_selection(self.argument_reset) def backward_word_extend_selection(self, e): # - '''Move back to the start of the current or previous word. Words are - composed of letters and digits.''' + """Move back to the start of the current or previous word. Words are + composed of letters and digits.""" self.l_buffer.backward_word_extend_selection(self.argument_reset) def forward_word_end_extend_selection(self, e): # - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) def backward_word_end_extend_selection(self, e): # - '''Move forward to the end of the next word. Words are composed of - letters and digits.''' + """Move forward to the end of the next word. Words are composed of + letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) ######## Change case def upcase_word(self, e): # (M-u) - '''Uppercase the current (or following) word. With a negative - argument, uppercase the previous word, but do not move the cursor.''' + """Uppercase the current (or following) word. With a negative + argument, uppercase the previous word, but do not move the cursor.""" self.l_buffer.upcase_word() def downcase_word(self, e): # (M-l) - '''Lowercase the current (or following) word. With a negative - argument, lowercase the previous word, but do not move the cursor.''' + """Lowercase the current (or following) word. With a negative + argument, lowercase the previous word, but do not move the cursor.""" self.l_buffer.downcase_word() def capitalize_word(self, e): # (M-c) - '''Capitalize the current (or following) word. With a negative - argument, capitalize the previous word, but do not move the cursor.''' + """Capitalize the current (or following) word. With a negative + argument, capitalize the previous word, but do not move the cursor.""" self.l_buffer.capitalize_word() ######## def clear_screen(self, e): # (C-l) - '''Clear the screen and redraw the current line, leaving the current - line at the top of the screen.''' + """Clear the screen and redraw the current line, leaving the current + line at the top of the screen.""" self.console.page() def redraw_current_line(self, e): # () - '''Refresh the current line. By default, this is unbound.''' + """Refresh the current line. By default, this is unbound.""" pass def accept_line(self, e): # (Newline or Return) - '''Accept the line regardless of where the cursor is. If this line + """Accept the line regardless of where the cursor is. If this line is non-empty, it may be added to the history list for future recall with add_history(). If this line is a modified history line, the - history line is restored to its original state.''' + history line is restored to its original state.""" return True def delete_char(self, e): # (C-d) - '''Delete the character at point. If point is at the beginning of + """Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last - character typed was not bound to delete-char, then return EOF.''' + character typed was not bound to delete-char, then return EOF.""" self.l_buffer.delete_char(self.argument_reset) def backward_delete_char(self, e): # (Rubout) - '''Delete the character behind the cursor. A numeric argument means - to kill the characters instead of deleting them.''' + """Delete the character behind the cursor. A numeric argument means + to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_char(self.argument_reset) def backward_delete_word(self, e): # (Control-Rubout) - '''Delete the character behind the cursor. A numeric argument means - to kill the characters instead of deleting them.''' + """Delete the character behind the cursor. A numeric argument means + to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_word(self.argument_reset) def forward_delete_word(self, e): # (Control-Delete) - '''Delete the character behind the cursor. A numeric argument means - to kill the characters instead of deleting them.''' + """Delete the character behind the cursor. A numeric argument means + to kill the characters instead of deleting them.""" self.l_buffer.forward_delete_word(self.argument_reset) def delete_horizontal_space(self, e): # () - '''Delete all spaces and tabs around point. By default, this is unbound. ''' + """Delete all spaces and tabs around point. By default, this is unbound. """ self.l_buffer.delete_horizontal_space() def self_insert(self, e): # (a, b, A, 1, !, ...) - '''Insert yourself. ''' - + """Insert yourself. """ if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) @@ -436,8 +435,8 @@ class BaseMode(object): # Paste from clipboard def paste(self,e): - '''Paste windows clipboard. - Assume single line strip other lines and end of line markers and trailing spaces''' #(Control-v) + """Paste windows clipboard. + Assume single line strip other lines and end of line markers and trailing spaces""" #(Control-v) if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) txt=txt.split("\n")[0].strip("\r").strip("\n") @@ -445,8 +444,8 @@ class BaseMode(object): self.insert_text(txt) def paste_mulitline_code(self,e): - '''Paste windows clipboard as multiline code. - Removes any empty lines in the code''' + """Paste windows clipboard as multiline code. + Removes any empty lines in the code""" reg=re.compile("\r?\n") if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) @@ -462,10 +461,10 @@ class BaseMode(object): return False def ipython_paste(self,e): - '''Paste windows clipboard. If enable_ipython_paste_list_of_lists is + """Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array. - If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space''' + If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space""" if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert( self.enable_ipython_paste_list_of_lists) @@ -476,22 +475,22 @@ class BaseMode(object): def copy_region_to_clipboard(self, e): # () - '''Copy the text in the region to the windows clipboard.''' + """Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_region_to_clipboard() def copy_selection_to_clipboard(self, e): # () - '''Copy the text in the region to the windows clipboard.''' + """Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_selection_to_clipboard() def cut_selection_to_clipboard(self, e): # () - '''Copy the text in the region to the windows clipboard.''' + """Copy the text in the region to the windows clipboard.""" self.l_buffer.cut_selection_to_clipboard() def dump_functions(self, e): # () - '''Print all of the functions and their key bindings to the Readline + """Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc - file. This command is unbound by default.''' + file. This command is unbound by default.""" print txt="\n".join(self.rl_settings_to_string()) print txt diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index cf2bcd6..617044f 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -490,7 +490,6 @@ class Readline(BaseReadline): event = c.getkeypress() except KeyboardInterrupt: event=self.handle_ctrl_c() - result=self.mode.process_keyevent(event.keyinfo) self._update_line() return result @@ -529,10 +528,6 @@ class Readline(BaseReadline): - - - - # create a Readline object to contain the state rl = Readline() From b20b6ea32012330ff28ec04b71982b5b138c7d64 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 30 Jun 2008 21:47:11 +0200 Subject: [PATCH 12/26] fixing search to use process_keyevent Changed ReadLine._update_line to always redraw prompt Moved keyboard using functions from history.py to EmacsMode --- pyreadline/lineeditor/history.py | 44 ------- pyreadline/modes/basemode.py | 3 + pyreadline/modes/emacs.py | 206 ++++++++++++++++++++----------- pyreadline/rlmain.py | 4 +- 4 files changed, 142 insertions(+), 115 deletions(-) diff --git a/pyreadline/lineeditor/history.py b/pyreadline/lineeditor/history.py index 10012a5..a433f55 100644 --- a/pyreadline/lineeditor/history.py +++ b/pyreadline/lineeditor/history.py @@ -143,50 +143,6 @@ class LineHistory(object): return res[0][1].get_line_text() return "" - def _non_i_search(self, direction, current): - c = pyreadline.rl.console - line = current.get_line_text() - query = '' - while 1: - c.pos(*pyreadline.rl.prompt_end_pos) - scroll = c.write_scrolling(":%s" % query) - pyreadline.rl._update_prompt_pos(scroll) - pyreadline.rl._clear_after() - - event = c.getkeypress() - - if event.keyinfo.keyname == 'backspace': - if len(query) > 0: - query = query[:-1] - else: - break - elif event.char in string.letters + string.digits + string.punctuation + ' ': - query += event.char - elif event.keyinfo.keyname == 'return': - break - else: - pyreadline.rl._bell() - res="" - if query: - if direction==-1: - res=self.reverse_search_history(query) - - else: - res=self.forward_search_history(query) - return lineobj.ReadLineTextBuffer(res,point=0) - - def non_incremental_reverse_search_history(self,current): # (M-p) - '''Search backward starting at the current line and moving up - through the history as necessary using a non-incremental search for - a string supplied by the user.''' - return self._non_i_search(-1,current) - - def non_incremental_forward_search_history(self,current): # (M-n) - '''Search forward starting at the current line and moving down - through the the history as necessary using a non-incremental search - for a string supplied by the user.''' - return self._non_i_search(1,current) - def _search(self, direction, partial): try: if (self.lastcommand != self.history_search_forward and diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 3767acf..d3c84f1 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -51,6 +51,9 @@ class BaseMode(object): self.paste_line_buffer=[] + self._sub_modes=[] + + def __repr__(self): return "" diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index b9c82a5..221e68c 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -25,17 +25,138 @@ def format(keyinfo): return "(%s,%s,%s,%s,%x)"%k in_ironpython="IronPython" in sys.version +class IncrementalSearchPromptMode(object): + def __init__(self, rlobj): + pass + + def _process_incremental_search_keyevent(self, keyinfo): + keytuple=keyinfo.tuple() + log_sock("%s %s"%(keyinfo,keytuple)) + if keyinfo.keyname == 'backspace': + self.subsearch_query = self.subsearch_query[:-1] + if len(self.subsearch_query) > 0: + self.line=self.subsearch_fun(self.subsearch_query) + else: + self._bell() + self.line="" #empty query means no search result + elif keyinfo.keyname in ['return', 'escape']: + self._bell() + self.prompt=self.subsearch_oldprompt + self.process_keyevent_queue=self.process_keyevent_queue[:-1] + self._history.history_cursor=len(self._history.history) + if keyinfo.keyname == 'escape': + self.l_buffer.set_line(self.subsearch_old_line) + return False + elif keyinfo.keyname: + pass + elif keytuple==self.subsearch_init_event: + self._history.history_cursor += self.subsearch_direction + self.line=self.subsearch_fun(self.subsearch_query) + elif keyinfo.control==False and keyinfo.meta==False : + self.subsearch_query += keyinfo.char + self.line=self.subsearch_fun(self.subsearch_query) + else: + pass + self.prompt=self.subsearch_prompt%self.subsearch_query + self.l_buffer.set_line(self.line) -class EmacsMode(basemode.BaseMode): + def _init_incremental_search(self, searchfun, direction, init_event): + """Initialize search prompt + """ + self.subsearch_init_event=init_event.tuple() + self.subsearch_direction=direction + self.subsearch_query = '' + self.subsearch_fun = searchfun + self.subsearch_old_line = self.l_buffer.get_line_text() + + self.process_keyevent_queue.append(self._process_incremental_search_keyevent) + + self.subsearch_oldprompt=self.prompt + + if (self.previous_func != self.history_search_forward and + self.previous_func != self.history_search_backward): + self.subsearch_query = ''.join(self.l_buffer[0:Point].get_line_text()) + + + if self.subsearch_direction < 0: + self.subsearch_prompt = "reverse-i-search`%s': " + else: + self.subsearch_prompt = "forward-i-search`%s': " + self.prompt=self.subsearch_prompt%"" + if self.subsearch_query: + self.line=self._process_search_keyevent(init_event) + else: + self.line="" + +class SearchPromptMode(object): + def __init__(self, rlobj): + pass + + def _process_non_incremental_search_keyevent(self, keyinfo): + keytuple=keyinfo.tuple() + log_sock("%s %s"%(keyinfo,keytuple)) + + if keyinfo.keyname == 'backspace': + self.non_inc_query = self.non_inc_query[:-1] + elif keyinfo.keyname in ['return', 'escape']: + if self.non_inc_query: + if self.non_inc_direction==-1: + res=self._history.reverse_search_history(self.non_inc_query) + else: + res=self._history.forward_search_history(self.non_inc_query) + + self._bell() + self.prompt=self.non_inc_oldprompt + self.process_keyevent_queue=self.process_keyevent_queue[:-1] + self._history.history_cursor=len(self._history.history) + if keyinfo.keyname == 'escape': + self.l_buffer=self.non_inc_oldline + else: + self.l_buffer.set_line(res) + return False + elif keyinfo.keyname: + pass + elif keyinfo.control==False and keyinfo.meta==False : + self.non_inc_query += keyinfo.char + else: + pass + self.prompt=self.non_inc_oldprompt+":"+self.non_inc_query + + def _init_non_i_search(self, direction): + self.non_inc_direction = direction + self.non_inc_query = "" + self.non_inc_oldprompt=self.prompt + self.non_inc_oldline=self.l_buffer.copy() + self.l_buffer.reset_line() + self.prompt=self.non_inc_oldprompt+":" + self.process_keyevent_queue.append(self._process_non_incremental_search_keyevent) + + def non_incremental_reverse_search_history(self, e): # (M-p) + '''Search backward starting at the current line and moving up + through the history as necessary using a non-incremental search for + a string supplied by the user.''' + return self._init_non_i_search(-1) + + def non_incremental_forward_search_history(self, e): # (M-n) + '''Search forward starting at the current line and moving down + through the the history as necessary using a non-incremental search + for a string supplied by the user.''' + return self._init_non_i_search(1) + +class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode): mode="emacs" - def __init__(self,rlobj): - super(EmacsMode,self).__init__(rlobj) + def __init__(self, rlobj): + basemode.BaseMode.__init__(self, rlobj) + IncrementalSearchPromptMode.__init__(self, rlobj) + SearchPromptMode.__init__(self, rlobj) self._keylog=(lambda x,y: None) self.previous_func=None self.prompt=">>>" self._insert_verbatim=False self.next_meta = False # True to force meta on next character + self.process_keyevent_queue=[self._process_keyevent] + def __repr__(self): return "" @@ -44,6 +165,13 @@ class EmacsMode(basemode.BaseMode): self._keylog=logfun def process_keyevent(self, keyinfo): + r=self.process_keyevent_queue[-1](keyinfo) + if r: + self.add_history(self.l_buffer.copy()) + return True + return False + + def _process_keyevent(self, keyinfo): """return True when line is final """ #Process exit keys. Only exit on empty line @@ -71,6 +199,7 @@ class EmacsMode(basemode.BaseMode): log("readline from keyboard:%s,%s"%(keytuple, dispatch_func)) log_sock((u"%s|%s"%(ensure_unicode(format(keytuple)),dispatch_func.__name__)),"bound_function") + r = None if dispatch_func: r = dispatch_func(keyinfo) @@ -78,10 +207,8 @@ class EmacsMode(basemode.BaseMode): self.l_buffer.push_undo() self.previous_func = dispatch_func - if r: - self.add_history(self.l_buffer.copy()) - return True - return False + return r + ######### History commands def previous_history(self, e): # (C-p) @@ -102,77 +229,16 @@ class EmacsMode(basemode.BaseMode): being entered.''' self._history.end_of_history(self.l_buffer) - def _i_search(self, searchfun, direction, init_event): - c = self.console - line = self.l_buffer.get_line_text() - query = '' - if (self.previous_func != self.history_search_forward and - self.previous_func != self.history_search_backward): - self.query = ''.join(self.l_buffer[0:Point].get_line_text()) - hc_start = self._history.history_cursor #+ direction - while 1: - x, y = self.prompt_end_pos - c.pos(0, y) - if direction < 0: - prompt = 'reverse-i-search' - else: - prompt = 'forward-i-search' - - scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line)) - self._update_prompt_pos(scroll) - self._clear_after() - - event = c.getkeypress().keyinfo - if event.keyname == 'backspace': - query = query[:-1] - if len(query) > 0: - #self._history.history_cursor = hc_start #forces search to restart when search empty - line=searchfun(query) - else: - self._bell() - line="" #empty query means no search result - elif event.char in string.letters + string.digits + string.punctuation + ' ': - #self._history.history_cursor = hc_start - query += event.char - line=searchfun(query) - elif event== init_event: - self._history.history_cursor += direction - line=searchfun(query) - else: - if event.keyname != 'return': - self._bell() - break - - px, py = self.prompt_begin_pos - c.pos(0, py) - self.l_buffer.set_line(line) - self._print_prompt() - self._history.history_cursor=len(self._history.history) def reverse_search_history(self, e): # (C-r) '''Search backward starting at the current line and moving up through the history as necessary. This is an incremental search.''' - self._i_search(self._history.reverse_search_history, -1, e) + self._init_incremental_search(self._history.reverse_search_history, -1, e) def forward_search_history(self, e): # (C-s) '''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' - self._i_search(self._history.forward_search_history, 1, e) - - - def non_incremental_reverse_search_history(self, e): # (M-p) - '''Search backward starting at the current line and moving up - through the history as necessary using a non-incremental search for - a string supplied by the user.''' - q=self._history.non_incremental_reverse_search_history(self.l_buffer) - self.l_buffer=q - - def non_incremental_forward_search_history(self, e): # (M-n) - '''Search forward starting at the current line and moving down - through the the history as necessary using a non-incremental search - for a string supplied by the user.''' - q=self._history.non_incremental_reverse_search_history(self.l_buffer) - self.l_buffer=q + self._init_incremental_search(self._history.forward_search_history, 1, e) def history_search_forward(self, e): # () '''Search forward through the history for the string of characters diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 617044f..026022d 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -422,7 +422,9 @@ class Readline(BaseReadline): c=self.console l_buffer=self.mode.l_buffer c.cursor(0) #Hide cursor avoiding flicking - c.pos(*self.prompt_end_pos) + #c.pos(*self.prompt_end_pos) + c.pos(*self.prompt_begin_pos) + self._print_prompt() ltext = l_buffer.quoted_text() if l_buffer.enable_selection and l_buffer.selection_mark>=0: start=len(l_buffer[:l_buffer.selection_mark].quoted_text()) From b4462fb1376211c50380374efb4c598bb71e56e4 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 1 Jul 2008 21:06:07 +0200 Subject: [PATCH 13/26] Fixed last functions in emacs mode that use console directly. Implemented digit_argument. Made changes to TextLine and ReadLineTextLine classes to handle argument in insert_text Added DigitArgumentMode to handle digit_arguments --- pyreadline/lineeditor/lineobj.py | 7 +- pyreadline/modes/basemode.py | 56 ++++- pyreadline/modes/emacs.py | 368 ++++++++++++++++++------------- 3 files changed, 265 insertions(+), 166 deletions(-) diff --git a/pyreadline/lineeditor/lineobj.py b/pyreadline/lineeditor/lineobj.py index e7c3486..8748dd1 100644 --- a/pyreadline/lineeditor/lineobj.py +++ b/pyreadline/lineeditor/lineobj.py @@ -267,7 +267,8 @@ class TextLine(object): def end_of_line(self): self.point = len(self.line_buffer) - def _insert_text(self, text): + def _insert_text(self, text, argument=1): + text=text*argument if self.overwrite: for c in text: #if self.point: @@ -406,10 +407,10 @@ class ReadLineTextBuffer(TextLine): return 'ReadLineTextBuffer("%s",point=%s,mark=%s,selection_mark=%s)'%(self.line_buffer,self.point,self.mark,self.selection_mark) - def insert_text(self,char): + def insert_text(self, char, argument=1): self.delete_selection() self.selection_mark=-1 - self._insert_text(char) + self._insert_text(char, argument) def to_clipboard(self): if self.enable_win32_clipboard: diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index d3c84f1..dc4e573 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -20,6 +20,7 @@ in_ironpython="IronPython" in sys.version class BaseMode(object): mode="base" def __init__(self,rlobj): + self.argument=0 self.rlobj=rlobj self.exit_dispatch = {} self.key_dispatch = {} @@ -71,7 +72,9 @@ class BaseMode(object): def _argreset(self): val=self.argument - self.argument=1 + self.argument=0 + if val==0: + val=1 return val argument_reset=property(_argreset) @@ -126,6 +129,12 @@ class BaseMode(object): #################################### + def finalize(self): + """Every bindable command should call this function for cleanup. + Except those that want to set argument to a non-zero value. + """ + self.argument=0 + def add_history(self, text): self._history.add_history(lineobj.ReadLineTextBuffer(text)) @@ -255,11 +264,13 @@ class BaseMode(object): self._bell() else: self._bell() + self.finalize() def possible_completions(self, e): # (M-?) """List the possible completions of the text before point. """ completions = self._get_completions() self._display_completions(completions) + self.finalize() def insert_completions(self, e): # (M-*) """Insert all completions of the text before point that would have @@ -274,6 +285,7 @@ class BaseMode(object): b += len(rep) e = b self.line_cursor = b + self.finalize() def menu_complete(self, e): # () """Similar to complete, but replaces the word to be completed with a @@ -285,87 +297,104 @@ class BaseMode(object): positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default.""" - pass + self.finalize() ### Methods below here are bindable emacs functions def insert_text(self, string): """Insert text into the command line.""" - self.l_buffer.insert_text(string) + self.l_buffer.insert_text(string, self.argument_reset) + self.finalize() def beginning_of_line(self, e): # (C-a) """Move to the start of the current line. """ self.l_buffer.beginning_of_line() + self.finalize() def end_of_line(self, e): # (C-e) """Move to the end of the line. """ self.l_buffer.end_of_line() + self.finalize() def forward_char(self, e): # (C-f) """Move forward a character. """ self.l_buffer.forward_char(self.argument_reset) + self.finalize() def backward_char(self, e): # (C-b) """Move back a character. """ self.l_buffer.backward_char(self.argument_reset) + self.finalize() def forward_word(self, e): # (M-f) """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word(self.argument_reset) + self.finalize() def backward_word(self, e): # (M-b) """Move back to the start of the current or previous word. Words are composed of letters and digits.""" self.l_buffer.backward_word(self.argument_reset) + self.finalize() def forward_word_end(self, e): # () """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end(self.argument_reset) + self.finalize() def backward_word_end(self, e): # () """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.backward_word_end(self.argument_reset) + self.finalize() ### Movement with extend selection def beginning_of_line_extend_selection(self, e): # """Move to the start of the current line. """ self.l_buffer.beginning_of_line_extend_selection() + self.finalize() def end_of_line_extend_selection(self, e): # """Move to the end of the line. """ self.l_buffer.end_of_line_extend_selection() + self.finalize() def forward_char_extend_selection(self, e): # """Move forward a character. """ self.l_buffer.forward_char_extend_selection(self.argument_reset) + self.finalize() def backward_char_extend_selection(self, e): # """Move back a character. """ self.l_buffer.backward_char_extend_selection(self.argument_reset) + self.finalize() def forward_word_extend_selection(self, e): # """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_extend_selection(self.argument_reset) + self.finalize() def backward_word_extend_selection(self, e): # """Move back to the start of the current or previous word. Words are composed of letters and digits.""" self.l_buffer.backward_word_extend_selection(self.argument_reset) + self.finalize() def forward_word_end_extend_selection(self, e): # """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) + self.finalize() def backward_word_end_extend_selection(self, e): # """Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) + self.finalize() ######## Change case @@ -374,16 +403,19 @@ class BaseMode(object): """Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor.""" self.l_buffer.upcase_word() + self.finalize() def downcase_word(self, e): # (M-l) """Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor.""" self.l_buffer.downcase_word() + self.finalize() def capitalize_word(self, e): # (M-c) """Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor.""" self.l_buffer.capitalize_word() + self.finalize() ######## @@ -391,48 +423,55 @@ class BaseMode(object): """Clear the screen and redraw the current line, leaving the current line at the top of the screen.""" self.console.page() + self.finalize() def redraw_current_line(self, e): # () """Refresh the current line. By default, this is unbound.""" - pass + self.finalize() def accept_line(self, e): # (Newline or Return) """Accept the line regardless of where the cursor is. If this line is non-empty, it may be added to the history list for future recall with add_history(). If this line is a modified history line, the history line is restored to its original state.""" + self.finalize() return True - def delete_char(self, e): # (C-d) """Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF.""" self.l_buffer.delete_char(self.argument_reset) + self.finalize() def backward_delete_char(self, e): # (Rubout) """Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_char(self.argument_reset) + self.finalize() def backward_delete_word(self, e): # (Control-Rubout) """Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_word(self.argument_reset) + self.finalize() def forward_delete_word(self, e): # (Control-Delete) """Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.forward_delete_word(self.argument_reset) + self.finalize() def delete_horizontal_space(self, e): # () """Delete all spaces and tabs around point. By default, this is unbound. """ self.l_buffer.delete_horizontal_space() + self.finalize() def self_insert(self, e): # (a, b, A, 1, !, ...) """Insert yourself. """ if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) + self.finalize() # Paste from clipboard @@ -445,6 +484,7 @@ class BaseMode(object): txt=txt.split("\n")[0].strip("\r").strip("\n") log("paste: >%s<"%map(ord,txt)) self.insert_text(txt) + self.finalize() def paste_mulitline_code(self,e): """Paste windows clipboard as multiline code. @@ -462,6 +502,7 @@ class BaseMode(object): return True else: return False + self.finalize() def ipython_paste(self,e): """Paste windows clipboard. If enable_ipython_paste_list_of_lists is @@ -475,19 +516,23 @@ class BaseMode(object): if len(txt)<300 and ("\t" not in txt) and ("\n" not in txt): txt=txt.replace("\\","/").replace(" ",r"\ ") self.insert_text(txt) + self.finalize() def copy_region_to_clipboard(self, e): # () """Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_region_to_clipboard() + self.finalize() def copy_selection_to_clipboard(self, e): # () """Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_selection_to_clipboard() + self.finalize() def cut_selection_to_clipboard(self, e): # () """Copy the text in the region to the windows clipboard.""" self.l_buffer.cut_selection_to_clipboard() + self.finalize() def dump_functions(self, e): # () """Print all of the functions and their key bindings to the Readline @@ -498,6 +543,7 @@ class BaseMode(object): txt="\n".join(self.rl_settings_to_string()) print txt self._print_prompt() + self.finalize() def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 221e68c..65478c2 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -88,6 +88,10 @@ class IncrementalSearchPromptMode(object): else: self.line="" + + + + class SearchPromptMode(object): def __init__(self, rlobj): pass @@ -143,12 +147,58 @@ class SearchPromptMode(object): for a string supplied by the user.''' return self._init_non_i_search(1) -class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode): +class LeaveModeTryNext(Exception): pass + +class DigitArgumentMode(object): + def __init__(self, rlobj): + pass + + def _process_digit_argument_keyevent(self, keyinfo): + log_sock("_process_digit_argument_keyevent %s"%keyinfo) + keytuple=keyinfo.tuple() + log_sock("%s %s"%(keyinfo,keytuple)) + if keyinfo.keyname in ['return']: + self.prompt=self._digit_argument_oldprompt + self.process_keyevent_queue=self.process_keyevent_queue[:-1] + return True + elif keyinfo.keyname: + pass + elif keyinfo.char in "0123456789" and keyinfo.control==False and keyinfo.meta==False : + log_sock("arg %s %s"%(self.argument,keyinfo.char)) + self.argument=self.argument*10+int(keyinfo.char) + else: + self.prompt=self._digit_argument_oldprompt + raise LeaveModeTryNext + self.prompt="(arg: %s) "%self.argument + + def _init_digit_argument(self, keyinfo): + """Initialize search prompt + """ + c = self.console + line = self.l_buffer.get_line_text() + self._digit_argument_oldprompt = self.prompt + self.process_keyevent_queue.append(self._process_digit_argument_keyevent) + + if keyinfo.char=="-": + self.argument=-1 + elif keyinfo.char in "0123456789": + self.argument=int(keyinfo.char) + log_sock("<%s> %s"%(self.argument,type(self.argument))) + self.prompt="(arg: %s) "%self.argument + log_sock("arg-init %s %s"%(self.argument,keyinfo.char)) + + + + + + +class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode): mode="emacs" def __init__(self, rlobj): basemode.BaseMode.__init__(self, rlobj) IncrementalSearchPromptMode.__init__(self, rlobj) SearchPromptMode.__init__(self, rlobj) + DigitArgumentMode.__init__(self, rlobj) self._keylog=(lambda x,y: None) self.previous_func=None self.prompt=">>>" @@ -165,7 +215,11 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode self._keylog=logfun def process_keyevent(self, keyinfo): - r=self.process_keyevent_queue[-1](keyinfo) + try: + r=self.process_keyevent_queue[-1](keyinfo) + except LeaveModeTryNext: + self.process_keyevent_queue=self.process_keyevent_queue[:-1] + r=self.process_keyevent(keyinfo) if r: self.add_history(self.l_buffer.copy()) return True @@ -175,6 +229,7 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode """return True when line is final """ #Process exit keys. Only exit on empty line + log_sock("_process_keyevent %s"%keyinfo) def nop(e): pass if self.next_meta: @@ -185,6 +240,7 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode if self._insert_verbatim: self.insert_text(keyinfo) self._insert_verbatim=False + self.argument=0 return False if keytuple in self.exit_dispatch: @@ -209,36 +265,40 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode self.previous_func = dispatch_func return r - ######### History commands def previous_history(self, e): # (C-p) '''Move back through the history list, fetching the previous command. ''' self._history.previous_history(self.l_buffer) self.l_buffer.point=lineobj.EndOfLine + self.finalize() def next_history(self, e): # (C-n) '''Move forward through the history list, fetching the next command. ''' self._history.next_history(self.l_buffer) + self.finalize() def beginning_of_history(self, e): # (M-<) '''Move to the first line in the history.''' self._history.beginning_of_history() + self.finalize() def end_of_history(self, e): # (M->) '''Move to the end of the input history, i.e., the line currently being entered.''' self._history.end_of_history(self.l_buffer) - + self.finalize() def reverse_search_history(self, e): # (C-r) '''Search backward starting at the current line and moving up through the history as necessary. This is an incremental search.''' self._init_incremental_search(self._history.reverse_search_history, -1, e) + self.finalize() def forward_search_history(self, e): # (C-s) '''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' self._init_incremental_search(self._history.forward_search_history, 1, e) + self.finalize() def history_search_forward(self, e): # () '''Search forward through the history for the string of characters @@ -251,6 +311,7 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode q=self._history.history_search_forward(self.l_buffer) self.l_buffer=q self.l_buffer.point=q.point + self.finalize() def history_search_backward(self, e): # () '''Search backward through the history for the string of characters @@ -263,6 +324,7 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode q=self._history.history_search_backward(self.l_buffer) self.l_buffer=q self.l_buffer.point=q.point + self.finalize() def yank_nth_arg(self, e): # (M-C-y) @@ -271,30 +333,32 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command.''' - pass + self.finalize() def yank_last_arg(self, e): # (M-. or M-_) '''Insert last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn.''' - pass + self.finalize() def forward_backward_delete_char(self, e): # () '''Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.''' - pass + self.finalize() def quoted_insert(self, e): # (C-q or C-v) '''Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example.''' self._insert_verbatim=True + self.finalize() def tab_insert(self, e): # (M-TAB) '''Insert a tab character. ''' ws = ' ' * (self.tabstop - (self.l_buffer.point%self.tabstop)) self.insert_text(ws) + self.finalize() def transpose_chars(self, e): # (C-t) '''Drag the character before the cursor forward over the character @@ -302,12 +366,14 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.''' self.l_buffer.transpose_chars() + self.finalize() def transpose_words(self, e): # (M-t) '''Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line.''' self.l_buffer.transpose_words() + self.finalize() def overwrite_mode(self, e): # () '''Toggle overwrite mode. With an explicit positive numeric @@ -318,115 +384,195 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space.''' - pass + self.finalize() def kill_line(self, e): # (C-k) '''Kill the text from point to the end of the line. ''' self.l_buffer.kill_line() + self.finalize() def backward_kill_line(self, e): # (C-x Rubout) '''Kill backward to the beginning of the line. ''' self.l_buffer.backward_kill_line() + self.finalize() def unix_line_discard(self, e): # (C-u) '''Kill backward from the cursor to the beginning of the current line. ''' # how is this different from backward_kill_line? self.l_buffer.unix_line_discard() + self.finalize() def kill_whole_line(self, e): # () '''Kill all characters on the current line, no matter where point is. By default, this is unbound.''' self.l_buffer.kill_whole_line() + self.finalize() def kill_word(self, e): # (M-d) '''Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word.''' self.l_buffer.kill_word() + self.finalize() + forward_kill_word=kill_word - + def backward_kill_word(self, e): # (M-DEL) '''Kill the word behind point. Word boundaries are the same as backward-word. ''' self.l_buffer.backward_kill_word() - + self.finalize() + def unix_word_rubout(self, e): # (C-w) '''Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring.''' self.l_buffer.unix_word_rubout() - + self.finalize() + def kill_region(self, e): # () '''Kill the text in the current region. By default, this command is unbound. ''' - pass - + self.finalize() + def copy_region_as_kill(self, e): # () '''Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound.''' - pass - + self.finalize() + def copy_backward_word(self, e): # () '''Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. By default, this command is unbound.''' - pass - + self.finalize() + def copy_forward_word(self, e): # () '''Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.''' - pass - + self.finalize() + def yank(self, e): # (C-y) '''Yank the top of the kill ring into the buffer at point. ''' self.l_buffer.yank() - + self.finalize() + def yank_pop(self, e): # (M-y) '''Rotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop.''' self.l_buffer.yank_pop() + self.finalize() + + def delete_char_or_list(self, e): # () + '''Deletes the character under the cursor if not at the beginning or + end of the line (like delete-char). If at the end of the line, + behaves identically to possible-completions. This command is unbound + by default.''' + self.finalize() + + def start_kbd_macro(self, e): # (C-x () + '''Begin saving the characters typed into the current keyboard macro. ''' + self.finalize() + + def end_kbd_macro(self, e): # (C-x )) + '''Stop saving the characters typed into the current keyboard macro + and save the definition.''' + self.finalize() + + def call_last_kbd_macro(self, e): # (C-x e) + '''Re-execute the last keyboard macro defined, by making the + characters in the macro appear as if typed at the keyboard.''' + self.finalize() + + def re_read_init_file(self, e): # (C-x C-r) + '''Read in the contents of the inputrc file, and incorporate any + bindings or variable assignments found there.''' + self.finalize() + + def abort(self, e): # (C-g) + '''Abort the current editing command and ring the terminals bell + (subject to the setting of bell-style).''' + self._bell() + self.finalize() + + def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...) + '''If the metafied character x is lowercase, run the command that is + bound to the corresponding uppercase character.''' + self.finalize() + + def prefix_meta(self, e): # (ESC) + '''Metafy the next character typed. This is for keyboards without a + meta key. Typing ESC f is equivalent to typing M-f. ''' + self.next_meta = True + self.finalize() + + def undo(self, e): # (C-_ or C-x C-u) + '''Incremental undo, separately remembered for each line.''' + self.l_buffer.pop_undo() + self.finalize() + + def revert_line(self, e): # (M-r) + '''Undo all changes made to this line. This is like executing the + undo command enough times to get back to the beginning.''' + self.finalize() + + def tilde_expand(self, e): # (M-~) + '''Perform tilde expansion on the current word.''' + self.finalize() + + def set_mark(self, e): # (C-@) + '''Set the mark to the point. If a numeric argument is supplied, the + mark is set to that position.''' + self.l_buffer.set_mark() + self.finalize() + + def exchange_point_and_mark(self, e): # (C-x C-x) + '''Swap the point with the mark. The current cursor position is set + to the saved position, and the old cursor position is saved as the + mark.''' + self.finalize() + + def character_search(self, e): # (C-]) + '''A character is read and point is moved to the next occurrence of + that character. A negative count searches for previous occurrences.''' + self.finalize() + + def character_search_backward(self, e): # (M-C-]) + '''A character is read and point is moved to the previous occurrence + of that character. A negative count searches for subsequent + occurrences.''' + self.finalize() + + def insert_comment(self, e): # (M-#) + '''Without a numeric argument, the value of the comment-begin + variable is inserted at the beginning of the current line. If a + numeric argument is supplied, this command acts as a toggle: if the + characters at the beginning of the line do not match the value of + comment-begin, the value is inserted, otherwise the characters in + comment-begin are deleted from the beginning of the line. In either + case, the line is accepted as if a newline had been typed.''' + self.finalize() + + def dump_variables(self, e): # () + '''Print all of the settable variables and their values to the + Readline output stream. If a numeric argument is supplied, the + output is formatted in such a way that it can be made part of an + inputrc file. This command is unbound by default.''' + self.finalize() + + def dump_macros(self, e): # () + '''Print all of the Readline key sequences bound to macros and the + strings they output. If a numeric argument is supplied, the output + is formatted in such a way that it can be made part of an inputrc + file. This command is unbound by default.''' + self.finalize() + def digit_argument(self, e): # (M-0, M-1, ... M--) '''Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument.''' - args=e.char - - c = self.console - line = self.l_buffer.get_line_text() - oldprompt=self.prompt - def nop(e): - pass - while 1: - x, y = self.prompt_end_pos - c.pos(0, y) - self.prompt="(arg: %s) "%args - self._print_prompt() - self._update_line() - - event = c.getkeypress() - if event.keyinfo.keyname == 'enter': - break - elif event.char in "0123456789": - args+=event.char - else: - self.argument=int(args) - keyinfo=event.keyinfo.tuple() - if len(keyinfo[-1])>1: - default=nop - else: - default=self.self_insert - dispatch_func = self.key_dispatch.get(keyinfo,default) - dispatch_func(event) - break - self.prompt=oldprompt - x, y = self.prompt_end_pos - c.pos(0, y) - self._print_prompt() - self._update_line() - - - + self._init_digit_argument(e) + #Should not finalize def universal_argument(self, e): # () '''This is another way to specify an argument. If this command is @@ -440,107 +586,7 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. By default, this is not bound to a key.''' - pass - - def delete_char_or_list(self, e): # () - '''Deletes the character under the cursor if not at the beginning or - end of the line (like delete-char). If at the end of the line, - behaves identically to possible-completions. This command is unbound - by default.''' - pass - - def start_kbd_macro(self, e): # (C-x () - '''Begin saving the characters typed into the current keyboard macro. ''' - pass - - def end_kbd_macro(self, e): # (C-x )) - '''Stop saving the characters typed into the current keyboard macro - and save the definition.''' - pass - - def call_last_kbd_macro(self, e): # (C-x e) - '''Re-execute the last keyboard macro defined, by making the - characters in the macro appear as if typed at the keyboard.''' - pass - - def re_read_init_file(self, e): # (C-x C-r) - '''Read in the contents of the inputrc file, and incorporate any - bindings or variable assignments found there.''' - pass - - def abort(self, e): # (C-g) - '''Abort the current editing command and ring the terminals bell - (subject to the setting of bell-style).''' - self._bell() - - def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...) - '''If the metafied character x is lowercase, run the command that is - bound to the corresponding uppercase character.''' - pass - - def prefix_meta(self, e): # (ESC) - '''Metafy the next character typed. This is for keyboards without a - meta key. Typing ESC f is equivalent to typing M-f. ''' - self.next_meta = True - - def undo(self, e): # (C-_ or C-x C-u) - '''Incremental undo, separately remembered for each line.''' - self.l_buffer.pop_undo() - - def revert_line(self, e): # (M-r) - '''Undo all changes made to this line. This is like executing the - undo command enough times to get back to the beginning.''' - pass - - def tilde_expand(self, e): # (M-~) - '''Perform tilde expansion on the current word.''' - pass - - def set_mark(self, e): # (C-@) - '''Set the mark to the point. If a numeric argument is supplied, the - mark is set to that position.''' - self.l_buffer.set_mark() - - def exchange_point_and_mark(self, e): # (C-x C-x) - '''Swap the point with the mark. The current cursor position is set - to the saved position, and the old cursor position is saved as the - mark.''' - pass - - def character_search(self, e): # (C-]) - '''A character is read and point is moved to the next occurrence of - that character. A negative count searches for previous occurrences.''' - pass - - def character_search_backward(self, e): # (M-C-]) - '''A character is read and point is moved to the previous occurrence - of that character. A negative count searches for subsequent - occurrences.''' - pass - - def insert_comment(self, e): # (M-#) - '''Without a numeric argument, the value of the comment-begin - variable is inserted at the beginning of the current line. If a - numeric argument is supplied, this command acts as a toggle: if the - characters at the beginning of the line do not match the value of - comment-begin, the value is inserted, otherwise the characters in - comment-begin are deleted from the beginning of the line. In either - case, the line is accepted as if a newline had been typed.''' - pass - - def dump_variables(self, e): # () - '''Print all of the settable variables and their values to the - Readline output stream. If a numeric argument is supplied, the - output is formatted in such a way that it can be made part of an - inputrc file. This command is unbound by default.''' - pass - - def dump_macros(self, e): # () - '''Print all of the Readline key sequences bound to macros and the - strings they output. If a numeric argument is supplied, the output - is formatted in such a way that it can be made part of an inputrc - file. This command is unbound by default.''' - pass + #Should not finalize #Create key bindings: @@ -622,6 +668,12 @@ class EmacsMode(IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode self._bind_key("divide", self.self_insert) self._bind_key("vk_decimal", self.self_insert) log("RUNNING INIT EMACS") + for i in range(0,10): + self._bind_key("alt-%d"%i, self.digit_argument) + self._bind_key("alt--", self.digit_argument) + + + # make it case insensitive def commonprefix(m): From e077db56c6879933fde5f4839a6e15ed817f2d0b Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 1 Jul 2008 22:06:38 +0200 Subject: [PATCH 14/26] improved tk_gui.py example to have a rudimentary python interpreter translation of KeyPress events needs much work. Dead keys, alt gr, and many special non-alphanumeric keys don't work properly. --- pyreadline/examples/tk_gui.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/pyreadline/examples/tk_gui.py b/pyreadline/examples/tk_gui.py index f4950b8..e8ef83e 100644 --- a/pyreadline/examples/tk_gui.py +++ b/pyreadline/examples/tk_gui.py @@ -16,15 +16,27 @@ import pyreadline.logger as log log.sock_silent=False import Tkinter,sys +translate={"plus":"+","minus":"-","asterisk":"*","slash":"/","exclam":"!","quotedbl":'"', + "parenleft":"(","parenright":")",} + def KeyPress_from_event(event): - if len(event.keysym)>1: - keysym=event.keysym.lower() - char=event.char - else: + keysym=event.keysym.lower() + char=event.char + if keysym in translate: + keysym=translate[keysym] + + shift=event.state&1!=0 + control=event.state&4!=0 + meta=event.state&(131072)!=0 + + if len(keysym)==1 and control and meta: keysym="" - char=event.keysym - return KeyPress(char, event.state&1!=0, event.state&4!=0, event.state&(131072)!=0, keysym) + elif len(keysym)==1: + char=keysym + keysym="" + + return KeyPress(char, shift, control, meta, keysym) class App: @@ -41,6 +53,7 @@ class App: self.text=Tkinter.Label(frame, textvariable=self.textvar,width=50,height=40,justify=Tkinter.LEFT,anchor=Tkinter.NW) self.text.pack(side=Tkinter.LEFT) master.bind("",self.handler) + self.locals={} def handler(self, event): keyevent=KeyPress_from_event(event) @@ -50,7 +63,14 @@ class App: self.frame.quit() return if result: - self.lines.append(self.RL.get_line_buffer()) + self.lines.append(self.prompt+" "+self.RL.get_line_buffer()) + line=self.RL.get_line_buffer() + if line.strip(): + try: + result=eval(line, globals(), self.locals) + self.lines.append(repr(result)) + except: + self.lines.append("ERROR") self.readline_setup(self.prompt) self._update_line() From dd9ea63fb782ff4561d66c57d6b586b3c9e1f183 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Mon, 7 Jul 2008 18:18:20 +0200 Subject: [PATCH 15/26] Changed logging to use the logging module. --- pyreadline/console/console.py | 18 ++++-- pyreadline/console/ironpython_console.py | 12 ++-- pyreadline/keysyms/ironpython_keysyms.py | 3 +- pyreadline/keysyms/keysyms.py | 15 ++--- pyreadline/lineeditor/history.py | 10 +-- pyreadline/lineeditor/lineobj.py | 2 +- pyreadline/logger.py | 79 ++++++++++++++---------- pyreadline/logserver.py | 67 ++++++++++---------- pyreadline/modes/basemode.py | 8 +-- pyreadline/modes/emacs.py | 25 ++++---- pyreadline/modes/vi.py | 2 +- pyreadline/rlmain.py | 37 ++++++++--- pyreadline/test/emacs_test.py | 6 +- pyreadline/test/history_test.py | 2 +- pyreadline/test/vi_test.py | 2 +- 15 files changed, 162 insertions(+), 126 deletions(-) diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index 413b7d9..38f7c35 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -16,7 +16,7 @@ This was modeled after the C extension of the same name by Fredrik Lundh. import sys,os import traceback import re -from pyreadline.logger import log,log_sock +from pyreadline.logger import log from pyreadline.unicode_helper import ensure_unicode,ensure_str import pyreadline.unicode_helper as unicode_helper try: @@ -29,6 +29,13 @@ except ImportError: from pyreadline.keysyms import make_KeyPress from pyreadline.console.ansi import AnsiState,AnsiWriter + +def nolog(string): + pass + +log=nolog + + # some constants we need STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 @@ -297,7 +304,6 @@ class Console(object): # split the string into ordinary characters and funny characters chunks = self.motion_char_re.split(text) for chunk in chunks: - log('C:'+chunk) n = self.write_color(chunk, attr) if len(chunk) == 1: # the funny characters will be alone if chunk[0] == '\n': # newline @@ -339,8 +345,8 @@ class Console(object): n,res= self.ansiwriter.write_color(text,attr) junk = c_int(0) for attr,chunk in res: - log(unicode(attr)) - log(unicode(chunk)) + log(u"console.attr:%s"%unicode(attr)) + log(u"console.chunk:%s"%unicode(chunk)) self.SetConsoleTextAttribute(self.hout, attr.winattr) for short_chunk in split_block(chunk): self.WriteConsoleW(self.hout, short_chunk, len(short_chunk), byref(junk), None) @@ -480,7 +486,7 @@ class Console(object): status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count)) if status and count.value == 1: e = event(self, Cevent) - log_sock(ensure_unicode(e.keyinfo),"keypress") + log(u"console.get %s"%ensure_unicode(e.keyinfo)) return e def getkeypress(self): @@ -488,7 +494,7 @@ class Console(object): while 1: e = self.get() if e.type == 'KeyPress' and e.keycode not in key_modifiers: - log(e) + log("console.getleypress %s"%e) if e.keyinfo.keyname == 'next': self.scroll_window(12) elif e.keyinfo.keyname == 'prior': diff --git a/pyreadline/console/ironpython_console.py b/pyreadline/console/ironpython_console.py index d8c048a..df18bd1 100644 --- a/pyreadline/console/ironpython_console.py +++ b/pyreadline/console/ironpython_console.py @@ -35,7 +35,7 @@ import os import System from event import Event -from pyreadline.logger import log,log_sock +from pyreadline.logger import log #print "Codepage",System.Console.InputEncoding.CodePage from pyreadline.keysyms import make_keysym, make_keyinfo,make_KeyPress,make_KeyPress_from_keydescr @@ -85,15 +85,14 @@ class Console(object): self.saveattr = winattr[str(System.Console.ForegroundColor).lower()] self.savebg=System.Console.BackgroundColor log('initial attr=%s' % self.attr) - log_sock("%s"%self.saveattr) def _get(self): top=System.Console.WindowTop - log_sock("WindowTop:%s"%top,"console") + log("WindowTop:%s"%top) return top def _set(self,value): top=System.Console.WindowTop - log_sock("Set WindowTop:old:%s,new:%s"%(top,value),"console") + log("Set WindowTop:old:%s,new:%s"%(top,value)) WindowTop=property(_get,_set) del _get,_set @@ -148,7 +147,6 @@ class Console(object): # split the string into ordinary characters and funny characters chunks = self.motion_char_re.split(text) for chunk in chunks: - log('C:'+chunk) n = self.write_color(chunk, attr) if len(chunk) == 1: # the funny characters will be alone if chunk[0] == '\n': # newline @@ -311,7 +309,7 @@ class Console(object): elif e.Key == System.ConsoleKey.PageUp:#PageUp self.scroll_window(-12) elif str(e.KeyChar)=="\000":#Drop deadkeys - log_sock("Deadkey: %s"%e) + log("Deadkey: %s"%e) return event(self,e) pass else: @@ -364,7 +362,7 @@ class event(Event): self.char = str(input.KeyChar) self.keycode = input.Key self.state = input.Modifiers - log_sock("%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar),"console") + log("%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar)) self.type="KeyRelease" self.keysym = make_keysym(self.keycode) self.keyinfo = make_KeyPress(self.char, self.state, self.keycode) diff --git a/pyreadline/keysyms/ironpython_keysyms.py b/pyreadline/keysyms/ironpython_keysyms.py index dc7168a..6b3534d 100644 --- a/pyreadline/keysyms/ironpython_keysyms.py +++ b/pyreadline/keysyms/ironpython_keysyms.py @@ -8,7 +8,7 @@ #***************************************************************************** import System from common import validkey,KeyPress,make_KeyPress_from_keydescr -#from pyreadline.logger import log_sock + c32=System.ConsoleKey Shift=System.ConsoleModifiers.Shift Control=System.ConsoleModifiers.Control @@ -196,7 +196,6 @@ def make_KeyPress(char,state,keycode): control=bool(int(state)&int(Control)) meta=bool(int(state)&int(Alt)) keyname=code2sym_map.get(keycode,"").lower() -# log_sock("make key %s %s %s %s"%(shift,control,meta,keycode),"keysyms") if control and meta: #equivalent to altgr so clear flags control=False meta=False diff --git a/pyreadline/keysyms/keysyms.py b/pyreadline/keysyms/keysyms.py index f07e1f5..1eecd34 100644 --- a/pyreadline/keysyms/keysyms.py +++ b/pyreadline/keysyms/keysyms.py @@ -7,6 +7,7 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** import winconstants as c32 +from pyreadline.logger import log from ctypes import windll import ctypes # table for translating virtual keys to X windows key symbols @@ -111,21 +112,21 @@ def char_to_keyinfo(char, control=False, meta=False, shift=False): k.char=chr(vk & 0xff) return k -def make_KeyPress(char,state,keycode): +def make_KeyPress(char, state, keycode): control = (state & (4+8)) != 0 meta = (state & (1+2)) != 0 shift = (state & 0x10) != 0 - if control and char !="\x00": - char = chr(VkKeyScan(ord(char)) & 0xff) - elif control and meta and char !="\x00": - char = chr(VkKeyScan(ord(char)) & 0xff) - elif control: + if control and not meta:#Matches ctrl- chords should pass keycode as char char=chr(keycode) + elif control and meta: #Matches alt gr and should just pass on char + control=False + meta=False try: keyname=code2sym_map[keycode] except KeyError: keyname="" - return KeyPress(char,shift,control,meta,keyname) + out=KeyPress(char, shift, control, meta, keyname) + return out if __name__=="__main__": import startup diff --git a/pyreadline/lineeditor/history.py b/pyreadline/lineeditor/history.py index a433f55..9eee20e 100644 --- a/pyreadline/lineeditor/history.py +++ b/pyreadline/lineeditor/history.py @@ -20,7 +20,7 @@ import exceptions class EscapeHistory(exceptions.Exception): pass -from pyreadline.logger import log_sock +from pyreadline.logger import log _ignore_leading_spaces=False @@ -35,20 +35,20 @@ class LineHistory(object): def get_history_length(self): value=self._history_length - log_sock("get_history_length:%d"%value,"history") + log("get_history_length:%d"%value) return value def set_history_length(self,value): - log_sock("set_history_length: old:%d new:%d"%(self._history_length,value),"history") + log("set_history_length: old:%d new:%d"%(self._history_length,value)) self._history_length=value def get_history_cursor(self): value=self._history_cursor - log_sock("get_history_cursor:%d"%value,"history") + log("get_history_cursor:%d"%value) return value def set_history_cursor(self,value): - log_sock("set_history_cursor: old:%d new:%d"%(self._history_cursor,value),"history") + log("set_history_cursor: old:%d new:%d"%(self._history_cursor,value)) self._history_cursor=value history_length=property(get_history_length,set_history_length) diff --git a/pyreadline/lineeditor/lineobj.py b/pyreadline/lineeditor/lineobj.py index 8748dd1..0e62108 100644 --- a/pyreadline/lineeditor/lineobj.py +++ b/pyreadline/lineeditor/lineobj.py @@ -9,7 +9,7 @@ import re,operator,sys import wordmatcher import pyreadline.clipboard as clipboard -from pyreadline.logger import log,log_sock +from pyreadline.logger import log from pyreadline.unicode_helper import ensure_unicode kill_ring_to_clipboard=False #set to true to copy every addition to kill ring to clipboard diff --git a/pyreadline/logger.py b/pyreadline/logger.py index 0996036..e4f7d3f 100644 --- a/pyreadline/logger.py +++ b/pyreadline/logger.py @@ -6,42 +6,59 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** -import socket +import socket, logging, logging.handlers from pyreadline.unicode_helper import ensure_str -_logfile=False - -def start_log(on,filename): - global _logfile - if on=="on": - _logfile=open(filename,"w") - else: - _logfile=False - -def log(s): - if _logfile: - s = ensure_str(s) - print >>_logfile, s - _logfile.flush() - host="localhost" -port=8081 -logsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) +port=logging.handlers.DEFAULT_TCP_LOGGING_PORT -show_event=["keypress","bound_function","bind_key","console"] -show_event=["bound_function"] -sock_silent=True +root_logger=logging.getLogger('') +root_logger.setLevel(logging.DEBUG) +formatter = logging.Formatter('%(message)s') +file_handler=None -def log_sock(s,event_type=None): - if sock_silent: +class NULLHandler(logging.Handler): + def emit(self, s): pass - else: - if event_type is None: - logsocket.sendto(ensure_str(s),(host,port)) - elif event_type in show_event: - logsocket.sendto(ensure_str(s),(host,port)) - else: - pass - +class SocketStream(object): + def __init__(self, host, port): + self.logsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + + def write(self, s): + self.logsocket.sendto(ensure_str(s),(host,port)) + + def flush(self): + pass + + def close(self): + pass + +socket_handler = logging.StreamHandler(SocketStream(host, port)) +socket_handler.setFormatter(formatter) +root_logger.addHandler(NULLHandler()) + + +def start_socket_log(): + root_logger.addHandler(socket_handler) + +def stop_socket_log(): + root_logger.removeHandler(socket_handler) + +def start_file_log(filename): + global file_handler + file_handler=logging.handlers.FileHandler(filename, "w") + root_logger.addHandler(file_handler) + +def stop_file_log(): + global file_handler + if file_handler: + root_logger.removeHandler(file_handler) + file_handler.close() + file_handler=None + +def log(s): + s = ensure_str(s) + root_logger.debug(s) + diff --git a/pyreadline/logserver.py b/pyreadline/logserver.py index 6b761b2..c5c73fe 100644 --- a/pyreadline/logserver.py +++ b/pyreadline/logserver.py @@ -5,28 +5,21 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -import socket - +import cPickle +import logging +import logging.handlers +import SocketServer +import struct,socket try: import msvcrt except ImportError: msvcrt=None print "problem" - -port =8081 - -s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - -s.bind(("",port)) -s.settimeout(0.05) - -print "Starting logserver on port:",port -print "Press q to quit logserver",port -singleline=False - +port=logging.handlers.DEFAULT_TCP_LOGGING_PORT +host='localhost' def check_key(): if msvcrt is None: @@ -34,27 +27,31 @@ def check_key(): else: if msvcrt.kbhit()!=0: q=msvcrt.getch() - - return q in "q" - else: - return False + return q + return "" -while 1: - try: - data,addr=s.recvfrom(1024) - except socket.timeout: - if check_key(): - print "Quitting logserver" - break - else: - continue - if data.startswith("@@"): - continue - if singleline: - print "\r"," "*78,"\r",data,#,addr - else: - print data - - +singleline=False +def main(): + print "Starting TCP logserver on port:",port + print "Press q to quit logserver", port + print "Press c to clear screen", port + s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + + s.bind(("",port)) + s.settimeout(1) + while 1: + try: + data, addr=s.recvfrom(100000) + print data, + except socket.timeout: + key=check_key().lower() + if "q"==key: + print "Quitting logserver" + break + elif "c" == key: + print "\n"*100 + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index dc4e573..6b5f9be 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -8,7 +8,7 @@ #***************************************************************************** import os,re,math,glob,sys,time import pyreadline.logger as logger -from pyreadline.logger import log,log_sock +from pyreadline.logger import log from pyreadline.keysyms.common import make_KeyPress_from_keydescr import pyreadline.lineeditor.lineobj as lineobj import pyreadline.lineeditor.history as history @@ -203,7 +203,7 @@ class BaseMode(object): completions.append(r) else: break - log('text completions=%s' % completions) + log('text completions=<%s>' % completions) if not completions: # get the filename to complete while self.begidx > 0: @@ -222,7 +222,7 @@ class BaseMode(object): else: mc.append(f) completions = mc - log('fnames=%s' % completions) + log('fnames=<%s>' % completions) return completions @@ -498,7 +498,7 @@ class BaseMode(object): self.insert_text(t[0]) self.add_history(self.l_buffer.copy()) self.paste_line_buffer=t[1:] - log("multi: %s"%self.paste_line_buffer) + log("multi: >%s<"%self.paste_line_buffer) return True else: return False diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 65478c2..2e4d47b 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -8,7 +8,7 @@ #***************************************************************************** import os,sys,time import pyreadline.logger as logger -from pyreadline.logger import log,log_sock +from pyreadline.logger import log from pyreadline.lineeditor.lineobj import Point import pyreadline.lineeditor.lineobj as lineobj import pyreadline.lineeditor.history as history @@ -31,7 +31,7 @@ class IncrementalSearchPromptMode(object): def _process_incremental_search_keyevent(self, keyinfo): keytuple=keyinfo.tuple() - log_sock("%s %s"%(keyinfo,keytuple)) + log("IncrementalSearchPromptMode %s %s"%(keyinfo,keytuple)) if keyinfo.keyname == 'backspace': self.subsearch_query = self.subsearch_query[:-1] if len(self.subsearch_query) > 0: @@ -98,7 +98,7 @@ class SearchPromptMode(object): def _process_non_incremental_search_keyevent(self, keyinfo): keytuple=keyinfo.tuple() - log_sock("%s %s"%(keyinfo,keytuple)) + log("SearchPromptMode %s %s"%(keyinfo,keytuple)) if keyinfo.keyname == 'backspace': self.non_inc_query = self.non_inc_query[:-1] @@ -154,9 +154,9 @@ class DigitArgumentMode(object): pass def _process_digit_argument_keyevent(self, keyinfo): - log_sock("_process_digit_argument_keyevent %s"%keyinfo) + log("DigitArgumentMode.keyinfo %s"%keyinfo) keytuple=keyinfo.tuple() - log_sock("%s %s"%(keyinfo,keytuple)) + log("DigitArgumentMode.keytuple %s %s"%(keyinfo,keytuple)) if keyinfo.keyname in ['return']: self.prompt=self._digit_argument_oldprompt self.process_keyevent_queue=self.process_keyevent_queue[:-1] @@ -164,7 +164,7 @@ class DigitArgumentMode(object): elif keyinfo.keyname: pass elif keyinfo.char in "0123456789" and keyinfo.control==False and keyinfo.meta==False : - log_sock("arg %s %s"%(self.argument,keyinfo.char)) + log("arg %s %s"%(self.argument,keyinfo.char)) self.argument=self.argument*10+int(keyinfo.char) else: self.prompt=self._digit_argument_oldprompt @@ -183,9 +183,9 @@ class DigitArgumentMode(object): self.argument=-1 elif keyinfo.char in "0123456789": self.argument=int(keyinfo.char) - log_sock("<%s> %s"%(self.argument,type(self.argument))) + log("<%s> %s"%(self.argument,type(self.argument))) self.prompt="(arg: %s) "%self.argument - log_sock("arg-init %s %s"%(self.argument,keyinfo.char)) + log("arg-init %s %s"%(self.argument,keyinfo.char)) @@ -229,7 +229,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode """return True when line is final """ #Process exit keys. Only exit on empty line - log_sock("_process_keyevent %s"%keyinfo) + log("_process_keyevent <%s>"%keyinfo) def nop(e): pass if self.next_meta: @@ -244,17 +244,16 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode return False if keytuple in self.exit_dispatch: - log_sock("exit_dispatch:%s, %s"%(self.l_buffer, lineobj.EndOfLine(self.l_buffer))) + log("exit_dispatch:<%s, %s>"%(self.l_buffer, lineobj.EndOfLine(self.l_buffer))) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError - if keyinfo.keyname: + if keyinfo.keyname or keyinfo.control or keyinfo.meta: default=nop else: default=self.self_insert dispatch_func = self.key_dispatch.get(keytuple, default) - log("readline from keyboard:%s,%s"%(keytuple, dispatch_func)) - log_sock((u"%s|%s"%(ensure_unicode(format(keytuple)),dispatch_func.__name__)),"bound_function") + log("readline from keyboard:<%s,%s>"%(keytuple, dispatch_func)) r = None if dispatch_func: diff --git a/pyreadline/modes/vi.py b/pyreadline/modes/vi.py index d6710ac..5b5683e 100644 --- a/pyreadline/modes/vi.py +++ b/pyreadline/modes/vi.py @@ -9,7 +9,7 @@ #***************************************************************************** import os import pyreadline.logger as logger -from pyreadline.logger import log,log_sock +from pyreadline.logger import log import pyreadline.lineeditor.lineobj as lineobj import pyreadline.lineeditor.history as history import basemode diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 026022d..8700b57 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -11,7 +11,7 @@ import sys,os,re,time from glob import glob import clipboard,logger,console -from logger import log,log_sock +from logger import log from error import ReadlineError,GetSetError from pyreadline.keysyms.common import make_KeyPress_from_keydescr @@ -146,7 +146,7 @@ class BaseReadline(object): '''Load a readline history file. The default filename is ~/.history.''' if filename is None: filename=self.mode._history.history_filename - log_sock("read_history_file from %s"%filename) + log("read_history_file from %s"%filename) self.mode._history.read_history_file(filename) def write_history_file(self, filename=None): @@ -266,7 +266,6 @@ class BaseReadline(object): def setmode(name): self.mode=modes[name] def bind_key(key,name): - log("bind %s %s"%(key,name)) if hasattr(modes[mode],name): modes[mode]._bind_key(key,getattr(modes[mode],name)) else: @@ -286,31 +285,51 @@ class BaseReadline(object): def setkill_ring_to_clipboard(killring): import pyreadline.lineeditor.lineobj pyreadline.lineeditor.lineobj.kill_ring_to_clipboard=killring + def sethistoryfilename(filename): self.mode._history.history_filename=os.path.expanduser(filename) + def setbellstyle(mode): self.bell_style=mode + def sethistorylength(length): self.mode._history.history_length=int(length) + def allow_ctrl_c(mode): - log_sock("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) + log("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) self.allow_ctrl_c=mode + def setbellstyle(mode): self.bell_style=mode + def show_all_if_ambiguous(mode): self.mode.show_all_if_ambiguous=mode + def ctrl_c_tap_time_interval(mode): self.ctrl_c_tap_time_interval=mode + def mark_directories(mode): self.mode.mark_directories=mode + def completer_delims(delims): self.mode.completer_delims=delims + def debug_output(on,filename="pyreadline_debug_log.txt"): #Not implemented yet if on in ["on","on_nologfile"]: self.debug=True - logger.start_log(on,filename) - logger.log("STARTING LOG") -# print release.branch + + if on == "on": + logger.start_file_log(filename) + logger.start_socket_log() + logger.log("STARTING LOG") + elif on =="on_nologfile": + logger.start_socket_log() + logger.log("STARTING LOG") + else: + logger.log("STOPING LOG") + logger.stop_file_log() + logger.stop_socket_log() + def set_prompt_color(color): trtable={"black":0,"darkred":4,"darkgreen":2,"darkyellow":6,"darkblue":1,"darkmagenta":5,"darkcyan":3,"gray":7, "red":4+8,"green":2+8,"yellow":6+8,"blue":1+8,"magenta":5+8,"cyan":3+8,"white":7+8} @@ -512,14 +531,14 @@ class Readline(BaseReadline): def handle_ctrl_c(self): from pyreadline.keysyms.common import KeyPress from pyreadline.console.event import Event - log_sock("KBDIRQ") + log("KBDIRQ") event=Event(0,0) event.char="c" event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) if self.allow_ctrl_c: now=time.time() if (now-self.ctrl_c_timeout) Date: Mon, 7 Jul 2008 18:48:45 +0200 Subject: [PATCH 16/26] Removed the last dependency on console from vi-mode. The cursor_size property of the BaseMode class should be used to determine the wanted cursorsize. Fixed some whitespace in emacsmode. --- pyreadline/modes/basemode.py | 1 + pyreadline/modes/emacs.py | 8 -------- pyreadline/modes/vi.py | 4 ++-- pyreadline/rlmain.py | 4 +++- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 6b5f9be..832dfd6 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -38,6 +38,7 @@ class BaseMode(object): self.startup_hook = None self.pre_input_hook = None self.first_prompt = True + self.cursor_size=25 self.prompt = ">>>" diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 2e4d47b..1d51730 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -88,10 +88,6 @@ class IncrementalSearchPromptMode(object): else: self.line="" - - - - class SearchPromptMode(object): def __init__(self, rlobj): pass @@ -188,10 +184,6 @@ class DigitArgumentMode(object): log("arg-init %s %s"%(self.argument,keyinfo.char)) - - - - class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode): mode="emacs" def __init__(self, rlobj): diff --git a/pyreadline/modes/vi.py b/pyreadline/modes/vi.py index 5b5683e..9481c07 100644 --- a/pyreadline/modes/vi.py +++ b/pyreadline/modes/vi.py @@ -158,9 +158,9 @@ class ViMode(basemode.BaseMode): self.__vi_insert_mode = value if value: self.vi_save_line () - self.console.cursor (size=25) + self.cursor_size=25 else: - self.console.cursor (size=100) + self.cursor_size=100 def vi_undo_restart (self): tpl_undo = (self.l_buffer.point, self.l_buffer.line_buffer[:], ) diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 8700b57..6f1252e 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -468,7 +468,9 @@ class Readline(BaseReadline): c.clear_to_end_of_window() #to System.Console's lack of FillFunction else: self._clear_after() - c.cursor(1) #Show cursor + + #Show cursor, set size vi mode changes size in insert/overwrite mode + c.cursor(1, size=self.mode.cursor_size) self._set_cursor() From 10b8512e5a69ac19a9df501f7aeea64bbeae6626 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Wed, 27 Aug 2008 19:28:45 +0200 Subject: [PATCH 17/26] removed unused code, and did some other cosmetic changes to the code --- pyreadline/modes/basemode.py | 2 -- pyreadline/modes/emacs.py | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 832dfd6..76d1a11 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -113,10 +113,8 @@ class BaseMode(object): print 'startup hook failed' traceback.print_exc() - c = self.console self.l_buffer.reset_line() self.prompt = prompt -# self._print_prompt() if self.pre_input_hook: try: diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 1d51730..11ac2fb 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -202,7 +202,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode def __repr__(self): return "" - def add_key_logger(self,logfun): + def add_key_logger(self, logfun): """logfun should be function that takes disp_fun and line_buffer object """ self._keylog=logfun From 2cda7c0863be3f56f3d16b2a6dcffc279089e91b Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 11 Nov 2008 20:22:45 +0100 Subject: [PATCH 18/26] Changed all strings to unicodestrings --- pyreadline/clipboard/__init__.py | 22 +- pyreadline/clipboard/ironpython_clipboard.py | 4 +- pyreadline/clipboard/no_clipboard.py | 2 +- pyreadline/clipboard/win32_clipboard.py | 5 +- pyreadline/console/ansi.py | 71 +- pyreadline/console/console.py | 174 +- pyreadline/console/consolebase.py | 12 +- pyreadline/console/event.py | 18 +- pyreadline/console/ironpython_console.py | 154 +- pyreadline/examples/callback_example.py | 16 +- pyreadline/get_doc.py | 6 +- pyreadline/keysyms/__init__.py | 4 +- pyreadline/keysyms/common.py | 74 +- pyreadline/keysyms/ironpython_keysyms.py | 188 +- pyreadline/keysyms/keysyms.py | 166 +- pyreadline/lineeditor/history.py | 64 +- pyreadline/lineeditor/lineobj.py | 71 +- pyreadline/lineeditor/wordmatcher.py | 32 +- pyreadline/logger.py | 4 +- pyreadline/logserver.py | 24 +- pyreadline/modes/basemode.py | 176 +- pyreadline/modes/emacs.py | 318 +-- pyreadline/modes/notemacs.py | 230 +- pyreadline/release.py | 36 +- pyreadline/rlmain.py | 218 +- pyreadline/test/common.py | 14 +- pyreadline/test/emacs_test.py | 354 +-- pyreadline/test/history_test.py | 54 +- pyreadline/test/lineeditor_test.py | 274 +- pyreadline/test/vi_test.py | 2566 +++++++++--------- pyreadline/unicode_helper.py | 10 +- 31 files changed, 2683 insertions(+), 2678 deletions(-) diff --git a/pyreadline/clipboard/__init__.py b/pyreadline/clipboard/__init__.py index b3112bc..71a8a14 100644 --- a/pyreadline/clipboard/__init__.py +++ b/pyreadline/clipboard/__init__.py @@ -1,6 +1,6 @@ import sys success=True -in_ironpython="IronPython" in sys.version +in_ironpython=u"IronPython" in sys.version if in_ironpython: try: from ironpython_clipboard import GetClipboardText,SetClipboardText @@ -22,15 +22,15 @@ def set_clipboard_text(toclipboard): SetClipboardText(str(toclipboard)) def make_tab(lists): - if hasattr(lists,"tolist"): + if hasattr(lists,u"tolist"): lists=lists.tolist() ut=[] for rad in lists: if type(rad) in [list,tuple]: - ut.append("\t".join(["%s"%x for x in rad])) + ut.append(u"\t".join([u"%s"%x for x in rad])) else: - ut.append("%s"%rad) - return "\n".join(ut) + ut.append(u"%s"%rad) + return u"\n".join(ut) def make_list_of_list(txt): def make_num(x): @@ -47,8 +47,8 @@ def make_list_of_list(txt): return x ut=[] flag=False - for rad in [x for x in txt.split("\r\n") if x!=""]: - raden=[make_num(x) for x in rad.split("\t")] + for rad in [x for x in txt.split(u"\r\n") if x!=u""]: + raden=[make_num(x) for x in rad.split(u"\t")] if str in map(type,raden): flag=True ut.append(raden) @@ -56,17 +56,17 @@ def make_list_of_list(txt): def get_clipboard_text_and_convert(paste_list=False): - """Get txt from clipboard. if paste_list==True the convert tab separated + u"""Get txt from clipboard. if paste_list==True the convert tab separated data to list of lists. Enclose list of list in array() if all elements are numeric""" txt=GetClipboardText() if txt: - if paste_list and "\t" in txt: + if paste_list and u"\t" in txt: array,flag=make_list_of_list(txt) if flag: txt=repr(array) else: - txt="array(%s)"%repr(array) - txt="".join([c for c in txt if c not in " \t\r\n"]) + txt=u"array(%s)"%repr(array) + txt=u"".join([c for c in txt if c not in u" \t\r\n"]) return txt diff --git a/pyreadline/clipboard/ironpython_clipboard.py b/pyreadline/clipboard/ironpython_clipboard.py index f91e099..9870ee9 100644 --- a/pyreadline/clipboard/ironpython_clipboard.py +++ b/pyreadline/clipboard/ironpython_clipboard.py @@ -6,7 +6,7 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** import clr -clr.AddReferenceByPartialName("System.Windows.Forms") +clr.AddReferenceByPartialName(u"System.Windows.Forms") import System.Windows.Forms.Clipboard as cb def GetClipboardText(): @@ -19,7 +19,7 @@ def GetClipboardText(): def SetClipboardText(text): cb.SetText(text) -if __name__ == '__main__': +if __name__ == u'__main__': txt=GetClipboardText() # display last text clipped print txt diff --git a/pyreadline/clipboard/no_clipboard.py b/pyreadline/clipboard/no_clipboard.py index b1c4664..9f0921c 100644 --- a/pyreadline/clipboard/no_clipboard.py +++ b/pyreadline/clipboard/no_clipboard.py @@ -7,7 +7,7 @@ #***************************************************************************** -mybuffer="" +mybuffer=u"" def GetClipboardText(): return mybuffer diff --git a/pyreadline/clipboard/win32_clipboard.py b/pyreadline/clipboard/win32_clipboard.py index 3dba355..95ad4fb 100644 --- a/pyreadline/clipboard/win32_clipboard.py +++ b/pyreadline/clipboard/win32_clipboard.py @@ -61,7 +61,6 @@ def enum(): OpenClipboard(0) q=EnumClipboardFormats(0) while q: - print q, q=EnumClipboardFormats(q) CloseClipboard() @@ -74,7 +73,7 @@ def getformatname(format): return buffer.value def GetClipboardText(): - text = "" + text = u"" if OpenClipboard(0): hClipMem = GetClipboardData(CF_TEXT) if hClipMem: @@ -97,6 +96,6 @@ def SetClipboardText(text): SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem)) CloseClipboard() -if __name__ == '__main__': +if __name__ == u'__main__': txt=GetClipboardText() # display last text clipped print txt diff --git a/pyreadline/console/ansi.py b/pyreadline/console/ansi.py index ffc0119..f564308 100644 --- a/pyreadline/console/ansi.py +++ b/pyreadline/console/ansi.py @@ -1,19 +1,19 @@ # -*- coding: ISO-8859-1 -*- import re,sys,os -terminal_escape = re.compile('(\001?\033\\[[0-9;]*m\002?)') -escape_parts = re.compile('\001?\033\\[([0-9;]*)m\002?') +terminal_escape = re.compile(u'(\001?\033\\[[0-9;]*m\002?)') +escape_parts = re.compile(u'\001?\033\\[([0-9;]*)m\002?') class AnsiState(object): - def __init__(self,bold=False,inverse=False,color="white",background="black",backgroundbold=False): + def __init__(self,bold=False,inverse=False,color=u"white",background=u"black",backgroundbold=False): self.bold=bold self.inverse=inverse self.color=color self.background=background self.backgroundbold=backgroundbold - trtable={"black":0,"red":4,"green":2,"yellow":6,"blue":1,"magenta":5,"cyan":3,"white":7} + trtable={u"black":0,u"red":4,u"green":2,u"yellow":6,u"blue":1,u"magenta":5,u"cyan":3,u"white":7} revtable=dict(zip(trtable.values(),trtable.keys())) def get_winattr(self): attr=0 @@ -36,7 +36,7 @@ class AnsiState(object): winattr=property(get_winattr,set_winattr) def __repr__(self): - return 'AnsiState(bold=%s,inverse=%s,color=%9s,background=%9s,backgroundbold=%s)# 0x%x'%(self.bold, + return u'AnsiState(bold=%s,inverse=%s,color=%9s,background=%9s,backgroundbold=%s)# 0x%x'%(self.bold, self.inverse, '"%s"'%self.color, '"%s"'%self.background, @@ -51,9 +51,9 @@ class AnsiState(object): x.background=self.background x.backgroundbold=self.backgroundbold return x -defaultstate=AnsiState(False,False,"white") +defaultstate=AnsiState(False,False,u"white") -trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"} +trtable={0:u"black",1:u"red",2:u"green",3:u"yellow",4:u"blue",5:u"magenta",6:u"cyan",7:u"white"} class AnsiWriter(object): def __init__(self,default=defaultstate): @@ -65,7 +65,7 @@ class AnsiWriter(object): def write_color(self,text, attr=None): - '''write text at current cursor position and interpret color escapes. + u'''write text at current cursor position and interpret color escapes. return the number of characters written. ''' @@ -83,21 +83,21 @@ class AnsiWriter(object): for chunk in chunks: m = escape_parts.match(chunk) if m: - parts=m.group(1).split(";") - if len(parts)==1 and parts[0]=="0": + parts=m.group(1).split(u";") + if len(parts)==1 and parts[0]==u"0": attr = self.defaultstate.copy() continue for part in parts: - if part == "0": # No text attribute + if part == u"0": # No text attribute attr = self.defaultstate.copy() attr.bold=False - elif part == "7": # switch on reverse + elif part == u"7": # switch on reverse attr.inverse=True - elif part == "1": # switch on bold (i.e. intensify foreground color) + elif part == u"1": # switch on bold (i.e. intensify foreground color) attr.bold=True - elif len(part) == 2 and "30" <= part <= "37": # set foreground color + elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color attr.color = trtable[int(part)-30] - elif len(part) == 2 and "40" <= part <= "47": # set background color + elif len(part) == 2 and u"40" <= part <= u"47": # set background color attr.color = trtable[int(part)-40] continue n += len(chunk) @@ -114,7 +114,7 @@ def write_color(text,attr=None): return a.write_color(text,attr) def write_color_old( text, attr=None): - '''write text at current cursor position and interpret color escapes. + u'''write text at current cursor position and interpret color escapes. return the number of characters written. ''' @@ -126,18 +126,18 @@ def write_color_old( text, attr=None): for chunk in chunks: m = escape_parts.match(chunk) if m: - for part in m.group(1).split(";"): - if part == "0": # No text attribute + for part in m.group(1).split(u";"): + if part == u"0": # No text attribute attr = 0 - elif part == "7": # switch on reverse + elif part == u"7": # switch on reverse attr |= 0x4000 - if part == "1": # switch on bold (i.e. intensify foreground color) + if part == u"1": # switch on bold (i.e. intensify foreground color) attr |= 0x08 - elif len(part) == 2 and "30" <= part <= "37": # set foreground color + elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color part = int(part)-30 # we have to mirror bits attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2) - elif len(part) == 2 and "40" <= part <= "47": # set background color + elif len(part) == 2 and u"40" <= part <= u"47": # set background color part = int(part)-40 # we have to mirror bits attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2) @@ -145,37 +145,44 @@ def write_color_old( text, attr=None): continue n += len(chunk) if chunk: - res.append(("0x%x"%attr,chunk)) + res.append((u"0x%x"%attr,chunk)) return res #trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"} -if __name__=="__main__": +if __name__==u"__main__x": import pprint pprint=pprint.pprint - s="\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m" + s=u"\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m" pprint (write_color(s)) pprint (write_color_old(s)) - s="\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m" + s=u"\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m" pprint (write_color(s)) pprint (write_color_old(s)) - s="\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m" + s=u"\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m" pprint (write_color(s)) pprint (write_color_old(s)) - s="\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m" + s=u"\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m" pprint (write_color(s)) pprint (write_color_old(s)) -if __name__=="__main__": +if __name__==u"__main__": import console + import pprint + pprint=pprint.pprint c=console.Console() - c.write_color("dhsjdhs") - c.write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:") + c.write_color(u"dhsjdhs") + c.write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:") print - pprint (write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:")) + pprint (write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:")) +if __name__==u"__main__x": + import pprint + pprint=pprint.pprint + s=u"\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m" + pprint (write_color(s)) diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index 38f7c35..b3a19c8 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -6,7 +6,7 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -'''Cursor control and color for the Windows console. +u'''Cursor control and color for the Windows console. This was modeled after the C extension of the same name by Fredrik Lundh. ''' @@ -23,7 +23,7 @@ try: from ctypes import * from _ctypes import call_function except ImportError: - raise ImportError("You need ctypes to run this code") + raise ImportError(u"You need ctypes to run this code") # my code from pyreadline.keysyms import make_KeyPress @@ -168,12 +168,12 @@ def split_block(text,size=1000): class Console(object): - '''Console driver for Windows. + u'''Console driver for Windows. ''' def __init__(self, newbuffer=0): - '''Initialize the Console object. + u'''Initialize the Console object. newbuffer=1 will allocate a new buffer so the old content will be restored on exit. @@ -208,16 +208,16 @@ class Console(object): for escape in self.escape_to_color: if self.escape_to_color[escape] is not None: self.escape_to_color[escape] |= background - log('initial attr=%x' % self.attr) + log(u'initial attr=%x' % self.attr) self.softspace = 0 # this is for using it as a file-like object self.serial = 0 - self.pythondll = CDLL('python%s%s' % (sys.version[0], sys.version[2])) + self.pythondll = CDLL(u'python%s%s' % (sys.version[0], sys.version[2])) self.inputHookPtr = c_int.from_address(addressof(self.pythondll.PyOS_InputHook)).value - setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc) + setattr(Console, u'PyMem_Malloc', self.pythondll.PyMem_Malloc) def __del__(self): - '''Cleanup the console when finished.''' + u'''Cleanup the console when finished.''' # I don't think this ever gets called self.SetConsoleTextAttribute(self.hout, self.saveattr) self.SetConsoleMode(self.hin, self.inmode) @@ -232,7 +232,7 @@ class Console(object): return top,bot def fixcoord(self, x, y): - '''Return a long with x and y packed inside, also handle negative x and y.''' + u'''Return a long with x and y packed inside, also handle negative x and y.''' if x < 0 or y < 0: info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) @@ -245,7 +245,7 @@ class Console(object): return c_int(y << 16 | x) def pos(self, x=None, y=None): - '''Move or query the window cursor.''' + u'''Move or query the window cursor.''' if x is None: info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) @@ -254,38 +254,38 @@ class Console(object): return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y)) def home(self): - '''Move to home.''' + u'''Move to home.''' self.pos(0,0) # Map ANSI color escape sequences into Windows Console Attributes - terminal_escape = re.compile('(\001?\033\\[[0-9;]+m\002?)') - escape_parts = re.compile('\001?\033\\[([0-9;]+)m\002?') - escape_to_color = { '0;30': 0x0, #black - '0;31': 0x4, #red - '0;32': 0x2, #green - '0;33': 0x4+0x2, #brown? - '0;34': 0x1, #blue - '0;35': 0x1+0x4, #purple - '0;36': 0x2+0x4, #cyan - '0;37': 0x1+0x2+0x4, #grey - '1;30': 0x1+0x2+0x4, #dark gray - '1;31': 0x4+0x8, #red - '1;32': 0x2+0x8, #light green - '1;33': 0x4+0x2+0x8, #yellow - '1;34': 0x1+0x8, #light blue - '1;35': 0x1+0x4+0x8, #light purple - '1;36': 0x1+0x2+0x8, #light cyan - '1;37': 0x1+0x2+0x4+0x8, #white - '0': None, + terminal_escape = re.compile(u'(\001?\033\\[[0-9;]+m\002?)') + escape_parts = re.compile(u'\001?\033\\[([0-9;]+)m\002?') + escape_to_color = { u'0;30': 0x0, #black + u'0;31': 0x4, #red + u'0;32': 0x2, #green + u'0;33': 0x4+0x2, #brown? + u'0;34': 0x1, #blue + u'0;35': 0x1+0x4, #purple + u'0;36': 0x2+0x4, #cyan + u'0;37': 0x1+0x2+0x4, #grey + u'1;30': 0x1+0x2+0x4, #dark gray + u'1;31': 0x4+0x8, #red + u'1;32': 0x2+0x8, #light green + u'1;33': 0x4+0x2+0x8, #yellow + u'1;34': 0x1+0x8, #light blue + u'1;35': 0x1+0x4+0x8, #light purple + u'1;36': 0x1+0x2+0x8, #light cyan + u'1;37': 0x1+0x2+0x4+0x8, #white + u'0': None, } # This pattern should match all characters that change the cursor position differently # than a normal character. - motion_char_re = re.compile('([\n\r\t\010\007])') + motion_char_re = re.compile(u'([\n\r\t\010\007])') def write_scrolling(self, text, attr=None): - '''write text at current cursor position while watching for scrolling. + u'''write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the @@ -306,19 +306,19 @@ class Console(object): for chunk in chunks: n = self.write_color(chunk, attr) if len(chunk) == 1: # the funny characters will be alone - if chunk[0] == '\n': # newline + if chunk[0] == u'\n': # newline x = 0 y += 1 - elif chunk[0] == '\r': # carriage return + elif chunk[0] == u'\r': # carriage return x = 0 - elif chunk[0] == '\t': # tab + elif chunk[0] == u'\t': # tab x = 8*(int(x/8)+1) if x > w: # newline x -= w y += 1 - elif chunk[0] == '\007': # bell + elif chunk[0] == u'\007': # bell pass - elif chunk[0] == '\010': + elif chunk[0] == u'\010': x -= 1 if x < 0: y -= 1 # backed up 1 line @@ -353,8 +353,8 @@ class Console(object): return n def write_plain(self, text, attr=None): - '''write text at current cursor position.''' - log('write("%s", %s)' %(text,attr)) + u'''write text at current cursor position.''' + log(u'write("%s", %s)' %(text,attr)) if attr is None: attr = self.attr n = c_int(0) @@ -365,7 +365,7 @@ class Console(object): #This function must be used to ensure functioning with EMACS #Emacs sets the EMACS environment variable - if os.environ.has_key("EMACS"): + if os.environ.has_key(u"EMACS"): def write_color(self, text, attr=None): junk = c_int(0) self.WriteFile(self.hout, text, len(text), byref(junk),None) @@ -374,7 +374,7 @@ class Console(object): # make this class look like a file object def write(self, text): - log('write("%s")' % text) + log(u'write("%s")' % text) return self.write_color(text) #write = write_scrolling @@ -385,8 +385,8 @@ class Console(object): def flush(self): pass - def page(self, attr=None, fill=' '): - '''Fill the entire screen.''' + def page(self, attr=None, fill=u' '): + u'''Fill the entire screen.''' if attr is None: attr = self.attr if len(fill) != 1: @@ -405,7 +405,7 @@ class Console(object): self.attr = attr def text(self, x, y, text, attr=None): - '''Write text at the given position.''' + u'''Write text at the given position.''' if attr is None: attr = self.attr @@ -422,8 +422,8 @@ class Console(object): if pos[1]>sys.stderr, 'Readline internal error' + print >>sys.stderr, u'Readline internal error' traceback.print_exc() - res = '\n' + res = u'\n' # we have to make a copy because the caller expects to free the result n = len(res) p = Console.PyMem_Malloc(n+1) @@ -688,23 +688,23 @@ def hook_wrapper_23(stdin, stdout, prompt): return p def hook_wrapper(prompt): - '''Wrap a Python readline so it behaves like GNU readline.''' + u'''Wrap a Python readline so it behaves like GNU readline.''' try: # call the Python hook res = ensure_str(readline_hook(prompt)) # make sure it returned the right sort of thing if res and not isinstance(res, str): - raise TypeError, 'readline must return a string.' + raise TypeError, u'readline must return a string.' except KeyboardInterrupt: # GNU readline returns 0 on keyboard interrupt return 0 except EOFError: # It returns an empty string on EOF - res = '' + res = u'' except: - print >>sys.stderr, 'Readline internal error' + print >>sys.stderr, u'Readline internal error' traceback.print_exc() - res = '\n' + res = u'\n' # we have to make a copy because the caller expects to free the result p = cdll.msvcrt._strdup(res) return p diff --git a/pyreadline/console/consolebase.py b/pyreadline/console/consolebase.py index 3409ced..d15350e 100644 --- a/pyreadline/console/consolebase.py +++ b/pyreadline/console/consolebase.py @@ -6,18 +6,18 @@ class baseconsole: raise NotImplementedError def pos(self, x=None, y=None): - '''Move or query the window cursor.''' + u'''Move or query the window cursor.''' raise NotImplementedError def size(self): raise NotImplementedError - def rectangle(self, rect, attr=None, fill=' '): - '''Fill Rectangle.''' + def rectangle(self, rect, attr=None, fill=u' '): + u'''Fill Rectangle.''' raise NotImplementedError def write_scrolling(self, text, attr=None): - '''write text at current cursor position while watching for scrolling. + u'''write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the @@ -33,14 +33,14 @@ class baseconsole: raise NotImplementedError def getkeypress(self): - '''Return next key press event from the queue, ignoring others.''' + u'''Return next key press event from the queue, ignoring others.''' raise NotImplementedError def write(self, text): raise NotImplementedError def page(self, attr=None, fill=' '): - '''Fill the entire screen.''' + u'''Fill the entire screen.''' raise NotImplementedError def isatty(self): diff --git a/pyreadline/console/event.py b/pyreadline/console/event.py index ce3d4b6..e3ba1d4 100644 --- a/pyreadline/console/event.py +++ b/pyreadline/console/event.py @@ -1,23 +1,23 @@ class Event(object): - '''Represent events from the console.''' + u'''Represent events from the console.''' def __init__(self, console, input): pass def __repr__(self): - '''Display an event for debugging.''' - if self.type in ['KeyPress', 'KeyRelease']: + u'''Display an event for debugging.''' + if self.type in [u'KeyPress', u'KeyRelease']: chr=self.char - if ord(chr) w: # newline x -= w y += 1 - elif chunk[0] == '\007': # bell + elif chunk[0] == u'\007': # bell pass - elif chunk[0] == '\010': + elif chunk[0] == u'\010': x -= 1 if x < 0: y -= 1 # backed up 1 line @@ -193,9 +193,9 @@ class Console(object): return the number of characters written. ''' - log('write_color("%s", %s)' % (text, attr)) + log(u'write_color("%s", %s)' % (text, attr)) chunks = self.terminal_escape.split(text) - log('chunks=%s' % repr(chunks)) + log(u'chunks=%s' % repr(chunks)) bg=self.savebg n = 0 # count the characters we actually write, omitting the escapes if attr is None:#use attribute from initial console @@ -219,8 +219,8 @@ class Console(object): return n def write_plain(self, text, attr=None): - '''write text at current cursor position.''' - log('write("%s", %s)' %(text,attr)) + u'''write text at current cursor position.''' + log(u'write("%s", %s)' %(text,attr)) if attr is None: attr = self.attr n = c_int(0) @@ -228,7 +228,7 @@ class Console(object): self.WriteConsoleA(self.hout, text, len(text), byref(n), None) return len(text) - if os.environ.has_key("EMACS"): + if os.environ.has_key(u"EMACS"): def write_color(self, text, attr=None): junk = c_int(0) self.WriteFile(self.hout, text, len(text), byref(junk), None) @@ -237,7 +237,7 @@ class Console(object): # make this class look like a file object def write(self, text): - log('write("%s")' % text) + log(u'write("%s")' % text) return self.write_color(text) #write = write_scrolling @@ -248,12 +248,12 @@ class Console(object): def flush(self): pass - def page(self, attr=None, fill=' '): - '''Fill the entire screen.''' + def page(self, attr=None, fill=u' '): + u'''Fill the entire screen.''' System.Console.Clear() def text(self, x, y, text, attr=None): - '''Write text at the given position.''' + u'''Write text at the given position.''' self.pos(x,y) self.write_color(text,attr) @@ -263,12 +263,12 @@ class Console(object): pos=self.pos() w,h=self.size() length=w-pos[0]+min((lastline-pos[1]-1),5)*w-1 - self.write_color(length*" ") + self.write_color(length*u" ") self.pos(*pos) self.WindowTop=oldtop - def rectangle(self, rect, attr=None, fill=' '): - '''Fill Rectangle.''' + def rectangle(self, rect, attr=None, fill=u' '): + u'''Fill Rectangle.''' pass oldtop=self.WindowTop oldpos=self.pos() @@ -279,19 +279,19 @@ class Console(object): if fill: rowfill=fill[:1]*abs(x1-x0) else: - rowfill=' '*abs(x1-x0) + rowfill=u' '*abs(x1-x0) for y in range(y0, y1): System.Console.SetCursorPosition(x0,y) self.write_color(rowfill,attr) self.pos(*oldpos) def scroll(self, rect, dx, dy, attr=None, fill=' '): - '''Scroll a rectangle.''' + u'''Scroll a rectangle.''' pass raise NotImplementedError def scroll_window(self, lines): - '''Scroll the window by the indicated number of lines.''' + u'''Scroll the window by the indicated number of lines.''' top=self.WindowTop+lines if top<0: top=0 @@ -300,7 +300,7 @@ class Console(object): self.WindowTop=top def getkeypress(self): - '''Return next key press event from the queue, ignoring others.''' + u'''Return next key press event from the queue, ignoring others.''' ck=System.ConsoleKey while 1: e = System.Console.ReadKey(True) @@ -308,22 +308,22 @@ class Console(object): self.scroll_window(12) elif e.Key == System.ConsoleKey.PageUp:#PageUp self.scroll_window(-12) - elif str(e.KeyChar)=="\000":#Drop deadkeys - log("Deadkey: %s"%e) + elif str(e.KeyChar)==u"\000":#Drop deadkeys + log(u"Deadkey: %s"%e) return event(self,e) pass else: return event(self,e) def title(self, txt=None): - '''Set/get title.''' + u'''Set/get title.''' if txt: System.Console.Title=txt else: return System.Console.Title def size(self, width=None, height=None): - '''Set/get window size.''' + u'''Set/get window size.''' sc=System.Console @@ -338,22 +338,22 @@ class Console(object): return sc.WindowWidth-1,sc.WindowHeight-1 def cursor(self, visible=True, size=None): - '''Set cursor on or off.''' + u'''Set cursor on or off.''' System.Console.CursorVisible=visible def bell(self): System.Console.Beep() def next_serial(self): - '''Get next event serial number.''' + u'''Get next event serial number.''' self.serial += 1 return self.serial class event(Event): - '''Represent events from the console.''' + u'''Represent events from the console.''' def __init__(self, console, input): - '''Initialize an event from the Windows input structure.''' - self.type = '??' + u'''Initialize an event from the Windows input structure.''' + self.type = u'??' self.serial = console.next_serial() self.width = 0 self.height = 0 @@ -362,7 +362,7 @@ class event(Event): self.char = str(input.KeyChar) self.keycode = input.Key self.state = input.Modifiers - log("%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar)) + log(u"%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar)) self.type="KeyRelease" self.keysym = make_keysym(self.keycode) self.keyinfo = make_KeyPress(self.char, self.state, self.keycode) @@ -370,7 +370,7 @@ class event(Event): def make_event_from_keydescr(keydescr): def input(): return 1 - input.KeyChar="a" + input.KeyChar=u"a" input.Key=System.ConsoleKey.A input.Modifiers=System.ConsoleModifiers.Shift input.next_serial=input @@ -380,17 +380,17 @@ def make_event_from_keydescr(keydescr): e.keyinfo=keyinfo return e -CTRL_C_EVENT=make_event_from_keydescr("Control-c") +CTRL_C_EVENT=make_event_from_keydescr(u"Control-c") def install_readline(hook): def hook_wrap(): try: res=hook() except KeyboardInterrupt,x: #this exception does not seem to be caught - res="" + res=u"" except EOFError: return None - if res[-1:]=="\n": + if res[-1:]==u"\n": return res[:-1] else: return res @@ -405,19 +405,19 @@ def install_readline(hook): -if __name__ == '__main__': +if __name__ == u'__main__': import time, sys c = Console(0) sys.stdout = c sys.stderr = c c.page() c.pos(5, 10) - c.write('hi there') - c.title("Testing console") + c.write(u'hi there') + c.title(u"Testing console") # c.bell() print - print "size",c.size() - print ' some printed output' + print u"size",c.size() + print u' some printed output' for i in range(10): e=c.getkeypress() print e.Key,chr(e.KeyChar),ord(e.KeyChar),e.Modifiers diff --git a/pyreadline/examples/callback_example.py b/pyreadline/examples/callback_example.py index d7fdc44..dac6e88 100644 --- a/pyreadline/examples/callback_example.py +++ b/pyreadline/examples/callback_example.py @@ -1,10 +1,10 @@ -''' +u''' Example script using the callback interface of readline. :author: strank ''' -__docformat__ = "restructuredtext en" +__docformat__ = u"restructuredtext en" import sys import os @@ -21,33 +21,33 @@ maxlines = 10 def main(): - readline.callback_handler_install('Starting test, please do type:' + os.linesep, lineReceived) + readline.callback_handler_install(u'Starting test, please do type:' + os.linesep, lineReceived) index = 0 start = int(time.time()) while prompting: # demonstrate that async stuff is possible: if start + index < time.time(): - rl.console.title("NON-BLOCKING: %d" % index) + rl.console.title(u"NON-BLOCKING: %d" % index) index += 1 # ugly busy waiting/polling on windows, using 'select' on Unix: (or use twisted) if msvcrt.kbhit(): readline.callback_read_char() - print "Done, index =", index + print u"Done, index =", index def lineReceived(line): global count, prompting count += 1 - print "Got line: %s" % line + print u"Got line: %s" % line if count > maxlines: prompting = False readline.callback_handler_remove() else: - readline.callback_handler_install('Got %s of %s, more typing please:' % (count, maxlines) + readline.callback_handler_install(u'Got %s of %s, more typing please:' % (count, maxlines) + os.linesep, lineReceived) -if __name__ == '__main__': +if __name__ == u'__main__': main() diff --git a/pyreadline/get_doc.py b/pyreadline/get_doc.py index 35d72ec..d6d66bb 100644 --- a/pyreadline/get_doc.py +++ b/pyreadline/get_doc.py @@ -1,6 +1,6 @@ import sys,textwrap -rlmain=sys.modules["pyreadline.rlmain"] +rlmain=sys.modules[u"pyreadline.rlmain"] rl=rlmain.rl def get_doc(rl): @@ -13,6 +13,6 @@ def get_rest(rl): out=[] for funcname,doc in q: out.append(funcname) - out.append("\n".join(textwrap.wrap(doc,80,initial_indent=" "))) - out.append("") + out.append(u"\n".join(textwrap.wrap(doc,80,initial_indent=u" "))) + out.append(u"") return out \ No newline at end of file diff --git a/pyreadline/keysyms/__init__.py b/pyreadline/keysyms/__init__.py index 6faa94f..8c3ef5e 100644 --- a/pyreadline/keysyms/__init__.py +++ b/pyreadline/keysyms/__init__.py @@ -1,7 +1,7 @@ import sys success=False -in_ironpython="IronPython" in sys.version +in_ironpython=u"IronPython" in sys.version if in_ironpython: try: @@ -17,4 +17,4 @@ else: pass if not success: - raise ImportError("Could not import keysym for local pythonversion",x) \ No newline at end of file + raise ImportError(u"Could not import keysym for local pythonversion",x) \ No newline at end of file diff --git a/pyreadline/keysyms/common.py b/pyreadline/keysyms/common.py index a40caf4..d1a6266 100644 --- a/pyreadline/keysyms/common.py +++ b/pyreadline/keysyms/common.py @@ -15,31 +15,31 @@ except NameError: from pyreadline.unicode_helper import ensure_unicode -validkey =set(['cancel', 'backspace', 'tab', 'clear', - 'return', 'shift_l', 'control_l', 'alt_l', - 'pause', 'caps_lock', 'escape', 'space', - 'prior', 'next', 'end', 'home', - 'left', 'up', 'right', 'down', - 'select', 'print', 'execute', 'snapshot', - 'insert', 'delete', 'help', 'f1', - 'f2', 'f3', 'f4', 'f5', - 'f6', 'f7', 'f8', 'f9', - 'f10', 'f11', 'f12', 'f13', - 'f14', 'f15', 'f16', 'f17', - 'f18', 'f19', 'f20', 'f21', - 'f22', 'f23', 'f24', 'num_lock', - 'scroll_lock', 'vk_apps', 'vk_processkey','vk_attn', - 'vk_crsel', 'vk_exsel', 'vk_ereof', 'vk_play', - 'vk_zoom', 'vk_noname', 'vk_pa1', 'vk_oem_clear', - 'numpad0', 'numpad1', 'numpad2', 'numpad3', - 'numpad4', 'numpad5', 'numpad6', 'numpad7', - 'numpad8', 'numpad9', 'divide', 'multiply', - 'add', 'subtract', 'vk_decimal']) +validkey =set([u'cancel', u'backspace', u'tab', u'clear', + u'return', u'shift_l', u'control_l', u'alt_l', + u'pause', u'caps_lock', u'escape', u'space', + u'prior', u'next', u'end', u'home', + u'left', u'up', u'right', u'down', + u'select', u'print', u'execute', u'snapshot', + u'insert', u'delete', u'help', u'f1', + u'f2', u'f3', u'f4', u'f5', + u'f6', u'f7', u'f8', u'f9', + u'f10', u'f11', u'f12', u'f13', + u'f14', u'f15', u'f16', u'f17', + u'f18', u'f19', u'f20', u'f21', + u'f22', u'f23', u'f24', u'num_lock', + u'scroll_lock', u'vk_apps', u'vk_processkey',u'vk_attn', + u'vk_crsel', u'vk_exsel', u'vk_ereof', u'vk_play', + u'vk_zoom', u'vk_noname', u'vk_pa1', u'vk_oem_clear', + u'numpad0', u'numpad1', u'numpad2', u'numpad3', + u'numpad4', u'numpad5', u'numpad6', u'numpad7', + u'numpad8', u'numpad9', u'divide', u'multiply', + u'add', u'subtract', u'vk_decimal']) -escape_sequence_to_special_key={"\\e[a":"up","\\e[b":"down","del":"delete"} +escape_sequence_to_special_key={u"\\e[a":u"up", u"\\e[b":u"down", u"del":u"delete"} class KeyPress(object): - def __init__(self,char="",shift=False,control=False,meta=False,keyname=""): + def __init__(self,char="",shift=False,control=False,meta=False,keyname=u""): if control or meta or shift: char=char.upper() self.info=dict(char=char, @@ -54,11 +54,11 @@ class KeyPress(object): def set(self,value): self.info[name]=value return property(get,set) - char=create("char") - shift=create("shift") - control=create("control") - meta=create("meta") - keyname=create("keyname") + char=create(u"char") + shift=create(u"shift") + control=create(u"control") + meta=create(u"meta") + keyname=create(u"keyname") def __repr__(self): return u"(%s,%s,%s,%s)"%tuple(map(ensure_unicode,self.tuple())) @@ -74,32 +74,32 @@ class KeyPress(object): def make_KeyPress_from_keydescr(keydescr): keyinfo=KeyPress() - if len(keydescr)>2 and keydescr[:1]=='"' and keydescr[-1:]=='"': + if len(keydescr)>2 and keydescr[:1]==u'"' and keydescr[-1:]==u'"': keydescr=keydescr[1:-1] while 1: lkeyname = keydescr.lower() - if lkeyname.startswith('control-'): + if lkeyname.startswith(u'control-'): keyinfo.control = True keydescr = keydescr[8:] - elif lkeyname.startswith('ctrl-'): + elif lkeyname.startswith(u'ctrl-'): keyinfo.control = True keydescr = keydescr[5:] - elif keydescr.lower().startswith('\\c-'): + elif keydescr.lower().startswith(u'\\c-'): keyinfo.control = True keydescr = keydescr[3:] - elif keydescr.lower().startswith('\\m-'): + elif keydescr.lower().startswith(u'\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] - elif lkeyname.startswith('meta-'): + elif lkeyname.startswith(u'meta-'): keyinfo.meta = True keydescr = keydescr[5:] - elif lkeyname.startswith('alt-'): + elif lkeyname.startswith(u'alt-'): keyinfo.meta = True keydescr = keydescr[4:] - elif lkeyname.startswith('shift-'): + elif lkeyname.startswith(u'shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: @@ -108,11 +108,11 @@ def make_KeyPress_from_keydescr(keydescr): keyinfo.keyname=keydescr.strip().lower() keyinfo.char="" else: - raise IndexError("Not a valid key: '%s'"%keydescr) + raise IndexError(u"Not a valid key: '%s'"%keydescr) else: keyinfo.char=keydescr return keyinfo -if __name__=="__main__": +if __name__==u"__main__": import startup \ No newline at end of file diff --git a/pyreadline/keysyms/ironpython_keysyms.py b/pyreadline/keysyms/ironpython_keysyms.py index 6b3534d..be387f2 100644 --- a/pyreadline/keysyms/ironpython_keysyms.py +++ b/pyreadline/keysyms/ironpython_keysyms.py @@ -14,85 +14,85 @@ Shift=System.ConsoleModifiers.Shift Control=System.ConsoleModifiers.Control Alt=System.ConsoleModifiers.Alt # table for translating virtual keys to X windows key symbols -code2sym_map = {#c32.CANCEL: 'Cancel', - c32.Backspace: 'BackSpace', - c32.Tab: 'Tab', - c32.Clear: 'Clear', - c32.Enter: 'Return', -# c32.Shift: 'Shift_L', -# c32.Control: 'Control_L', -# c32.Menu: 'Alt_L', - c32.Pause: 'Pause', -# c32.Capital: 'Caps_Lock', - c32.Escape: 'Escape', -# c32.Space: 'space', - c32.PageUp: 'Prior', - c32.PageDown: 'Next', - c32.End: 'End', - c32.Home: 'Home', - c32.LeftArrow: 'Left', - c32.UpArrow: 'Up', - c32.RightArrow: 'Right', - c32.DownArrow: 'Down', - c32.Select: 'Select', - c32.Print: 'Print', - c32.Execute: 'Execute', -# c32.Snapshot: 'Snapshot', - c32.Insert: 'Insert', - c32.Delete: 'Delete', - c32.Help: 'Help', - c32.F1: 'F1', - c32.F2: 'F2', - c32.F3: 'F3', - c32.F4: 'F4', - c32.F5: 'F5', - c32.F6: 'F6', - c32.F7: 'F7', - c32.F8: 'F8', - c32.F9: 'F9', - c32.F10: 'F10', - c32.F11: 'F11', - c32.F12: 'F12', - c32.F13: 'F13', - c32.F14: 'F14', - c32.F15: 'F15', - c32.F16: 'F16', - c32.F17: 'F17', - c32.F18: 'F18', - c32.F19: 'F19', - c32.F20: 'F20', - c32.F21: 'F21', - c32.F22: 'F22', - c32.F23: 'F23', - c32.F24: 'F24', -# c32.Numlock: 'Num_Lock,', -# c32.Scroll: 'Scroll_Lock', -# c32.Apps: 'VK_APPS', -# c32.ProcesskeY: 'VK_PROCESSKEY', -# c32.Attn: 'VK_ATTN', -# c32.Crsel: 'VK_CRSEL', -# c32.Exsel: 'VK_EXSEL', -# c32.Ereof: 'VK_EREOF', -# c32.Play: 'VK_PLAY', -# c32.Zoom: 'VK_ZOOM', -# c32.Noname: 'VK_NONAME', -# c32.Pa1: 'VK_PA1', - c32.OemClear: 'VK_OEM_CLEAR', - c32.NumPad0: 'NUMPAD0', - c32.NumPad1: 'NUMPAD1', - c32.NumPad2: 'NUMPAD2', - c32.NumPad3: 'NUMPAD3', - c32.NumPad4: 'NUMPAD4', - c32.NumPad5: 'NUMPAD5', - c32.NumPad6: 'NUMPAD6', - c32.NumPad7: 'NUMPAD7', - c32.NumPad8: 'NUMPAD8', - c32.NumPad9: 'NUMPAD9', - c32.Divide: 'Divide', - c32.Multiply: 'Multiply', - c32.Add: 'Add', - c32.Subtract: 'Subtract', - c32.Decimal: 'VK_DECIMAL' +code2sym_map = {#c32.CANCEL: u'Cancel', + c32.Backspace: u'BackSpace', + c32.Tab: u'Tab', + c32.Clear: u'Clear', + c32.Enter: u'Return', +# c32.Shift: u'Shift_L', +# c32.Control: u'Control_L', +# c32.Menu: u'Alt_L', + c32.Pause: u'Pause', +# c32.Capital: u'Caps_Lock', + c32.Escape: u'Escape', +# c32.Space: u'space', + c32.PageUp: u'Prior', + c32.PageDown: u'Next', + c32.End: u'End', + c32.Home: u'Home', + c32.LeftArrow: u'Left', + c32.UpArrow: u'Up', + c32.RightArrow: u'Right', + c32.DownArrow: u'Down', + c32.Select: u'Select', + c32.Print: u'Print', + c32.Execute: u'Execute', +# c32.Snapshot: u'Snapshot', + c32.Insert: u'Insert', + c32.Delete: u'Delete', + c32.Help: u'Help', + c32.F1: u'F1', + c32.F2: u'F2', + c32.F3: u'F3', + c32.F4: u'F4', + c32.F5: u'F5', + c32.F6: u'F6', + c32.F7: u'F7', + c32.F8: u'F8', + c32.F9: u'F9', + c32.F10: u'F10', + c32.F11: u'F11', + c32.F12: u'F12', + c32.F13: u'F13', + c32.F14: u'F14', + c32.F15: u'F15', + c32.F16: u'F16', + c32.F17: u'F17', + c32.F18: u'F18', + c32.F19: u'F19', + c32.F20: u'F20', + c32.F21: u'F21', + c32.F22: u'F22', + c32.F23: u'F23', + c32.F24: u'F24', +# c32.Numlock: u'Num_Lock,', +# c32.Scroll: u'Scroll_Lock', +# c32.Apps: u'VK_APPS', +# c32.ProcesskeY: u'VK_PROCESSKEY', +# c32.Attn: u'VK_ATTN', +# c32.Crsel: u'VK_CRSEL', +# c32.Exsel: u'VK_EXSEL', +# c32.Ereof: u'VK_EREOF', +# c32.Play: u'VK_PLAY', +# c32.Zoom: u'VK_ZOOM', +# c32.Noname: u'VK_NONAME', +# c32.Pa1: u'VK_PA1', + c32.OemClear: u'VK_OEM_CLEAR', + c32.NumPad0: u'NUMPAD0', + c32.NumPad1: u'NUMPAD1', + c32.NumPad2: u'NUMPAD2', + c32.NumPad3: u'NUMPAD3', + c32.NumPad4: u'NUMPAD4', + c32.NumPad5: u'NUMPAD5', + c32.NumPad6: u'NUMPAD6', + c32.NumPad7: u'NUMPAD7', + c32.NumPad8: u'NUMPAD8', + c32.NumPad9: u'NUMPAD9', + c32.Divide: u'Divide', + c32.Multiply: u'Multiply', + c32.Add: u'Add', + c32.Subtract: u'Subtract', + c32.Decimal: u'VK_DECIMAL' } # function to handle the mapping @@ -100,7 +100,7 @@ def make_keysym(keycode): try: sym = code2sym_map[keycode] except KeyError: - sym = '' + sym = u'' return sym sym2code_map = {} @@ -108,7 +108,7 @@ for code,sym in code2sym_map.iteritems(): sym2code_map[sym.lower()] = code def key_text_to_keyinfo(keytext): - '''Convert a GNU readline style textual description of a key to keycode with modifiers''' + u'''Convert a GNU readline style textual description of a key to keycode with modifiers''' if keytext.startswith('"'): # " return keyseq_to_keyinfo(keytext[1:-1]) else: @@ -118,8 +118,8 @@ def key_text_to_keyinfo(keytext): def char_to_keyinfo(char, control=False, meta=False, shift=False): vk = (ord(char)) if vk & 0xffff == 0xffff: - print 'VkKeyScan("%s") = %x' % (char, vk) - raise ValueError, 'bad key' + print u'VkKeyScan("%s") = %x' % (char, vk) + raise ValueError, u'bad key' if vk & 0x100: shift = True if vk & 0x200: @@ -135,24 +135,24 @@ def keyname_to_keyinfo(keyname): while 1: lkeyname = keyname.lower() - if lkeyname.startswith('control-'): + if lkeyname.startswith(u'control-'): control = True keyname = keyname[8:] - elif lkeyname.startswith('ctrl-'): + elif lkeyname.startswith(u'ctrl-'): control = True keyname = keyname[5:] - elif lkeyname.startswith('meta-'): + elif lkeyname.startswith(u'meta-'): meta = True keyname = keyname[5:] - elif lkeyname.startswith('alt-'): + elif lkeyname.startswith(u'alt-'): meta = True keyname = keyname[4:] - elif lkeyname.startswith('shift-'): + elif lkeyname.startswith(u'shift-'): shift = True keyname = keyname[6:] else: if len(keyname) > 1: - return (control, meta, shift, sym2code_map.get(keyname.lower()," ")) + return (control, meta, shift, sym2code_map.get(keyname.lower(),u" ")) else: return char_to_keyinfo(keyname, control, meta, shift) @@ -163,14 +163,14 @@ def keyseq_to_keyinfo(keyseq): shift = False while 1: - if keyseq.startswith('\\C-'): + if keyseq.startswith(u'\\C-'): control = True keyseq = keyseq[3:] - elif keyseq.startswith('\\M-'): + elif keyseq.startswith(u'\\M-'): meta = True keyseq = keyseq[3:] - elif keyseq.startswith('\\e'): - res.append(char_to_keyinfo('\033', control, meta, shift)) + elif keyseq.startswith(u'\\e'): + res.append(char_to_keyinfo(u'\033', control, meta, shift)) control = meta = shift = False keyseq = keyseq[2:] elif len(keyseq) >= 1: @@ -195,7 +195,7 @@ def make_KeyPress(char,state,keycode): shift=bool(int(state)&int(Shift)) control=bool(int(state)&int(Control)) meta=bool(int(state)&int(Alt)) - keyname=code2sym_map.get(keycode,"").lower() + keyname=code2sym_map.get(keycode,u"").lower() if control and meta: #equivalent to altgr so clear flags control=False meta=False diff --git a/pyreadline/keysyms/keysyms.py b/pyreadline/keysyms/keysyms.py index 1eecd34..ee77186 100644 --- a/pyreadline/keysyms/keysyms.py +++ b/pyreadline/keysyms/keysyms.py @@ -14,85 +14,85 @@ import ctypes from common import validkey,KeyPress,make_KeyPress_from_keydescr -code2sym_map = {c32.VK_CANCEL: 'cancel', - c32.VK_BACK: 'backspace', - c32.VK_TAB: 'tab', - c32.VK_CLEAR: 'clear', - c32.VK_RETURN: 'return', - c32.VK_SHIFT: 'shift_l', - c32.VK_CONTROL: 'control_l', - c32.VK_MENU: 'alt_l', - c32.VK_PAUSE: 'pause', - c32.VK_CAPITAL: 'caps_lock', - c32.VK_ESCAPE: 'escape', - c32.VK_SPACE: 'space', - c32.VK_PRIOR: 'prior', - c32.VK_NEXT: 'next', - c32.VK_END: 'end', - c32.VK_HOME: 'home', - c32.VK_LEFT: 'left', - c32.VK_UP: 'up', - c32.VK_RIGHT: 'right', - c32.VK_DOWN: 'down', - c32.VK_SELECT: 'select', - c32.VK_PRINT: 'print', - c32.VK_EXECUTE: 'execute', - c32.VK_SNAPSHOT: 'snapshot', - c32.VK_INSERT: 'insert', - c32.VK_DELETE: 'delete', - c32.VK_HELP: 'help', - c32.VK_F1: 'f1', - c32.VK_F2: 'f2', - c32.VK_F3: 'f3', - c32.VK_F4: 'f4', - c32.VK_F5: 'f5', - c32.VK_F6: 'f6', - c32.VK_F7: 'f7', - c32.VK_F8: 'f8', - c32.VK_F9: 'f9', - c32.VK_F10: 'f10', - c32.VK_F11: 'f11', - c32.VK_F12: 'f12', - c32.VK_F13: 'f13', - c32.VK_F14: 'f14', - c32.VK_F15: 'f15', - c32.VK_F16: 'f16', - c32.VK_F17: 'f17', - c32.VK_F18: 'f18', - c32.VK_F19: 'f19', - c32.VK_F20: 'f20', - c32.VK_F21: 'f21', - c32.VK_F22: 'f22', - c32.VK_F23: 'f23', - c32.VK_F24: 'f24', - c32.VK_NUMLOCK: 'num_lock,', - c32.VK_SCROLL: 'scroll_lock', - c32.VK_APPS: 'vk_apps', - c32.VK_PROCESSKEY: 'vk_processkey', - c32.VK_ATTN: 'vk_attn', - c32.VK_CRSEL: 'vk_crsel', - c32.VK_EXSEL: 'vk_exsel', - c32.VK_EREOF: 'vk_ereof', - c32.VK_PLAY: 'vk_play', - c32.VK_ZOOM: 'vk_zoom', - c32.VK_NONAME: 'vk_noname', - c32.VK_PA1: 'vk_pa1', - c32.VK_OEM_CLEAR :'vk_oem_clear', - c32.VK_NUMPAD0: 'numpad0', - c32.VK_NUMPAD1: 'numpad1', - c32.VK_NUMPAD2: 'numpad2', - c32.VK_NUMPAD3: 'numpad3', - c32.VK_NUMPAD4: 'numpad4', - c32.VK_NUMPAD5: 'numpad5', - c32.VK_NUMPAD6: 'numpad6', - c32.VK_NUMPAD7: 'numpad7', - c32.VK_NUMPAD8: 'numpad8', - c32.VK_NUMPAD9: 'numpad9', - c32.VK_DIVIDE: 'divide', - c32.VK_MULTIPLY: 'multiply', - c32.VK_ADD: 'add', - c32.VK_SUBTRACT: 'subtract', - c32.VK_DECIMAL: 'vk_decimal' +code2sym_map = {c32.VK_CANCEL: u'cancel', + c32.VK_BACK: u'backspace', + c32.VK_TAB: u'tab', + c32.VK_CLEAR: u'clear', + c32.VK_RETURN: u'return', + c32.VK_SHIFT: u'shift_l', + c32.VK_CONTROL: u'control_l', + c32.VK_MENU: u'alt_l', + c32.VK_PAUSE: u'pause', + c32.VK_CAPITAL: u'caps_lock', + c32.VK_ESCAPE: u'escape', + c32.VK_SPACE: u'space', + c32.VK_PRIOR: u'prior', + c32.VK_NEXT: u'next', + c32.VK_END: u'end', + c32.VK_HOME: u'home', + c32.VK_LEFT: u'left', + c32.VK_UP: u'up', + c32.VK_RIGHT: u'right', + c32.VK_DOWN: u'down', + c32.VK_SELECT: u'select', + c32.VK_PRINT: u'print', + c32.VK_EXECUTE: u'execute', + c32.VK_SNAPSHOT: u'snapshot', + c32.VK_INSERT: u'insert', + c32.VK_DELETE: u'delete', + c32.VK_HELP: u'help', + c32.VK_F1: u'f1', + c32.VK_F2: u'f2', + c32.VK_F3: u'f3', + c32.VK_F4: u'f4', + c32.VK_F5: u'f5', + c32.VK_F6: u'f6', + c32.VK_F7: u'f7', + c32.VK_F8: u'f8', + c32.VK_F9: u'f9', + c32.VK_F10: u'f10', + c32.VK_F11: u'f11', + c32.VK_F12: u'f12', + c32.VK_F13: u'f13', + c32.VK_F14: u'f14', + c32.VK_F15: u'f15', + c32.VK_F16: u'f16', + c32.VK_F17: u'f17', + c32.VK_F18: u'f18', + c32.VK_F19: u'f19', + c32.VK_F20: u'f20', + c32.VK_F21: u'f21', + c32.VK_F22: u'f22', + c32.VK_F23: u'f23', + c32.VK_F24: u'f24', + c32.VK_NUMLOCK: u'num_lock,', + c32.VK_SCROLL: u'scroll_lock', + c32.VK_APPS: u'vk_apps', + c32.VK_PROCESSKEY: u'vk_processkey', + c32.VK_ATTN: u'vk_attn', + c32.VK_CRSEL: u'vk_crsel', + c32.VK_EXSEL: u'vk_exsel', + c32.VK_EREOF: u'vk_ereof', + c32.VK_PLAY: u'vk_play', + c32.VK_ZOOM: u'vk_zoom', + c32.VK_NONAME: u'vk_noname', + c32.VK_PA1: u'vk_pa1', + c32.VK_OEM_CLEAR: u'vk_oem_clear', + c32.VK_NUMPAD0: u'numpad0', + c32.VK_NUMPAD1: u'numpad1', + c32.VK_NUMPAD2: u'numpad2', + c32.VK_NUMPAD3: u'numpad3', + c32.VK_NUMPAD4: u'numpad4', + c32.VK_NUMPAD5: u'numpad5', + c32.VK_NUMPAD6: u'numpad6', + c32.VK_NUMPAD7: u'numpad7', + c32.VK_NUMPAD8: u'numpad8', + c32.VK_NUMPAD9: u'numpad9', + c32.VK_DIVIDE: u'divide', + c32.VK_MULTIPLY: u'multiply', + c32.VK_ADD: u'add', + c32.VK_SUBTRACT: u'subtract', + c32.VK_DECIMAL: u'vk_decimal' } VkKeyScan = windll.user32.VkKeyScanA @@ -101,8 +101,8 @@ def char_to_keyinfo(char, control=False, meta=False, shift=False): k=KeyPress() vk = VkKeyScan(ord(char)) if vk & 0xffff == 0xffff: - print 'VkKeyScan("%s") = %x' % (char, vk) - raise ValueError, 'bad key' + print u'VkKeyScan("%s") = %x' % (char, vk) + raise ValueError, u'bad key' if vk & 0x100: k.shift = True if vk & 0x200: @@ -124,10 +124,10 @@ def make_KeyPress(char, state, keycode): try: keyname=code2sym_map[keycode] except KeyError: - keyname="" + keyname=u"" out=KeyPress(char, shift, control, meta, keyname) return out -if __name__=="__main__": +if __name__==u"__main__": import startup \ No newline at end of file diff --git a/pyreadline/lineeditor/history.py b/pyreadline/lineeditor/history.py index 9eee20e..15a25c8 100644 --- a/pyreadline/lineeditor/history.py +++ b/pyreadline/lineeditor/history.py @@ -8,8 +8,8 @@ import re,operator,string,sys,os from pyreadline.unicode_helper import ensure_unicode,ensure_str -if "pyreadline" in sys.modules: - pyreadline= sys.modules["pyreadline"] +if u"pyreadline" in sys.modules: + pyreadline= sys.modules[u"pyreadline"] else: import pyreadline @@ -29,60 +29,60 @@ class LineHistory(object): self.history=[] self._history_length=100 self._history_cursor=0 - self.history_filename=os.path.expanduser('~/.history') + self.history_filename=os.path.expanduser('~/.history') #Cannot expand unicode strings correctly on python2.4 self.lastcommand=None - self.query="" + self.query=u"" def get_history_length(self): value=self._history_length - log("get_history_length:%d"%value) + log(u"get_history_length:%d"%value) return value def set_history_length(self,value): - log("set_history_length: old:%d new:%d"%(self._history_length,value)) + log(u"set_history_length: old:%d new:%d"%(self._history_length,value)) self._history_length=value def get_history_cursor(self): value=self._history_cursor - log("get_history_cursor:%d"%value) + log(u"get_history_cursor:%d"%value) return value def set_history_cursor(self,value): - log("set_history_cursor: old:%d new:%d"%(self._history_cursor,value)) + log(u"set_history_cursor: old:%d new:%d"%(self._history_cursor,value)) self._history_cursor=value history_length=property(get_history_length,set_history_length) history_cursor=property(get_history_cursor,set_history_cursor) def clear_history(self): - '''Clear readline history.''' + u'''Clear readline history.''' self.history[:] = [] self.history_cursor = 0 def read_history_file(self, filename=None): - '''Load a readline history file.''' + u'''Load a readline history file.''' if filename is None: filename=self.history_filename try: - for line in open(filename, 'r'): + for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip()))) except IOError: self.history = [] self.history_cursor = 0 def write_history_file(self, filename=None): - '''Save a readline history file.''' + u'''Save a readline history file.''' if filename is None: filename=self.history_filename - fp = open(filename, 'wb') + fp = open(filename, u'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_text())) - fp.write('\n') + fp.write(u'\n') fp.close() def add_history(self, line): - '''Append a line to the history buffer, as if it was the last line typed.''' + u'''Append a line to the history buffer, as if it was the last line typed.''' if not line.get_line_text(): pass elif len(self.history) > 0 and self.history[-1].get_line_text() == line.get_line_text(): @@ -92,7 +92,7 @@ class LineHistory(object): self.history_cursor = len(self.history) def previous_history(self,current): # (C-p) - '''Move back through the history list, fetching the previous command. ''' + u'''Move back through the history list, fetching the previous command. ''' if self.history_cursor==len(self.history): self.history.append(current.copy()) #do not use add_history since we do not want to increment cursor @@ -102,19 +102,19 @@ class LineHistory(object): current.point=lineobj.EndOfLine def next_history(self,current): # (C-n) - '''Move forward through the history list, fetching the next command. ''' + u'''Move forward through the history list, fetching the next command. ''' if self.history_cursor < len(self.history)-1: self.history_cursor += 1 current.set_line(self.history[self.history_cursor].get_line_text()) def beginning_of_history(self): # (M-<) - '''Move to the first line in the history.''' + u'''Move to the first line in the history.''' self.history_cursor = 0 if len(self.history) > 0: self.l_buffer = self.history[0] def end_of_history(self,current): # (M->) - '''Move to the end of the input history, i.e., the line currently + u'''Move to the end of the input history, i.e., the line currently being entered.''' self.history_cursor=len(self.history) current.set_line(self.history[-1].get_line_text()) @@ -129,7 +129,7 @@ class LineHistory(object): if res: self.history_cursor-=res[0][0] return res[0][1].get_line_text() - return "" + return u"" def forward_search_history(self,searchfor,startpos=None): if startpos is None: @@ -141,13 +141,13 @@ class LineHistory(object): if res: self.history_cursor+=res[0][0] return res[0][1].get_line_text() - return "" + return u"" def _search(self, direction, partial): try: if (self.lastcommand != self.history_search_forward and self.lastcommand != self.history_search_backward): - self.query = ''.join(partial[0:partial.point].get_line_text()) + self.query = u''.join(partial[0:partial.point].get_line_text()) hcstart=max(self.history_cursor,0) hc = self.history_cursor + direction while (direction < 0 and hc >= 0) or (direction > 0 and hc < len(self.history)): @@ -166,7 +166,7 @@ class LineHistory(object): pass elif hc>=len(self.history) and not self.query: self.history_cursor=len(self.history) - return lineobj.ReadLineTextBuffer("",point=0) + return lineobj.ReadLineTextBuffer(u"",point=0) elif self.history[max(min(hcstart,len(self.history)-1),0)].get_line_text().startswith(self.query) and self.query: return lineobj.ReadLineTextBuffer(self.history[max(min(hcstart,len(self.history)-1),0)],point=partial.point) else: @@ -176,26 +176,26 @@ class LineHistory(object): raise def history_search_forward(self,partial): # () - '''Search forward through the history for the string of characters + u'''Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' q= self._search(1,partial) return q def history_search_backward(self,partial): # () - '''Search backward through the history for the string of characters + u'''Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' q= self._search(-1,partial) return q -if __name__=="__main__": +if __name__==u"__main__": q=LineHistory() RL=lineobj.ReadLineTextBuffer - q.add_history(RL("aaaa")) - q.add_history(RL("aaba")) - q.add_history(RL("aaca")) - q.add_history(RL("akca")) - q.add_history(RL("bbb")) - q.add_history(RL("ako")) + q.add_history(RL(u"aaaa")) + q.add_history(RL(u"aaba")) + q.add_history(RL(u"aaca")) + q.add_history(RL(u"akca")) + q.add_history(RL(u"bbb")) + q.add_history(RL(u"ako")) diff --git a/pyreadline/lineeditor/lineobj.py b/pyreadline/lineeditor/lineobj.py index 0e62108..9b3ab0f 100644 --- a/pyreadline/lineeditor/lineobj.py +++ b/pyreadline/lineeditor/lineobj.py @@ -27,7 +27,7 @@ def quote_char(c): class LinePositioner(object): def __call__(self,line): - NotImplementedError("Base class !!!") + NotImplementedError(u"Base class !!!") class NextChar(LinePositioner): def __call__(self,line): @@ -69,7 +69,7 @@ class WordStart(LinePositioner): else: return line.point else: - raise NotAWordError("Point is not in a word") + raise NotAWordError(u"Point is not in a word") WordStart=WordStart() class WordEnd(LinePositioner): @@ -80,7 +80,7 @@ class WordEnd(LinePositioner): else: return line.point else: - raise NotAWordError("Point is not in a word") + raise NotAWordError(u"Point is not in a word") WordEnd=WordEnd() class PrevWordEnd(LinePositioner): @@ -91,10 +91,10 @@ PrevWordEnd=PrevWordEnd() class PrevSpace(LinePositioner): def __call__(self,line): point=line.point - if line[point-1:point].get_line_text()==" ": - while point>0 and line[point-1:point].get_line_text()==" ": + if line[point-1:point].get_line_text()==u" ": + while point>0 and line[point-1:point].get_line_text()==u" ": point-=1 - while point>0 and line[point-1:point].get_line_text()!=" ": + while point>0 and line[point-1:point].get_line_text()!=u" ": point-=1 return point PrevSpace=PrevSpace() @@ -127,7 +127,7 @@ all_positioners.sort() class LineSlice(object): def __call__(self,line): - NotImplementedError("Base class !!!") + NotImplementedError(u"Base class !!!") class CurrentWord(LineSlice): @@ -221,7 +221,7 @@ class TextLine(object): pass def __repr__(self): - return 'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer,self.point,self.mark) + return u'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer,self.point,self.mark) def copy(self): return self.__class__(self) @@ -241,7 +241,7 @@ class TextLine(object): def visible_line_width(self,position=Point): """Return the visible width of the text in line buffer up to position.""" extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD]) - return len(self[:position].quoted_text())+self[:position].line_buffer.count("\t")*7 + extra_char_width + return len(self[:position].quoted_text())+self[:position].line_buffer.count(u"\t")*7 + extra_char_width def quoted_text(self): quoted = [ quote_char(c) for c in self.line_buffer ] @@ -305,7 +305,7 @@ class TextLine(object): elif isinstance(key,LinePositioner): return self.line_buffer[key(self)] elif isinstance(key,tuple): - raise IndexError("Cannot use step in line buffer indexing") #Multiple slice not allowed + raise IndexError(u"Cannot use step in line buffer indexing") #Multiple slice not allowed else: # return TextLine(self.line_buffer[key]) return self.line_buffer[key] @@ -385,10 +385,10 @@ class TextLine(object): return txt in self.get_line_text() -lines=[TextLine("abc"), - TextLine("abc def"), - TextLine("abc def ghi"), - TextLine(" abc def "), +lines=[TextLine(u"abc"), + TextLine(u"abc def"), + TextLine(u"abc def ghi"), + TextLine(u" abc def "), ] l=lines[2] l.point=5 @@ -404,7 +404,7 @@ class ReadLineTextBuffer(TextLine): self.kill_ring=[] def __repr__(self): - return 'ReadLineTextBuffer("%s",point=%s,mark=%s,selection_mark=%s)'%(self.line_buffer,self.point,self.mark,self.selection_mark) + return u'ReadLineTextBuffer("%s",point=%s,mark=%s,selection_mark=%s)'%(self.line_buffer,self.point,self.mark,self.selection_mark) def insert_text(self, char, argument=1): @@ -714,7 +714,7 @@ class ReadLineTextBuffer(TextLine): def copy_region_to_clipboard(self): # () - '''Copy the text in the region to the windows clipboard.''' + u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard: mark=min(self.mark,len(self.line_buffer)) cursor=min(self.point,len(self.line_buffer)) @@ -722,11 +722,11 @@ class ReadLineTextBuffer(TextLine): return begin=min(cursor,mark) end=max(cursor,mark) - toclipboard="".join(self.line_buffer[begin:end]) + toclipboard=u"".join(self.line_buffer[begin:end]) clipboard.SetClipboardText(toclipboard) def copy_selection_to_clipboard(self): # () - '''Copy the text in the region to the windows clipboard.''' + u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard and self.enable_selection and self.selection_mark>=0: selection_mark=min(self.selection_mark,len(self.line_buffer)) cursor=min(self.point,len(self.line_buffer)) @@ -734,7 +734,7 @@ class ReadLineTextBuffer(TextLine): return begin=min(cursor,selection_mark) end=max(cursor,selection_mark) - toclipboard="".join(self.line_buffer[begin:end]) + toclipboard=u"".join(self.line_buffer[begin:end]) clipboard.SetClipboardText(toclipboard) @@ -757,46 +757,45 @@ class ReadLineTextBuffer(TextLine): ################################################################## -q=ReadLineTextBuffer("asff asFArw ewrWErhg",point=8) -q=TextLine("asff asFArw ewrWErhg",point=8) +q=ReadLineTextBuffer(u"asff asFArw ewrWErhg",point=8) +q=TextLine(u"asff asFArw ewrWErhg",point=8) -def show_pos(buff,pos,chr="."): +def show_pos(buff,pos,chr=u"."): l=len(buff.line_buffer) def choice(bool): if bool: return chr else: - return " " - return "".join([choice(pos==idx) for idx in range(l+1)]) + return u" " + return u"".join([choice(pos==idx) for idx in range(l+1)]) def test_positioner(buff,points,positioner): - print (" %s "%positioner.__class__.__name__).center(40,"-") + print (u" %s "%positioner.__class__.__name__).center(40,u"-") buffstr=buff.line_buffer - print '"%s"'%(buffstr) + print u'"%s"'%(buffstr) for point in points: b=TextLine(buff,point=point) - out=[" "]*(len(buffstr)+1) + out=[u" "]*(len(buffstr)+1) pos=positioner(b) if pos==point: - out[pos]="&" + out[pos]=u"&" else: - out[point]="." - out[pos]="^" - print '"%s"'%("".join(out)) + out[point]=u"." + out[pos]=u"^" + print u'"%s"'%(u"".join(out)) if __name__=="__main__": - import startup - print '%-15s "%s"'%("Position",q.get_line_text()) - print '%-15s "%s"'%("Point",show_pos(q,q.point)) + print u'%-15s "%s"'%(u"Position",q.get_line_text()) + print u'%-15s "%s"'%(u"Point",show_pos(q,q.point)) for name,positioner in all_positioners: pos=positioner(q) [] - print '%-15s "%s"'%(name,show_pos(q,pos,"^")) + print u'%-15s "%s"'%(name,show_pos(q,pos,u"^")) - l=ReadLineTextBuffer("kjjk asads asad") + l=ReadLineTextBuffer(u"kjjk asads asad") l.point=EndOfLine diff --git a/pyreadline/lineeditor/wordmatcher.py b/pyreadline/lineeditor/wordmatcher.py index 7a01108..9bb8b28 100644 --- a/pyreadline/lineeditor/wordmatcher.py +++ b/pyreadline/lineeditor/wordmatcher.py @@ -20,36 +20,36 @@ def str_find_all(str,ch): return result -word_pattern=re.compile("(x*)") +word_pattern=re.compile(u"(x*)") def markwords(str,iswordfun): - markers={True:"x",False:"o"} + markers={True:u"x",False:u"o"} return "".join([markers[iswordfun(ch)] for ch in str]) def split_words(str,iswordfun): - return [x for x in word_pattern.split(markwords(str,iswordfun)) if x !=""] + return [x for x in word_pattern.split(markwords(str,iswordfun)) if x !=u""] def mark_start_segment(str,is_segment): def mark_start(s): - if s[0:1]=="x": - return "s"+s[1:] + if s[0:1]==u"x": + return u"s"+s[1:] else: return s - return "".join(map(mark_start,split_words(str,is_segment))) + return u"".join(map(mark_start,split_words(str,is_segment))) def mark_end_segment(str,is_segment): def mark_start(s): - if s[0:1]=="x": - return s[:-1]+"s" + if s[0:1]==u"x": + return s[:-1]+u"s" else: return s - return "".join(map(mark_start,split_words(str,is_segment))) + return u"".join(map(mark_start,split_words(str,is_segment))) def mark_start_segment_index(str,is_segment): - return str_find_all(mark_start_segment(str,is_segment),"s") + return str_find_all(mark_start_segment(str,is_segment),u"s") def mark_end_segment_index(str,is_segment): - return [x+1 for x in str_find_all(mark_end_segment(str,is_segment),"s")] + return [x+1 for x in str_find_all(mark_end_segment(str,is_segment),u"s")] ################ Following are used in lineobj ########################### @@ -58,13 +58,13 @@ def is_word_token(str): return not is_non_word_token(str) def is_non_word_token(str): - if len(str)!=1 or str in " \t\n": + if len(str)!=1 or str in u" \t\n": return True else: return False def next_start_segment(str,is_segment): - str="".join(str) + str=u"".join(str) result=[] for start in mark_start_segment_index(str,is_segment): result[len(result):start]=[start for x in range(start-len(result))] @@ -72,7 +72,7 @@ def next_start_segment(str,is_segment): return result def next_end_segment(str,is_segment): - str="".join(str) + str=u"".join(str) result=[] for start in mark_end_segment_index(str,is_segment): result[len(result):start]=[start for x in range(start-len(result))] @@ -81,7 +81,7 @@ def next_end_segment(str,is_segment): def prev_start_segment(str,is_segment): - str="".join(str) + str=u"".join(str) result=[] prev=0 for start in mark_start_segment_index(str,is_segment): @@ -91,7 +91,7 @@ def prev_start_segment(str,is_segment): return result def prev_end_segment(str,is_segment): - str="".join(str) + str=u"".join(str) result=[] prev=0 for start in mark_end_segment_index(str,is_segment): diff --git a/pyreadline/logger.py b/pyreadline/logger.py index e4f7d3f..bfaeeb0 100644 --- a/pyreadline/logger.py +++ b/pyreadline/logger.py @@ -9,11 +9,11 @@ import socket, logging, logging.handlers from pyreadline.unicode_helper import ensure_str -host="localhost" +host=u"localhost" port=logging.handlers.DEFAULT_TCP_LOGGING_PORT -root_logger=logging.getLogger('') +root_logger=logging.getLogger(u'') root_logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') file_handler=None diff --git a/pyreadline/logserver.py b/pyreadline/logserver.py index c5c73fe..df7798d 100644 --- a/pyreadline/logserver.py +++ b/pyreadline/logserver.py @@ -15,11 +15,11 @@ try: import msvcrt except ImportError: msvcrt=None - print "problem" + print u"problem" port=logging.handlers.DEFAULT_TCP_LOGGING_PORT -host='localhost' +host=u'localhost' def check_key(): if msvcrt is None: @@ -28,18 +28,18 @@ def check_key(): if msvcrt.kbhit()!=0: q=msvcrt.getch() return q - return "" + return u"" singleline=False def main(): - print "Starting TCP logserver on port:",port - print "Press q to quit logserver", port - print "Press c to clear screen", port + print u"Starting TCP logserver on port:",port + print u"Press q to quit logserver", port + print u"Press c to clear screen", port s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - s.bind(("",port)) + s.bind((u"",port)) s.settimeout(1) while 1: try: @@ -47,11 +47,11 @@ def main(): print data, except socket.timeout: key=check_key().lower() - if "q"==key: - print "Quitting logserver" + if u"q"==key: + print u"Quitting logserver" break - elif "c" == key: - print "\n"*100 + elif u"c" == key: + print u"\n"*100 -if __name__ == "__main__": +if __name__ == u"__main__": main() \ No newline at end of file diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index 76d1a11..c5596ef 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -15,10 +15,10 @@ import pyreadline.lineeditor.history as history import pyreadline.clipboard as clipboard from pyreadline.error import ReadlineError,GetSetError from pyreadline.unicode_helper import ensure_str, ensure_unicode -in_ironpython="IronPython" in sys.version +in_ironpython=u"IronPython" in sys.version class BaseMode(object): - mode="base" + mode=u"base" def __init__(self,rlobj): self.argument=0 self.rlobj=rlobj @@ -28,9 +28,9 @@ class BaseMode(object): self.prevargument=None self.l_buffer=lineobj.ReadLineTextBuffer("") self._history=history.LineHistory() - self.completer_delims = " \t\n\"\\'`@$><=;|&{(" - self.show_all_if_ambiguous = 'off' - self.mark_directories = 'on' + self.completer_delims = u" \t\n\"\\'`@$><=;|&{(" + self.show_all_if_ambiguous = u'off' + self.mark_directories = u'on' self.completer = None self.begidx = 0 self.endidx = 0 @@ -40,7 +40,7 @@ class BaseMode(object): self.first_prompt = True self.cursor_size=25 - self.prompt = ">>>" + self.prompt = u">>> " #Paste settings #assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n @@ -57,7 +57,7 @@ class BaseMode(object): def __repr__(self): - return "" + return u"" def _gs(x): def g(self): @@ -80,29 +80,29 @@ class BaseMode(object): argument_reset=property(_argreset) #used in readline - ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval")) - allow_ctrl_c=property(*_gs("allow_ctrl_c")) - _print_prompt=property(_g("_print_prompt")) - _update_line=property(_g("_update_line")) - console=property(_g("console")) - prompt_begin_pos=property(_g("prompt_begin_pos")) - prompt_end_pos=property(_g("prompt_end_pos")) + ctrl_c_tap_time_interval=property(*_gs(u"ctrl_c_tap_time_interval")) + allow_ctrl_c=property(*_gs(u"allow_ctrl_c")) + _print_prompt=property(_g(u"_print_prompt")) + _update_line=property(_g(u"_update_line")) + console=property(_g(u"console")) + prompt_begin_pos=property(_g(u"prompt_begin_pos")) + prompt_end_pos=property(_g(u"prompt_end_pos")) #used in completer _completions # completer_delims=property(*_gs("completer_delims")) - _bell=property(_g("_bell")) - bell_style=property(_g("bell_style")) + _bell=property(_g(u"_bell")) + bell_style=property(_g(u"bell_style")) #used in emacs - _clear_after=property(_g("_clear_after")) - _update_prompt_pos=property(_g("_update_prompt_pos")) + _clear_after=property(_g(u"_clear_after")) + _update_prompt_pos=property(_g(u"_update_prompt_pos")) #not used in basemode or emacs def process_keyevent(self, keyinfo): raise NotImplementedError - def readline_setup(self, prompt=''): + def readline_setup(self, prompt=u''): self.l_buffer.selection_mark=-1 if self.first_prompt: self.first_prompt = False @@ -110,7 +110,7 @@ class BaseMode(object): try: self.startup_hook() except: - print 'startup hook failed' + print u'startup hook failed' traceback.print_exc() self.l_buffer.reset_line() @@ -120,7 +120,7 @@ class BaseMode(object): try: self.pre_input_hook() except: - print 'pre_input_hook failed' + print u'pre_input_hook failed' traceback.print_exc() self.pre_input_hook = None @@ -129,7 +129,7 @@ class BaseMode(object): def finalize(self): - """Every bindable command should call this function for cleanup. + u"""Every bindable command should call this function for cleanup. Except those that want to set argument to a non-zero value. """ self.argument=0 @@ -141,12 +141,12 @@ class BaseMode(object): #Create key bindings: def rl_settings_to_string(self): - out=["%-20s: %s"%("show all if ambigous",self.show_all_if_ambiguous)] - out.append("%-20s: %s"%("mark_directories",self.mark_directories)) - out.append("%-20s: %s"%("bell_style",self.bell_style)) - out.append("------------- key bindings ------------") - tablepat="%-7s %-7s %-7s %-15s %-15s " - out.append(tablepat%("Control","Meta","Shift","Keycode/char","Function")) + out=[u"%-20s: %s"%(u"show all if ambigous",self.show_all_if_ambiguous)] + out.append(u"%-20s: %s"%(u"mark_directories",self.mark_directories)) + out.append(u"%-20s: %s"%(u"bell_style",self.bell_style)) + out.append(u"------------- key bindings ------------") + tablepat=u"%-7s %-7s %-7s %-15s %-15s " + out.append(tablepat%(u"Control",u"Meta",u"Shift",u"Keycode/char",u"Function")) bindings=[(k[0],k[1],k[2],k[3],v.__name__) for k,v in self.key_dispatch.iteritems()] bindings.sort() for key in bindings: @@ -155,16 +155,16 @@ class BaseMode(object): def _bind_key(self, key, func): - """setup the mapping from key to call the function.""" + u"""setup the mapping from key to call the function.""" if type(func) != type(self._bind_key): - print "Trying to bind non method to keystroke:%s,%s"%(key,func) - raise PyreadlineError("Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(self._bind_key))) + print u"Trying to bind non method to keystroke:%s,%s"%(key,func) + raise PyreadlineError(u"Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(self._bind_key))) keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple() - log(">>>%s -> %s<<<"%(keyinfo,func.__name__)) + log(u">>>%s -> %s<<<"%(keyinfo,func.__name__)) self.key_dispatch[keyinfo] = func def _bind_exit_key(self, key): - """setup the mapping from key to call the function.""" + u"""setup the mapping from key to call the function.""" keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple() self.exit_dispatch[keyinfo] = None @@ -189,8 +189,8 @@ class BaseMode(object): if buf[self.begidx] in self.completer_delims: self.begidx += 1 break - text = ensure_str(''.join(buf[self.begidx:self.endidx])) - log('complete text="%s"' % text) + text = ensure_str(u''.join(buf[self.begidx:self.endidx])) + log(u'complete text="%s"' % text) i = 0 while 1: try: @@ -202,18 +202,18 @@ class BaseMode(object): completions.append(r) else: break - log('text completions=<%s>' % completions) + log(u'text completions=<%s>' % completions) if not completions: # get the filename to complete while self.begidx > 0: self.begidx -= 1 - if buf[self.begidx] in ' \t\n': + if buf[self.begidx] in u' \t\n': self.begidx += 1 break - text = ensure_str(''.join(buf[self.begidx:self.endidx])) - log('file complete text="%s"' % text) + text = ensure_str(u''.join(buf[self.begidx:self.endidx])) + log(u'file complete text="%s"' % text) completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*')) - if self.mark_directories == 'on': + if self.mark_directories == u'on': mc = [] for f in completions: if os.path.isdir(f): @@ -221,32 +221,32 @@ class BaseMode(object): else: mc.append(f) completions = mc - log('fnames=<%s>' % completions) + log(u'fnames=<%s>' % completions) return completions def _display_completions(self, completions): if not completions: return - self.console.write('\n') + self.console.write(u'\n') wmax = max(map(len, completions)) w, h = self.console.size() cols = max(1, int((w-1) / (wmax+1))) rows = int(math.ceil(float(len(completions)) / cols)) for row in range(rows): - s = '' + s = u'' for col in range(cols): i = col*rows + row if i < len(completions): self.console.write(completions[i].ljust(wmax+1)) - self.console.write('\n') + self.console.write(u'\n') if in_ironpython: self.prompt=sys.ps1 self._print_prompt() def complete(self, e): # (TAB) - """Attempt to perform completion on the text before point. The + u"""Attempt to perform completion on the text before point. The actual completion performed is application-specific. The default is filename completion.""" completions = self._get_completions() @@ -257,7 +257,7 @@ class BaseMode(object): self.l_buffer[self.begidx:self.endidx] = rep self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx) if len(completions) > 1: - if self.show_all_if_ambiguous == 'on': + if self.show_all_if_ambiguous == u'on': self._display_completions(completions) else: self._bell() @@ -266,13 +266,13 @@ class BaseMode(object): self.finalize() def possible_completions(self, e): # (M-?) - """List the possible completions of the text before point. """ + u"""List the possible completions of the text before point. """ completions = self._get_completions() self._display_completions(completions) self.finalize() def insert_completions(self, e): # (M-*) - """Insert all completions of the text before point that would have + u"""Insert all completions of the text before point that would have been generated by possible-completions.""" completions = self._get_completions() b = self.begidx @@ -287,7 +287,7 @@ class BaseMode(object): self.finalize() def menu_complete(self, e): # () - """Similar to complete, but replaces the word to be completed with a + u"""Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of @@ -302,95 +302,95 @@ class BaseMode(object): def insert_text(self, string): - """Insert text into the command line.""" + u"""Insert text into the command line.""" self.l_buffer.insert_text(string, self.argument_reset) self.finalize() def beginning_of_line(self, e): # (C-a) - """Move to the start of the current line. """ + u"""Move to the start of the current line. """ self.l_buffer.beginning_of_line() self.finalize() def end_of_line(self, e): # (C-e) - """Move to the end of the line. """ + u"""Move to the end of the line. """ self.l_buffer.end_of_line() self.finalize() def forward_char(self, e): # (C-f) - """Move forward a character. """ + u"""Move forward a character. """ self.l_buffer.forward_char(self.argument_reset) self.finalize() def backward_char(self, e): # (C-b) - """Move back a character. """ + u"""Move back a character. """ self.l_buffer.backward_char(self.argument_reset) self.finalize() def forward_word(self, e): # (M-f) - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word(self.argument_reset) self.finalize() def backward_word(self, e): # (M-b) - """Move back to the start of the current or previous word. Words are + u"""Move back to the start of the current or previous word. Words are composed of letters and digits.""" self.l_buffer.backward_word(self.argument_reset) self.finalize() def forward_word_end(self, e): # () - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end(self.argument_reset) self.finalize() def backward_word_end(self, e): # () - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.backward_word_end(self.argument_reset) self.finalize() ### Movement with extend selection def beginning_of_line_extend_selection(self, e): # - """Move to the start of the current line. """ + u"""Move to the start of the current line. """ self.l_buffer.beginning_of_line_extend_selection() self.finalize() def end_of_line_extend_selection(self, e): # - """Move to the end of the line. """ + u"""Move to the end of the line. """ self.l_buffer.end_of_line_extend_selection() self.finalize() def forward_char_extend_selection(self, e): # - """Move forward a character. """ + u"""Move forward a character. """ self.l_buffer.forward_char_extend_selection(self.argument_reset) self.finalize() def backward_char_extend_selection(self, e): # - """Move back a character. """ + u"""Move back a character. """ self.l_buffer.backward_char_extend_selection(self.argument_reset) self.finalize() def forward_word_extend_selection(self, e): # - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_extend_selection(self.argument_reset) self.finalize() def backward_word_extend_selection(self, e): # - """Move back to the start of the current or previous word. Words are + u"""Move back to the start of the current or previous word. Words are composed of letters and digits.""" self.l_buffer.backward_word_extend_selection(self.argument_reset) self.finalize() def forward_word_end_extend_selection(self, e): # - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) self.finalize() def backward_word_end_extend_selection(self, e): # - """Move forward to the end of the next word. Words are composed of + u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) self.finalize() @@ -399,19 +399,19 @@ class BaseMode(object): ######## Change case def upcase_word(self, e): # (M-u) - """Uppercase the current (or following) word. With a negative + u"""Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor.""" self.l_buffer.upcase_word() self.finalize() def downcase_word(self, e): # (M-l) - """Lowercase the current (or following) word. With a negative + u"""Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor.""" self.l_buffer.downcase_word() self.finalize() def capitalize_word(self, e): # (M-c) - """Capitalize the current (or following) word. With a negative + u"""Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor.""" self.l_buffer.capitalize_word() self.finalize() @@ -419,17 +419,17 @@ class BaseMode(object): ######## def clear_screen(self, e): # (C-l) - """Clear the screen and redraw the current line, leaving the current + u"""Clear the screen and redraw the current line, leaving the current line at the top of the screen.""" self.console.page() self.finalize() def redraw_current_line(self, e): # () - """Refresh the current line. By default, this is unbound.""" + u"""Refresh the current line. By default, this is unbound.""" self.finalize() def accept_line(self, e): # (Newline or Return) - """Accept the line regardless of where the cursor is. If this line + u"""Accept the line regardless of where the cursor is. If this line is non-empty, it may be added to the history list for future recall with add_history(). If this line is a modified history line, the history line is restored to its original state.""" @@ -437,37 +437,37 @@ class BaseMode(object): return True def delete_char(self, e): # (C-d) - """Delete the character at point. If point is at the beginning of + u"""Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF.""" self.l_buffer.delete_char(self.argument_reset) self.finalize() def backward_delete_char(self, e): # (Rubout) - """Delete the character behind the cursor. A numeric argument means + u"""Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_char(self.argument_reset) self.finalize() def backward_delete_word(self, e): # (Control-Rubout) - """Delete the character behind the cursor. A numeric argument means + u"""Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.backward_delete_word(self.argument_reset) self.finalize() def forward_delete_word(self, e): # (Control-Delete) - """Delete the character behind the cursor. A numeric argument means + u"""Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.""" self.l_buffer.forward_delete_word(self.argument_reset) self.finalize() def delete_horizontal_space(self, e): # () - """Delete all spaces and tabs around point. By default, this is unbound. """ + u"""Delete all spaces and tabs around point. By default, this is unbound. """ self.l_buffer.delete_horizontal_space() self.finalize() def self_insert(self, e): # (a, b, A, 1, !, ...) - """Insert yourself. """ + u"""Insert yourself. """ if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) self.finalize() @@ -476,7 +476,7 @@ class BaseMode(object): # Paste from clipboard def paste(self,e): - """Paste windows clipboard. + u"""Paste windows clipboard. Assume single line strip other lines and end of line markers and trailing spaces""" #(Control-v) if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) @@ -486,7 +486,7 @@ class BaseMode(object): self.finalize() def paste_mulitline_code(self,e): - """Paste windows clipboard as multiline code. + u"""Paste windows clipboard as multiline code. Removes any empty lines in the code""" reg=re.compile("\r?\n") if self.enable_win32_clipboard: @@ -504,7 +504,7 @@ class BaseMode(object): self.finalize() def ipython_paste(self,e): - """Paste windows clipboard. If enable_ipython_paste_list_of_lists is + u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array. If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space""" @@ -519,22 +519,22 @@ class BaseMode(object): def copy_region_to_clipboard(self, e): # () - """Copy the text in the region to the windows clipboard.""" + u"""Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_region_to_clipboard() self.finalize() def copy_selection_to_clipboard(self, e): # () - """Copy the text in the region to the windows clipboard.""" + u"""Copy the text in the region to the windows clipboard.""" self.l_buffer.copy_selection_to_clipboard() self.finalize() def cut_selection_to_clipboard(self, e): # () - """Copy the text in the region to the windows clipboard.""" + u"""Copy the text in the region to the windows clipboard.""" self.l_buffer.cut_selection_to_clipboard() self.finalize() def dump_functions(self, e): # () - """Print all of the functions and their key bindings to the Readline + u"""Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.""" @@ -545,13 +545,13 @@ class BaseMode(object): self.finalize() def commonprefix(m): - "Given a list of pathnames, returns the longest common leading component" - if not m: return '' + u"Given a list of pathnames, returns the longest common leading component" + if not m: return u'' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1].lower() != item[:i+1].lower(): prefix = prefix[:i] - if i == 0: return '' + if i == 0: return u'' break return prefix diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index ee45531..77074b4 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -22,8 +22,8 @@ def format(keyinfo): else: k=keyinfo+(ord(keyinfo[-1]),) - return "(%s,%s,%s,%s,%x)"%k -in_ironpython="IronPython" in sys.version + return u"(%s,%s,%s,%s,%x)"%k +in_ironpython=u"IronPython" in sys.version class IncrementalSearchPromptMode(object): def __init__(self, rlobj): @@ -31,20 +31,20 @@ class IncrementalSearchPromptMode(object): def _process_incremental_search_keyevent(self, keyinfo): keytuple=keyinfo.tuple() - log("IncrementalSearchPromptMode %s %s"%(keyinfo,keytuple)) - if keyinfo.keyname == 'backspace': + log(u"IncrementalSearchPromptMode %s %s"%(keyinfo,keytuple)) + if keyinfo.keyname == u'backspace': self.subsearch_query = self.subsearch_query[:-1] if len(self.subsearch_query) > 0: self.line=self.subsearch_fun(self.subsearch_query) else: self._bell() self.line="" #empty query means no search result - elif keyinfo.keyname in ['return', 'escape']: + elif keyinfo.keyname in [u'return', u'escape']: self._bell() self.prompt=self.subsearch_oldprompt self.process_keyevent_queue=self.process_keyevent_queue[:-1] self._history.history_cursor=len(self._history.history) - if keyinfo.keyname == 'escape': + if keyinfo.keyname == u'escape': self.l_buffer.set_line(self.subsearch_old_line) return False elif keyinfo.keyname: @@ -61,11 +61,11 @@ class IncrementalSearchPromptMode(object): self.l_buffer.set_line(self.line) def _init_incremental_search(self, searchfun, direction, init_event): - """Initialize search prompt + u"""Initialize search prompt """ self.subsearch_init_event=init_event.tuple() self.subsearch_direction=direction - self.subsearch_query = '' + self.subsearch_query = u'' self.subsearch_fun = searchfun self.subsearch_old_line = self.l_buffer.get_line_text() @@ -75,18 +75,18 @@ class IncrementalSearchPromptMode(object): if (self.previous_func != self.history_search_forward and self.previous_func != self.history_search_backward): - self.subsearch_query = ''.join(self.l_buffer[0:Point].get_line_text()) + self.subsearch_query = u''.join(self.l_buffer[0:Point].get_line_text()) if self.subsearch_direction < 0: - self.subsearch_prompt = "reverse-i-search`%s': " + self.subsearch_prompt = u"reverse-i-search`%s': " else: - self.subsearch_prompt = "forward-i-search`%s': " + self.subsearch_prompt = u"forward-i-search`%s': " self.prompt=self.subsearch_prompt%"" if self.subsearch_query: self.line=self._process_search_keyevent(init_event) else: - self.line="" + self.line=u"" class SearchPromptMode(object): def __init__(self, rlobj): @@ -94,11 +94,11 @@ class SearchPromptMode(object): def _process_non_incremental_search_keyevent(self, keyinfo): keytuple=keyinfo.tuple() - log("SearchPromptMode %s %s"%(keyinfo,keytuple)) + log(u"SearchPromptMode %s %s"%(keyinfo,keytuple)) - if keyinfo.keyname == 'backspace': + if keyinfo.keyname == u'backspace': self.non_inc_query = self.non_inc_query[:-1] - elif keyinfo.keyname in ['return', 'escape']: + elif keyinfo.keyname in [u'return', u'escape']: if self.non_inc_query: if self.non_inc_direction==-1: res=self._history.reverse_search_history(self.non_inc_query) @@ -109,7 +109,7 @@ class SearchPromptMode(object): self.prompt=self.non_inc_oldprompt self.process_keyevent_queue=self.process_keyevent_queue[:-1] self._history.history_cursor=len(self._history.history) - if keyinfo.keyname == 'escape': + if keyinfo.keyname == u'escape': self.l_buffer=self.non_inc_oldline else: self.l_buffer.set_line(res) @@ -120,25 +120,25 @@ class SearchPromptMode(object): self.non_inc_query += keyinfo.char else: pass - self.prompt=self.non_inc_oldprompt+":"+self.non_inc_query + self.prompt=self.non_inc_oldprompt+u":"+self.non_inc_query def _init_non_i_search(self, direction): self.non_inc_direction = direction - self.non_inc_query = "" + self.non_inc_query = u"" self.non_inc_oldprompt=self.prompt self.non_inc_oldline=self.l_buffer.copy() self.l_buffer.reset_line() - self.prompt=self.non_inc_oldprompt+":" + self.prompt=self.non_inc_oldprompt+u":" self.process_keyevent_queue.append(self._process_non_incremental_search_keyevent) def non_incremental_reverse_search_history(self, e): # (M-p) - '''Search backward starting at the current line and moving up + u'''Search backward starting at the current line and moving up through the history as necessary using a non-incremental search for a string supplied by the user.''' return self._init_non_i_search(-1) def non_incremental_forward_search_history(self, e): # (M-n) - '''Search forward starting at the current line and moving down + u'''Search forward starting at the current line and moving down through the the history as necessary using a non-incremental search for a string supplied by the user.''' return self._init_non_i_search(1) @@ -150,22 +150,22 @@ class DigitArgumentMode(object): pass def _process_digit_argument_keyevent(self, keyinfo): - log("DigitArgumentMode.keyinfo %s"%keyinfo) + log(u"DigitArgumentMode.keyinfo %s"%keyinfo) keytuple=keyinfo.tuple() - log("DigitArgumentMode.keytuple %s %s"%(keyinfo,keytuple)) + log(u"DigitArgumentMode.keytuple %s %s"%(keyinfo,keytuple)) if keyinfo.keyname in ['return']: self.prompt=self._digit_argument_oldprompt self.process_keyevent_queue=self.process_keyevent_queue[:-1] return True elif keyinfo.keyname: pass - elif keyinfo.char in "0123456789" and keyinfo.control==False and keyinfo.meta==False : - log("arg %s %s"%(self.argument,keyinfo.char)) + elif keyinfo.char in u"0123456789" and keyinfo.control==False and keyinfo.meta==False : + log(u"arg %s %s"%(self.argument,keyinfo.char)) self.argument=self.argument*10+int(keyinfo.char) else: self.prompt=self._digit_argument_oldprompt raise LeaveModeTryNext - self.prompt="(arg: %s) "%self.argument + self.prompt=u"(arg: %s) "%self.argument def _init_digit_argument(self, keyinfo): """Initialize search prompt @@ -177,11 +177,11 @@ class DigitArgumentMode(object): if keyinfo.char=="-": self.argument=-1 - elif keyinfo.char in "0123456789": + elif keyinfo.char in u"0123456789": self.argument=int(keyinfo.char) - log("<%s> %s"%(self.argument,type(self.argument))) - self.prompt="(arg: %s) "%self.argument - log("arg-init %s %s"%(self.argument,keyinfo.char)) + log(u"<%s> %s"%(self.argument,type(self.argument))) + self.prompt=u"(arg: %s) "%self.argument + log(u"arg-init %s %s"%(self.argument,keyinfo.char)) class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode): @@ -193,17 +193,17 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode DigitArgumentMode.__init__(self, rlobj) self._keylog=(lambda x,y: None) self.previous_func=None - self.prompt=">>>" + self.prompt=u">>> " self._insert_verbatim=False self.next_meta = False # True to force meta on next character self.process_keyevent_queue=[self._process_keyevent] def __repr__(self): - return "" + return u"" def add_key_logger(self, logfun): - """logfun should be function that takes disp_fun and line_buffer object """ + u"""logfun should be function that takes disp_fun and line_buffer object """ self._keylog=logfun def process_keyevent(self, keyinfo): @@ -218,10 +218,10 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode return False def _process_keyevent(self, keyinfo): - """return True when line is final + u"""return True when line is final """ #Process exit keys. Only exit on empty line - log("_process_keyevent <%s>"%keyinfo) + log(u"_process_keyevent <%s>"%keyinfo) def nop(e): pass if self.next_meta: @@ -236,7 +236,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode return False if keytuple in self.exit_dispatch: - log("exit_dispatch:<%s, %s>"%(self.l_buffer, lineobj.EndOfLine(self.l_buffer))) + log(u"exit_dispatch:<%s, %s>"%(self.l_buffer, lineobj.EndOfLine(self.l_buffer))) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError if keyinfo.keyname or keyinfo.control or keyinfo.meta: @@ -245,7 +245,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode default=self.self_insert dispatch_func = self.key_dispatch.get(keytuple, default) - log("readline from keyboard:<%s,%s>"%(keytuple, dispatch_func)) + log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func)) r = None if dispatch_func: @@ -258,7 +258,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode ######### History commands def previous_history(self, e): # (C-p) - '''Move back through the history list, fetching the previous command. ''' + u'''Move back through the history list, fetching the previous command. ''' self._history.previous_history(self.l_buffer) self.l_buffer.point=lineobj.EndOfLine self.finalize() @@ -269,30 +269,30 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def beginning_of_history(self, e): # (M-<) - '''Move to the first line in the history.''' + u'''Move to the first line in the history.''' self._history.beginning_of_history() self.finalize() def end_of_history(self, e): # (M->) - '''Move to the end of the input history, i.e., the line currently + u'''Move to the end of the input history, i.e., the line currently being entered.''' self._history.end_of_history(self.l_buffer) self.finalize() def reverse_search_history(self, e): # (C-r) - '''Search backward starting at the current line and moving up + u'''Search backward starting at the current line and moving up through the history as necessary. This is an incremental search.''' self._init_incremental_search(self._history.reverse_search_history, -1, e) self.finalize() def forward_search_history(self, e): # (C-s) - '''Search forward starting at the current line and moving down + u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' self._init_incremental_search(self._history.forward_search_history, 1, e) self.finalize() def history_search_forward(self, e): # () - '''Search forward through the history for the string of characters + u'''Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' if self.previous_func and hasattr(self._history,self.previous_func.__name__): @@ -305,7 +305,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def history_search_backward(self, e): # () - '''Search backward through the history for the string of characters + u'''Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' if self.previous_func and hasattr(self._history,self.previous_func.__name__): @@ -319,7 +319,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode def yank_nth_arg(self, e): # (M-C-y) - '''Insert the first argument to the previous command (usually the + u'''Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the @@ -327,33 +327,33 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def yank_last_arg(self, e): # (M-. or M-_) - '''Insert last argument to the previous command (the last word of + u'''Insert last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn.''' self.finalize() def forward_backward_delete_char(self, e): # () - '''Delete the character under the cursor, unless the cursor is at + u'''Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.''' self.finalize() def quoted_insert(self, e): # (C-q or C-v) - '''Add the next character typed to the line verbatim. This is how to + u'''Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example.''' self._insert_verbatim=True self.finalize() def tab_insert(self, e): # (M-TAB) - '''Insert a tab character. ''' + u'''Insert a tab character. ''' cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer)) ws = ' ' * (self.tabstop - (cursor % self.tabstop)) self.insert_text(ws) self.finalize() def transpose_chars(self, e): # (C-t) - '''Drag the character before the cursor forward over the character + u'''Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.''' @@ -361,14 +361,14 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def transpose_words(self, e): # (M-t) - '''Drag the word before point past the word after point, moving + u'''Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line.''' self.l_buffer.transpose_words() self.finalize() def overwrite_mode(self, e): # () - '''Toggle overwrite mode. With an explicit positive numeric + u'''Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to @@ -379,29 +379,29 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def kill_line(self, e): # (C-k) - '''Kill the text from point to the end of the line. ''' + u'''Kill the text from point to the end of the line. ''' self.l_buffer.kill_line() self.finalize() def backward_kill_line(self, e): # (C-x Rubout) - '''Kill backward to the beginning of the line. ''' + u'''Kill backward to the beginning of the line. ''' self.l_buffer.backward_kill_line() self.finalize() def unix_line_discard(self, e): # (C-u) - '''Kill backward from the cursor to the beginning of the current line. ''' + u'''Kill backward from the cursor to the beginning of the current line. ''' # how is this different from backward_kill_line? self.l_buffer.unix_line_discard() self.finalize() def kill_whole_line(self, e): # () - '''Kill all characters on the current line, no matter where point + u'''Kill all characters on the current line, no matter where point is. By default, this is unbound.''' self.l_buffer.kill_whole_line() self.finalize() def kill_word(self, e): # (M-d) - '''Kill from point to the end of the current word, or if between + u'''Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word.''' self.l_buffer.kill_word() @@ -410,132 +410,132 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode forward_kill_word=kill_word def backward_kill_word(self, e): # (M-DEL) - '''Kill the word behind point. Word boundaries are the same as + u'''Kill the word behind point. Word boundaries are the same as backward-word. ''' self.l_buffer.backward_kill_word() self.finalize() def unix_word_rubout(self, e): # (C-w) - '''Kill the word behind point, using white space as a word + u'''Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring.''' self.l_buffer.unix_word_rubout() self.finalize() def kill_region(self, e): # () - '''Kill the text in the current region. By default, this command is unbound. ''' + u'''Kill the text in the current region. By default, this command is unbound. ''' self.finalize() def copy_region_as_kill(self, e): # () - '''Copy the text in the region to the kill buffer, so it can be + u'''Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound.''' self.finalize() def copy_backward_word(self, e): # () - '''Copy the word before point to the kill buffer. The word + u'''Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. By default, this command is unbound.''' self.finalize() def copy_forward_word(self, e): # () - '''Copy the word following point to the kill buffer. The word + u'''Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.''' self.finalize() def yank(self, e): # (C-y) - '''Yank the top of the kill ring into the buffer at point. ''' + u'''Yank the top of the kill ring into the buffer at point. ''' self.l_buffer.yank() self.finalize() def yank_pop(self, e): # (M-y) - '''Rotate the kill-ring, and yank the new top. You can only do this + u'''Rotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop.''' self.l_buffer.yank_pop() self.finalize() def delete_char_or_list(self, e): # () - '''Deletes the character under the cursor if not at the beginning or + u'''Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default.''' self.finalize() def start_kbd_macro(self, e): # (C-x () - '''Begin saving the characters typed into the current keyboard macro. ''' + u'''Begin saving the characters typed into the current keyboard macro. ''' self.finalize() def end_kbd_macro(self, e): # (C-x )) - '''Stop saving the characters typed into the current keyboard macro + u'''Stop saving the characters typed into the current keyboard macro and save the definition.''' self.finalize() def call_last_kbd_macro(self, e): # (C-x e) - '''Re-execute the last keyboard macro defined, by making the + u'''Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard.''' self.finalize() def re_read_init_file(self, e): # (C-x C-r) - '''Read in the contents of the inputrc file, and incorporate any + u'''Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there.''' self.finalize() def abort(self, e): # (C-g) - '''Abort the current editing command and ring the terminals bell + u'''Abort the current editing command and ring the terminals bell (subject to the setting of bell-style).''' self._bell() self.finalize() def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...) - '''If the metafied character x is lowercase, run the command that is + u'''If the metafied character x is lowercase, run the command that is bound to the corresponding uppercase character.''' self.finalize() def prefix_meta(self, e): # (ESC) - '''Metafy the next character typed. This is for keyboards without a + u'''Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f. ''' self.next_meta = True self.finalize() def undo(self, e): # (C-_ or C-x C-u) - '''Incremental undo, separately remembered for each line.''' + u'''Incremental undo, separately remembered for each line.''' self.l_buffer.pop_undo() self.finalize() def revert_line(self, e): # (M-r) - '''Undo all changes made to this line. This is like executing the + u'''Undo all changes made to this line. This is like executing the undo command enough times to get back to the beginning.''' self.finalize() def tilde_expand(self, e): # (M-~) - '''Perform tilde expansion on the current word.''' + u'''Perform tilde expansion on the current word.''' self.finalize() def set_mark(self, e): # (C-@) - '''Set the mark to the point. If a numeric argument is supplied, the + u'''Set the mark to the point. If a numeric argument is supplied, the mark is set to that position.''' self.l_buffer.set_mark() self.finalize() def exchange_point_and_mark(self, e): # (C-x C-x) - '''Swap the point with the mark. The current cursor position is set + u'''Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark.''' self.finalize() def character_search(self, e): # (C-]) - '''A character is read and point is moved to the next occurrence of + u'''A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences.''' self.finalize() def character_search_backward(self, e): # (M-C-]) - '''A character is read and point is moved to the previous occurrence + u'''A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences.''' self.finalize() def insert_comment(self, e): # (M-#) - '''Without a numeric argument, the value of the comment-begin + u'''Without a numeric argument, the value of the comment-begin variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of @@ -545,14 +545,14 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode self.finalize() def dump_variables(self, e): # () - '''Print all of the settable variables and their values to the + u'''Print all of the settable variables and their values to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' self.finalize() def dump_macros(self, e): # () - '''Print all of the Readline key sequences bound to macros and the + u'''Print all of the Readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' @@ -561,13 +561,13 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode def digit_argument(self, e): # (M-0, M-1, ... M--) - '''Add this digit to the argument already accumulating, or start a + u'''Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument.''' self._init_digit_argument(e) #Should not finalize def universal_argument(self, e): # () - '''This is another way to specify an argument. If this command is + u'''This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric @@ -584,99 +584,99 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode #Create key bindings: def init_editing_mode(self, e): # (C-e) - '''When in vi command mode, this causes a switch to emacs editing + u'''When in vi command mode, this causes a switch to emacs editing mode.''' - self._bind_exit_key('Control-d') - self._bind_exit_key('Control-z') + self._bind_exit_key(u'Control-d') + self._bind_exit_key(u'Control-z') # I often accidentally hold the shift or control while typing space - self._bind_key('space', self.self_insert) - self._bind_key('Shift-space', self.self_insert) - self._bind_key('Control-space', self.self_insert) - self._bind_key('Return', self.accept_line) - self._bind_key('Left', self.backward_char) - self._bind_key('Control-b', self.backward_char) - self._bind_key('Right', self.forward_char) - self._bind_key('Control-f', self.forward_char) - self._bind_key('BackSpace', self.backward_delete_char) - self._bind_key('Control-BackSpace', self.backward_delete_word) + self._bind_key(u'space', self.self_insert) + self._bind_key(u'Shift-space', self.self_insert) + self._bind_key(u'Control-space', self.self_insert) + self._bind_key(u'Return', self.accept_line) + self._bind_key(u'Left', self.backward_char) + self._bind_key(u'Control-b', self.backward_char) + self._bind_key(u'Right', self.forward_char) + self._bind_key(u'Control-f', self.forward_char) + self._bind_key(u'BackSpace', self.backward_delete_char) + self._bind_key(u'Control-BackSpace', self.backward_delete_word) - self._bind_key('Home', self.beginning_of_line) - self._bind_key('End', self.end_of_line) - self._bind_key('Delete', self.delete_char) - self._bind_key('Control-d', self.delete_char) - self._bind_key('Clear', self.clear_screen) - self._bind_key('Alt-f', self.forward_word) - self._bind_key('Alt-b', self.backward_word) - self._bind_key('Control-l', self.clear_screen) - self._bind_key('Control-p', self.previous_history) - self._bind_key('Up', self.history_search_backward) - self._bind_key('Control-n', self.next_history) - self._bind_key('Down', self.history_search_forward) - self._bind_key('Control-a', self.beginning_of_line) - self._bind_key('Control-e', self.end_of_line) - self._bind_key('Alt-<', self.beginning_of_history) - self._bind_key('Alt->', self.end_of_history) - self._bind_key('Control-r', self.reverse_search_history) - self._bind_key('Control-s', self.forward_search_history) - self._bind_key('Alt-p', self.non_incremental_reverse_search_history) - self._bind_key('Alt-n', self.non_incremental_forward_search_history) - self._bind_key('Control-z', self.undo) - self._bind_key('Control-_', self.undo) - self._bind_key('Escape', self.kill_whole_line) - self._bind_key('Meta-d', self.kill_word) - self._bind_key('Control-Delete', self.forward_delete_word) - self._bind_key('Control-w', self.unix_word_rubout) + self._bind_key(u'Home', self.beginning_of_line) + self._bind_key(u'End', self.end_of_line) + self._bind_key(u'Delete', self.delete_char) + self._bind_key(u'Control-d', self.delete_char) + self._bind_key(u'Clear', self.clear_screen) + self._bind_key(u'Alt-f', self.forward_word) + self._bind_key(u'Alt-b', self.backward_word) + self._bind_key(u'Control-l', self.clear_screen) + self._bind_key(u'Control-p', self.previous_history) + self._bind_key(u'Up', self.history_search_backward) + self._bind_key(u'Control-n', self.next_history) + self._bind_key(u'Down', self.history_search_forward) + self._bind_key(u'Control-a', self.beginning_of_line) + self._bind_key(u'Control-e', self.end_of_line) + self._bind_key(u'Alt-<', self.beginning_of_history) + self._bind_key(u'Alt->', self.end_of_history) + self._bind_key(u'Control-r', self.reverse_search_history) + self._bind_key(u'Control-s', self.forward_search_history) + self._bind_key(u'Alt-p', self.non_incremental_reverse_search_history) + self._bind_key(u'Alt-n', self.non_incremental_forward_search_history) + self._bind_key(u'Control-z', self.undo) + self._bind_key(u'Control-_', self.undo) + self._bind_key(u'Escape', self.kill_whole_line) + self._bind_key(u'Meta-d', self.kill_word) + self._bind_key(u'Control-Delete', self.forward_delete_word) + self._bind_key(u'Control-w', self.unix_word_rubout) #self._bind_key('Control-Shift-v', self.quoted_insert) - self._bind_key('Control-v', self.paste) - self._bind_key('Alt-v', self.ipython_paste) - self._bind_key('Control-y', self.yank) - self._bind_key('Control-k', self.kill_line) - self._bind_key('Control-m', self.set_mark) - self._bind_key('Control-q', self.copy_region_to_clipboard) + self._bind_key(u'Control-v', self.paste) + self._bind_key(u'Alt-v', self.ipython_paste) + self._bind_key(u'Control-y', self.yank) + self._bind_key(u'Control-k', self.kill_line) + self._bind_key(u'Control-m', self.set_mark) + self._bind_key(u'Control-q', self.copy_region_to_clipboard) # self._bind_key('Control-shift-k', self.kill_whole_line) - self._bind_key('Control-Shift-v', self.paste_mulitline_code) - self._bind_key("Control-Right", self.forward_word_end) - self._bind_key("Control-Left", self.backward_word) - self._bind_key("Shift-Right", self.forward_char_extend_selection) - self._bind_key("Shift-Left", self.backward_char_extend_selection) - self._bind_key("Shift-Control-Right", self.forward_word_end_extend_selection) - self._bind_key("Shift-Control-Left", self.backward_word_extend_selection) - self._bind_key("Shift-Home", self.beginning_of_line_extend_selection) - self._bind_key("Shift-End", self.end_of_line_extend_selection) - self._bind_key("numpad0", self.self_insert) - self._bind_key("numpad1", self.self_insert) - self._bind_key("numpad2", self.self_insert) - self._bind_key("numpad3", self.self_insert) - self._bind_key("numpad4", self.self_insert) - self._bind_key("numpad5", self.self_insert) - self._bind_key("numpad6", self.self_insert) - self._bind_key("numpad7", self.self_insert) - self._bind_key("numpad8", self.self_insert) - self._bind_key("numpad9", self.self_insert) - self._bind_key("add", self.self_insert) - self._bind_key("subtract", self.self_insert) - self._bind_key("multiply", self.self_insert) - self._bind_key("divide", self.self_insert) - self._bind_key("vk_decimal", self.self_insert) - log("RUNNING INIT EMACS") + self._bind_key(u'Control-Shift-v', self.paste_mulitline_code) + self._bind_key(u"Control-Right", self.forward_word_end) + self._bind_key(u"Control-Left", self.backward_word) + self._bind_key(u"Shift-Right", self.forward_char_extend_selection) + self._bind_key(u"Shift-Left", self.backward_char_extend_selection) + self._bind_key(u"Shift-Control-Right", self.forward_word_end_extend_selection) + self._bind_key(u"Shift-Control-Left", self.backward_word_extend_selection) + self._bind_key(u"Shift-Home", self.beginning_of_line_extend_selection) + self._bind_key(u"Shift-End", self.end_of_line_extend_selection) + self._bind_key(u"numpad0", self.self_insert) + self._bind_key(u"numpad1", self.self_insert) + self._bind_key(u"numpad2", self.self_insert) + self._bind_key(u"numpad3", self.self_insert) + self._bind_key(u"numpad4", self.self_insert) + self._bind_key(u"numpad5", self.self_insert) + self._bind_key(u"numpad6", self.self_insert) + self._bind_key(u"numpad7", self.self_insert) + self._bind_key(u"numpad8", self.self_insert) + self._bind_key(u"numpad9", self.self_insert) + self._bind_key(u"add", self.self_insert) + self._bind_key(u"subtract", self.self_insert) + self._bind_key(u"multiply", self.self_insert) + self._bind_key(u"divide", self.self_insert) + self._bind_key(u"vk_decimal", self.self_insert) + log(u"RUNNING INIT EMACS") for i in range(0,10): - self._bind_key("alt-%d"%i, self.digit_argument) - self._bind_key("alt--", self.digit_argument) + self._bind_key(u"alt-%d"%i, self.digit_argument) + self._bind_key(u"alt--", self.digit_argument) # make it case insensitive def commonprefix(m): - "Given a list of pathnames, returns the longest common leading component" + u"Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1].lower() != item[:i+1].lower(): prefix = prefix[:i] - if i == 0: return '' + if i == 0: return u'' break return prefix diff --git a/pyreadline/modes/notemacs.py b/pyreadline/modes/notemacs.py index 67b2efa..0e08e2a 100644 --- a/pyreadline/modes/notemacs.py +++ b/pyreadline/modes/notemacs.py @@ -14,12 +14,12 @@ import pyreadline.lineeditor.history as history import basemode class NotEmacsMode(basemode.BaseMode): - mode="notemacs" + mode=u"notemacs" def __init__(self,rlobj): super(NotEmacsMode,self).__init__(rlobj) def __repr__(self): - return "" + return u"" def _readline_from_keyboard(self): c=self.console @@ -37,7 +37,7 @@ class NotEmacsMode(basemode.BaseMode): raise EOFError dispatch_func = self.key_dispatch.get(event.keyinfo,self.self_insert) - log("readline from keyboard:%s"%(event.keyinfo,)) + log(u"readline from keyboard:%s"%(event.keyinfo,)) r = None if dispatch_func: r = dispatch_func(event) @@ -49,7 +49,7 @@ class NotEmacsMode(basemode.BaseMode): break def readline(self, prompt=''): - '''Try to act like GNU readline.''' + u'''Try to act like GNU readline.''' # handle startup_hook if self.first_prompt: self.first_prompt = False @@ -57,7 +57,7 @@ class NotEmacsMode(basemode.BaseMode): try: self.startup_hook() except: - print 'startup hook failed' + print u'startup hook failed' traceback.print_exc() c = self.console @@ -69,64 +69,64 @@ class NotEmacsMode(basemode.BaseMode): try: self.pre_input_hook() except: - print 'pre_input_hook failed' + print u'pre_input_hook failed' traceback.print_exc() self.pre_input_hook = None - log("in readline: %s"%self.paste_line_buffer) + log(u"in readline: %s"%self.paste_line_buffer) if len(self.paste_line_buffer)>0: self.l_buffer=lineobj.ReadlineTextBuffer(self.paste_line_buffer[0]) self._update_line() self.paste_line_buffer=self.paste_line_buffer[1:] - c.write('\r\n') + c.write(u'\r\n') else: self._readline_from_keyboard() - c.write('\r\n') + c.write(u'\r\n') self.add_history(self.l_buffer.copy()) - log('returning(%s)' % self.l_buffer.get_line_text()) + log(u'returning(%s)' % self.l_buffer.get_line_text()) return self.l_buffer.get_line_text() + '\n' ### Methods below here are bindable emacs functions def beginning_of_line(self, e): # (C-a) - '''Move to the start of the current line. ''' + u'''Move to the start of the current line. ''' self.l_buffer.beginning_of_line() def end_of_line(self, e): # (C-e) - '''Move to the end of the line. ''' + u'''Move to the end of the line. ''' self.l_buffer.end_of_line() def forward_char(self, e): # (C-f) - '''Move forward a character. ''' + u'''Move forward a character. ''' self.l_buffer.forward_char() def backward_char(self, e): # (C-b) - '''Move back a character. ''' + u'''Move back a character. ''' self.l_buffer.backward_char() def forward_word(self, e): # (M-f) - '''Move forward to the end of the next word. Words are composed of + u'''Move forward to the end of the next word. Words are composed of letters and digits.''' self.l_buffer.forward_word() def backward_word(self, e): # (M-b) - '''Move back to the start of the current or previous word. Words are + u'''Move back to the start of the current or previous word. Words are composed of letters and digits.''' self.l_buffer.backward_word() def clear_screen(self, e): # (C-l) - '''Clear the screen and redraw the current line, leaving the current + u'''Clear the screen and redraw the current line, leaving the current line at the top of the screen.''' self.console.page() def redraw_current_line(self, e): # () - '''Refresh the current line. By default, this is unbound.''' + u'''Refresh the current line. By default, this is unbound.''' pass def accept_line(self, e): # (Newline or Return) - '''Accept the line regardless of where the cursor is. If this line + u'''Accept the line regardless of where the cursor is. If this line is non-empty, it may be added to the history list for future recall with add_history(). If this line is a modified history line, the history line is restored to its original state.''' @@ -134,47 +134,47 @@ class NotEmacsMode(basemode.BaseMode): ######### History commands def previous_history(self, e): # (C-p) - '''Move back through the history list, fetching the previous command. ''' + u'''Move back through the history list, fetching the previous command. ''' self._history.previous_history(self.l_buffer) def next_history(self, e): # (C-n) - '''Move forward through the history list, fetching the next command. ''' + u'''Move forward through the history list, fetching the next command. ''' self._history.next_history(self.l_buffer) def beginning_of_history(self, e): # (M-<) - '''Move to the first line in the history.''' + u'''Move to the first line in the history.''' self._history.beginning_of_history() def end_of_history(self, e): # (M->) - '''Move to the end of the input history, i.e., the line currently + u'''Move to the end of the input history, i.e., the line currently being entered.''' self._history.end_of_history(self.l_buffer) def _i_search(self, searchfun, direction, init_event): c = self.console line = self.get_line_buffer() - query = '' + query = u'' hc_start = self._history.history_cursor #+ direction while 1: x, y = self.prompt_end_pos c.pos(0, y) if direction < 0: - prompt = 'reverse-i-search' + prompt = u'reverse-i-search' else: - prompt = 'forward-i-search' + prompt = u'forward-i-search' - scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line)) + scroll = c.write_scrolling(u"%s`%s': %s" % (prompt, query, line)) self._update_prompt_pos(scroll) self._clear_after() event = c.getkeypress() - if event.keysym == 'BackSpace': + if event.keysym == u'BackSpace': if len(query) > 0: query = query[:-1] self._history.history_cursor = hc_start else: self._bell() - elif event.char in string.letters + string.digits + string.punctuation + ' ': + elif event.char in string.letters + string.digits + string.punctuation + u' ': self._history.history_cursor = hc_start query += event.char elif event.keyinfo == init_event.keyinfo: @@ -182,7 +182,7 @@ class NotEmacsMode(basemode.BaseMode): line=searchfun(query) pass else: - if event.keysym != 'Return': + if event.keysym != u'Return': self._bell() break line=searchfun(query) @@ -194,14 +194,14 @@ class NotEmacsMode(basemode.BaseMode): self._history.history_cursor=len(self._history.history) def reverse_search_history(self, e): # (C-r) - '''Search backward starting at the current line and moving up + u'''Search backward starting at the current line and moving up through the history as necessary. This is an incremental search.''' # print "HEJ" # self.console.bell() self._i_search(self._history.reverse_search_history, -1, e) def forward_search_history(self, e): # (C-s) - '''Search forward starting at the current line and moving down + u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' # print "HEJ" # self.console.bell() @@ -209,31 +209,31 @@ class NotEmacsMode(basemode.BaseMode): def non_incremental_reverse_search_history(self, e): # (M-p) - '''Search backward starting at the current line and moving up + u'''Search backward starting at the current line and moving up through the history as necessary using a non-incremental search for a string supplied by the user.''' self._history.non_incremental_reverse_search_history(self.l_buffer) def non_incremental_forward_search_history(self, e): # (M-n) - '''Search forward starting at the current line and moving down + u'''Search forward starting at the current line and moving down through the the history as necessary using a non-incremental search for a string supplied by the user.''' self._history.non_incremental_reverse_search_history(self.l_buffer) def history_search_forward(self, e): # () - '''Search forward through the history for the string of characters + u'''Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' self.l_buffer=self._history.history_search_forward(self.l_buffer) def history_search_backward(self, e): # () - '''Search backward through the history for the string of characters + u'''Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' self.l_buffer=self._history.history_search_backward(self.l_buffer) def yank_nth_arg(self, e): # (M-C-y) - '''Insert the first argument to the previous command (usually the + u'''Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the @@ -241,76 +241,76 @@ class NotEmacsMode(basemode.BaseMode): pass def yank_last_arg(self, e): # (M-. or M-_) - '''Insert last argument to the previous command (the last word of + u'''Insert last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn.''' pass def delete_char(self, e): # (C-d) - '''Delete the character at point. If point is at the beginning of + u'''Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF.''' self.l_buffer.delete_char() def backward_delete_char(self, e): # (Rubout) - '''Delete the character behind the cursor. A numeric argument means + u'''Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.''' self.l_buffer.backward_delete_char() def forward_backward_delete_char(self, e): # () - '''Delete the character under the cursor, unless the cursor is at + u'''Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.''' pass def quoted_insert(self, e): # (C-q or C-v) - '''Add the next character typed to the line verbatim. This is how to + u'''Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example.''' e = self.console.getkeypress() self.insert_text(e.char) def tab_insert(self, e): # (M-TAB) - '''Insert a tab character. ''' + u'''Insert a tab character. ''' cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer)) ws = ' ' * (self.tabstop - (cursor % self.tabstop)) self.insert_text(ws) def self_insert(self, e): # (a, b, A, 1, !, ...) - '''Insert yourself. ''' + u'''Insert yourself. ''' if ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) def transpose_chars(self, e): # (C-t) - '''Drag the character before the cursor forward over the character + u'''Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.''' self.l_buffer.transpose_chars() def transpose_words(self, e): # (M-t) - '''Drag the word before point past the word after point, moving + u'''Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line.''' self.l_buffer.transpose_words() def upcase_word(self, e): # (M-u) - '''Uppercase the current (or following) word. With a negative + u'''Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor.''' self.l_buffer.upcase_word() def downcase_word(self, e): # (M-l) - '''Lowercase the current (or following) word. With a negative + u'''Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor.''' self.l_buffer.downcase_word() def capitalize_word(self, e): # (M-c) - '''Capitalize the current (or following) word. With a negative + u'''Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor.''' self.l_buffer.capitalize_word() def overwrite_mode(self, e): # () - '''Toggle overwrite mode. With an explicit positive numeric + u'''Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to @@ -321,54 +321,54 @@ class NotEmacsMode(basemode.BaseMode): pass def kill_line(self, e): # (C-k) - '''Kill the text from point to the end of the line. ''' + u'''Kill the text from point to the end of the line. ''' self.l_buffer.kill_line() def backward_kill_line(self, e): # (C-x Rubout) - '''Kill backward to the beginning of the line. ''' + u'''Kill backward to the beginning of the line. ''' self.l_buffer.backward_kill_line() def unix_line_discard(self, e): # (C-u) - '''Kill backward from the cursor to the beginning of the current line. ''' + u'''Kill backward from the cursor to the beginning of the current line. ''' # how is this different from backward_kill_line? self.l_buffer.unix_line_discard() def kill_whole_line(self, e): # () - '''Kill all characters on the current line, no matter where point + u'''Kill all characters on the current line, no matter where point is. By default, this is unbound.''' self.l_buffer.kill_whole_line() def kill_word(self, e): # (M-d) - '''Kill from point to the end of the current word, or if between + u'''Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word.''' self.l_buffer.kill_word() def backward_kill_word(self, e): # (M-DEL) - '''Kill the word behind point. Word boundaries are the same as + u'''Kill the word behind point. Word boundaries are the same as backward-word. ''' self.l_buffer.backward_kill_word() def unix_word_rubout(self, e): # (C-w) - '''Kill the word behind point, using white space as a word + u'''Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring.''' self.l_buffer.unix_word_rubout() def delete_horizontal_space(self, e): # () - '''Delete all spaces and tabs around point. By default, this is unbound. ''' + u'''Delete all spaces and tabs around point. By default, this is unbound. ''' pass def kill_region(self, e): # () - '''Kill the text in the current region. By default, this command is unbound. ''' + u'''Kill the text in the current region. By default, this command is unbound. ''' pass def copy_region_as_kill(self, e): # () - '''Copy the text in the region to the kill buffer, so it can be + u'''Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound.''' pass def copy_region_to_clipboard(self, e): # () - '''Copy the text in the region to the windows clipboard.''' + u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard: mark=min(self.l_buffer.mark,len(self.l_buffer.line_buffer)) cursor=min(self.l_buffer.point,len(self.l_buffer.line_buffer)) @@ -376,72 +376,72 @@ class NotEmacsMode(basemode.BaseMode): return begin=min(cursor,mark) end=max(cursor,mark) - toclipboard="".join(self.l_buffer.line_buffer[begin:end]) + toclipboard=u"".join(self.l_buffer.line_buffer[begin:end]) clipboard.SetClipboardText(str(toclipboard)) def copy_backward_word(self, e): # () - '''Copy the word before point to the kill buffer. The word + u'''Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. By default, this command is unbound.''' pass def copy_forward_word(self, e): # () - '''Copy the word following point to the kill buffer. The word + u'''Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.''' pass def paste(self,e): - '''Paste windows clipboard''' + u'''Paste windows clipboard''' if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) self.insert_text(txt) def paste_mulitline_code(self,e): - '''Paste windows clipboard''' - reg=re.compile("\r?\n") + u'''Paste windows clipboard''' + reg=re.compile(u"\r?\n") if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) t=reg.split(txt) - t=[row for row in t if row.strip()!=""] #remove empty lines - if t!=[""]: + t=[row for row in t if row.strip()!=u""] #remove empty lines + if t!=[u""]: self.insert_text(t[0]) self.add_history(self.l_buffer.copy()) self.paste_line_buffer=t[1:] - log("multi: %s"%self.paste_line_buffer) + log(u"multi: %s"%self.paste_line_buffer) return True else: return False def ipython_paste(self,e): - '''Paste windows clipboard. If enable_ipython_paste_list_of_lists is + u'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array''' if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert( self.enable_ipython_paste_list_of_lists) if self.enable_ipython_paste_for_paths: - if len(txt)<300 and ("\t" not in txt) and ("\n" not in txt): - txt=txt.replace("\\","/").replace(" ",r"\ ") + if len(txt)<300 and (u"\t" not in txt) and (u"\n" not in txt): + txt=txt.replace(u"\\", u"/").replace(u" ", ur"\ ") self.insert_text(txt) def yank(self, e): # (C-y) - '''Yank the top of the kill ring into the buffer at point. ''' + u'''Yank the top of the kill ring into the buffer at point. ''' pass def yank_pop(self, e): # (M-y) - '''Rotate the kill-ring, and yank the new top. You can only do this + u'''Rotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop.''' pass def digit_argument(self, e): # (M-0, M-1, ... M--) - '''Add this digit to the argument already accumulating, or start a + u'''Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument.''' pass def universal_argument(self, e): # () - '''This is another way to specify an argument. If this command is + u'''This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric @@ -455,83 +455,83 @@ class NotEmacsMode(basemode.BaseMode): pass def delete_char_or_list(self, e): # () - '''Deletes the character under the cursor if not at the beginning or + u'''Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default.''' pass def start_kbd_macro(self, e): # (C-x () - '''Begin saving the characters typed into the current keyboard macro. ''' + u'''Begin saving the characters typed into the current keyboard macro. ''' pass def end_kbd_macro(self, e): # (C-x )) - '''Stop saving the characters typed into the current keyboard macro + u'''Stop saving the characters typed into the current keyboard macro and save the definition.''' pass def call_last_kbd_macro(self, e): # (C-x e) - '''Re-execute the last keyboard macro defined, by making the + u'''Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard.''' pass def re_read_init_file(self, e): # (C-x C-r) - '''Read in the contents of the inputrc file, and incorporate any + u'''Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there.''' pass def abort(self, e): # (C-g) - '''Abort the current editing command and ring the terminals bell + u'''Abort the current editing command and ring the terminals bell (subject to the setting of bell-style).''' self._bell() def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...) - '''If the metafied character x is lowercase, run the command that is + u'''If the metafied character x is lowercase, run the command that is bound to the corresponding uppercase character.''' pass def prefix_meta(self, e): # (ESC) - '''Metafy the next character typed. This is for keyboards without a + u'''Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f. ''' self.next_meta = True def undo(self, e): # (C-_ or C-x C-u) - '''Incremental undo, separately remembered for each line.''' + u'''Incremental undo, separately remembered for each line.''' self.l_buffer.pop_undo() def revert_line(self, e): # (M-r) - '''Undo all changes made to this line. This is like executing the + u'''Undo all changes made to this line. This is like executing the undo command enough times to get back to the beginning.''' pass def tilde_expand(self, e): # (M-~) - '''Perform tilde expansion on the current word.''' + u'''Perform tilde expansion on the current word.''' pass def set_mark(self, e): # (C-@) - '''Set the mark to the point. If a numeric argument is supplied, the + u'''Set the mark to the point. If a numeric argument is supplied, the mark is set to that position.''' self.l_buffer.set_mark() def exchange_point_and_mark(self, e): # (C-x C-x) - '''Swap the point with the mark. The current cursor position is set + u'''Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark.''' pass def character_search(self, e): # (C-]) - '''A character is read and point is moved to the next occurrence of + u'''A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences.''' pass def character_search_backward(self, e): # (M-C-]) - '''A character is read and point is moved to the previous occurrence + u'''A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences.''' pass def insert_comment(self, e): # (M-#) - '''Without a numeric argument, the value of the comment-begin + u'''Without a numeric argument, the value of the comment-begin variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of @@ -541,21 +541,21 @@ class NotEmacsMode(basemode.BaseMode): pass def dump_functions(self, e): # () - '''Print all of the functions and their key bindings to the Readline + u'''Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' pass def dump_variables(self, e): # () - '''Print all of the settable variables and their values to the + u'''Print all of the settable variables and their values to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' pass def dump_macros(self, e): # () - '''Print all of the Readline key sequences bound to macros and the + u'''Print all of the Readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' @@ -565,38 +565,38 @@ class NotEmacsMode(basemode.BaseMode): #Create key bindings: def init_editing_mode(self, e): # (C-e) - '''When in vi command mode, this causes a switch to emacs editing + u'''When in vi command mode, this causes a switch to emacs editing mode.''' - self._bind_exit_key('Control-d') - self._bind_exit_key('Control-z') + self._bind_exit_key(u'Control-d') + self._bind_exit_key(u'Control-z') # I often accidentally hold the shift or control while typing space - self._bind_key('Shift-space', self.self_insert) - self._bind_key('Control-space', self.self_insert) - self._bind_key('Return', self.accept_line) - self._bind_key('Left', self.backward_char) - self._bind_key('Control-b', self.backward_char) - self._bind_key('Right', self.forward_char) - self._bind_key('Control-f', self.forward_char) - self._bind_key('BackSpace', self.backward_delete_char) - self._bind_key('Home', self.beginning_of_line) - self._bind_key('End', self.end_of_line) - self._bind_key('Delete', self.delete_char) - self._bind_key('Control-d', self.delete_char) - self._bind_key('Clear', self.clear_screen) + self._bind_key(u'Shift-space', self.self_insert) + self._bind_key(u'Control-space', self.self_insert) + self._bind_key(u'Return', self.accept_line) + self._bind_key(u'Left', self.backward_char) + self._bind_key(u'Control-b', self.backward_char) + self._bind_key(u'Right', self.forward_char) + self._bind_key(u'Control-f', self.forward_char) + self._bind_key(u'BackSpace', self.backward_delete_char) + self._bind_key(u'Home', self.beginning_of_line) + self._bind_key(u'End', self.end_of_line) + self._bind_key(u'Delete', self.delete_char) + self._bind_key(u'Control-d', self.delete_char) + self._bind_key(u'Clear', self.clear_screen) # make it case insensitive def commonprefix(m): - "Given a list of pathnames, returns the longest common leading component" - if not m: return '' + u"Given a list of pathnames, returns the longest common leading component" + if not m: return u'' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1].lower() != item[:i+1].lower(): prefix = prefix[:i] - if i == 0: return '' + if i == 0: return u'' break return prefix diff --git a/pyreadline/release.py b/pyreadline/release.py index 6d496e6..b49fbba 100644 --- a/pyreadline/release.py +++ b/pyreadline/release.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""Release data for the pyreadline project. +u"""Release data for the pyreadline project. $Id$""" @@ -13,23 +13,23 @@ $Id$""" # Name of the package for release purposes. This is the name which labels # the tarballs and RPMs made by distutils, so it's best to lowercase it. -name = 'pyreadline' +name = u'pyreadline' # For versions with substrings (like 0.6.16.svn), use an extra . to separate # the new substring. We have to avoid using either dashes or underscores, # because bdist_rpm does not accept dashes (an RPM) convention, and # bdist_deb does not accept underscores (a Debian convention). -branch = '' +branch = u'' -version = '1.6.svn' +version = u'1.6.svn' -revision = '$Revision$' +revision = u'$Revision$' -description = "A python implmementation of GNU readline." +description = u"A python implmementation of GNU readline." long_description = \ -""" +u""" The pyreadline package is a python implementation of GNU readline functionality it is based on the ctypes based UNC readline package by Gary Bishop. It is not complete. It has been tested for use with windows 2000 and windows xp. @@ -52,23 +52,23 @@ Features: .. _repository: http://ipython.scipy.org/svn/ipython/pyreadline/trunk#egg=pyreadline-dev """ -license = 'BSD' +license = u'BSD' -authors = {'Jorgen' : ('Jorgen Stenarson','jorgen.stenarson@bostream.nu'), - 'Gary': ('Gary Bishop', ''), - 'Jack': ('Jack Trainor', ''), +authors = {u'Jorgen' : (u'Jorgen Stenarson',u'jorgen.stenarson@bostream.nu'), + u'Gary': (u'Gary Bishop', ''), + u'Jack': (u'Jack Trainor', ''), } -url = 'http://ipython.scipy.org/moin/PyReadline/Intro' +url = u'http://ipython.scipy.org/moin/PyReadline/Intro' -download_url = '' +download_url = u'' -platforms = ['Windows XP/2000/NT','Windows 95/98/ME'] +platforms = [u'Windows XP/2000/NT',u'Windows 95/98/ME'] -keywords = ['readline','pyreadline'] +keywords = [u'readline',u'pyreadline'] -classifiers = ['Development Status :: 4 - Beta', - 'Environment :: Console', - 'Operating System :: Microsoft :: Windows',] +classifiers = [u'Development Status :: 4 - Beta', + u'Environment :: Console', + u'Operating System :: Microsoft :: Windows',] diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index 6f1252e..e7b40e9 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -6,37 +6,37 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -''' an attempt to implement readline for Python in Python using ctypes''' +u''' an attempt to implement readline for Python in Python using ctypes''' import sys,os,re,time from glob import glob import clipboard,logger,console from logger import log -from error import ReadlineError,GetSetError +from error import ReadlineError, GetSetError from pyreadline.keysyms.common import make_KeyPress_from_keydescr - +from pyreadline.unicode_helper import ensure_unicode import pyreadline.lineeditor.lineobj as lineobj import pyreadline.lineeditor.history as history import release from modes import editingmodes -in_ironpython="IronPython" in sys.version +in_ironpython=u"IronPython" in sys.version if in_ironpython:#ironpython does not provide a prompt string to readline import System - default_prompt=">>> " + default_prompt=u">>> " else: - default_prompt="" + default_prompt=u"" import pdb class MockConsoleError(Exception): pass class MockConsole(object): - """object used during refactoring. Should raise errors when someone tries to use it. + u"""object used during refactoring. Should raise errors when someone tries to use it. """ def __setattr__(self,x): - raise MockConsoleError("Should not try to get attributes from MockConsole") + raise MockConsoleError(u"Should not try to get attributes from MockConsole") def cursor(self,size=50): pass @@ -47,7 +47,7 @@ class BaseReadline(object): self.ctrl_c_tap_time_interval=0.3 self.debug=False - self.bell_style = 'none' + self.bell_style = u'none' self.mark=-1 self.console=MockConsole() # this code needs to follow l_buffer and history creation @@ -57,44 +57,44 @@ class BaseReadline(object): self.mode=self.editingmodes[0] self.read_inputrc() - log("\n".join(self.mode.rl_settings_to_string())) + log(u"\n".join(self.mode.rl_settings_to_string())) self.callback = None def parse_and_bind(self, string): - '''Parse and execute single line of a readline init file.''' + u'''Parse and execute single line of a readline init file.''' try: - log('parse_and_bind("%s")' % string) - if string.startswith('#'): + log(u'parse_and_bind("%s")' % string) + if string.startswith(u'#'): return - if string.startswith('set'): - m = re.compile(r'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string) + if string.startswith(u'set'): + m = re.compile(ur'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string) if m: var_name = m.group(1) val = m.group(2) try: - setattr(self, var_name.replace('-','_'), val) + setattr(self, var_name.replace(u'-',u'_'), val) except AttributeError: - log('unknown var="%s" val="%s"' % (var_name, val)) + log(u'unknown var="%s" val="%s"' % (var_name, val)) else: - log('bad set "%s"' % string) + log(u'bad set "%s"' % string) return - m = re.compile(r'\s*(.+)\s*:\s*([-a-zA-Z]+)\s*$').match(string) + m = re.compile(ur'\s*(.+)\s*:\s*([-a-zA-Z]+)\s*$').match(string) if m: key = m.group(1) func_name = m.group(2) - py_name = func_name.replace('-', '_') + py_name = func_name.replace(u'-', u'_') try: func = getattr(self.mode, py_name) except AttributeError: - log('unknown func key="%s" func="%s"' % (key, func_name)) + log(u'unknown func key="%s" func="%s"' % (key, func_name)) if self.debug: - print 'pyreadline parse_and_bind error, unknown function to bind: "%s"' % func_name + print u'pyreadline parse_and_bind error, unknown function to bind: "%s"' % func_name return self.mode._bind_key(key, func) except: - log('error') + log(u'error') raise def _set_prompt(self, prompt): @@ -107,31 +107,31 @@ class BaseReadline(object): def get_line_buffer(self): - '''Return the current contents of the line buffer.''' + u'''Return the current contents of the line buffer.''' return self.mode.l_buffer.get_line_text() def insert_text(self, string): - '''Insert text into the command line.''' + u'''Insert text into the command line.''' self.mode.insert_text(string) def read_init_file(self, filename=None): - '''Parse a readline initialization file. The default filename is the last filename used.''' - log('read_init_file("%s")' % filename) + u'''Parse a readline initialization file. The default filename is the last filename used.''' + log(u'read_init_file("%s")' % filename) #History file book keeping methods (non-bindable) def add_history(self, line): - '''Append a line to the history buffer, as if it was the last line typed.''' + u'''Append a line to the history buffer, as if it was the last line typed.''' self.mode._history.add_history(line) def get_history_length(self ): - '''Return the desired length of the history file. + u'''Return the desired length of the history file. Negative values imply unlimited history file size.''' return self.mode._history.get_history_length() def set_history_length(self, length): - '''Set the number of lines to save in the history file. + u'''Set the number of lines to save in the history file. write_history_file() uses this value to truncate the history file when saving. Negative values imply unlimited history file size. @@ -139,24 +139,24 @@ class BaseReadline(object): self.mode._history.set_history_length(length) def clear_history(self): - '''Clear readline history''' + u'''Clear readline history''' self.mode._history.clear_history() def read_history_file(self, filename=None): - '''Load a readline history file. The default filename is ~/.history.''' + u'''Load a readline history file. The default filename is ~/.history.''' if filename is None: filename=self.mode._history.history_filename - log("read_history_file from %s"%filename) + log(u"read_history_file from %s"%ensure_unicode(filename)) self.mode._history.read_history_file(filename) def write_history_file(self, filename=None): - '''Save a readline history file. The default filename is ~/.history.''' + u'''Save a readline history file. The default filename is ~/.history.''' self.mode._history.write_history_file(filename) #Completer functions def set_completer(self, function=None): - '''Set or remove the completer function. + u'''Set or remove the completer function. If function is specified, it will be used as the new completer function; if omitted or None, any completer function already @@ -165,34 +165,34 @@ class BaseReadline(object): non-string value. It should return the next possible completion starting with text. ''' - log('set_completer') + log(u'set_completer') self.mode.completer = function def get_completer(self): - '''Get the completer function. + u'''Get the completer function. ''' - log('get_completer') + log(u'get_completer') return self.mode.completer def get_begidx(self): - '''Get the beginning index of the readline tab-completion scope.''' + u'''Get the beginning index of the readline tab-completion scope.''' return self.mode.begidx def get_endidx(self): - '''Get the ending index of the readline tab-completion scope.''' + u'''Get the ending index of the readline tab-completion scope.''' return self.mode.endidx def set_completer_delims(self, string): - '''Set the readline word delimiters for tab-completion.''' + u'''Set the readline word delimiters for tab-completion.''' self.mode.completer_delims = string def get_completer_delims(self): - '''Get the readline word delimiters for tab-completion.''' + u'''Get the readline word delimiters for tab-completion.''' return self.mode.completer_delims def set_startup_hook(self, function=None): - '''Set or remove the startup_hook function. + u'''Set or remove the startup_hook function. If function is specified, it will be used as the new startup_hook function; if omitted or None, any hook function already installed is @@ -203,7 +203,7 @@ class BaseReadline(object): self.mode.startup_hook = function def set_pre_input_hook(self, function=None): - '''Set or remove the pre_input_hook function. + u'''Set or remove the pre_input_hook function. If function is specified, it will be used as the new pre_input_hook function; if omitted or None, any hook function already installed is @@ -223,7 +223,7 @@ class BaseReadline(object): # Standard call, not available for all implementations # - def readline(self, prompt=''): + def readline(self, prompt=u''): raise NotImplementedError # @@ -232,27 +232,27 @@ class BaseReadline(object): def process_keyevent(self, keyinfo): return self.mode.process_keyevent(keyinfo) - def readline_setup(self,prompt=""): + def readline_setup(self,prompt=u""): return self.mode.readline_setup(prompt) def keyboard_poll(self): return self.mode._readline_from_keyboard_poll() def callback_handler_install(self, prompt, callback): - '''bool readline_callback_handler_install ( string prompt, callback callback) + u'''bool readline_callback_handler_install ( string prompt, callback callback) Initializes the readline callback interface and terminal, prints the prompt and returns immediately ''' self.callback = callback self.readline_setup(prompt) def callback_handler_remove(self): - '''Removes a previously installed callback handler and restores terminal settings''' + u'''Removes a previously installed callback handler and restores terminal settings''' self.callback = None def callback_read_char(self): - '''Reads a character and informs the readline callback interface when a line is received''' + u'''Reads a character and informs the readline callback interface when a line is received''' if self.keyboard_poll(): - line = self.get_line_buffer() + '\n' + line = self.get_line_buffer() + u'\n' # however there is another newline added by # self.mode.readline_setup(prompt) which is called by callback_handler_install # this differs from GNU readline @@ -260,7 +260,7 @@ class BaseReadline(object): # TADA: self.callback(line) - def read_inputrc(self,inputrcpath=os.path.expanduser("~/pyreadlineconfig.ini")): + def read_inputrc(self,inputrcpath=os.path.expanduser("~/pyreadlineconfig.ini")):#in 2.4 we cannot call expanduser with unicode string modes=dict([(x.mode,x) for x in self.editingmodes]) mode=self.editingmodes[0].mode def setmode(name): @@ -269,7 +269,7 @@ class BaseReadline(object): if hasattr(modes[mode],name): modes[mode]._bind_key(key,getattr(modes[mode],name)) else: - print "Trying to bind unknown command '%s' to key '%s'"%(name,key) + print u"Trying to bind unknown command '%s' to key '%s'"%(name,key) def un_bind_key(key): keyinfo = make_KeyPress_from_keydescr(key).tuple() if keyinfo in modes[mode].key_dispatch: @@ -296,7 +296,7 @@ class BaseReadline(object): self.mode._history.history_length=int(length) def allow_ctrl_c(mode): - log("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) + log(u"allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) self.allow_ctrl_c=mode def setbellstyle(mode): @@ -314,52 +314,52 @@ class BaseReadline(object): def completer_delims(delims): self.mode.completer_delims=delims - def debug_output(on,filename="pyreadline_debug_log.txt"): #Not implemented yet - if on in ["on","on_nologfile"]: + def debug_output(on,filename=u"pyreadline_debug_log.txt"): #Not implemented yet + if on in [u"on",u"on_nologfile"]: self.debug=True if on == "on": logger.start_file_log(filename) logger.start_socket_log() - logger.log("STARTING LOG") - elif on =="on_nologfile": + logger.log(u"STARTING LOG") + elif on ==u"on_nologfile": logger.start_socket_log() - logger.log("STARTING LOG") + logger.log(u"STARTING LOG") else: - logger.log("STOPING LOG") + logger.log(u"STOPING LOG") logger.stop_file_log() logger.stop_socket_log() def set_prompt_color(color): - trtable={"black":0,"darkred":4,"darkgreen":2,"darkyellow":6,"darkblue":1,"darkmagenta":5,"darkcyan":3,"gray":7, - "red":4+8,"green":2+8,"yellow":6+8,"blue":1+8,"magenta":5+8,"cyan":3+8,"white":7+8} + trtable={u"black":0,u"darkred":4,u"darkgreen":2,u"darkyellow":6,u"darkblue":1,u"darkmagenta":5,u"darkcyan":3,u"gray":7, + u"red":4+8,"green":2+8,u"yellow":6+8,u"blue":1+8,u"magenta":5+8,u"cyan":3+8,u"white":7+8} self.prompt_color=trtable.get(color.lower(),7) def set_input_color(color): - trtable={"black":0,"darkred":4,"darkgreen":2,"darkyellow":6,"darkblue":1,"darkmagenta":5,"darkcyan":3,"gray":7, - "red":4+8,"green":2+8,"yellow":6+8,"blue":1+8,"magenta":5+8,"cyan":3+8,"white":7+8} + trtable={u"black":0,u"darkred":4,u"darkgreen":2,u"darkyellow":6,u"darkblue":1,u"darkmagenta":5,u"darkcyan":3,u"gray":7, + u"red":4+8,u"green":2+8,u"yellow":6+8,u"blue":1+8,u"magenta":5+8,u"cyan":3+8,u"white":7+8} self.command_color=trtable.get(color.lower(),7) - loc={"branch":release.branch, - "version":release.version, - "mode":mode, - "modes":modes, - "set_mode":setmode, - "bind_key":bind_key, - "bind_exit_key":bind_exit_key, - "un_bind_key":un_bind_key, - "un_bind_exit_key":un_bind_exit_key, - "bell_style":setbellstyle, - "mark_directories":mark_directories, - "show_all_if_ambiguous":show_all_if_ambiguous, - "completer_delims":completer_delims, - "debug_output":debug_output, - "history_filename":sethistoryfilename, - "history_length":sethistorylength, - "set_prompt_color":set_prompt_color, - "set_input_color":set_input_color, - "allow_ctrl_c":allow_ctrl_c, - "ctrl_c_tap_time_interval":ctrl_c_tap_time_interval, - "kill_ring_to_clipboard":setkill_ring_to_clipboard, + loc={u"branch":release.branch, + u"version":release.version, + u"mode":mode, + u"modes":modes, + u"set_mode":setmode, + u"bind_key":bind_key, + u"bind_exit_key":bind_exit_key, + u"un_bind_key":un_bind_key, + u"un_bind_exit_key":un_bind_exit_key, + u"bell_style":setbellstyle, + u"mark_directories":mark_directories, + u"show_all_if_ambiguous":show_all_if_ambiguous, + u"completer_delims":completer_delims, + u"debug_output":debug_output, + u"history_filename":sethistoryfilename, + u"history_length":sethistorylength, + u"set_prompt_color":set_prompt_color, + u"set_input_color":set_input_color, + u"allow_ctrl_c":allow_ctrl_c, + u"ctrl_c_tap_time_interval":ctrl_c_tap_time_interval, + u"kill_ring_to_clipboard":setkill_ring_to_clipboard, } if os.path.isfile(inputrcpath): try: @@ -367,11 +367,11 @@ class BaseReadline(object): except Exception,x: raise import traceback - print >>sys.stderr, "Error reading .pyinputrc" + print >>sys.stderr, u"Error reading .pyinputrc" filepath,lineno=traceback.extract_tb(sys.exc_traceback)[1][:2] - print >>sys.stderr, "Line: %s in file %s"%(lineno,filepath) + print >>sys.stderr, u"Line: %s in file %s"%(lineno,filepath) print >>sys.stderr, x - raise ReadlineError("Error reading .pyinputrc") + raise ReadlineError(u"Error reading .pyinputrc") @@ -394,15 +394,15 @@ class Readline(BaseReadline): ## Internal functions def _bell(self): - '''ring the bell if requested.''' - if self.bell_style == 'none': + u'''ring the bell if requested.''' + if self.bell_style == u'none': pass - elif self.bell_style == 'visible': - raise NotImplementedError("Bellstyle visible is not implemented yet.") - elif self.bell_style == 'audible': + elif self.bell_style == u'visible': + raise NotImplementedError(u"Bellstyle visible is not implemented yet.") + elif self.bell_style == u'audible': self.console.bell() else: - raise ReadlineError("Bellstyle %s unknown."%self.bell_style) + raise ReadlineError(u"Bellstyle %s unknown."%self.bell_style) def _clear_after(self): c = self.console @@ -464,7 +464,7 @@ class Readline(BaseReadline): n += 1 self._update_prompt_pos(n) - if hasattr(c,"clear_to_end_of_window"): #Work around function for ironpython due + if hasattr(c,u"clear_to_end_of_window"): #Work around function for ironpython due c.clear_to_end_of_window() #to System.Console's lack of FillFunction else: self._clear_after() @@ -476,10 +476,10 @@ class Readline(BaseReadline): def callback_read_char(self): #Override base to get automatic newline - '''Reads a character and informs the readline callback interface when a line is received''' + u'''Reads a character and informs the readline callback interface when a line is received''' if self.keyboard_poll(): - line = self.get_line_buffer() + '\n' - self.console.write("\r\n") + line = self.get_line_buffer() + u'\n' + self.console.write(u"\r\n") # however there is another newline added by # self.mode.readline_setup(prompt) which is called by callback_handler_install # this differs from GNU readline @@ -517,30 +517,30 @@ class Readline(BaseReadline): self._update_line() return result - def readline_setup(self, prompt=''): + def readline_setup(self, prompt=u''): BaseReadline.readline_setup(self, prompt) self._print_prompt() self._update_line() - def readline(self, prompt=''): + def readline(self, prompt=u''): self.readline_setup(prompt) self.ctrl_c_timeout=time.time() self._readline_from_keyboard() - self.console.write('\r\n') - log('returning(%s)' % self.get_line_buffer()) - return self.get_line_buffer() + '\n' + self.console.write(u'\r\n') + log(u'returning(%s)' % self.get_line_buffer()) + return self.get_line_buffer() + u'\n' def handle_ctrl_c(self): from pyreadline.keysyms.common import KeyPress from pyreadline.console.event import Event - log("KBDIRQ") + log(u"KBDIRQ") event=Event(0,0) - event.char="c" - event.keyinfo=KeyPress("c",shift=False,control=True,meta=False,keyname=None) + event.char=u"c" + event.keyinfo=KeyPress(u"c",shift=False,control=True,meta=False,keyname=None) if self.allow_ctrl_c: now=time.time() if (now-self.ctrl_c_timeout) import sys, unittest -sys.path.append ('../..') +sys.path.append (u'../..') #from pyreadline.modes.vi import * #from pyreadline import keysyms from pyreadline.lineeditor import lineobj @@ -19,76 +19,76 @@ from pyreadline.logger import log RL=lineobj.ReadLineTextBuffer class Test_linepos (unittest.TestCase): - t="test text" + t=u"test text" def init_test(self): history._ignore_leading_spaces=False self.q=q=LineHistory() - for x in ["aaaa","aaba","aaca","akca","bbb","ako"]: + for x in [u"aaaa",u"aaba",u"aaca",u"akca",u"bbb",u"ako"]: q.add_history(RL(x)) def test_previous_history (self): self.init_test() hist=self.q assert hist.history_cursor==6 - l=RL("") + l=RL(u"") hist.previous_history(l) - assert l.get_line_text()=="ako" + assert l.get_line_text()==u"ako" hist.previous_history(l) - assert l.get_line_text()=="bbb" + assert l.get_line_text()==u"bbb" hist.previous_history(l) - assert l.get_line_text()=="akca" + assert l.get_line_text()==u"akca" hist.previous_history(l) - assert l.get_line_text()=="aaca" + assert l.get_line_text()==u"aaca" hist.previous_history(l) - assert l.get_line_text()=="aaba" + assert l.get_line_text()==u"aaba" hist.previous_history(l) - assert l.get_line_text()=="aaaa" + assert l.get_line_text()==u"aaaa" hist.previous_history(l) - assert l.get_line_text()=="aaaa" + assert l.get_line_text()==u"aaaa" def test_next_history (self): self.init_test() hist=self.q hist.beginning_of_history() assert hist.history_cursor==0 - l=RL("") + l=RL(u"") hist.next_history(l) - assert l.get_line_text()=="aaba" + assert l.get_line_text()==u"aaba" hist.next_history(l) - assert l.get_line_text()=="aaca" + assert l.get_line_text()==u"aaca" hist.next_history(l) - assert l.get_line_text()=="akca" + assert l.get_line_text()==u"akca" hist.next_history(l) - assert l.get_line_text()=="bbb" + assert l.get_line_text()==u"bbb" hist.next_history(l) - assert l.get_line_text()=="ako" + assert l.get_line_text()==u"ako" hist.next_history(l) - assert l.get_line_text()=="ako" + assert l.get_line_text()==u"ako" def init_test2(self): self.q=q=LineHistory() - for x in ["aaaa","aaba","aaca","akca","bbb","ako"]: + for x in [u"aaaa",u"aaba",u"aaca",u"akca",u"bbb",u"ako"]: q.add_history(RL(x)) def test_history_search_backward (self): history._ignore_leading_spaces=False q=LineHistory() - for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","ako"]: + for x in [u"aaaa",u"aaba",u"aaca",u" aacax",u"akca",u"bbb",u"ako"]: q.add_history(RL(x)) - a=RL("aa",point=2) - for x in ["aaca","aaba","aaaa","aaaa"]: + a=RL(u"aa",point=2) + for x in [u"aaca",u"aaba",u"aaaa",u"aaaa"]: res=q.history_search_backward(a) assert res.get_line_text()==x def test_history_search_forward (self): history._ignore_leading_spaces=False q=LineHistory() - for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","ako"]: + for x in [u"aaaa",u"aaba",u"aaca",u" aacax",u"akca",u"bbb",u"ako"]: q.add_history(RL(x)) q.beginning_of_history() - a=RL("aa",point=2) - for x in ["aaba","aaca","aaca"]: + a=RL(u"aa",point=2) + for x in [u"aaba",u"aaca",u"aaca"]: res=q.history_search_forward(a) assert res.get_line_text()==x @@ -98,7 +98,7 @@ class Test_linepos (unittest.TestCase): #---------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == u'__main__': unittest.main() - l=lineobj.ReadLineTextBuffer("First Second Third") \ No newline at end of file + l=lineobj.ReadLineTextBuffer(u"First Second Third") \ No newline at end of file diff --git a/pyreadline/test/lineeditor_test.py b/pyreadline/test/lineeditor_test.py index 2e4dd0f..5ae1f3a 100644 --- a/pyreadline/test/lineeditor_test.py +++ b/pyreadline/test/lineeditor_test.py @@ -1,7 +1,7 @@ # Copyright (C) 2006 Michael Graz. import sys, unittest -sys.path.append ('../..') +sys.path.append (u'../..') #from pyreadline.modes.vi import * #from pyreadline import keysyms from pyreadline.lineeditor import lineobj @@ -13,14 +13,14 @@ from pyreadline.lineeditor import lineobj class Test_copy (unittest.TestCase): def test_copy1 (self): - l=lineobj.ReadLineTextBuffer("first second") + l=lineobj.ReadLineTextBuffer(u"first second") q=l.copy() self.assertEqual(q.get_line_text(),l.get_line_text()) self.assertEqual(q.point,l.point) self.assertEqual(q.mark,l.mark) def test_copy2 (self): - l=lineobj.ReadLineTextBuffer("first second",point=5) + l=lineobj.ReadLineTextBuffer(u"first second",point=5) q=l.copy() self.assertEqual(q.get_line_text(),l.get_line_text()) self.assertEqual(q.point,l.point) @@ -77,19 +77,19 @@ class Test_movement (unittest.TestCase): def test_NextChar (self): cmd=lineobj.NextChar tests=[ - # "First" + # u"First" (cmd, - "First", - "# ", - " # "), + u"First", + u"# u", + u" # u"), (cmd, - "First", - " # ", - " #"), + u"First", + u" # u", + u" #"), (cmd, - "First", - " #", - " #"), + u"First", + u" #", + u" #"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -99,19 +99,19 @@ class Test_movement (unittest.TestCase): def test_PrevChar (self): cmd=lineobj.PrevChar tests=[ - # "First" + # u"First" (cmd, - "First", - " #", - " # "), + u"First", + u" #", + u" # u"), (cmd, - "First", - " # ", - "# "), + u"First", + u" # u", + u"# u"), (cmd, - "First", - "# ", - "# "), + u"First", + u"# u", + u"# u"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -123,23 +123,23 @@ class Test_movement (unittest.TestCase): def test_PrevWordStart (self): cmd=lineobj.PrevWordStart tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - " #", - " # "), + u"First Second Third", + u" #", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - "# "), + u"First Second Third", + u" # u", + u"# u"), (cmd, - "First Second Third", - "# ", - "# "), + u"First Second Third", + u"# u", + u"# u"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -149,23 +149,23 @@ class Test_movement (unittest.TestCase): def test_NextWordStart (self): cmd=lineobj.NextWordStart tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - " # "), + u"First Second Third", + u"# u", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - " #"), + u"First Second Third", + u" # u", + u" #"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -175,23 +175,23 @@ class Test_movement (unittest.TestCase): def test_NextWordEnd (self): cmd=lineobj.NextWordEnd tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - " # "), + u"First Second Third", + u"# u", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - " #"), + u"First Second Third", + u" # u", + u" #"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -201,23 +201,23 @@ class Test_movement (unittest.TestCase): def test_PrevWordEnd (self): cmd=lineobj.PrevWordEnd tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - " #", - " # "), + u"First Second Third", + u" #", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - "# "), + u"First Second Third", + u" # u", + u"# u"), (cmd, - "First Second Third", - "# ", - "# "), + u"First Second Third", + u"# u", + u"# u"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -227,19 +227,19 @@ class Test_movement (unittest.TestCase): def test_WordEnd_1 (self): cmd=lineobj.WordEnd tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - " # "), + u"First Second Third", + u"# u", + u" # u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), (cmd, - "First Second Third", - " # ", - " #"), + u"First Second Third", + u" # u", + u" #"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -249,16 +249,16 @@ class Test_movement (unittest.TestCase): def test_WordEnd_2 (self): cmd=lineobj.WordEnd tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - " # "), + u"First Second Third", + u" # u"), (cmd, - "First Second Third", - " # "), + u"First Second Third", + u" # u"), (cmd, - "First Second Third", - " #"), + u"First Second Third", + u" #"), ] for cmd,text,init_point in tests: @@ -269,19 +269,19 @@ class Test_movement (unittest.TestCase): def test_WordStart_1 (self): cmd=lineobj.WordStart tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - "# "), + u"First Second Third", + u"# u", + u"# u"), (cmd, - "First Second Third", - " # ", - "# "), + u"First Second Third", + u" # u", + u"# u"), (cmd, - "First Second Third", - " # ", - " # "), + u"First Second Third", + u" # u", + u" # u"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -291,16 +291,16 @@ class Test_movement (unittest.TestCase): def test_WordStart_2 (self): cmd=lineobj.WordStart tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - " # "), + u"First Second Third", + u" # u"), (cmd, - "First Second Third", - " # "), + u"First Second Third", + u" # u"), (cmd, - "First Second Third", - " #"), + u"First Second Third", + u" #"), ] for cmd,text,init_point in tests: @@ -311,19 +311,19 @@ class Test_movement (unittest.TestCase): def test_StartOfLine (self): cmd=lineobj.StartOfLine tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - "# "), + u"First Second Third", + u"# u", + u"# u"), (cmd, - "First Second Third", - " # ", - "# "), + u"First Second Third", + u" # u", + u"# u"), (cmd, - "First Second Third", - " #", - "# "), + u"First Second Third", + u" #", + u"# u"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -333,19 +333,19 @@ class Test_movement (unittest.TestCase): def test_EndOfLine (self): cmd=lineobj.EndOfLine tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", - "# ", - " #"), + u"First Second Third", + u"# u", + u" #"), (cmd, - "First Second Third", - " # ", - " #"), + u"First Second Third", + u" # u", + u" #"), (cmd, - "First Second Third", - " #", - " #"), + u"First Second Third", + u" #", + u" #"), ] for cmd,text,init_point,expected_point in tests: l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point)) @@ -355,15 +355,15 @@ class Test_movement (unittest.TestCase): def test_Point(self): cmd=lineobj.Point tests=[ - # "First Second Third" + # u"First Second Third" (cmd, - "First Second Third", + u"First Second Third", 0), (cmd, - "First Second Third", + u"First Second Third", 12), (cmd, - "First Second Third", + u"First Second Third", 18), ] for cmd,text,p in tests: @@ -375,16 +375,16 @@ class Test_movement (unittest.TestCase): # utility functions def get_point_pos(pstr): - return pstr.index("#") + return pstr.index(u"#") def get_mark_pos(mstr): try: - return mstr.index("#") + return mstr.index(u"#") except ValueError: return -1 #---------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == u'__main__': unittest.main() - l=lineobj.ReadLineTextBuffer("First Second Third") \ No newline at end of file + l=lineobj.ReadLineTextBuffer(u"First Second Third") \ No newline at end of file diff --git a/pyreadline/test/vi_test.py b/pyreadline/test/vi_test.py index 332e767..0728193 100644 --- a/pyreadline/test/vi_test.py +++ b/pyreadline/test/vi_test.py @@ -7,7 +7,7 @@ #***************************************************************************** import sys, unittest,pdb -sys.path.append ('../..') +sys.path.append (u'../..') from pyreadline.modes.vi import * from pyreadline import keysyms from pyreadline.lineeditor import lineobj @@ -27,7 +27,7 @@ class ViModeTest (ViMode): self.vi_set_insert_mode (True) self.lst_completions = [] self.completer = self.mock_completer - self.completer_delims = ' ' + self.completer_delims = u' u' self.tabstop = 4 def get_mock_console (self): @@ -46,8 +46,8 @@ class ViModeTest (ViMode): line_cursor = property (get_line_cursor) def input (self, keytext): - if keytext[0] == '"' and keytext[-1] == '"': - lst_key = ['"%s"' % c for c in keytext[1:-1]] + if keytext[0] == u'"' and keytext[-1] == u'"': + lst_key = [u'"%s"' % c for c in keytext[1:-1]] else: lst_key = [keytext] for key in lst_key: @@ -69,17 +69,17 @@ class ViExternalEditorTest (ViExternalEditor): def __init__ (self, line): import StringIO self.sio_write = StringIO.StringIO () - self.sio_read = StringIO.StringIO ('qwerty after') + self.sio_read = StringIO.StringIO (u'qwerty after') ViExternalEditor.__init__ (self, line) def get_tempfile (self): - return 'temp.py' + return u'temp.py' def get_editor (self): - return 'vim.exe' + return u'vim.exe' def file_open (self, filename, mode): - if mode == 'w': + if mode == u'w': return self.sio_write else: return self.sio_read @@ -95,1622 +95,1622 @@ class ViExternalEditorTest (ViExternalEditor): class Tests (unittest.TestCase): def test_keyinfo (self): - keyinfo, event = keytext_to_keyinfo_and_event ('"d"') - self.assertEqual ('d', event.char) - keyinfo, event = keytext_to_keyinfo_and_event ('"D"') - self.assertEqual ('D', event.char) - keyinfo, event = keytext_to_keyinfo_and_event ('"$"') - self.assertEqual ('$', event.char) - keyinfo, event = keytext_to_keyinfo_and_event ('Escape') - self.assertEqual ('\x1b', event.char) + keyinfo, event = keytext_to_keyinfo_and_event (u'"d"') + self.assertEqual (u'd', event.char) + keyinfo, event = keytext_to_keyinfo_and_event (u'"D"') + self.assertEqual (u'D', event.char) + keyinfo, event = keytext_to_keyinfo_and_event (u'"$"') + self.assertEqual (u'$', event.char) + keyinfo, event = keytext_to_keyinfo_and_event (u'Escape') + self.assertEqual (u'\x1b', event.char) def test_simple (self): r = ViModeTest () - r._set_line ('abc') + r._set_line (u'abc') self.assert_ (r.vi_is_insert_mode) - r.input ('"d"') + r.input (u'"d"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual ('abcd', r.line) - r.input ('Escape') + self.assertEqual (u'abcd', r.line) + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) - self.assertEqual ('abcd', r.line) - r.input ('"i"') + self.assertEqual (u'abcd', r.line) + r.input (u'"i"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual ('abcd', r.line) - r.input ('"x"') - self.assertEqual ('abcxd', r.line) - r.input ('"y"') - self.assertEqual ('abcxyd', r.line) + self.assertEqual (u'abcd', r.line) + r.input (u'"x"') + self.assertEqual (u'abcxd', r.line) + r.input (u'"y"') + self.assertEqual (u'abcxyd', r.line) def test_begin_and_end (self): r = ViModeTest () - r._set_line ('abc') + r._set_line (u'abc') self.assertEqual (3, r.line_cursor) - r.input ('Escape') + r.input (u'Escape') self.assertEqual (2, r.line_cursor) - r.input ('"0"') + r.input (u'"0"') self.assertEqual (0, r.line_cursor) - r.input ('"$"') + r.input (u'"$"') self.assertEqual (2, r.line_cursor) - r.input ('"^"') + r.input (u'"^"') self.assertEqual (0, r.line_cursor) def test_history_alpha (self): r = ViModeTest () - r.add_history ('abc') - r.add_history ('def') - r._set_line ('ghi') - r.input ('Escape') - r.input ('"k"') + r.add_history (u'abc') + r.add_history (u'def') + r._set_line (u'ghi') + r.input (u'Escape') + r.input (u'"k"') self.assertEqual (0, r.line_cursor) - self.assertEqual ('def', r.line) - r.input ('"k"') - self.assertEqual ('abc', r.line) + self.assertEqual (u'def', r.line) + r.input (u'"k"') + self.assertEqual (u'abc', r.line) self.assertEqual (0, r.console.bell_count) - r.input ('"k"') - self.assertEqual ('abc', r.line) + r.input (u'"k"') + self.assertEqual (u'abc', r.line) # TODO up history with no more -> error ? # self.assertEqual (1, r.console.bell_count) - r.input ('"j"') - self.assertEqual ('def', r.line) + r.input (u'"j"') + self.assertEqual (u'def', r.line) self.assertEqual (0, r.line_cursor) - r.input ('"j"') - self.assertEqual ('ghi', r.line) + r.input (u'"j"') + self.assertEqual (u'ghi', r.line) # TODO returning to original line loses cursor pos? # self.assertEqual (2, r.line_cursor) - r.input ('"j"') - self.assertEqual ('ghi', r.line) + r.input (u'"j"') + self.assertEqual (u'ghi', r.line) self.assertEqual (2, r.line_cursor) def test_history_arrow (self): r = ViModeTest () - r.add_history ('abc') - r.add_history ('def') - r.input ('"ghi"') + r.add_history (u'abc') + r.add_history (u'def') + r.input (u'"ghi"') self.assertEqual (3, r.line_cursor) - r.input ('Up') + r.input (u'Up') self.assertEqual (3, r.line_cursor) - self.assertEqual ('def', r.line) - r.input ('Up') + self.assertEqual (u'def', r.line) + r.input (u'Up') self.assertEqual (3, r.line_cursor) - self.assertEqual ('abc', r.line) + self.assertEqual (u'abc', r.line) self.assertEqual (0, r.console.bell_count) - r.input ('Up') - self.assertEqual ('abc', r.line) + r.input (u'Up') + self.assertEqual (u'abc', r.line) # TODO up history with no more -> error ? # self.assertEqual (1, r.console.bell_count) - r.input ('Down') - self.assertEqual ('def', r.line) + r.input (u'Down') + self.assertEqual (u'def', r.line) self.assertEqual (3, r.line_cursor) - r.input ('Down') - self.assertEqual ('ghi', r.line) + r.input (u'Down') + self.assertEqual (u'ghi', r.line) self.assertEqual (3, r.line_cursor) - r.input ('Down') - self.assertEqual ('ghi', r.line) + r.input (u'Down') + self.assertEqual (u'ghi', r.line) self.assertEqual (3, r.line_cursor) def test_history_arrow_after_undo (self): r = ViModeTest () - r.input ('"aaa"') - r.input ('Return') - r.input ('"bbb ccc"') - r.input ('Escape') - r.input ('"F D"') - self.assertEqual (r.line, 'bbb') - r.input ('"u"') - self.assertEqual (r.line, 'bbb ccc') - r.input ('Return') + r.input (u'"aaa"') + r.input (u'Return') + r.input (u'"bbb ccc"') + r.input (u'Escape') + r.input (u'"F D"') + self.assertEqual (r.line, u'bbb') + r.input (u'"u"') + self.assertEqual (r.line, u'bbb ccc') + r.input (u'Return') self.assertEqual (r.console.bell_count, 0) - r.input ('"ddd"') - r.input ('Down') - self.assertEqual (r.line, 'ddd') + r.input (u'"ddd"') + r.input (u'Down') + self.assertEqual (r.line, u'ddd') # TODO down history with no more -> error ? # self.assertEqual (r.console.bell_count, 1) def test_vi_is_word (self): - self.assert_ (vi_is_word ('a')) - self.assert_ (not vi_is_word (' ')) + self.assert_ (vi_is_word (u'a')) + self.assert_ (not vi_is_word (u' u')) def test_pos_word_short (self): - self.assertEqual (0, vi_pos_word_short ('')) - self.assertEqual (4, vi_pos_word_short ('abc def ')) - self.assertEqual (4, vi_pos_word_short ('abc def ', 2)) - self.assertEqual (4, vi_pos_word_short ('abc def ', 3)) - self.assertEqual (8, vi_pos_word_short ('abc def ', 4)) - self.assertEqual (3, vi_pos_word_short ('abc.def ')) - self.assertEqual (5, vi_pos_word_short ('abc..def ', 3)) - self.assertEqual (8, vi_pos_word_short ('ab cd ef gh', count=2)) - self.assertEqual (8, vi_pos_word_short ('ab cd ef gh', 1, 2)) - self.assertEqual (8, vi_pos_word_short ('ab cd ef gh', 3, 2)) - self.assertEqual (14, vi_pos_word_short ('ab cd ef gh', count=10)) + self.assertEqual (0, vi_pos_word_short (u'')) + self.assertEqual (4, vi_pos_word_short (u'abc def u')) + self.assertEqual (4, vi_pos_word_short (u'abc def u', 2)) + self.assertEqual (4, vi_pos_word_short (u'abc def u', 3)) + self.assertEqual (8, vi_pos_word_short (u'abc def u', 4)) + self.assertEqual (3, vi_pos_word_short (u'abc.def u')) + self.assertEqual (5, vi_pos_word_short (u'abc..def u', 3)) + self.assertEqual (8, vi_pos_word_short (u'ab cd ef gh', count=2)) + self.assertEqual (8, vi_pos_word_short (u'ab cd ef gh', 1, 2)) + self.assertEqual (8, vi_pos_word_short (u'ab cd ef gh', 3, 2)) + self.assertEqual (14, vi_pos_word_short (u'ab cd ef gh', count=10)) def test_pos_word_long (self): - self.assertEqual (0, vi_pos_word_long ('')) - self.assertEqual (4, vi_pos_word_long ('abc def ')) - self.assertEqual (4, vi_pos_word_long ('abc def ', 2)) - self.assertEqual (4, vi_pos_word_long ('abc def ', 3)) - self.assertEqual (8, vi_pos_word_long ('abc def ', 4)) - self.assertEqual (8, vi_pos_word_long ('abc.def ')) - self.assertEqual (9, vi_pos_word_long ('abc..def ', 3)) - self.assertEqual (10, vi_pos_word_long ('a.b c.d e.f g.h', count=2)) - self.assertEqual (10, vi_pos_word_long ('a.b c.d e.f g.h', 2, 2)) - self.assertEqual (10, vi_pos_word_long ('a.b c.d e.f g.h', 4, 2)) + self.assertEqual (0, vi_pos_word_long (u'')) + self.assertEqual (4, vi_pos_word_long (u'abc def u')) + self.assertEqual (4, vi_pos_word_long (u'abc def u', 2)) + self.assertEqual (4, vi_pos_word_long (u'abc def u', 3)) + self.assertEqual (8, vi_pos_word_long (u'abc def u', 4)) + self.assertEqual (8, vi_pos_word_long (u'abc.def u')) + self.assertEqual (9, vi_pos_word_long (u'abc..def u', 3)) + self.assertEqual (10, vi_pos_word_long (u'a.b c.d e.f g.h', count=2)) + self.assertEqual (10, vi_pos_word_long (u'a.b c.d e.f g.h', 2, 2)) + self.assertEqual (10, vi_pos_word_long (u'a.b c.d e.f g.h', 4, 2)) def test_pos_end_short (self): - self.assertEqual (0, vi_pos_end_short ('')) - self.assertEqual (2, vi_pos_end_short ('abc def ')) - self.assertEqual (6, vi_pos_end_short ('abc def ', 2)) - self.assertEqual (6, vi_pos_end_short ('abc def ', 3)) - self.assertEqual (6, vi_pos_end_short ('abc def ', 4)) - self.assertEqual (2, vi_pos_end_short ('abc.def ')) - self.assertEqual (7, vi_pos_end_short ('abc ... def ', 3)) - self.assertEqual (7, vi_pos_end_short ('abc ... def ', 5)) - self.assertEqual (12, vi_pos_end_short ('abc ... def ', 8)) - self.assertEqual (5, vi_pos_end_short ('ab cd ef gh', count=2)) - self.assertEqual (9, vi_pos_end_short ('ab cd ef gh', 1, 2)) - self.assertEqual (9, vi_pos_end_short ('ab cd ef gh', 3, 2)) + self.assertEqual (0, vi_pos_end_short (u'')) + self.assertEqual (2, vi_pos_end_short (u'abc def u')) + self.assertEqual (6, vi_pos_end_short (u'abc def u', 2)) + self.assertEqual (6, vi_pos_end_short (u'abc def u', 3)) + self.assertEqual (6, vi_pos_end_short (u'abc def u', 4)) + self.assertEqual (2, vi_pos_end_short (u'abc.def u')) + self.assertEqual (7, vi_pos_end_short (u'abc ... def u', 3)) + self.assertEqual (7, vi_pos_end_short (u'abc ... def u', 5)) + self.assertEqual (12, vi_pos_end_short (u'abc ... def u', 8)) + self.assertEqual (5, vi_pos_end_short (u'ab cd ef gh', count=2)) + self.assertEqual (9, vi_pos_end_short (u'ab cd ef gh', 1, 2)) + self.assertEqual (9, vi_pos_end_short (u'ab cd ef gh', 3, 2)) def test_pos_end_long (self): - self.assertEqual (0, vi_pos_end_long ('')) - self.assertEqual (2, vi_pos_end_long ('abc def ')) - self.assertEqual (6, vi_pos_end_long ('abc def ', 2)) - self.assertEqual (6, vi_pos_end_long ('abc def ', 3)) - self.assertEqual (6, vi_pos_end_long ('abc def ', 4)) - self.assertEqual (6, vi_pos_end_long ('abc.def ')) - self.assertEqual (10, vi_pos_end_long (' abc...def ')) - self.assertEqual (10, vi_pos_end_long ('abc ...def ', 5)) - self.assertEqual (7, vi_pos_end_long ('a.b c.d e.f g.h', count=2)) - self.assertEqual (12, vi_pos_end_long ('a.b c.d e.f g.h', 2, 2)) - self.assertEqual (12, vi_pos_end_long ('a.b c.d e.f g.h', 4, 2)) + self.assertEqual (0, vi_pos_end_long (u'')) + self.assertEqual (2, vi_pos_end_long (u'abc def u')) + self.assertEqual (6, vi_pos_end_long (u'abc def u', 2)) + self.assertEqual (6, vi_pos_end_long (u'abc def u', 3)) + self.assertEqual (6, vi_pos_end_long (u'abc def u', 4)) + self.assertEqual (6, vi_pos_end_long (u'abc.def u')) + self.assertEqual (10, vi_pos_end_long (u' abc...def u')) + self.assertEqual (10, vi_pos_end_long (u'abc ...def u', 5)) + self.assertEqual (7, vi_pos_end_long (u'a.b c.d e.f g.h', count=2)) + self.assertEqual (12, vi_pos_end_long (u'a.b c.d e.f g.h', 2, 2)) + self.assertEqual (12, vi_pos_end_long (u'a.b c.d e.f g.h', 4, 2)) def test_pos_back_short (self): - self.assertEqual (0, vi_pos_back_short ('')) - self.assertEqual (4, vi_pos_back_short ('abc def', 6)) - self.assertEqual (4, vi_pos_back_short ('abc def', 5)) - self.assertEqual (0, vi_pos_back_short ('abc def', 4)) - self.assertEqual (0, vi_pos_back_short ('abc def', 3)) - self.assertEqual (8, vi_pos_back_short ('abc ...def ', 11)) - self.assertEqual (5, vi_pos_back_short ('abc ...def ', 8)) - self.assertEqual (0, vi_pos_back_short ('abc ...def ', 5)) - self.assertEqual (0, vi_pos_back_short ('abc ...def ')) - self.assertEqual (8, vi_pos_back_short ('abc def... ', 11)) - self.assertEqual (5, vi_pos_back_short ('abc def... ', 8)) - self.assertEqual (0, vi_pos_back_short ('abc def... ', 5)) - self.assertEqual (11, vi_pos_back_short ('abc def... ghi...', 16, count=2)) - self.assertEqual (0, vi_pos_back_short ('abc def... ghi...', 11, count=3)) + self.assertEqual (0, vi_pos_back_short (u'')) + self.assertEqual (4, vi_pos_back_short (u'abc def', 6)) + self.assertEqual (4, vi_pos_back_short (u'abc def', 5)) + self.assertEqual (0, vi_pos_back_short (u'abc def', 4)) + self.assertEqual (0, vi_pos_back_short (u'abc def', 3)) + self.assertEqual (8, vi_pos_back_short (u'abc ...def u', 11)) + self.assertEqual (5, vi_pos_back_short (u'abc ...def u', 8)) + self.assertEqual (0, vi_pos_back_short (u'abc ...def u', 5)) + self.assertEqual (0, vi_pos_back_short (u'abc ...def u')) + self.assertEqual (8, vi_pos_back_short (u'abc def... u', 11)) + self.assertEqual (5, vi_pos_back_short (u'abc def... u', 8)) + self.assertEqual (0, vi_pos_back_short (u'abc def... u', 5)) + self.assertEqual (11, vi_pos_back_short (u'abc def... ghi...', 16, count=2)) + self.assertEqual (0, vi_pos_back_short (u'abc def... ghi...', 11, count=3)) def test_pos_back_long (self): - self.assertEqual (0, vi_pos_back_long ('')) - self.assertEqual (4, vi_pos_back_long ('abc def', 6)) - self.assertEqual (4, vi_pos_back_long ('abc def', 5)) - self.assertEqual (0, vi_pos_back_long ('abc def', 4)) - self.assertEqual (0, vi_pos_back_long ('abc def', 3)) - self.assertEqual (5, vi_pos_back_long ('abc ...def ', 11)) - self.assertEqual (0, vi_pos_back_long ('abc ...def ', 5)) - self.assertEqual (0, vi_pos_back_long ('abc ...def ')) - self.assertEqual (5, vi_pos_back_long ('abc def... ', 11)) - self.assertEqual (0, vi_pos_back_long ('abc def... ', 5)) - self.assertEqual (4, vi_pos_back_long ('abc def... ghi...', 16, count=2)) + self.assertEqual (0, vi_pos_back_long (u'')) + self.assertEqual (4, vi_pos_back_long (u'abc def', 6)) + self.assertEqual (4, vi_pos_back_long (u'abc def', 5)) + self.assertEqual (0, vi_pos_back_long (u'abc def', 4)) + self.assertEqual (0, vi_pos_back_long (u'abc def', 3)) + self.assertEqual (5, vi_pos_back_long (u'abc ...def u', 11)) + self.assertEqual (0, vi_pos_back_long (u'abc ...def u', 5)) + self.assertEqual (0, vi_pos_back_long (u'abc ...def u')) + self.assertEqual (5, vi_pos_back_long (u'abc def... u', 11)) + self.assertEqual (0, vi_pos_back_long (u'abc def... u', 5)) + self.assertEqual (4, vi_pos_back_long (u'abc def... ghi...', 16, count=2)) def test_pos_find_char_forward (self): - self.assertEqual (-1, vi_pos_find_char_forward ('', 'x')) - self.assertEqual (-1, vi_pos_find_char_forward ('abc def', 'x')) - self.assertEqual (4, vi_pos_find_char_forward ('abc def', 'd')) - self.assertEqual (4, vi_pos_find_char_forward ('abc def', 'd', 3)) - self.assertEqual (-1, vi_pos_find_char_forward ('abc def', 'd', 4)) - self.assertEqual (-1, vi_pos_find_char_forward ('abc def', 'd', count=2)) - self.assertEqual (12, vi_pos_find_char_forward ('abc def abc def', 'd', count=2)) + self.assertEqual (-1, vi_pos_find_char_forward (u'', u'x')) + self.assertEqual (-1, vi_pos_find_char_forward (u'abc def', u'x')) + self.assertEqual (4, vi_pos_find_char_forward (u'abc def', u'd')) + self.assertEqual (4, vi_pos_find_char_forward (u'abc def', u'd', 3)) + self.assertEqual (-1, vi_pos_find_char_forward (u'abc def', u'd', 4)) + self.assertEqual (-1, vi_pos_find_char_forward (u'abc def', u'd', count=2)) + self.assertEqual (12, vi_pos_find_char_forward (u'abc def abc def', u'd', count=2)) def test_pos_find_char_backward (self): - self.assertEqual (-1, vi_pos_find_char_backward ('', 'x')) - self.assertEqual (-1, vi_pos_find_char_backward ('abc def', 'x', 6)) - self.assertEqual (4, vi_pos_find_char_backward ('abc def', 'd', 6)) - self.assertEqual (4, vi_pos_find_char_backward ('abc def', 'd', 5)) - self.assertEqual (-1, vi_pos_find_char_backward ('abc def', 'd', 4)) - self.assertEqual (-1, vi_pos_find_char_backward ('abc def', 'd', 6, count=2)) - self.assertEqual (4, vi_pos_find_char_backward ('abc def abc def', 'd', 14, count=2)) + self.assertEqual (-1, vi_pos_find_char_backward (u'', u'x')) + self.assertEqual (-1, vi_pos_find_char_backward (u'abc def', u'x', 6)) + self.assertEqual (4, vi_pos_find_char_backward (u'abc def', u'd', 6)) + self.assertEqual (4, vi_pos_find_char_backward (u'abc def', u'd', 5)) + self.assertEqual (-1, vi_pos_find_char_backward (u'abc def', u'd', 4)) + self.assertEqual (-1, vi_pos_find_char_backward (u'abc def', u'd', 6, count=2)) + self.assertEqual (4, vi_pos_find_char_backward (u'abc def abc def', u'd', 14, count=2)) def test_pos_to_char_forward (self): - self.assertEqual (-1, vi_pos_to_char_forward ('', 'x')) - self.assertEqual (-1, vi_pos_to_char_forward ('abc def', 'x')) - self.assertEqual (3, vi_pos_to_char_forward ('abc def', 'd')) - self.assertEqual (3, vi_pos_to_char_forward ('abc def', 'd', 2)) - self.assertEqual (-1, vi_pos_to_char_forward ('abc def', 'd', 4)) - self.assertEqual (-1, vi_pos_to_char_forward ('abc def', 'd', count=2)) - self.assertEqual (11, vi_pos_to_char_forward ('abc def abc def', 'd', count=2)) + self.assertEqual (-1, vi_pos_to_char_forward (u'', u'x')) + self.assertEqual (-1, vi_pos_to_char_forward (u'abc def', u'x')) + self.assertEqual (3, vi_pos_to_char_forward (u'abc def', u'd')) + self.assertEqual (3, vi_pos_to_char_forward (u'abc def', u'd', 2)) + self.assertEqual (-1, vi_pos_to_char_forward (u'abc def', u'd', 4)) + self.assertEqual (-1, vi_pos_to_char_forward (u'abc def', u'd', count=2)) + self.assertEqual (11, vi_pos_to_char_forward (u'abc def abc def', u'd', count=2)) def test_pos_to_char_backward (self): - self.assertEqual (-1, vi_pos_to_char_backward ('', 'x')) - self.assertEqual (-1, vi_pos_to_char_backward ('abc def', 'x', 6)) - self.assertEqual (5, vi_pos_to_char_backward ('abc def', 'd', 6)) - self.assertEqual (5, vi_pos_to_char_backward ('abc def', 'd', 5)) - self.assertEqual (-1, vi_pos_to_char_backward ('abc def', 'd', 4)) - self.assertEqual (-1, vi_pos_to_char_backward ('abc def', 'd', 6, count=2)) - self.assertEqual (5, vi_pos_to_char_backward ('abc def abc def', 'd', 14, count=2)) + self.assertEqual (-1, vi_pos_to_char_backward (u'', u'x')) + self.assertEqual (-1, vi_pos_to_char_backward (u'abc def', u'x', 6)) + self.assertEqual (5, vi_pos_to_char_backward (u'abc def', u'd', 6)) + self.assertEqual (5, vi_pos_to_char_backward (u'abc def', u'd', 5)) + self.assertEqual (-1, vi_pos_to_char_backward (u'abc def', u'd', 4)) + self.assertEqual (-1, vi_pos_to_char_backward (u'abc def', u'd', 6, count=2)) + self.assertEqual (5, vi_pos_to_char_backward (u'abc def abc def', u'd', 14, count=2)) def test_motion_word (self): - '''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces + u'''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces w/W: forward short/long word''' r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"0"') - r.input ('"w"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"w"') self.assertEqual (9, r.line_cursor) - r.input ('"w"') + r.input (u'"w"') self.assertEqual (12, r.line_cursor) - r.input ('"w"') + r.input (u'"w"') self.assertEqual (14, r.line_cursor) - r.input ('"W"') + r.input (u'"W"') self.assertEqual (23, r.line_cursor) def test_motion_word_multiplier (self): r = ViModeTest () - r._set_line ('a b c d e f g h i j k l m n o p q r s t u v w x y z') - r.input ('Escape') - r.input ('"0"') - r.input ('"2"') + r._set_line (u'a b c d e f g h i j k l m n o p q r s t u v w x y z') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2"') self.assertEqual (0, r.line_cursor) - r.input ('"w"') + r.input (u'"w"') self.assertEqual (4, r.line_cursor) - r.input ('"2"') - r.input ('"0"') - r.input ('"w"') + r.input (u'"2"') + r.input (u'"0"') + r.input (u'"w"') self.assertEqual (44, r.line_cursor) - r.input ('"2"') - r.input ('"W"') + r.input (u'"2"') + r.input (u'"W"') self.assertEqual (48, r.line_cursor) def test_motion_end (self): - '''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces + u'''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces e/E: to end of short/long word''' r = ViModeTest () - r._set_line (' abc_123 --def--456.789 x') - r.input ('Escape') - r.input ('"0"') - r.input ('"e"') + r._set_line (u' abc_123 --def--456.789 x') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"e"') self.assertEqual (8, r.line_cursor) - r.input ('"e"') + r.input (u'"e"') self.assertEqual (12, r.line_cursor) - r.input ('"e"') + r.input (u'"e"') self.assertEqual (15, r.line_cursor) - r.input ('"E"') + r.input (u'"E"') self.assertEqual (24, r.line_cursor) def test_motion_end_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef gh ij kl mn op qr st uv wx yz') - r.input ('Escape') - r.input ('"0"') - r.input ('"3"') - r.input ('"e"') + r._set_line (u'ab cd ef gh ij kl mn op qr st uv wx yz') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"3"') + r.input (u'"e"') self.assertEqual (7, r.line_cursor) - r.input ('"4"') - r.input ('"E"') + r.input (u'"4"') + r.input (u'"E"') self.assertEqual (19, r.line_cursor) def test_motion_backward (self): - '''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces + u'''motions: lowercase mode is alpha, digit and _, uppercase is delim by spaces b/B: backward short/long word''' r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (23, r.line_cursor) - r.input ('"b"') + r.input (u'"b"') self.assertEqual (18, r.line_cursor) - r.input ('"b"') + r.input (u'"b"') self.assertEqual (17, r.line_cursor) - r.input ('"B"') + r.input (u'"B"') self.assertEqual (9, r.line_cursor) - r.input ('"B"') + r.input (u'"B"') self.assertEqual (0, r.line_cursor) def test_motion_backward_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef gh ij kl mn op qr st uv wx yz') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'ab cd ef gh ij kl mn op qr st uv wx yz') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (37, r.line_cursor) - r.input ('"3"') - r.input ('"b"') + r.input (u'"3"') + r.input (u'"b"') self.assertEqual (30, r.line_cursor) - r.input ('"5"') - r.input ('"b"') + r.input (u'"5"') + r.input (u'"b"') self.assertEqual (15, r.line_cursor) def test_motion_find_char_forward (self): r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"0"') - r.input ('"f"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"f"') self.assertEqual (0, r.line_cursor) - r.input ('"c"') + r.input (u'"c"') self.assertEqual (2, r.line_cursor) def test_motion_find_char_backward (self): r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (23, r.line_cursor) - r.input ('"F"') + r.input (u'"F"') self.assertEqual (23, r.line_cursor) - r.input ('"c"') + r.input (u'"c"') self.assertEqual (2, r.line_cursor) def test_motion_find_char_forward_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') - r.input ('Escape') - r.input ('"0"') - r.input ('"2"') - r.input ('"f"') - r.input ('"0"') + r._set_line (u'ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2"') + r.input (u'"f"') + r.input (u'"0"') self.assertEqual (27, r.line_cursor) def test_motion_find_char_backward_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (52, r.line_cursor) - r.input ('"2"') - r.input ('"F"') - r.input ('"0"') + r.input (u'"2"') + r.input (u'"F"') + r.input (u'"0"') self.assertEqual (27, r.line_cursor) def test_motion_find_char_again (self): r = ViModeTest () - r._set_line ('1234512345123451234512345') - r.input ('Escape') - r.input ('"0"') - r.input ('"2"') - r.input ('"f"') - r.input ('"3"') + r._set_line (u'1234512345123451234512345') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2"') + r.input (u'"f"') + r.input (u'"3"') self.assertEqual (7, r.line_cursor) - r.input ('";"') + r.input (u'";"') self.assertEqual (12, r.line_cursor) - r.input ('"2"') - r.input ('";"') + r.input (u'"2"') + r.input (u'";"') self.assertEqual (22, r.line_cursor) - r.input ('","') + r.input (u'","') self.assertEqual (17, r.line_cursor) - r.input ('"2"') - r.input ('","') + r.input (u'"2"') + r.input (u'","') self.assertEqual (7, r.line_cursor) def test_motion_find_char_opposite (self): r = ViModeTest () - r._set_line ('1234512345123451234512345') - r.input ('Escape') - r.input ('"$"') - r.input ('"2"') - r.input ('"F"') - r.input ('"3"') + r._set_line (u'1234512345123451234512345') + r.input (u'Escape') + r.input (u'"$"') + r.input (u'"2"') + r.input (u'"F"') + r.input (u'"3"') self.assertEqual (17, r.line_cursor) - r.input ('";"') + r.input (u'";"') self.assertEqual (12, r.line_cursor) - r.input ('"2"') - r.input ('";"') + r.input (u'"2"') + r.input (u'";"') self.assertEqual (2, r.line_cursor) - r.input ('","') + r.input (u'","') self.assertEqual (7, r.line_cursor) - r.input ('"2"') - r.input ('","') + r.input (u'"2"') + r.input (u'","') self.assertEqual (17, r.line_cursor) - r.input ('"2"') - r.input ('","') + r.input (u'"2"') + r.input (u'","') self.assertEqual (17, r.line_cursor) def test_motion_to_char_forward (self): r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"0"') - r.input ('"t"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"t"') self.assertEqual (0, r.line_cursor) - r.input ('"c"') + r.input (u'"c"') self.assertEqual (1, r.line_cursor) def test_motion_to_char_backward (self): r = ViModeTest () - r._set_line ('abc_123 def--456.789 x') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc_123 def--456.789 x') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (23, r.line_cursor) - r.input ('"T"') + r.input (u'"T"') self.assertEqual (23, r.line_cursor) - r.input ('"c"') + r.input (u'"c"') self.assertEqual (3, r.line_cursor) def test_motion_to_char_forward_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') - r.input ('Escape') - r.input ('"0"') - r.input ('"2"') - r.input ('"t"') - r.input ('"0"') + r._set_line (u'ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2"') + r.input (u'"t"') + r.input (u'"0"') self.assertEqual (26, r.line_cursor) def test_motion_to_char_backward_multiplier (self): r = ViModeTest () - r._set_line ('ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'ab cd ef 01 23 45 ab cd ef 01 23 45 ab cd ef 01 23 45') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (52, r.line_cursor) - r.input ('"2"') - r.input ('"T"') - r.input ('"0"') + r.input (u'"2"') + r.input (u'"T"') + r.input (u'"0"') self.assertEqual (28, r.line_cursor) def test_delete_word (self): r = ViModeTest () - r._set_line ('abc de fghi jkl mnopq rst') - r.input ('Escape') - r.input ('"0"') - r.input ('"d"') - r.input ('"w"') + r._set_line (u'abc de fghi jkl mnopq rst') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"d"') + r.input (u'"w"') self.assertEqual (0, r.line_cursor) - self.assertEqual (r.line, 'de fghi jkl mnopq rst') - r.input ('"d"') - r.input ('"2"') - r.input ('"w"') + self.assertEqual (r.line, u'de fghi jkl mnopq rst') + r.input (u'"d"') + r.input (u'"2"') + r.input (u'"w"') self.assertEqual (0, r.line_cursor) - self.assertEqual (r.line, 'jkl mnopq rst') - r.input ('"2"') - r.input ('"d"') - r.input ('"w"') + self.assertEqual (r.line, u'jkl mnopq rst') + r.input (u'"2"') + r.input (u'"d"') + r.input (u'"w"') self.assertEqual (0, r.line_cursor) - self.assertEqual (r.line, 'rst') + self.assertEqual (r.line, u'rst') def test_delete_word_two_multipliers (self): r = ViModeTest () - r._set_line ('abc de fghi jkl mnopq rst uv wx yz') - r.input ('Escape') - r.input ('"0w"') - r.input ('"2d3w"') + r._set_line (u'abc de fghi jkl mnopq rst uv wx yz') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"2d3w"') self.assertEqual (4, r.line_cursor) - self.assertEqual (r.line, 'abc wx yz') + self.assertEqual (r.line, u'abc wx yz') def test_delete_find_char_forward_two_multipliers (self): r = ViModeTest () - r._set_line ('0123456789012345678901234567890123456789012345678901234567890123456789') - r.input ('Escape') - r.input ('"0"') - r.input ('"2d3f4"') - self.assertEqual (r.line, '567890123456789') + r._set_line (u'0123456789012345678901234567890123456789012345678901234567890123456789') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2d3f4"') + self.assertEqual (r.line, u'567890123456789') def test_delete_end_of_line (self): r = ViModeTest () - r._set_line ('abc de fghi jkl mnopq rst uv wx yz') - r.input ('Escape') - r.input ('"0w"') - r.input ('"D"') - self.assertEqual (r.line, 'abc ') + r._set_line (u'abc de fghi jkl mnopq rst uv wx yz') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"D"') + self.assertEqual (r.line, u'abc ') def test_two_lines (self): r = ViModeTest () - r.input ('"abcdef"') - self.assertEqual (r.line, 'abcdef') - r.input ('Escape') - r.input ('"0iqq"') - self.assertEqual (r.line, 'qqabcdef') - r.input ('Return') - self.assertEqual (r.line, '') - r.input ('"xyz"') - self.assertEqual (r.line, 'xyz') + r.input (u'"abcdef"') + self.assertEqual (r.line, u'abcdef') + r.input (u'Escape') + r.input (u'"0iqq"') + self.assertEqual (r.line, u'qqabcdef') + r.input (u'Return') + self.assertEqual (r.line, u'') + r.input (u'"xyz"') + self.assertEqual (r.line, u'xyz') def test_delete_word_short_to_end_of_line (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"03dw"') - self.assertEqual ('', r.line) - r._set_line ('abc def ghi ') - r.input ('Escape') - r.input ('"03dw"') - self.assertEqual ('', r.line) + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"03dw"') + self.assertEqual (u'', r.line) + r._set_line (u'abc def ghi ') + r.input (u'Escape') + r.input (u'"03dw"') + self.assertEqual (u'', r.line) def test_delete_word_long_to_end_of_line (self): r = ViModeTest () - r._set_line ('a.c d.f g.i') - r.input ('Escape') - r.input ('"03dW"') - self.assertEqual ('', r.line) - r._set_line ('a.c d.f g.i ') - r.input ('Escape') - r.input ('"03dW"') - self.assertEqual ('', r.line) + r._set_line (u'a.c d.f g.i') + r.input (u'Escape') + r.input (u'"03dW"') + self.assertEqual (u'', r.line) + r._set_line (u'a.c d.f g.i ') + r.input (u'Escape') + r.input (u'"03dW"') + self.assertEqual (u'', r.line) def test_delete_end_short_to_end_of_line (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"03de"') - self.assertEqual ('', r.line) - r._set_line ('abc def ghi ') - r.input ('Escape') - r.input ('"03de"') - self.assertEqual (' ', r.line) + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"03de"') + self.assertEqual (u'', r.line) + r._set_line (u'abc def ghi ') + r.input (u'Escape') + r.input (u'"03de"') + self.assertEqual (u' ', r.line) def test_delete_end_long_to_end_of_line (self): r = ViModeTest () - r._set_line ('a.c d.f g.i') - r.input ('Escape') - r.input ('"03dE"') - self.assertEqual ('', r.line) - r._set_line ('a.c d.f g.i ') - r.input ('Escape') - r.input ('"03dE"') - self.assertEqual (' ', r.line) + r._set_line (u'a.c d.f g.i') + r.input (u'Escape') + r.input (u'"03dE"') + self.assertEqual (u'', r.line) + r._set_line (u'a.c d.f g.i ') + r.input (u'Escape') + r.input (u'"03dE"') + self.assertEqual (u' ', r.line) def test_delete_back_short_to_begining_of_line (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"$3db"') - self.assertEqual ('i', r.line) - r._set_line ('abc def ghi ') - r.input ('Escape') - r.input ('"$3db"') - self.assertEqual (' ', r.line) + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"$3db"') + self.assertEqual (u'i', r.line) + r._set_line (u'abc def ghi ') + r.input (u'Escape') + r.input (u'"$3db"') + self.assertEqual (u' ', r.line) def test_delete_back_long_to_begining_of_line (self): r = ViModeTest () - r._set_line ('a.c d.f g.i') - r.input ('Escape') - r.input ('"$3dB"') - self.assertEqual ('i', r.line) - r._set_line ('a.c d.f g.i ') - r.input ('Escape') - r.input ('"$3dB"') - self.assertEqual (' ', r.line) + r._set_line (u'a.c d.f g.i') + r.input (u'Escape') + r.input (u'"$3dB"') + self.assertEqual (u'i', r.line) + r._set_line (u'a.c d.f g.i ') + r.input (u'Escape') + r.input (u'"$3dB"') + self.assertEqual (u' ', r.line) def test_delete_dollar (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0ld$"') - self.assertEqual (r.line, 'a') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0ld$"') + self.assertEqual (r.line, u'a') self.assertEqual (r.line_cursor, 0) def test_motion_left (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (10, r.line_cursor) - r.input ('"h"') + r.input (u'"h"') self.assertEqual (9, r.line_cursor) - r.input ('"2h"') + r.input (u'"2h"') self.assertEqual (7, r.line_cursor) - r.input ('"2d3h"') + r.input (u'"2d3h"') self.assertEqual (1, r.line_cursor) - self.assertEqual ('a ghi', r.line) - r.input ('"4dh"') + self.assertEqual (u'a ghi', r.line) + r.input (u'"4dh"') self.assertEqual (0, r.line_cursor) - self.assertEqual (' ghi', r.line) + self.assertEqual (u' ghi', r.line) def test_motion_right (self): r = ViModeTest () - r.input ('Escape') - self.assertEqual (r.line, '') + r.input (u'Escape') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) - r.input ('"a"') - self.assertEqual (r.line, '') + r.input (u'"a"') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) - r.input ('"abc"') - self.assertEqual (r.line, 'abc') + r.input (u'"abc"') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 3) - r.input ('Escape') - self.assertEqual (r.line, 'abc') + r.input (u'Escape') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 2) - r.input ('"l"') - self.assertEqual (r.line, 'abc') + r.input (u'"l"') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 2) - r.input ('Left') - self.assertEqual (r.line, 'abc') + r.input (u'Left') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 1) - r.input ('"l"') - self.assertEqual (r.line, 'abc') + r.input (u'"l"') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 2) - r.input ('"l"') - self.assertEqual (r.line, 'abc') + r.input (u'"l"') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 2) def test_motion_right_delete (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0"') self.assertEqual (0, r.line_cursor) - r.input ('"l"') + r.input (u'"l"') self.assertEqual (1, r.line_cursor) - r.input ('"2l"') + r.input (u'"2l"') self.assertEqual (3, r.line_cursor) - r.input ('"2d3l"') + r.input (u'"2d3l"') self.assertEqual (3, r.line_cursor) - self.assertEqual ('abchi', r.line) - r.input ('"4dl"') + self.assertEqual (u'abchi', r.line) + r.input (u'"4dl"') self.assertEqual (2, r.line_cursor) - self.assertEqual ('abc', r.line) + self.assertEqual (u'abc', r.line) def test_backspace_motion (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (10, r.line_cursor) - r.input ('BackSpace') + r.input (u'BackSpace') self.assertEqual (9, r.line_cursor) - r.input ('"2"') - r.input ('BackSpace') + r.input (u'"2"') + r.input (u'BackSpace') self.assertEqual (7, r.line_cursor) - r.input ('"2d3"') - r.input ('BackSpace') + r.input (u'"2d3"') + r.input (u'BackSpace') self.assertEqual (1, r.line_cursor) - self.assertEqual ('a ghi', r.line) - r.input ('"4d"') - r.input ('BackSpace') + self.assertEqual (u'a ghi', r.line) + r.input (u'"4d"') + r.input (u'BackSpace') self.assertEqual (0, r.line_cursor) - self.assertEqual (' ghi', r.line) + self.assertEqual (u' ghi', r.line) def test_backspace_insert (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"$"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"$"') self.assertEqual (10, r.line_cursor) - r.input ('"i"') + r.input (u'"i"') self.assertEqual (10, r.line_cursor) - r.input ('BackSpace') + r.input (u'BackSpace') self.assertEqual (9, r.line_cursor) - self.assertEqual ('abc def gi', r.line) + self.assertEqual (u'abc def gi', r.line) def test_insert_lower_i (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0w"') - r.input ('"i"') - r.input ('"zz"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"i"') + r.input (u'"zz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'abc zzdef ghi') - r.input ('Escape') - r.input ('"w"') - r.input ('"2iyy"') - r.input ('Escape') - self.assertEqual (r.line, 'abc zzdef yyyyghi') + self.assertEqual (r.line, u'abc zzdef ghi') + r.input (u'Escape') + r.input (u'"w"') + r.input (u'"2iyy"') + r.input (u'Escape') + self.assertEqual (r.line, u'abc zzdef yyyyghi') def test_insert_upper_i (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0w"') - r.input ('"I"') - r.input ('"zz"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"I"') + r.input (u'"zz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zzabc def ghi') - r.input ('Escape') - r.input ('"w"') - r.input ('"2Iyy"') - r.input ('Escape') - self.assertEqual (r.line, 'yyyyzzabc def ghi') + self.assertEqual (r.line, u'zzabc def ghi') + r.input (u'Escape') + r.input (u'"w"') + r.input (u'"2Iyy"') + r.input (u'Escape') + self.assertEqual (r.line, u'yyyyzzabc def ghi') def test_append_lower_a (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0"') - r.input ('"a"') - r.input ('"zz"') - self.assertEqual (r.line, 'azzbc def ghi') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"a"') + r.input (u'"zz"') + self.assertEqual (r.line, u'azzbc def ghi') self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') - r.input ('"w"') - r.input ('"2ayy"') - r.input ('Escape') - self.assertEqual (r.line, 'azzbc dyyyyef ghi') + r.input (u'Escape') + r.input (u'"w"') + r.input (u'"2ayy"') + r.input (u'Escape') + self.assertEqual (r.line, u'azzbc dyyyyef ghi') def test_append_upper_a_simple (self): r = ViModeTest () - r._set_line ('') - r.input ('Escape') - r.input ('"2A"') - r.input ('"jj"') - r.input ('Escape') - self.assertEqual (r.line, 'jjjj') + r._set_line (u'') + r.input (u'Escape') + r.input (u'"2A"') + r.input (u'"jj"') + r.input (u'Escape') + self.assertEqual (r.line, u'jjjj') self.assert_ (not r.vi_is_insert_mode) def test_append_upper_a (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0"') - r.input ('"A"') - r.input ('"zz"') - self.assertEqual (r.line, 'abc def ghizz') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"A"') + r.input (u'"zz"') + self.assertEqual (r.line, u'abc def ghizz') self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') - r.input ('"0w"') - r.input ('"2Ayy"') - r.input ('Escape') - self.assertEqual (r.line, 'abc def ghizzyyyy') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"2Ayy"') + r.input (u'Escape') + self.assertEqual (r.line, u'abc def ghizzyyyy') def test_delete_lower_x (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0w"') - r.input ('"x"') - self.assertEqual (r.line, 'abc ef') - r.input ('"4x"') - self.assertEqual (r.line, 'abc ') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"x"') + self.assertEqual (r.line, u'abc ef') + r.input (u'"4x"') + self.assertEqual (r.line, u'abc ') self.assertEqual (r.line_cursor, 3) - r.input ('"x"') - self.assertEqual (r.line, 'abc') + r.input (u'"x"') + self.assertEqual (r.line, u'abc') self.assertEqual (r.line_cursor, 2) - r.input ('"x"') - self.assertEqual (r.line, 'ab') + r.input (u'"x"') + self.assertEqual (r.line, u'ab') self.assertEqual (r.line_cursor, 1) - r.input ('"x"') - self.assertEqual (r.line, 'a') + r.input (u'"x"') + self.assertEqual (r.line, u'a') self.assertEqual (r.line_cursor, 0) - r.input ('"x"') - self.assertEqual (r.line, '') + r.input (u'"x"') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) - r.input ('"x"') - self.assertEqual (r.line, '') + r.input (u'"x"') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) def test_delete_upper_x (self): r = ViModeTest () - r._set_line ('abc def') + r._set_line (u'abc def') self.assertEqual (r.line_cursor, 7) - r.input ('Escape') + r.input (u'Escape') self.assertEqual (r.line_cursor, 6) - r.input ('"$"') + r.input (u'"$"') self.assertEqual (r.line_cursor, 6) - r.input ('"X"') - self.assertEqual (r.line, 'abc df') + r.input (u'"X"') + self.assertEqual (r.line, u'abc df') self.assertEqual (r.line_cursor, 5) - r.input ('"4X"') - self.assertEqual (r.line, 'af') + r.input (u'"4X"') + self.assertEqual (r.line, u'af') self.assertEqual (r.line_cursor, 1) - r.input ('"2X"') - self.assertEqual (r.line, 'f') + r.input (u'"2X"') + self.assertEqual (r.line, u'f') self.assertEqual (r.line_cursor, 0) - r.input ('"X"') - self.assertEqual (r.line, 'f') + r.input (u'"X"') + self.assertEqual (r.line, u'f') self.assertEqual (r.line_cursor, 0) def test_substitute_lower_s (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0"') - r.input ('"s"') - r.input ('"qq"') - r.input ('Escape') - self.assertEqual (r.line, 'qqbc def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"s"') + r.input (u'"qq"') + r.input (u'Escape') + self.assertEqual (r.line, u'qqbc def') self.assertEqual (r.line_cursor, 1) - r.input ('"3s"') - r.input ('"yyy"') - r.input ('Escape') - self.assertEqual (r.line, 'qyyy def') + r.input (u'"3s"') + r.input (u'"yyy"') + r.input (u'Escape') + self.assertEqual (r.line, u'qyyy def') self.assertEqual (r.line_cursor, 3) - r.input ('"w"') - r.input ('"5"') - r.input ('"s"') - r.input ('"zz"') - r.input ('Escape') - self.assertEqual (r.line, 'qyyy zz') + r.input (u'"w"') + r.input (u'"5"') + r.input (u'"s"') + r.input (u'"zz"') + r.input (u'Escape') + self.assertEqual (r.line, u'qyyy zz') self.assertEqual (r.line_cursor, 6) def test_change_to_end_of_line (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0w"') - r.input ('"C"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"C"') self.assert_ (r.vi_is_insert_mode) - r.input ('"123"') - self.assertEqual (r.line, 'abc 123') - r.input ('Escape') + r.input (u'"123"') + self.assertEqual (r.line, u'abc 123') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) def test_change_whole_line (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0w"') - r.input ('"S"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"S"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, '') - r.input ('"123"') - self.assertEqual (r.line, '123') - r.input ('Escape') + self.assertEqual (r.line, u'') + r.input (u'"123"') + self.assertEqual (r.line, u'123') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) def test_change_word_short (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0cwzzz"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0cwzzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zzz def ghi') + self.assertEqual (r.line, u'zzz def ghi') self.assertEqual (r.line_cursor, 3) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 2) - r.input ('"w"') + r.input (u'"w"') self.assertEqual (r.line_cursor, 4) - r.input ('"2cwyyy"') - self.assertEqual (r.line, 'zzz yyy') - r.input ('Escape') - self.assertEqual (r.line, 'zzz yyy') + r.input (u'"2cwyyy"') + self.assertEqual (r.line, u'zzz yyy') + r.input (u'Escape') + self.assertEqual (r.line, u'zzz yyy') def test_change_word_long (self): r = ViModeTest () - r._set_line ('abc.def ghi.jkl mno.pqr') - r.input ('Escape') - r.input ('"0cWss"') - self.assertEqual (r.line, 'ss ghi.jkl mno.pqr') + r._set_line (u'abc.def ghi.jkl mno.pqr') + r.input (u'Escape') + r.input (u'"0cWss"') + self.assertEqual (r.line, u'ss ghi.jkl mno.pqr') self.assert_ (r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 2) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 1) - r.input ('"w2."') - self.assertEqual (r.line, 'ss ss') + r.input (u'"w2."') + self.assertEqual (r.line, u'ss ss') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 4) def test_change_end_short (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0cezzz"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0cezzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zzz def ghi') + self.assertEqual (r.line, u'zzz def ghi') self.assertEqual (r.line_cursor, 3) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 2) - r.input ('"w2."') - self.assertEqual (r.line, 'zzz zzz') + r.input (u'"w2."') + self.assertEqual (r.line, u'zzz zzz') def test_change_end_long (self): r = ViModeTest () - r._set_line ('abc.def ghi jkl.mno pqr stu.vwx') - r.input ('Escape') - r.input ('"02cEzz"') + r._set_line (u'abc.def ghi jkl.mno pqr stu.vwx') + r.input (u'Escape') + r.input (u'"02cEzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zz jkl.mno pqr stu.vwx') + self.assertEqual (r.line, u'zz jkl.mno pqr stu.vwx') self.assertEqual (r.line_cursor, 2) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 1) - r.input ('"w2."') - self.assertEqual (r.line, 'zz zz stu.vwx') + r.input (u'"w2."') + self.assertEqual (r.line, u'zz zz stu.vwx') self.assertEqual (r.line_cursor, 5) def test_change_back_short (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"$cbzz"') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"$cbzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'abc def zzi') + self.assertEqual (r.line, u'abc def zzi') self.assertEqual (r.line_cursor, 10) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 9) - r.input ('"b2."') - self.assertEqual (r.line, 'zzzzi') + r.input (u'"b2."') + self.assertEqual (r.line, u'zzzzi') self.assertEqual (r.line_cursor, 2) def test_change_back_long (self): r = ViModeTest () - r._set_line ('abc.def ghi jkl.mno pqr stu.vwx') - r.input ('Escape') - r.input ('"$2cBzz"') + r._set_line (u'abc.def ghi jkl.mno pqr stu.vwx') + r.input (u'Escape') + r.input (u'"$2cBzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'abc.def ghi jkl.mno zzx') + self.assertEqual (r.line, u'abc.def ghi jkl.mno zzx') self.assertEqual (r.line_cursor, 22) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 21) - r.input ('"5."') - self.assertEqual (r.line, 'zzzx') + r.input (u'"5."') + self.assertEqual (r.line, u'zzzx') self.assertEqual (r.line_cursor, 2) self.assert_ (not r.vi_is_insert_mode) def test_change_find_lower (self): r = ViModeTest () - r._set_line ('aa bb cc dd ee aa bb cc dd ee') - r.input ('Escape') - r.input ('"0cfbzz"') + r._set_line (u'aa bb cc dd ee aa bb cc dd ee') + r.input (u'Escape') + r.input (u'"0cfbzz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zzb cc dd ee aa bb cc dd ee') + self.assertEqual (r.line, u'zzb cc dd ee aa bb cc dd ee') self.assertEqual (r.line_cursor, 2) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 1) - r.input ('"c2fcyy"') - self.assertEqual (r.line, 'zyy dd ee aa bb cc dd ee') - r.input ('Escape') - r.input ('"."') - self.assertEqual (r.line, 'zyyy dd ee') + r.input (u'"c2fcyy"') + self.assertEqual (r.line, u'zyy dd ee aa bb cc dd ee') + r.input (u'Escape') + r.input (u'"."') + self.assertEqual (r.line, u'zyyy dd ee') def test_change_find_upper (self): r = ViModeTest () - r._set_line ('aa bb cc aa bb cc') - r.input ('Escape') - r.input ('"$2c2Fazz"') + r._set_line (u'aa bb cc aa bb cc') + r.input (u'Escape') + r.input (u'"$2c2Fazz"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'zzc') + self.assertEqual (r.line, u'zzc') self.assertEqual (r.line_cursor, 2) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 1) - r.input ('"."') - self.assertEqual (r.line, 'zzc') + r.input (u'"."') + self.assertEqual (r.line, u'zzc') def test_change_to_lower (self): r = ViModeTest () - r._set_line ('aa bb cc aa bb cc aa bb cc') - r.input ('Escape') - r.input ('"02c2ta"') + r._set_line (u'aa bb cc aa bb cc aa bb cc') + r.input (u'Escape') + r.input (u'"02c2ta"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'aa bb cc') + self.assertEqual (r.line, u'aa bb cc') self.assertEqual (r.line_cursor, 0) - r.input ('"zz "') - self.assertEqual (r.line, 'zz aa bb cc') + r.input (u'"zz "') + self.assertEqual (r.line, u'zz aa bb cc') self.assertEqual (r.line_cursor, 3) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 2) def test_change_to_upper (self): r = ViModeTest () - r._set_line ('aa bb cc aa bb cc aa bb cc') - r.input ('Escape') - r.input ('"$2c2Ta"') + r._set_line (u'aa bb cc aa bb cc aa bb cc') + r.input (u'Escape') + r.input (u'"$2c2Ta"') self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.line, 'aa bb cc ac') + self.assertEqual (r.line, u'aa bb cc ac') self.assertEqual (r.line_cursor, 10) - r.input ('"zz"') - self.assertEqual (r.line, 'aa bb cc azzc') + r.input (u'"zz"') + self.assertEqual (r.line, u'aa bb cc azzc') self.assertEqual (r.line_cursor, 12) - r.input ('Escape') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 11) - r.input ('"3."') - self.assertEqual (r.line, 'azzzc') + r.input (u'"3."') + self.assertEqual (r.line, u'azzzc') # The following fails but it does not seem that important # self.assertEqual (r.line_cursor, 2) self.assert_ (not r.vi_is_insert_mode) def test_pos_matching (self): - self.assertEqual (6, vi_pos_matching ('aa (bb)')) - self.assertEqual (6, vi_pos_matching ('aa (bb)', 3)) - self.assertEqual (3, vi_pos_matching ('aa (bb)', 6)) - self.assertEqual (11, vi_pos_matching ('aa (bb (cc))')) - self.assertEqual (3, vi_pos_matching ('aa (bb (cc))', 11)) - self.assertEqual (10, vi_pos_matching ('aa (bb (cc))', 4)) - self.assertEqual (7, vi_pos_matching ('aa (bb (cc))', 10)) - self.assertEqual (7, vi_pos_matching ('aa (bb (cc))', 8)) - self.assertEqual (3, vi_pos_matching ('aa (bb (cc) dd)', 12)) - self.assertEqual (3, vi_pos_matching ('aa (bb (cc) dd)', 14)) - self.assertEqual (-1, vi_pos_matching ('aa ((bb (cc) dd)', 3)) - self.assertEqual (-1, vi_pos_matching ('aa (bb (cc) dd) ee)', 16)) - self.assertEqual (-1, vi_pos_matching ('aa (bb (cc) dd) ee)', 18)) - self.assertEqual (6, vi_pos_matching ('aa ')) - self.assertEqual (11, vi_pos_matching ('aa >')) - self.assertEqual (10, vi_pos_matching ('aa >', 4)) - self.assertEqual (6, vi_pos_matching ('aa {bb}')) - self.assertEqual (11, vi_pos_matching ('aa {bb {cc}}')) - self.assertEqual (10, vi_pos_matching ('aa {bb {cc}}', 4)) - self.assertEqual (6, vi_pos_matching ('aa [bb]')) - self.assertEqual (11, vi_pos_matching ('aa [bb [cc]]')) - self.assertEqual (10, vi_pos_matching ('aa [bb [cc]]', 4)) + self.assertEqual (6, vi_pos_matching (u'aa (bb)')) + self.assertEqual (6, vi_pos_matching (u'aa (bb)', 3)) + self.assertEqual (3, vi_pos_matching (u'aa (bb)', 6)) + self.assertEqual (11, vi_pos_matching (u'aa (bb (cc))')) + self.assertEqual (3, vi_pos_matching (u'aa (bb (cc))', 11)) + self.assertEqual (10, vi_pos_matching (u'aa (bb (cc))', 4)) + self.assertEqual (7, vi_pos_matching (u'aa (bb (cc))', 10)) + self.assertEqual (7, vi_pos_matching (u'aa (bb (cc))', 8)) + self.assertEqual (3, vi_pos_matching (u'aa (bb (cc) dd)', 12)) + self.assertEqual (3, vi_pos_matching (u'aa (bb (cc) dd)', 14)) + self.assertEqual (-1, vi_pos_matching (u'aa ((bb (cc) dd)', 3)) + self.assertEqual (-1, vi_pos_matching (u'aa (bb (cc) dd) ee)', 16)) + self.assertEqual (-1, vi_pos_matching (u'aa (bb (cc) dd) ee)', 18)) + self.assertEqual (6, vi_pos_matching (u'aa ')) + self.assertEqual (11, vi_pos_matching (u'aa >')) + self.assertEqual (10, vi_pos_matching (u'aa >', 4)) + self.assertEqual (6, vi_pos_matching (u'aa {bb}')) + self.assertEqual (11, vi_pos_matching (u'aa {bb {cc}}')) + self.assertEqual (10, vi_pos_matching (u'aa {bb {cc}}', 4)) + self.assertEqual (6, vi_pos_matching (u'aa [bb]')) + self.assertEqual (11, vi_pos_matching (u'aa [bb [cc]]')) + self.assertEqual (10, vi_pos_matching (u'aa [bb [cc]]', 4)) def test_matching_paren_forward (self): r = ViModeTest () - r._set_line ('abc (def (ghi)) jkl') - r.input ('Escape') - r.input ('"0w"') - r.input ('"d"') - r.input ('"%"') - self.assertEqual (r.line, 'abc jkl') + r._set_line (u'abc (def (ghi)) jkl') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"d"') + r.input (u'"%"') + self.assertEqual (r.line, u'abc jkl') self.assertEqual (r.line_cursor, 4) def test_matching_paren_backward (self): r = ViModeTest () - r._set_line ('abc (def (ghi)) jkl') - r.input ('Escape') - r.input ('"0w"') - r.input ('"%"') + r._set_line (u'abc (def (ghi)) jkl') + r.input (u'Escape') + r.input (u'"0w"') + r.input (u'"%"') self.assertEqual (r.line_cursor, 14) - r.input ('"d"') - r.input ('"%"') - self.assertEqual (r.line, 'abc jkl') + r.input (u'"d"') + r.input (u'"%"') + self.assertEqual (r.line, u'abc jkl') self.assertEqual (r.line_cursor, 4) def test_yank_and_put (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0"') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0"') self.assert_ (not r.vi_is_insert_mode) - r.input ('"yw"') + r.input (u'"yw"') self.assert_ (not r.vi_is_insert_mode) - self.assertEqual (r.line, 'abc def') + self.assertEqual (r.line, u'abc def') self.assertEqual (r.line_cursor, 0) - r.input ('"P"') - self.assertEqual (r.line, 'abc abc def') + r.input (u'"P"') + self.assertEqual (r.line, u'abc abc def') self.assertEqual (r.line_cursor, 3) - r.input ('"p"') - self.assertEqual (r.line, 'abc abc abc def') + r.input (u'"p"') + self.assertEqual (r.line, u'abc abc abc def') self.assertEqual (r.line_cursor, 7) def test_put_multiple (self): r = ViModeTest () - r._set_line ('001122') - r.input ('Escape') - r.input ('"0"') - r.input ('"y3l"') + r._set_line (u'001122') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"y3l"') self.assert_ (not r.vi_is_insert_mode) self.assertEqual (r.line_cursor, 0) - r.input ('"2P"') - self.assertEqual (r.line, '001001001122') + r.input (u'"2P"') + self.assertEqual (r.line, u'001001001122') self.assertEqual (r.line_cursor, 5) - r.input ('"f2"') - r.input ('"3p"') - self.assertEqual (r.line, '001001001120010010012') + r.input (u'"f2"') + r.input (u'"3p"') + self.assertEqual (r.line, u'001001001120010010012') self.assertEqual (r.line_cursor, 19) def test_put_undo (self): r = ViModeTest () - r._set_line ('aaa b ccc') - r.input ('Escape') - r.input ('"0ywwp"') - self.assertEqual (r.line, 'aaa baaa ccc') - r.input ('"u"') - self.assertEqual (r.line, 'aaa b ccc') - r.input ('"P"') - self.assertEqual (r.line, 'aaa aaa b ccc') - r.input ('"u"') - self.assertEqual (r.line, 'aaa b ccc') + r._set_line (u'aaa b ccc') + r.input (u'Escape') + r.input (u'"0ywwp"') + self.assertEqual (r.line, u'aaa baaa ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa b ccc') + r.input (u'"P"') + self.assertEqual (r.line, u'aaa aaa b ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa b ccc') def test_x_and_p (self): r = ViModeTest () - r._set_line ('abc') - r.input ('Escape') - r.input ('"0xp"') - self.assertEqual (r.line, 'bac') + r._set_line (u'abc') + r.input (u'Escape') + r.input (u'"0xp"') + self.assertEqual (r.line, u'bac') def test_delete_and_put (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0dwep"') - self.assertEqual (r.line, 'defabc ') - r.input ('"0xp"') - self.assertEqual (r.line, 'edfabc ') - r.input ('"p"') - self.assertEqual (r.line, 'eddfabc ') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0dwep"') + self.assertEqual (r.line, u'defabc ') + r.input (u'"0xp"') + self.assertEqual (r.line, u'edfabc ') + r.input (u'"p"') + self.assertEqual (r.line, u'eddfabc ') def test_dot_simple (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0x"') - self.assertEqual (r.line, 'bc def') - r.input ('"."') - self.assertEqual (r.line, 'c def') - r.input ('"3."') - self.assertEqual (r.line, 'ef') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0x"') + self.assertEqual (r.line, u'bc def') + r.input (u'"."') + self.assertEqual (r.line, u'c def') + r.input (u'"3."') + self.assertEqual (r.line, u'ef') def test_dot_movement_not_repeated_one (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0x"') - self.assertEqual (r.line, 'bc def') - r.input ('"$."') - self.assertEqual (r.line, 'bc de') - r.input ('"0."') - self.assertEqual (r.line, 'c de') - r.input ('"$."') - self.assertEqual (r.line, 'c d') - r.input ('"^."') - self.assertEqual (r.line, ' d') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0x"') + self.assertEqual (r.line, u'bc def') + r.input (u'"$."') + self.assertEqual (r.line, u'bc de') + r.input (u'"0."') + self.assertEqual (r.line, u'c de') + r.input (u'"$."') + self.assertEqual (r.line, u'c d') + r.input (u'"^."') + self.assertEqual (r.line, u' d') def test_dot_movement_not_repeated_two (self): r = ViModeTest () - r._set_line ('abc def ghi jkl mno pqr') - r.input ('Escape') - r.input ('"0x"') - self.assertEqual (r.line, 'bc def ghi jkl mno pqr') - r.input ('"w."') - self.assertEqual (r.line, 'bc ef ghi jkl mno pqr') - r.input ('"fg."') - self.assertEqual (r.line, 'bc ef hi jkl mno pqr') - r.input ('"2b."') - self.assertEqual (r.line, 'c ef hi jkl mno pqr') - r.input ('"3e."') - self.assertEqual (r.line, 'c ef hi jk mno pqr') - r.input ('"Fh."') - self.assertEqual (r.line, 'c ef i jk mno pqr') - r.input ('"tn."') - self.assertEqual (r.line, 'c ef i jk no pqr') - r.input ('"3h."') - self.assertEqual (r.line, 'c ef i k no pqr') - r.input ('"5l."') - self.assertEqual (r.line, 'c ef i k no qr') + r._set_line (u'abc def ghi jkl mno pqr') + r.input (u'Escape') + r.input (u'"0x"') + self.assertEqual (r.line, u'bc def ghi jkl mno pqr') + r.input (u'"w."') + self.assertEqual (r.line, u'bc ef ghi jkl mno pqr') + r.input (u'"fg."') + self.assertEqual (r.line, u'bc ef hi jkl mno pqr') + r.input (u'"2b."') + self.assertEqual (r.line, u'c ef hi jkl mno pqr') + r.input (u'"3e."') + self.assertEqual (r.line, u'c ef hi jk mno pqr') + r.input (u'"Fh."') + self.assertEqual (r.line, u'c ef i jk mno pqr') + r.input (u'"tn."') + self.assertEqual (r.line, u'c ef i jk no pqr') + r.input (u'"3h."') + self.assertEqual (r.line, u'c ef i k no pqr') + r.input (u'"5l."') + self.assertEqual (r.line, u'c ef i k no qr') def test_dot_insert (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0"') - r.input ('"2izz "') - r.input ('Escape') - self.assertEqual (r.line, 'zz zz abc def') - r.input ('"2w."') - self.assertEqual (r.line, 'zz zz abc zz zz def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0"') + r.input (u'"2izz "') + r.input (u'Escape') + self.assertEqual (r.line, u'zz zz abc def') + r.input (u'"2w."') + self.assertEqual (r.line, u'zz zz abc zz zz def') def test_dot_delete_word (self): r = ViModeTest () - r._set_line ('0 1 2 3 4 5 6 7 8 9') - r.input ('Escape') - r.input ('"02dw"') - self.assertEqual (r.line, '2 3 4 5 6 7 8 9') - r.input ('"."') - self.assertEqual (r.line, '4 5 6 7 8 9') - r.input ('"1."') - self.assertEqual (r.line, '5 6 7 8 9') + r._set_line (u'0 1 2 3 4 5 6 7 8 9') + r.input (u'Escape') + r.input (u'"02dw"') + self.assertEqual (r.line, u'2 3 4 5 6 7 8 9') + r.input (u'"."') + self.assertEqual (r.line, u'4 5 6 7 8 9') + r.input (u'"1."') + self.assertEqual (r.line, u'5 6 7 8 9') def test_dot_override_multiplier (self): r = ViModeTest () - r._set_line ('ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab') - r.input ('Escape') - r.input ('"02d2fb"') - self.assertEqual (r.line, ' ab ab ab ab ab ab ab ab ab ab ab ab') - r.input ('"."') - self.assertEqual (r.line, ' ab ab ab ab ab ab ab ab') - r.input ('"3."') - self.assertEqual (r.line, ' ab ab ab ab ab') - r.input ('"."') - self.assertEqual (r.line, ' ab ab') + r._set_line (u'ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab') + r.input (u'Escape') + r.input (u'"02d2fb"') + self.assertEqual (r.line, u' ab ab ab ab ab ab ab ab ab ab ab ab') + r.input (u'"."') + self.assertEqual (r.line, u' ab ab ab ab ab ab ab ab') + r.input (u'"3."') + self.assertEqual (r.line, u' ab ab ab ab ab') + r.input (u'"."') + self.assertEqual (r.line, u' ab ab') def test_dot_yank_and_put (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0ywP"') - self.assertEqual (r.line, 'abc abc def') - r.input ('"."') - self.assertEqual (r.line, 'abcabc abc def') - r.input ('"p"') - self.assertEqual (r.line, 'abcabc abc abc def') - r.input ('"2."') - self.assertEqual (r.line, 'abcabc abc abc abc abc def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0ywP"') + self.assertEqual (r.line, u'abc abc def') + r.input (u'"."') + self.assertEqual (r.line, u'abcabc abc def') + r.input (u'"p"') + self.assertEqual (r.line, u'abcabc abc abc def') + r.input (u'"2."') + self.assertEqual (r.line, u'abcabc abc abc abc abc def') def test_dot_insert_begin (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"Izz "') - r.input ('Escape') - self.assertEqual (r.line, 'zz abc def') - r.input ('"."') - self.assertEqual (r.line, 'zz zz abc def') - r.input ('"2."') - self.assertEqual (r.line, 'zz zz zz zz abc def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"Izz "') + r.input (u'Escape') + self.assertEqual (r.line, u'zz abc def') + r.input (u'"."') + self.assertEqual (r.line, u'zz zz abc def') + r.input (u'"2."') + self.assertEqual (r.line, u'zz zz zz zz abc def') def test_dot_append_end (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"A yy"') - r.input ('Escape') - self.assertEqual (r.line, 'abc def yy') - r.input ('"."') - self.assertEqual (r.line, 'abc def yy yy') - r.input ('"2."') - self.assertEqual (r.line, 'abc def yy yy yy yy') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"A yy"') + r.input (u'Escape') + self.assertEqual (r.line, u'abc def yy') + r.input (u'"."') + self.assertEqual (r.line, u'abc def yy yy') + r.input (u'"2."') + self.assertEqual (r.line, u'abc def yy yy yy yy') def test_dot_insert_lower (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"b2izz "') - r.input ('Escape') - self.assertEqual (r.line, 'abc zz zz def') - r.input ('"3."') - self.assertEqual (r.line, 'abc zz zzzz zz zz def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"b2izz "') + r.input (u'Escape') + self.assertEqual (r.line, u'abc zz zz def') + r.input (u'"3."') + self.assertEqual (r.line, u'abc zz zzzz zz zz def') def test_dot_append_lower (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"0e2a zz"') - r.input ('Escape') - self.assertEqual (r.line, 'abc zz zz def') - r.input ('"1."') - self.assertEqual (r.line, 'abc zz zz zz def') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"0e2a zz"') + r.input (u'Escape') + self.assertEqual (r.line, u'abc zz zz def') + r.input (u'"1."') + self.assertEqual (r.line, u'abc zz zz zz def') def test_dot_substitute_lower (self): r = ViModeTest () - r._set_line ('abc def') - r.input ('Escape') - r.input ('"03sqq"') - r.input ('Escape') - self.assertEqual (r.line, 'qq def') - r.input ('"2."') - self.assertEqual (r.line, 'qqqdef') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"03sqq"') + r.input (u'Escape') + self.assertEqual (r.line, u'qq def') + r.input (u'"2."') + self.assertEqual (r.line, u'qqqdef') def test_undo (self): r = ViModeTest () - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"0wdw"') - self.assertEqual (r.line, 'abc ghi') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"0wdw"') + self.assertEqual (r.line, u'abc ghi') self.assertEqual (r.line_cursor, 4) - r.input ('"u"') - self.assertEqual (r.line, 'abc def ghi') + r.input (u'"u"') + self.assertEqual (r.line, u'abc def ghi') self.assertEqual (r.line_cursor, 4) def test_undo_line (self): r = ViModeTest () - r._set_line ('') - r.input ('"abc def ghi"') - r.input ('Escape') - r.input ('"0dwdw"') - self.assertEqual (r.line, 'ghi') - r.input ('"U"') - self.assertEqual (r.line, '') + r._set_line (u'') + r.input (u'"abc def ghi"') + r.input (u'Escape') + r.input (u'"0dwdw"') + self.assertEqual (r.line, u'ghi') + r.input (u'"U"') + self.assertEqual (r.line, u'') def test_undo_line_with_history (self): r = ViModeTest () - r.add_history ('abc 123') - r._set_line ('') - r.input ('"abc def ghi"') - r.input ('Escape') - r.input ('"0dwdw"') - self.assertEqual (r.line, 'ghi') - r.input ('"U"') - self.assertEqual (r.line, '') + r.add_history (u'abc 123') + r._set_line (u'') + r.input (u'"abc def ghi"') + r.input (u'Escape') + r.input (u'"0dwdw"') + self.assertEqual (r.line, u'ghi') + r.input (u'"U"') + self.assertEqual (r.line, u'') def test_history_no_match (self): r = ViModeTest () - r.add_history ('abc 123') - r.add_history ('def 456') - r.add_history ('ghi 789') - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"/"') - self.assertEqual (r.line, '/') + r.add_history (u'abc 123') + r.add_history (u'def 456') + r.add_history (u'ghi 789') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"/"') + self.assertEqual (r.line, u'/') self.assertEqual (r.line_cursor, 1) - r.input ('"zz"') - self.assertEqual (r.line, '/zz') + r.input (u'"zz"') + self.assertEqual (r.line, u'/zz') self.assertEqual (r.line_cursor, 3) self.assertEqual (r.console.bell_count, 0) - r.input ('Return') + r.input (u'Return') # TODO should bell be rung here? # self.assertEqual (r.console.bell_count, 1) - self.assertEqual (r.line, 'abc def ghi') + self.assertEqual (r.line, u'abc def ghi') self.assertEqual (r.line_cursor, 10) def test_history_found_match (self): r = ViModeTest () - r.add_history ('abc 123') - r.add_history ('def 456') - r.add_history ('ghi 789') - r._set_line ('abc def ghi') - r.input ('Escape') - r.input ('"/"') - self.assertEqual (r.line, '/') + r.add_history (u'abc 123') + r.add_history (u'def 456') + r.add_history (u'ghi 789') + r._set_line (u'abc def ghi') + r.input (u'Escape') + r.input (u'"/"') + self.assertEqual (r.line, u'/') self.assertEqual (r.line_cursor, 1) - r.input ('"de"') - self.assertEqual (r.line, '/de') + r.input (u'"de"') + self.assertEqual (r.line, u'/de') self.assertEqual (r.line_cursor, 3) - r.input ('Return') - self.assertEqual (r.line, 'def 456') + r.input (u'Return') + self.assertEqual (r.line, u'def 456') self.assertEqual (r.line_cursor, 0) def test_history_multi_match (self): r = ViModeTest () - r.add_history ('xyz 123') - r.add_history ('xyz 456') - r.add_history ('xyz 789') - r._set_line ('abc def') - r.input ('Escape') - r.input ('"/xyz"') - r.input ('Return') - self.assertEqual (r.line, 'xyz 789') - r.input ('"n"') - self.assertEqual (r.line, 'xyz 456') - r.input ('"n"') - self.assertEqual (r.line, 'xyz 123') + r.add_history (u'xyz 123') + r.add_history (u'xyz 456') + r.add_history (u'xyz 789') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"/xyz"') + r.input (u'Return') + self.assertEqual (r.line, u'xyz 789') + r.input (u'"n"') + self.assertEqual (r.line, u'xyz 456') + r.input (u'"n"') + self.assertEqual (r.line, u'xyz 123') self.assertEqual (r.console.bell_count, 0) - r.input ('"n"') + r.input (u'"n"') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 1) - self.assertEqual (r.line, 'xyz 123') - r.input ('"N"') - self.assertEqual (r.line, 'xyz 456') - r.input ('"N"') - self.assertEqual (r.line, 'xyz 789') + self.assertEqual (r.line, u'xyz 123') + r.input (u'"N"') + self.assertEqual (r.line, u'xyz 456') + r.input (u'"N"') + self.assertEqual (r.line, u'xyz 789') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 1) - r.input ('"N"') + r.input (u'"N"') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 2) - self.assertEqual (r.line, 'xyz 789') + self.assertEqual (r.line, u'xyz 789') def test_history_search_empty_string (self): r = ViModeTest () - r.add_history ('xyz 123') - r.add_history ('xyz 456') - r.add_history ('xyz 789') - r.input ('Escape') - r.input ('"/"') - r.input ('Return') - self.assertEqual (r.line, '') + r.add_history (u'xyz 123') + r.add_history (u'xyz 456') + r.add_history (u'xyz 789') + r.input (u'Escape') + r.input (u'"/"') + r.input (u'Return') + self.assertEqual (r.line, u'') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 1) - r.input ('"/"') - r.input ('Return') - self.assertEqual (r.line, '') + r.input (u'"/"') + r.input (u'Return') + self.assertEqual (r.line, u'') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 2) - r.input ('"/x"') - r.input ('Return') - self.assertEqual (r.line, 'xyz 789') - r.input ('"/"') - r.input ('Return') - self.assertEqual (r.line, 'xyz 456') + r.input (u'"/x"') + r.input (u'Return') + self.assertEqual (r.line, u'xyz 789') + r.input (u'"/"') + r.input (u'Return') + self.assertEqual (r.line, u'xyz 456') def test_history_search_again_after_return (self): r = ViModeTest () - r.add_history ('xyz 123') - r.add_history ('xyz 456') - r.add_history ('xyz 789') - r._set_line ('abc def') - r.input ('Escape') - r.input ('"/xyz"') - r.input ('Return') - self.assertEqual (r.line, 'xyz 789') - r.input ('"n"') - self.assertEqual (r.line, 'xyz 456') - r.input ('Return') - self.assertEqual (r.line, '') - r.input ('Escape') - r.input ('"n"') - self.assertEqual (r.line, 'xyz 123') - r.input ('Return') - r.input ('Escape') - r.input ('"N"') - self.assertEqual (r.line, 'xyz 456') + r.add_history (u'xyz 123') + r.add_history (u'xyz 456') + r.add_history (u'xyz 789') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"/xyz"') + r.input (u'Return') + self.assertEqual (r.line, u'xyz 789') + r.input (u'"n"') + self.assertEqual (r.line, u'xyz 456') + r.input (u'Return') + self.assertEqual (r.line, u'') + r.input (u'Escape') + r.input (u'"n"') + self.assertEqual (r.line, u'xyz 123') + r.input (u'Return') + r.input (u'Escape') + r.input (u'"N"') + self.assertEqual (r.line, u'xyz 456') def test_history_search_again_after_search_failed (self): r = ViModeTest () - r.add_history ('xyz 123') - r.add_history ('xyz 456') - r.add_history ('xyz 789') - r._set_line ('abc def') - r.input ('Escape') - r.input ('"/xyz"') - r.input ('Return') - self.assertEqual (r.line, 'xyz 789') - r.input ('"C"') - self.assertEqual (r.line, '') - r.input ('Escape') + r.add_history (u'xyz 123') + r.add_history (u'xyz 456') + r.add_history (u'xyz 789') + r._set_line (u'abc def') + r.input (u'Escape') + r.input (u'"/xyz"') + r.input (u'Return') + self.assertEqual (r.line, u'xyz 789') + r.input (u'"C"') + self.assertEqual (r.line, u'') + r.input (u'Escape') self.assertEqual (r.console.bell_count, 0) - r.input ('"/abc"') - r.input ('Return') + r.input (u'"/abc"') + r.input (u'Return') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 1) - self.assertEqual (r.line, '') - r.input ('Escape') - r.input ('"n"') - self.assertEqual (r.line, '') + self.assertEqual (r.line, u'') + r.input (u'Escape') + r.input (u'"n"') + self.assertEqual (r.line, u'') def test_history_search_and_backspace (self): r = ViModeTest () - r.add_history ('aaa') - r.add_history ('bbb') - r._set_line ('') - r.input ('Escape') - r.input ('"/aaz"') - self.assertEqual (r.line, '/aaz') - r.input ('BackSpace') - self.assertEqual (r.line, '/aa') - r.input ('Return') - self.assertEqual (r.line, 'aaa') - r.input ('Escape') - r.input ('"/z"') - r.input ('BackSpace') - r.input ('BackSpace') - self.assertEqual (r.line, '') - r.input ('"j"') - self.assertEqual (r.line, 'bbb') - r.input ('"k"') - self.assertEqual (r.line, 'aaa') + r.add_history (u'aaa') + r.add_history (u'bbb') + r._set_line (u'') + r.input (u'Escape') + r.input (u'"/aaz"') + self.assertEqual (r.line, u'/aaz') + r.input (u'BackSpace') + self.assertEqual (r.line, u'/aa') + r.input (u'Return') + self.assertEqual (r.line, u'aaa') + r.input (u'Escape') + r.input (u'"/z"') + r.input (u'BackSpace') + r.input (u'BackSpace') + self.assertEqual (r.line, u'') + r.input (u'"j"') + self.assertEqual (r.line, u'bbb') + r.input (u'"k"') + self.assertEqual (r.line, u'aaa') def test_history_insert_mode (self): r = ViModeTest () - r.add_history ('aaa') - r.add_history ('bbb') - r.add_history ('ccc') - r.input ('Up') - self.assertEqual (r.line, 'ccc') + r.add_history (u'aaa') + r.add_history (u'bbb') + r.add_history (u'ccc') + r.input (u'Up') + self.assertEqual (r.line, u'ccc') self.assert_ (r.vi_is_insert_mode) - r.input ('"z"') - self.assertEqual (r.line, 'cccz') - r.input ('Escape') + r.input (u'"z"') + self.assertEqual (r.line, u'cccz') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) - r.input ('Up') - self.assertEqual (r.line, 'bbb') + r.input (u'Up') + self.assertEqual (r.line, u'bbb') self.assert_ (r.vi_is_insert_mode) - r.input ('"z"') - self.assertEqual (r.line, 'bbbz') - r.input ('Escape') - r.input ('"k"') - self.assertEqual (r.line, 'aaa') + r.input (u'"z"') + self.assertEqual (r.line, u'bbbz') + r.input (u'Escape') + r.input (u'"k"') + self.assertEqual (r.line, u'aaa') self.assert_ (not r.vi_is_insert_mode) - r.input ('"iz"') - self.assertEqual (r.line, 'zaaa') - r.input ('Down') - self.assertEqual (r.line, 'bbb') + r.input (u'"iz"') + self.assertEqual (r.line, u'zaaa') + r.input (u'Down') + self.assertEqual (r.line, u'bbb') self.assert_ (r.vi_is_insert_mode) - r.input ('"y"') - self.assertEqual (r.line, 'bbby') - r.input ('Escape') - r.input ('"j"') - self.assertEqual (r.line, 'ccc') + r.input (u'"y"') + self.assertEqual (r.line, u'bbby') + r.input (u'Escape') + r.input (u'"j"') + self.assertEqual (r.line, u'ccc') self.assert_ (not r.vi_is_insert_mode) - r.input ('"iy"') - self.assertEqual (r.line, 'yccc') + r.input (u'"iy"') + self.assertEqual (r.line, u'yccc') self.assert_ (r.vi_is_insert_mode) def test_history_cursor_arrow (self): r = ViModeTest () self.assertEqual (r._history.history_cursor, 0) - r.add_history ('aaa') + r.add_history (u'aaa') self.assertEqual (r._history.history_cursor, 1) - r.add_history ('bbb') + r.add_history (u'bbb') self.assertEqual (r._history.history_cursor, 2) - self.assertEqual (r.line, '') - r.input ('Up') + self.assertEqual (r.line, u'') + r.input (u'Up') self.assertEqual (r._history.history_cursor, 1) - self.assertEqual (r.line, 'bbb') - r.input ('Up') + self.assertEqual (r.line, u'bbb') + r.input (u'Up') self.assertEqual (r._history.history_cursor, 0) - self.assertEqual (r.line, 'aaa') - r.input ('Down') + self.assertEqual (r.line, u'aaa') + r.input (u'Down') self.assertEqual (r._history.history_cursor, 1) - self.assertEqual (r.line, 'bbb') - r.input ('Down') + self.assertEqual (r.line, u'bbb') + r.input (u'Down') self.assertEqual (r._history.history_cursor, 2) - self.assertEqual (r.line, '') - r.input ('Up') + self.assertEqual (r.line, u'') + r.input (u'Up') self.assertEqual (r._history.history_cursor, 1) - self.assertEqual (r.line, 'bbb') + self.assertEqual (r.line, u'bbb') def test_history_control_n_and_p (self): r = ViModeTest () - r.add_history ('aa') - r.add_history ('bbb') - self.assertEqual (r.line, '') - r.input ('Control-p') - self.assertEqual (r.line, 'bbb') + r.add_history (u'aa') + r.add_history (u'bbb') + self.assertEqual (r.line, u'') + r.input (u'Control-p') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 3) self.assert_ (r.vi_is_insert_mode) - r.input ('Control-p') - self.assertEqual (r.line, 'aa') + r.input (u'Control-p') + self.assertEqual (r.line, u'aa') self.assertEqual (r.line_cursor, 2) self.assert_ (r.vi_is_insert_mode) - r.input ('Control-n') - self.assertEqual (r.line, 'bbb') + r.input (u'Control-n') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 3) self.assert_ (r.vi_is_insert_mode) - r.input ('Control-n') - self.assertEqual (r.line, '') + r.input (u'Control-n') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) self.assert_ (r.vi_is_insert_mode) - r.input ('Control-p') - self.assertEqual (r.line, 'bbb') + r.input (u'Control-p') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 3) self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') - self.assertEqual (r.line, 'bbb') + r.input (u'Escape') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 2) self.assert_ (not r.vi_is_insert_mode) - r.input ('Control-p') - self.assertEqual (r.line, 'aa') + r.input (u'Control-p') + self.assertEqual (r.line, u'aa') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('Control-n') - self.assertEqual (r.line, 'bbb') + r.input (u'Control-n') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('Control-n') - self.assertEqual (r.line, '') + r.input (u'Control-n') + self.assertEqual (r.line, u'') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('"/a"') - r.input ('Return') - self.assertEqual (r.line, 'aa') + r.input (u'"/a"') + r.input (u'Return') + self.assertEqual (r.line, u'aa') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('Control-n') - self.assertEqual (r.line, 'bbb') + r.input (u'Control-n') + self.assertEqual (r.line, u'bbb') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) def test_history_cursor_j_and_k (self): r = ViModeTest () - r.add_history ('aaa') - r.input ('Escape') - r.input ('"kiz"') - self.assertEqual (r.line, 'zaaa') - r.input ('Escape') - r.input ('"j"') - self.assertEqual (r.line, '') + r.add_history (u'aaa') + r.input (u'Escape') + r.input (u'"kiz"') + self.assertEqual (r.line, u'zaaa') + r.input (u'Escape') + r.input (u'"j"') + self.assertEqual (r.line, u'') def test_history_input_j_and_k (self): r = ViModeTest () - r.add_history ('aaa') - r.input ('Escape') - r.input ('"kAjk"') - self.assertEqual (r.line, 'aaajk') + r.add_history (u'aaa') + r.input (u'Escape') + r.input (u'"kAjk"') + self.assertEqual (r.line, u'aaajk') def test_history_cursor_search (self): r = ViModeTest () - r.add_history ('aaa') - r.input ('Escape') - r.input ('"/a"') - r.input ('Return') - self.assertEqual (r.line, 'aaa') - r.input ('"iz"') - self.assertEqual (r.line, 'zaaa') + r.add_history (u'aaa') + r.input (u'Escape') + r.input (u'"/a"') + r.input (u'Return') + self.assertEqual (r.line, u'aaa') + r.input (u'"iz"') + self.assertEqual (r.line, u'zaaa') self.assertEqual (r.console.bell_count, 0) - r.input ('Escape') - r.input ('"j"') - self.assertEqual (r.line, 'zaaa') + r.input (u'Escape') + r.input (u'"j"') + self.assertEqual (r.line, u'zaaa') # TODO check bell ringing # self.assertEqual (r.console.bell_count, 1) def test_history_undo (self): r = ViModeTest () - r.add_history ('aaa') - r.input ('Escape') - r.input ('"k"') - r.input ('"A b"') - r.input ('Escape') - r.input ('"A c"') - r.input ('Escape') - self.assertEqual (r.line, 'aaa b c') - r.input ('"U"') - self.assertEqual (r.line, 'aaa') + r.add_history (u'aaa') + r.input (u'Escape') + r.input (u'"k"') + r.input (u'"A b"') + r.input (u'Escape') + r.input (u'"A c"') + r.input (u'Escape') + self.assertEqual (r.line, u'aaa b c') + r.input (u'"U"') + self.assertEqual (r.line, u'aaa') def test_history_arrow_undo (self): r = ViModeTest () - r.add_history ('aaa') - r.input ('Up') - r.input ('" zz"') - self.assertEqual (r.line, 'aaa zz') - r.input ('Escape') - r.input ('"u"') - self.assertEqual (r.line, 'aaa') + r.add_history (u'aaa') + r.input (u'Up') + r.input (u'" zz"') + self.assertEqual (r.line, u'aaa zz') + r.input (u'Escape') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa') # TODO: mode support? # def test_mode (self): @@ -1742,17 +1742,17 @@ class Tests (unittest.TestCase): # # def test_switch_mode (self): # r = ViModeTest () -# r._set_line ('') -# r.input ('Escape') +# r._set_line (u'') +# r.input (u'Escape') # self.assertEqual (r.editing_mode, Readline.mode_vi) # self.assertEqual (r.count_vi_editing_mode, 1) # self.assertEqual (r.count_emacs_editing_mode, 0) -# r.input ('"abc"') -# r.input ('Control-e') +# r.input (u'"abc"') +# r.input (u'Control-e') # self.assertEqual (r.editing_mode, Readline.mode_emacs) # self.assertEqual (r.count_vi_editing_mode, 1) # self.assertEqual (r.count_emacs_editing_mode, 1) -# r.input ('Meta-Control-j') +# r.input (u'Meta-Control-j') # self.assertEqual (r.editing_mode, Readline.mode_vi) # self.assertEqual (r.count_vi_editing_mode, 2) # self.assertEqual (r.count_emacs_editing_mode, 1) @@ -1762,364 +1762,364 @@ class Tests (unittest.TestCase): # import StringIO # sio = StringIO.StringIO () # r = ViModeTest () -# r.add_history ('abc') -# r.add_history ('def') -# r.add_history ('ghi') +# r.add_history (u'abc') +# r.add_history (u'def') +# r.add_history (u'ghi') # r.show_history (sio) # sio.seek (0) -# self.assertEqual (sio.read(), ' 1 abc\n 2 def\n 3 ghi\n') +# self.assertEqual (sio.read(), u' 1 abc\n 2 def\n 3 ghi\n') def test_editor (self): - vee = ViExternalEditorTest ('qwerty before') + vee = ViExternalEditorTest (u'qwerty before') self.assert_ (vee.sio_write.closed) - self.assertEqual (vee.command, 'vim.exe temp.py') + self.assertEqual (vee.command, u'vim.exe temp.py') self.assert_ (vee.sio_read.closed) - self.assertEqual (vee.remove, 'temp.py') - self.assertEqual (vee.result, 'qwerty after') + self.assertEqual (vee.remove, u'temp.py') + self.assertEqual (vee.result, u'qwerty after') def test_completer (self): r = ViModeTest () - r.lst_completions = ['aab', 'aac', 'aad', ] - r.input ('"aa"') - r.input ('Tab') - self.assertEqual (r.line, 'aa') - self.assertEqual (r.console.text, '\naab \naac \naad \n') + r.lst_completions = ['aab', u'aac', u'aad', ] + r.input (u'"aa"') + r.input (u'Tab') + self.assertEqual (r.line, u'aa') + self.assertEqual (r.console.text, u'\naab \naac \naad \n') def test_completer_star (self): r = ViModeTest () - r.lst_completions = ['bbc', 'bbd', 'bbe', ] - r.input ('"aa bb"') - r.input ('Escape') + r.lst_completions = ['bbc', u'bbd', u'bbe', ] + r.input (u'"aa bb"') + r.input (u'Escape') self.assert_ (not r.vi_is_insert_mode) - r.input ('"*"') - self.assertEqual (r.line, 'aa bbc bbd bbe ') + r.input (u'"*"') + self.assertEqual (r.line, u'aa bbc bbd bbe ') self.assertEqual (r.line_cursor, 15) self.assert_ (r.vi_is_insert_mode) - self.assertEqual (r.console.text, '') - r.input ('" "') - r.input ('Escape') - self.assertEqual (r.line, 'aa bbc bbd bbe ') + self.assertEqual (r.console.text, u'') + r.input (u'" "') + r.input (u'Escape') + self.assertEqual (r.line, u'aa bbc bbd bbe ') self.assertEqual (r.line_cursor, 15) - r.input ('"."') - self.assertEqual (r.line, 'aa bbc bbd bbe bbc bbd bbe ') + r.input (u'"."') + self.assertEqual (r.line, u'aa bbc bbd bbe bbc bbd bbe ') self.assertEqual (r.line_cursor, 27) def test_completer_beginning_of_line (self): r = ViModeTest () - r.input ('Tab') - self.assertEqual (r.line, ' ') + r.input (u'Tab') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 4) - r.input ('Space') - self.assertEqual (r.line, ' ') + r.input (u'Space') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 5) - r.input ('Tab') - self.assertEqual (r.line, ' ') + r.input (u'Tab') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 8) - r.input ('Space') - r.input ('Space') - r.input ('Space') - self.assertEqual (r.line, ' ') + r.input (u'Space') + r.input (u'Space') + r.input (u'Space') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 11) - r.input ('Tab') - self.assertEqual (r.line, ' ') + r.input (u'Tab') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 12) - r.input ('Tab') - self.assertEqual (r.line, ' ') + r.input (u'Tab') + self.assertEqual (r.line, u' ') self.assertEqual (r.line_cursor, 16) def test_replace_lower (self): r = ViModeTest () - r._set_line ('aaa bbb ccc') - r.input ('Escape') - r.input ('"0ry"') - self.assertEqual (r.line, 'yaa bbb ccc') + r._set_line (u'aaa bbb ccc') + r.input (u'Escape') + r.input (u'"0ry"') + self.assertEqual (r.line, u'yaa bbb ccc') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('"i"') - self.assertEqual (r.line, 'yaa bbb ccc') + r.input (u'"i"') + self.assertEqual (r.line, u'yaa bbb ccc') self.assertEqual (r.line_cursor, 0) self.assert_ (r.vi_is_insert_mode) - r.input ('"x"') - self.assertEqual (r.line, 'xyaa bbb ccc') + r.input (u'"x"') + self.assertEqual (r.line, u'xyaa bbb ccc') self.assertEqual (r.line_cursor, 1) self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') - self.assertEqual (r.line, 'xyaa bbb ccc') + r.input (u'Escape') + self.assertEqual (r.line, u'xyaa bbb ccc') self.assertEqual (r.line_cursor, 0) self.assert_ (not r.vi_is_insert_mode) - r.input ('"ll"') - r.input ('"2rz"') - self.assertEqual (r.line, 'xyzz bbb ccc') + r.input (u'"ll"') + r.input (u'"2rz"') + self.assertEqual (r.line, u'xyzz bbb ccc') self.assertEqual (r.line_cursor, 3) self.assert_ (not r.vi_is_insert_mode) - r.input ('"w7."') - self.assertEqual (r.line, 'xyzz zzzzzzz') + r.input (u'"w7."') + self.assertEqual (r.line, u'xyzz zzzzzzz') self.assertEqual (r.line_cursor, 11) self.assert_ (not r.vi_is_insert_mode) def test_replace_lower_undo (self): r = ViModeTest () - r._set_line ('aaa') - r.input ('Escape') - # print 'xx', sys._getframe().f_lineno, r._vi_undo_cursor, r._vi_undo_stack - r.input ('"0rz"') - self.assertEqual (r.line, 'zaa') - r.input ('"u"') - self.assertEqual (r.line, 'aaa') - r.input ('"2."') - self.assertEqual (r.line, 'zza') - r.input ('"u"') - self.assertEqual (r.line, 'aaa') + r._set_line (u'aaa') + r.input (u'Escape') + # print u'xx', sys._getframe().f_lineno, r._vi_undo_cursor, r._vi_undo_stack + r.input (u'"0rz"') + self.assertEqual (r.line, u'zaa') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa') + r.input (u'"2."') + self.assertEqual (r.line, u'zza') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa') def test_replace_lower_escape (self): r = ViModeTest () - r._set_line ('aaa') - r.input ('Escape') - r.input ('"0r"') - self.assertEqual (r.line, 'aaa') - r.input ('Escape') - self.assertEqual (r.line, 'aaa') - r.input ('"r"') - self.assertEqual (r.line, 'aaa') - r.input ('"z"') - self.assertEqual (r.line, 'zaa') + r._set_line (u'aaa') + r.input (u'Escape') + r.input (u'"0r"') + self.assertEqual (r.line, u'aaa') + r.input (u'Escape') + self.assertEqual (r.line, u'aaa') + r.input (u'"r"') + self.assertEqual (r.line, u'aaa') + r.input (u'"z"') + self.assertEqual (r.line, u'zaa') def test_replace_lower_escape_undo (self): r = ViModeTest () - r._set_line ('aa bb cc') - r.input ('Escape') - r.input ('"0cwdd"') - r.input ('Escape') - self.assertEqual (r.line, 'dd bb cc') - r.input ('"wr"') - r.input ('Escape') - self.assertEqual (r.line, 'dd bb cc') - r.input ('"."') - self.assertEqual (r.line, 'dd dd cc') - r.input ('"u"') - self.assertEqual (r.line, 'dd bb cc') - r.input ('"u"') - self.assertEqual (r.line, 'aa bb cc') + r._set_line (u'aa bb cc') + r.input (u'Escape') + r.input (u'"0cwdd"') + r.input (u'Escape') + self.assertEqual (r.line, u'dd bb cc') + r.input (u'"wr"') + r.input (u'Escape') + self.assertEqual (r.line, u'dd bb cc') + r.input (u'"."') + self.assertEqual (r.line, u'dd dd cc') + r.input (u'"u"') + self.assertEqual (r.line, u'dd bb cc') + r.input (u'"u"') + self.assertEqual (r.line, u'aa bb cc') def test_replace_dot (self): r = ViModeTest () - r._set_line ('ab') - r.input ('Escape') - r.input ('"0rzl"') - self.assertEqual (r.line, 'zb') + r._set_line (u'ab') + r.input (u'Escape') + r.input (u'"0rzl"') + self.assertEqual (r.line, u'zb') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) - r.input ('"r."') - self.assertEqual (r.line, 'z.') + r.input (u'"r."') + self.assertEqual (r.line, u'z.') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) def test_replace_upper (self): r = ViModeTest () - r._set_line ('aaa bbb') - r.input ('Escape') - r.input ('"0wR"') - self.assertEqual (r.line, 'aaa bbb') + r._set_line (u'aaa bbb') + r.input (u'Escape') + r.input (u'"0wR"') + self.assertEqual (r.line, u'aaa bbb') self.assertEqual (r.line_cursor, 4) self.assert_ (r.vi_is_insert_mode) - r.input ('"z"') - self.assertEqual (r.line, 'aaa zbb') + r.input (u'"z"') + self.assertEqual (r.line, u'aaa zbb') self.assertEqual (r.line_cursor, 5) self.assert_ (r.vi_is_insert_mode) - r.input ('"zzz"') - self.assertEqual (r.line, 'aaa zzzz') + r.input (u'"zzz"') + self.assertEqual (r.line, u'aaa zzzz') self.assertEqual (r.line_cursor, 8) self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') + r.input (u'Escape') self.assertEqual (r.line_cursor, 7) self.assert_ (not r.vi_is_insert_mode) def test_replace_upper_dot (self): r = ViModeTest () - r._set_line ('aaa bbb ccc ddd') - r.input ('Escape') - r.input ('"02Rz"') - r.input ('Escape') - self.assertEqual (r.line, 'zza bbb ccc ddd') + r._set_line (u'aaa bbb ccc ddd') + r.input (u'Escape') + r.input (u'"02Rz"') + r.input (u'Escape') + self.assertEqual (r.line, u'zza bbb ccc ddd') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) - r.input ('"w."') - self.assertEqual (r.line, 'zza zzb ccc ddd') + r.input (u'"w."') + self.assertEqual (r.line, u'zza zzb ccc ddd') self.assertEqual (r.line_cursor, 5) self.assert_ (not r.vi_is_insert_mode) - r.input ('"w6."') - self.assertEqual (r.line, 'zza zzb zzzzzzd') + r.input (u'"w6."') + self.assertEqual (r.line, u'zza zzb zzzzzzd') self.assertEqual (r.line_cursor, 13) self.assert_ (not r.vi_is_insert_mode) def test_replace_upper_undo (self): r = ViModeTest () - r._set_line ('aaa bbb ccc') - r.input ('Escape') - r.input ('"0Rzz"') - r.input ('Escape') - self.assertEqual (r.line, 'zza bbb ccc') - r.input ('"w3."') - self.assertEqual (r.line, 'zza zzzzzzc') - r.input ('"u"') - self.assertEqual (r.line, 'zza bbb ccc') - r.input ('"u"') - self.assertEqual (r.line, 'aaa bbb ccc') + r._set_line (u'aaa bbb ccc') + r.input (u'Escape') + r.input (u'"0Rzz"') + r.input (u'Escape') + self.assertEqual (r.line, u'zza bbb ccc') + r.input (u'"w3."') + self.assertEqual (r.line, u'zza zzzzzzc') + r.input (u'"u"') + self.assertEqual (r.line, u'zza bbb ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa bbb ccc') def test_replace_backspace_and_dot (self): r = ViModeTest () - r._set_line ('aa bb') - r.input ('Escape') - r.input ('"0wRc"') - self.assertEqual (r.line, 'aa cb') + r._set_line (u'aa bb') + r.input (u'Escape') + r.input (u'"0wRc"') + self.assertEqual (r.line, u'aa cb') self.assertEqual (r.line_cursor, 4) self.assert_ (r.vi_is_insert_mode) - r.input ('"c"') - self.assertEqual (r.line, 'aa cc') + r.input (u'"c"') + self.assertEqual (r.line, u'aa cc') self.assertEqual (r.line_cursor, 5) - r.input ('"c"') - self.assertEqual (r.line, 'aa ccc') + r.input (u'"c"') + self.assertEqual (r.line, u'aa ccc') self.assertEqual (r.line_cursor, 6) - r.input ('BackSpace') - self.assertEqual (r.line, 'aa cc') + r.input (u'BackSpace') + self.assertEqual (r.line, u'aa cc') self.assertEqual (r.line_cursor, 5) self.assert_ (r.vi_is_insert_mode) - r.input ('BackSpace') - self.assertEqual (r.line, 'aa cb') + r.input (u'BackSpace') + self.assertEqual (r.line, u'aa cb') self.assertEqual (r.line_cursor, 4) self.assert_ (r.vi_is_insert_mode) - r.input ('BackSpace') - self.assertEqual (r.line, 'aa bb') + r.input (u'BackSpace') + self.assertEqual (r.line, u'aa bb') self.assertEqual (r.line_cursor, 3) self.assert_ (r.vi_is_insert_mode) - r.input ('BackSpace') - self.assertEqual (r.line, 'aa bb') + r.input (u'BackSpace') + self.assertEqual (r.line, u'aa bb') self.assertEqual (r.line_cursor, 2) self.assert_ (r.vi_is_insert_mode) - r.input ('"d"') - self.assertEqual (r.line, 'aadbb') + r.input (u'"d"') + self.assertEqual (r.line, u'aadbb') self.assertEqual (r.line_cursor, 3) self.assert_ (r.vi_is_insert_mode) - r.input ('Escape') - self.assertEqual (r.line, 'aadbb') + r.input (u'Escape') + self.assertEqual (r.line, u'aadbb') self.assertEqual (r.line_cursor, 2) self.assert_ (not r.vi_is_insert_mode) - r.input ('"u"') - self.assertEqual (r.line, 'aa bb') + r.input (u'"u"') + self.assertEqual (r.line, u'aa bb') self.assertEqual (r.line_cursor, 3) self.assert_ (not r.vi_is_insert_mode) - r.input ('"hh"') - r.input ('"."') - self.assertEqual (r.line, 'da bb') + r.input (u'"hh"') + r.input (u'"."') + self.assertEqual (r.line, u'da bb') self.assert_ (not r.vi_is_insert_mode) def test_yank_line (self): r = ViModeTest () - r._set_line ('aa bb') - r.input ('Escape') - r.input ('"0wY"') - self.assertEqual (r.line, 'aa bb') + r._set_line (u'aa bb') + r.input (u'Escape') + r.input (u'"0wY"') + self.assertEqual (r.line, u'aa bb') self.assert_ (not r.vi_is_insert_mode) - r.input ('"P"') - self.assertEqual (r.line, 'aa aa bbbb') + r.input (u'"P"') + self.assertEqual (r.line, u'aa aa bbbb') self.assert_ (not r.vi_is_insert_mode) - r.input ('"u"') - self.assertEqual (r.line, 'aa bb') + r.input (u'"u"') + self.assertEqual (r.line, u'aa bb') self.assert_ (not r.vi_is_insert_mode) def test_column (self): r = ViModeTest () - r._set_line ('aaa bbb') - r.input ('Escape') - r.input ('"099|"') - self.assertEqual (r.line, 'aaa bbb') + r._set_line (u'aaa bbb') + r.input (u'Escape') + r.input (u'"099|"') + self.assertEqual (r.line, u'aaa bbb') self.assertEqual (r.line_cursor, 6) - r.input ('"4|"') - self.assertEqual (r.line, 'aaa bbb') + r.input (u'"4|"') + self.assertEqual (r.line, u'aaa bbb') self.assertEqual (r.line_cursor, 3) - r.input ('"d1|"') - self.assertEqual (r.line, ' bbb') + r.input (u'"d1|"') + self.assertEqual (r.line, u' bbb') self.assertEqual (r.line_cursor, 0) - r.input ('"u"') - self.assertEqual (r.line, 'aaa bbb') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa bbb') self.assertEqual (r.line_cursor, 3) - r.input ('"d7|"') - self.assertEqual (r.line, 'aaab') + r.input (u'"d7|"') + self.assertEqual (r.line, u'aaab') self.assertEqual (r.line_cursor, 3) def test_change_case (self): r = ViModeTest () - r._set_line ('aaa B7B ccc') - r.input ('Escape') - r.input ('"0~"') - self.assertEqual (r.line, 'Aaa B7B ccc') + r._set_line (u'aaa B7B ccc') + r.input (u'Escape') + r.input (u'"0~"') + self.assertEqual (r.line, u'Aaa B7B ccc') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) - r.input ('"h."') - self.assertEqual (r.line, 'aaa B7B ccc') + r.input (u'"h."') + self.assertEqual (r.line, u'aaa B7B ccc') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) - r.input ('"9~"') - self.assertEqual (r.line, 'aAA b7b CCc') + r.input (u'"9~"') + self.assertEqual (r.line, u'aAA b7b CCc') self.assertEqual (r.line_cursor, 10) self.assert_ (not r.vi_is_insert_mode) - r.input ('"u"') - self.assertEqual (r.line, 'aaa B7B ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa B7B ccc') self.assertEqual (r.line_cursor, 1) self.assert_ (not r.vi_is_insert_mode) def test_redo (self): r = ViModeTest () - r._set_line ('') - r.input ('Escape') - r.input ('"Saaa"') - self.assertEqual (r.line, 'aaa') - r.input ('Escape') - r.input ('"Sbbb"') - self.assertEqual (r.line, 'bbb') - r.input ('Escape') - r.input ('"Sccc"') - r.input ('Escape') - self.assertEqual (r.line, 'ccc') - r.input ('"u"') - self.assertEqual (r.line, 'bbb') - r.input ('Control-r') - self.assertEqual (r.line, 'ccc') - r.input ('"u"') - self.assertEqual (r.line, 'bbb') - r.input ('"u"') - self.assertEqual (r.line, 'aaa') - r.input ('"u"') - self.assertEqual (r.line, '') - r.input ('"u"') - self.assertEqual (r.line, '') - r.input ('Control-r') - self.assertEqual (r.line, 'aaa') - r.input ('Control-r') - self.assertEqual (r.line, 'bbb') - r.input ('Control-r') - self.assertEqual (r.line, 'ccc') - r.input ('Control-r') - self.assertEqual (r.line, 'ccc') - r.input ('"u"') - self.assertEqual (r.line, 'bbb') - r.input ('"Szzz"') - r.input ('Escape') - self.assertEqual (r.line, 'zzz') - r.input ('"u"') - self.assertEqual (r.line, 'bbb') - r.input ('Control-r') - self.assertEqual (r.line, 'zzz') - r.input ('"U"') - self.assertEqual (r.line, '') - r.input ('Control-r') - self.assertEqual (r.line, 'aaa') - r.input ('Control-r') - self.assertEqual (r.line, 'bbb') - r.input ('Control-r') - self.assertEqual (r.line, 'zzz') - r.input ('Control-r') - self.assertEqual (r.line, 'zzz') + r._set_line (u'') + r.input (u'Escape') + r.input (u'"Saaa"') + self.assertEqual (r.line, u'aaa') + r.input (u'Escape') + r.input (u'"Sbbb"') + self.assertEqual (r.line, u'bbb') + r.input (u'Escape') + r.input (u'"Sccc"') + r.input (u'Escape') + self.assertEqual (r.line, u'ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'bbb') + r.input (u'Control-r') + self.assertEqual (r.line, u'ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'bbb') + r.input (u'"u"') + self.assertEqual (r.line, u'aaa') + r.input (u'"u"') + self.assertEqual (r.line, u'') + r.input (u'"u"') + self.assertEqual (r.line, u'') + r.input (u'Control-r') + self.assertEqual (r.line, u'aaa') + r.input (u'Control-r') + self.assertEqual (r.line, u'bbb') + r.input (u'Control-r') + self.assertEqual (r.line, u'ccc') + r.input (u'Control-r') + self.assertEqual (r.line, u'ccc') + r.input (u'"u"') + self.assertEqual (r.line, u'bbb') + r.input (u'"Szzz"') + r.input (u'Escape') + self.assertEqual (r.line, u'zzz') + r.input (u'"u"') + self.assertEqual (r.line, u'bbb') + r.input (u'Control-r') + self.assertEqual (r.line, u'zzz') + r.input (u'"U"') + self.assertEqual (r.line, u'') + r.input (u'Control-r') + self.assertEqual (r.line, u'aaa') + r.input (u'Control-r') + self.assertEqual (r.line, u'bbb') + r.input (u'Control-r') + self.assertEqual (r.line, u'zzz') + r.input (u'Control-r') + self.assertEqual (r.line, u'zzz') #---------------------------------------------------------------------- # utility functions @@ -2127,7 +2127,7 @@ class Tests (unittest.TestCase): #---------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == u'__main__': Tester() tested=ViModeTest.tested_commands.keys() diff --git a/pyreadline/unicode_helper.py b/pyreadline/unicode_helper.py index ebfa581..d08e88e 100644 --- a/pyreadline/unicode_helper.py +++ b/pyreadline/unicode_helper.py @@ -11,23 +11,23 @@ try: pyreadline_codepage=sys.stdout.encoding except AttributeError: #This error occurs when pdb imports readline and doctest has replaced #stdout with stdout collector - pyreadline_codepage="ascii" #assume ascii codepage + pyreadline_codepage=u"ascii" #assume ascii codepage def ensure_unicode(text): """helper to ensure that text passed to WriteConsoleW is unicode""" if isinstance(text, str): try: - return text.decode(pyreadline_codepage, "replace") + return text.decode(pyreadline_codepage, u"replace") except (LookupError, TypeError): - return text.decode("ascii", "replace") + return text.decode(u"ascii", u"replace") return text def ensure_str(text): """Convert unicode to str using pyreadline_codepage""" if isinstance(text, unicode): try: - return text.encode(pyreadline_codepage, "replace") + return text.encode(pyreadline_codepage, u"replace") except (LookupError, TypeError): - return text.encode("ascii", "replace") + return text.encode(u"ascii", u"replace") return text From 7295340c3178e89674525f38a7381ab17646d4ea Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 11 Nov 2008 20:59:36 +0100 Subject: [PATCH 19/26] Reformatted code pyreadline/*.py --- pyreadline/__init__.py | 2 +- pyreadline/get_doc.py | 16 +-- pyreadline/logger.py | 16 +-- pyreadline/logserver.py | 24 ++-- pyreadline/rlmain.py | 241 ++++++++++++++++++----------------- pyreadline/unicode_helper.py | 8 +- 6 files changed, 160 insertions(+), 147 deletions(-) diff --git a/pyreadline/__init__.py b/pyreadline/__init__.py index c0845c5..b32f480 100644 --- a/pyreadline/__init__.py +++ b/pyreadline/__init__.py @@ -6,7 +6,7 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -import unicode_helper,logger,clipboard,lineeditor,modes +import unicode_helper, logger, clipboard, lineeditor, modes from rlmain import * import rlmain __all__ = [ 'parse_and_bind', diff --git a/pyreadline/get_doc.py b/pyreadline/get_doc.py index d6d66bb..b56eb95 100644 --- a/pyreadline/get_doc.py +++ b/pyreadline/get_doc.py @@ -1,18 +1,18 @@ import sys,textwrap -rlmain=sys.modules[u"pyreadline.rlmain"] -rl=rlmain.rl +rlmain = sys.modules[u"pyreadline.rlmain"] +rl = rlmain.rl def get_doc(rl): - methods=[(x,getattr(rl,x)) for x in dir(rl) if callable(getattr(rl,x))] - return [ (x,m.__doc__ )for x,m in methods if m.__doc__] + methods = [(x, getattr(rl, x)) for x in dir(rl) if callable(getattr(rl, x))] + return [ (x, m.__doc__ )for x, m in methods if m.__doc__] def get_rest(rl): - q=get_doc(rl) - out=[] - for funcname,doc in q: + q = get_doc(rl) + out = [] + for funcname, doc in q: out.append(funcname) - out.append(u"\n".join(textwrap.wrap(doc,80,initial_indent=u" "))) + out.append(u"\n".join(textwrap.wrap(doc, 80, initial_indent=u" "))) out.append(u"") return out \ No newline at end of file diff --git a/pyreadline/logger.py b/pyreadline/logger.py index bfaeeb0..d85ffb0 100644 --- a/pyreadline/logger.py +++ b/pyreadline/logger.py @@ -9,14 +9,14 @@ import socket, logging, logging.handlers from pyreadline.unicode_helper import ensure_str -host=u"localhost" -port=logging.handlers.DEFAULT_TCP_LOGGING_PORT +host = u"localhost" +port = logging.handlers.DEFAULT_TCP_LOGGING_PORT -root_logger=logging.getLogger(u'') +root_logger = logging.getLogger(u'') root_logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') -file_handler=None +file_handler = None class NULLHandler(logging.Handler): def emit(self, s): @@ -24,10 +24,10 @@ class NULLHandler(logging.Handler): class SocketStream(object): def __init__(self, host, port): - self.logsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + self.logsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) def write(self, s): - self.logsocket.sendto(ensure_str(s),(host,port)) + self.logsocket.sendto(ensure_str(s), (host, port)) def flush(self): pass @@ -48,7 +48,7 @@ def stop_socket_log(): def start_file_log(filename): global file_handler - file_handler=logging.handlers.FileHandler(filename, "w") + file_handler = logging.handlers.FileHandler(filename, "w") root_logger.addHandler(file_handler) def stop_file_log(): @@ -56,7 +56,7 @@ def stop_file_log(): if file_handler: root_logger.removeHandler(file_handler) file_handler.close() - file_handler=None + file_handler = None def log(s): s = ensure_str(s) diff --git a/pyreadline/logserver.py b/pyreadline/logserver.py index df7798d..df2f365 100644 --- a/pyreadline/logserver.py +++ b/pyreadline/logserver.py @@ -14,19 +14,19 @@ import struct,socket try: import msvcrt except ImportError: - msvcrt=None + msvcrt = None print u"problem" -port=logging.handlers.DEFAULT_TCP_LOGGING_PORT -host=u'localhost' +port = logging.handlers.DEFAULT_TCP_LOGGING_PORT +host = u'localhost' def check_key(): if msvcrt is None: return False else: - if msvcrt.kbhit()!=0: - q=msvcrt.getch() + if msvcrt.kbhit() != 0: + q = msvcrt.getch() return q return u"" @@ -34,24 +34,24 @@ def check_key(): singleline=False def main(): - print u"Starting TCP logserver on port:",port + print u"Starting TCP logserver on port:", port print u"Press q to quit logserver", port print u"Press c to clear screen", port - s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.bind((u"",port)) + s.bind((u"", port)) s.settimeout(1) while 1: try: - data, addr=s.recvfrom(100000) + data, addr = s.recvfrom(100000) print data, except socket.timeout: - key=check_key().lower() - if u"q"==key: + key = check_key().lower() + if u"q" == key: print u"Quitting logserver" break elif u"c" == key: - print u"\n"*100 + print u"\n" * 100 if __name__ == u"__main__": main() \ No newline at end of file diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index e7b40e9..cd213a8 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -10,51 +10,55 @@ u''' an attempt to implement readline for Python in Python using ctypes''' import sys,os,re,time from glob import glob -import clipboard,logger,console -from logger import log -from error import ReadlineError, GetSetError -from pyreadline.keysyms.common import make_KeyPress_from_keydescr -from pyreadline.unicode_helper import ensure_unicode -import pyreadline.lineeditor.lineobj as lineobj -import pyreadline.lineeditor.history as history import release -from modes import editingmodes +import pyreadline.lineeditor.lineobj as lineobj +import pyreadline.lineeditor.history as history +import pyreadline.clipboard as clipboard +import pyreadline.console as console +import pyreadline.logger as logger -in_ironpython=u"IronPython" in sys.version +from pyreadline.keysyms.common import make_KeyPress_from_keydescr +from pyreadline.unicode_helper import ensure_unicode +from logger import log +from modes import editingmodes +from error import ReadlineError, GetSetError + +in_ironpython = u"IronPython" in sys.version if in_ironpython:#ironpython does not provide a prompt string to readline import System - default_prompt=u">>> " + default_prompt = u">>> " else: - default_prompt=u"" + default_prompt = u"" import pdb class MockConsoleError(Exception): pass + class MockConsole(object): u"""object used during refactoring. Should raise errors when someone tries to use it. """ - def __setattr__(self,x): + def __setattr__(self, x): raise MockConsoleError(u"Should not try to get attributes from MockConsole") - def cursor(self,size=50): + def cursor(self, size=50): pass class BaseReadline(object): def __init__(self): - self.allow_ctrl_c=False - self.ctrl_c_tap_time_interval=0.3 + self.allow_ctrl_c = False + self.ctrl_c_tap_time_interval = 0.3 - self.debug=False + self.debug = False self.bell_style = u'none' - self.mark=-1 + self.mark = -1 self.console=MockConsole() # this code needs to follow l_buffer and history creation - self.editingmodes=[mode(self) for mode in editingmodes] + self.editingmodes = [mode(self) for mode in editingmodes] for mode in self.editingmodes: mode.init_editing_mode(None) - self.mode=self.editingmodes[0] + self.mode = self.editingmodes[0] self.read_inputrc() log(u"\n".join(self.mode.rl_settings_to_string())) @@ -98,12 +102,12 @@ class BaseReadline(object): raise def _set_prompt(self, prompt): - self.mode.prompt=prompt + self.mode.prompt = prompt def _get_prompt(self): return self.mode.prompt - prompt=property(_get_prompt, _set_prompt) + prompt = property(_get_prompt, _set_prompt) def get_line_buffer(self): @@ -145,7 +149,7 @@ class BaseReadline(object): def read_history_file(self, filename=None): u'''Load a readline history file. The default filename is ~/.history.''' if filename is None: - filename=self.mode._history.history_filename + filename = self.mode._history.history_filename log(u"read_history_file from %s"%ensure_unicode(filename)) self.mode._history.read_history_file(filename) @@ -232,7 +236,7 @@ class BaseReadline(object): def process_keyevent(self, keyinfo): return self.mode.process_keyevent(keyinfo) - def readline_setup(self,prompt=u""): + def readline_setup(self, prompt=u""): return self.mode.readline_setup(prompt) def keyboard_poll(self): @@ -260,16 +264,17 @@ class BaseReadline(object): # TADA: self.callback(line) - def read_inputrc(self,inputrcpath=os.path.expanduser("~/pyreadlineconfig.ini")):#in 2.4 we cannot call expanduser with unicode string - modes=dict([(x.mode,x) for x in self.editingmodes]) - mode=self.editingmodes[0].mode + def read_inputrc(self, #in 2.4 we cannot call expanduser with unicode string + inputrcpath=os.path.expanduser("~/pyreadlineconfig.ini")): + modes = dict([(x.mode,x) for x in self.editingmodes]) + mode = self.editingmodes[0].mode def setmode(name): - self.mode=modes[name] - def bind_key(key,name): - if hasattr(modes[mode],name): - modes[mode]._bind_key(key,getattr(modes[mode],name)) + self.mode = modes[name] + def bind_key(key, name): + if hasattr(modes[mode], name): + modes[mode]._bind_key(key, getattr(modes[mode], name)) else: - print u"Trying to bind unknown command '%s' to key '%s'"%(name,key) + print u"Trying to bind unknown command '%s' to key '%s'"%(name, key) def un_bind_key(key): keyinfo = make_KeyPress_from_keydescr(key).tuple() if keyinfo in modes[mode].key_dispatch: @@ -277,6 +282,7 @@ class BaseReadline(object): def bind_exit_key(key): modes[mode]._bind_exit_key(key) + def un_bind_exit_key(key): keyinfo = make_KeyPress_from_keydescr(key).tuple() if keyinfo in modes[mode].exit_dispatch: @@ -284,45 +290,45 @@ class BaseReadline(object): def setkill_ring_to_clipboard(killring): import pyreadline.lineeditor.lineobj - pyreadline.lineeditor.lineobj.kill_ring_to_clipboard=killring + pyreadline.lineeditor.lineobj.kill_ring_to_clipboard = killring def sethistoryfilename(filename): self.mode._history.history_filename=os.path.expanduser(filename) def setbellstyle(mode): - self.bell_style=mode + self.bell_style = mode def sethistorylength(length): - self.mode._history.history_length=int(length) + self.mode._history.history_length = int(length) def allow_ctrl_c(mode): - log(u"allow_ctrl_c:%s:%s"%(self.allow_ctrl_c,mode)) - self.allow_ctrl_c=mode + log(u"allow_ctrl_c:%s:%s"%(self.allow_ctrl_c, mode)) + self.allow_ctrl_c = mode def setbellstyle(mode): - self.bell_style=mode + self.bell_style = mode def show_all_if_ambiguous(mode): - self.mode.show_all_if_ambiguous=mode + self.mode.show_all_if_ambiguous = mode def ctrl_c_tap_time_interval(mode): - self.ctrl_c_tap_time_interval=mode + self.ctrl_c_tap_time_interval = mode def mark_directories(mode): - self.mode.mark_directories=mode + self.mode.mark_directories = mode def completer_delims(delims): - self.mode.completer_delims=delims + self.mode.completer_delims = delims - def debug_output(on,filename=u"pyreadline_debug_log.txt"): #Not implemented yet - if on in [u"on",u"on_nologfile"]: + def debug_output(on, filename=u"pyreadline_debug_log.txt"): #Not implemented yet + if on in [u"on", u"on_nologfile"]: self.debug=True if on == "on": logger.start_file_log(filename) logger.start_socket_log() logger.log(u"STARTING LOG") - elif on ==u"on_nologfile": + elif on == u"on_nologfile": logger.start_socket_log() logger.log(u"STARTING LOG") else: @@ -330,46 +336,49 @@ class BaseReadline(object): logger.stop_file_log() logger.stop_socket_log() + _color_trtable={u"black":0, u"darkred":4, u"darkgreen":2, + u"darkyellow":6, u"darkblue":1, u"darkmagenta":5, + u"darkcyan":3, u"gray":7, u"red":4+8, + u"green":2+8, u"yellow":6+8, u"blue":1+8, + u"magenta":5+8, u"cyan":3+8, u"white":7+8} + def set_prompt_color(color): - trtable={u"black":0,u"darkred":4,u"darkgreen":2,u"darkyellow":6,u"darkblue":1,u"darkmagenta":5,u"darkcyan":3,u"gray":7, - u"red":4+8,"green":2+8,u"yellow":6+8,u"blue":1+8,u"magenta":5+8,u"cyan":3+8,u"white":7+8} - self.prompt_color=trtable.get(color.lower(),7) + self.prompt_color = self._color_trtable.get(color.lower(),7) def set_input_color(color): - trtable={u"black":0,u"darkred":4,u"darkgreen":2,u"darkyellow":6,u"darkblue":1,u"darkmagenta":5,u"darkcyan":3,u"gray":7, - u"red":4+8,u"green":2+8,u"yellow":6+8,u"blue":1+8,u"magenta":5+8,u"cyan":3+8,u"white":7+8} - self.command_color=trtable.get(color.lower(),7) - loc={u"branch":release.branch, - u"version":release.version, - u"mode":mode, - u"modes":modes, - u"set_mode":setmode, - u"bind_key":bind_key, - u"bind_exit_key":bind_exit_key, - u"un_bind_key":un_bind_key, - u"un_bind_exit_key":un_bind_exit_key, - u"bell_style":setbellstyle, - u"mark_directories":mark_directories, - u"show_all_if_ambiguous":show_all_if_ambiguous, - u"completer_delims":completer_delims, - u"debug_output":debug_output, - u"history_filename":sethistoryfilename, - u"history_length":sethistorylength, - u"set_prompt_color":set_prompt_color, - u"set_input_color":set_input_color, - u"allow_ctrl_c":allow_ctrl_c, - u"ctrl_c_tap_time_interval":ctrl_c_tap_time_interval, - u"kill_ring_to_clipboard":setkill_ring_to_clipboard, - } + self.command_color=self._color_trtable.get(color.lower(),7) + + loc = {u"branch":release.branch, + u"version":release.version, + u"mode":mode, + u"modes":modes, + u"set_mode":setmode, + u"bind_key":bind_key, + u"bind_exit_key":bind_exit_key, + u"un_bind_key":un_bind_key, + u"un_bind_exit_key":un_bind_exit_key, + u"bell_style":setbellstyle, + u"mark_directories":mark_directories, + u"show_all_if_ambiguous":show_all_if_ambiguous, + u"completer_delims":completer_delims, + u"debug_output":debug_output, + u"history_filename":sethistoryfilename, + u"history_length":sethistorylength, + u"set_prompt_color":set_prompt_color, + u"set_input_color":set_input_color, + u"allow_ctrl_c":allow_ctrl_c, + u"ctrl_c_tap_time_interval":ctrl_c_tap_time_interval, + u"kill_ring_to_clipboard":setkill_ring_to_clipboard, + } if os.path.isfile(inputrcpath): try: - execfile(inputrcpath,loc,loc) + execfile(inputrcpath, loc, loc) except Exception,x: raise import traceback print >>sys.stderr, u"Error reading .pyinputrc" filepath,lineno=traceback.extract_tb(sys.exc_traceback)[1][:2] - print >>sys.stderr, u"Line: %s in file %s"%(lineno,filepath) + print >>sys.stderr, u"Line: %s in file %s"%(lineno, filepath) print >>sys.stderr, x raise ReadlineError(u"Error reading .pyinputrc") @@ -381,10 +390,10 @@ class Readline(BaseReadline): def __init__(self): BaseReadline.__init__(self) self.console = console.Console() - self.size = self.console.size() - self.prompt_color = None - self.command_color = None self.selection_color = self.console.saveattr<<4 + self.command_color = None + self.prompt_color = None + self.size = self.console.size() # variables you can control with parse_and_bind @@ -438,33 +447,32 @@ class Readline(BaseReadline): self.prompt_end_pos = (ex, ey - n) def _update_line(self): - c=self.console - l_buffer=self.mode.l_buffer + c = self.console + l_buffer = self.mode.l_buffer c.cursor(0) #Hide cursor avoiding flicking - #c.pos(*self.prompt_end_pos) c.pos(*self.prompt_begin_pos) self._print_prompt() ltext = l_buffer.quoted_text() - if l_buffer.enable_selection and l_buffer.selection_mark>=0: - start=len(l_buffer[:l_buffer.selection_mark].quoted_text()) - stop=len(l_buffer[:l_buffer.point].quoted_text()) - if start>stop: - stop,start=start,stop + if l_buffer.enable_selection and (l_buffer.selection_mark >= 0): + start = len(l_buffer[:l_buffer.selection_mark].quoted_text()) + stop = len(l_buffer[:l_buffer.point].quoted_text()) + if start > stop: + stop,start = start,stop n = c.write_scrolling(ltext[:start], self.command_color) n = c.write_scrolling(ltext[start:stop], self.selection_color) n = c.write_scrolling(ltext[stop:], self.command_color) else: n = c.write_scrolling(ltext, self.command_color) - x,y = c.pos() #Preserve one line for Asian IME(Input Method Editor) statusbar - w,h = c.size() - if y >= h - 1 or n > 0: + x, y = c.pos() #Preserve one line for Asian IME(Input Method Editor) statusbar + w, h = c.size() + if (y >= h - 1) or (n > 0): c.scroll_window(-1) - c.scroll((0,0,w,h),0,-1) + c.scroll((0, 0, w, h), 0, -1) n += 1 self._update_prompt_pos(n) - if hasattr(c,u"clear_to_end_of_window"): #Work around function for ironpython due + if hasattr(c, u"clear_to_end_of_window"): #Work around function for ironpython due c.clear_to_end_of_window() #to System.Console's lack of FillFunction else: self._clear_after() @@ -489,7 +497,7 @@ class Readline(BaseReadline): def event_available(self): - return self.console.peek() or (len(self.paste_line_buffer)>0) + return self.console.peek() or (len(self.paste_line_buffer) > 0) def _readline_from_keyboard(self): @@ -498,22 +506,22 @@ class Readline(BaseReadline): break def _readline_from_keyboard_poll(self): - pastebuffer=self.mode.paste_line_buffer - if len(pastebuffer)>0: + pastebuffer = self.mode.paste_line_buffer + if len(pastebuffer) > 0: #paste first line in multiline paste buffer - self.l_buffer=lineobj.ReadLineTextBuffer(pastebuffer[0]) + self.l_buffer = lineobj.ReadLineTextBuffer(pastebuffer[0]) self._update_line() - self.mode.paste_line_buffer=pastebuffer[1:] + self.mode.paste_line_buffer = pastebuffer[1:] return True - c=self.console + c = self.console def nop(e): pass try: event = c.getkeypress() except KeyboardInterrupt: - event=self.handle_ctrl_c() - result=self.mode.process_keyevent(event.keyinfo) + event = self.handle_ctrl_c() + result = self.mode.process_keyevent(event.keyinfo) self._update_line() return result @@ -524,7 +532,7 @@ class Readline(BaseReadline): def readline(self, prompt=u''): self.readline_setup(prompt) - self.ctrl_c_timeout=time.time() + self.ctrl_c_timeout = time.time() self._readline_from_keyboard() self.console.write(u'\r\n') log(u'returning(%s)' % self.get_line_buffer()) @@ -534,16 +542,17 @@ class Readline(BaseReadline): from pyreadline.keysyms.common import KeyPress from pyreadline.console.event import Event log(u"KBDIRQ") - event=Event(0,0) - event.char=u"c" - event.keyinfo=KeyPress(u"c",shift=False,control=True,meta=False,keyname=None) + event = Event(0,0) + event.char = u"c" + event.keyinfo = KeyPress(u"c", shift=False, control=True, + meta=False, keyname=None) if self.allow_ctrl_c: - now=time.time() - if (now-self.ctrl_c_timeout) Date: Tue, 11 Nov 2008 21:11:01 +0100 Subject: [PATCH 20/26] Reformatted pyreadline/clipboard/ --- pyreadline/clipboard/__init__.py | 40 ++++++++--------- pyreadline/clipboard/ironpython_clipboard.py | 6 +-- pyreadline/clipboard/no_clipboard.py | 4 +- pyreadline/clipboard/win32_clipboard.py | 45 +++++++++++--------- 4 files changed, 51 insertions(+), 44 deletions(-) diff --git a/pyreadline/clipboard/__init__.py b/pyreadline/clipboard/__init__.py index 71a8a14..ec9fff2 100644 --- a/pyreadline/clipboard/__init__.py +++ b/pyreadline/clipboard/__init__.py @@ -1,17 +1,17 @@ import sys -success=True -in_ironpython=u"IronPython" in sys.version +success = True +in_ironpython = u"IronPython" in sys.version if in_ironpython: try: - from ironpython_clipboard import GetClipboardText,SetClipboardText + from ironpython_clipboard import GetClipboardText, SetClipboardText except ImportError: - from no_clipboard import GetClipboardText,SetClipboardText + from no_clipboard import GetClipboardText, SetClipboardText else: try: - from win32_clipboard import GetClipboardText,SetClipboardText + from win32_clipboard import GetClipboardText, SetClipboardText except ImportError: - from no_clipboard import GetClipboardText,SetClipboardText + from no_clipboard import GetClipboardText, SetClipboardText def send_data(lists): @@ -22,11 +22,11 @@ def set_clipboard_text(toclipboard): SetClipboardText(str(toclipboard)) def make_tab(lists): - if hasattr(lists,u"tolist"): - lists=lists.tolist() - ut=[] + if hasattr(lists, u"tolist"): + lists = lists.tolist() + ut = [] for rad in lists: - if type(rad) in [list,tuple]: + if type(rad) in [list, tuple]: ut.append(u"\t".join([u"%s"%x for x in rad])) else: ut.append(u"%s"%rad) @@ -45,28 +45,28 @@ def make_list_of_list(txt): except ValueError: return x return x - ut=[] - flag=False - for rad in [x for x in txt.split(u"\r\n") if x!=u""]: + ut = [] + flag = False + for rad in [x for x in txt.split(u"\r\n") if x != u""]: raden=[make_num(x) for x in rad.split(u"\t")] if str in map(type,raden): - flag=True + flag = True ut.append(raden) - return ut,flag + return ut, flag def get_clipboard_text_and_convert(paste_list=False): u"""Get txt from clipboard. if paste_list==True the convert tab separated data to list of lists. Enclose list of list in array() if all elements are numeric""" - txt=GetClipboardText() + txt = GetClipboardText() if txt: if paste_list and u"\t" in txt: - array,flag=make_list_of_list(txt) + array, flag = make_list_of_list(txt) if flag: - txt=repr(array) + txt = repr(array) else: - txt=u"array(%s)"%repr(array) - txt=u"".join([c for c in txt if c not in u" \t\r\n"]) + txt = u"array(%s)"%repr(array) + txt = u"".join([c for c in txt if c not in u" \t\r\n"]) return txt diff --git a/pyreadline/clipboard/ironpython_clipboard.py b/pyreadline/clipboard/ironpython_clipboard.py index 9870ee9..10187d4 100644 --- a/pyreadline/clipboard/ironpython_clipboard.py +++ b/pyreadline/clipboard/ironpython_clipboard.py @@ -10,9 +10,9 @@ clr.AddReferenceByPartialName(u"System.Windows.Forms") import System.Windows.Forms.Clipboard as cb def GetClipboardText(): - text="" + text = "" if cb.ContainsText(): - text=cb.GetText() + text = cb.GetText() return text @@ -20,7 +20,7 @@ def SetClipboardText(text): cb.SetText(text) if __name__ == u'__main__': - txt=GetClipboardText() # display last text clipped + txt = GetClipboardText() # display last text clipped print txt diff --git a/pyreadline/clipboard/no_clipboard.py b/pyreadline/clipboard/no_clipboard.py index 9f0921c..195b0ad 100644 --- a/pyreadline/clipboard/no_clipboard.py +++ b/pyreadline/clipboard/no_clipboard.py @@ -7,12 +7,12 @@ #***************************************************************************** -mybuffer=u"" +mybuffer = u"" def GetClipboardText(): return mybuffer def SetClipboardText(text): global mybuffer - mybuffer=text + mybuffer = text diff --git a/pyreadline/clipboard/win32_clipboard.py b/pyreadline/clipboard/win32_clipboard.py index 95ad4fb..c0f4ef4 100644 --- a/pyreadline/clipboard/win32_clipboard.py +++ b/pyreadline/clipboard/win32_clipboard.py @@ -37,38 +37,45 @@ from pyreadline.keysyms.winconstants import CF_TEXT, GHND from pyreadline.unicode_helper import ensure_unicode,ensure_str OpenClipboard = windll.user32.OpenClipboard -EmptyClipboard = windll.user32.EmptyClipboard -GetClipboardData = windll.user32.GetClipboardData -GetClipboardFormatName = windll.user32.GetClipboardFormatNameA -SetClipboardData = windll.user32.SetClipboardData -EnumClipboardFormats = windll.user32.EnumClipboardFormats -CloseClipboard = windll.user32.CloseClipboard -OpenClipboard.argtypes=[c_int] -EnumClipboardFormats.argtypes=[c_int] -CloseClipboard.argtypes=[] -GetClipboardFormatName.argtypes=[c_uint,c_char_p,c_int] -GetClipboardData.argtypes=[c_int] -SetClipboardData.argtypes=[c_int,c_int] +OpenClipboard.argtypes = [c_int] + +EmptyClipboard = windll.user32.EmptyClipboard + +GetClipboardData = windll.user32.GetClipboardData +GetClipboardData.argtypes = [c_int] + +GetClipboardFormatName = windll.user32.GetClipboardFormatNameA +GetClipboardFormatName.argtypes = [c_uint,c_char_p,c_int] + +SetClipboardData = windll.user32.SetClipboardData +SetClipboardData.argtypes = [c_int,c_int] + +EnumClipboardFormats = windll.user32.EnumClipboardFormats +EnumClipboardFormats.argtypes = [c_int] + +CloseClipboard = windll.user32.CloseClipboard +CloseClipboard.argtypes = [] + -GlobalLock = windll.kernel32.GlobalLock GlobalAlloc = windll.kernel32.GlobalAlloc +GlobalLock = windll.kernel32.GlobalLock +GlobalLock.argtypes = [c_int] GlobalUnlock = windll.kernel32.GlobalUnlock -GlobalLock.argtypes=[c_int] -GlobalUnlock.argtypes=[c_int] +GlobalUnlock.argtypes = [c_int] memcpy = cdll.msvcrt.memcpy def enum(): OpenClipboard(0) - q=EnumClipboardFormats(0) + q = EnumClipboardFormats(0) while q: - q=EnumClipboardFormats(q) + q = EnumClipboardFormats(q) CloseClipboard() def getformatname(format): buffer = c_buffer(" "*100) bufferSize = sizeof(buffer) OpenClipboard(0) - GetClipboardFormatName(format,buffer,bufferSize) + GetClipboardFormatName(format, buffer, bufferSize) CloseClipboard() return buffer.value @@ -97,5 +104,5 @@ def SetClipboardText(text): CloseClipboard() if __name__ == u'__main__': - txt=GetClipboardText() # display last text clipped + txt = GetClipboardText() # display last text clipped print txt From 095b86f9e6acce047eeeec784a24e77ffd13954c Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 11 Nov 2008 21:37:11 +0100 Subject: [PATCH 21/26] reformatted pyreadline/console --- pyreadline/console/__init__.py | 11 +- pyreadline/console/ansi.py | 110 +++++++------- pyreadline/console/console.py | 138 +++++++++-------- pyreadline/console/event.py | 5 +- pyreadline/console/ironpython_console.py | 182 +++++++++++------------ 5 files changed, 233 insertions(+), 213 deletions(-) diff --git a/pyreadline/console/__init__.py b/pyreadline/console/__init__.py index 039e4a9..805fb95 100644 --- a/pyreadline/console/__init__.py +++ b/pyreadline/console/__init__.py @@ -1,21 +1,22 @@ import glob,sys -success=False -in_ironpython="IronPython" in sys.version +success = False +in_ironpython = "IronPython" in sys.version if in_ironpython: try: from ironpython_console import * - success=True + success = True except ImportError: raise else: try: from console import * - success=True + success = True except ImportError: pass if not success: - raise ImportError("Could not find a console implementation for your platform") + raise ImportError( + "Could not find a console implementation for your platform") diff --git a/pyreadline/console/ansi.py b/pyreadline/console/ansi.py index f564308..e8ba92a 100644 --- a/pyreadline/console/ansi.py +++ b/pyreadline/console/ansi.py @@ -7,61 +7,63 @@ escape_parts = re.compile(u'\001?\033\\[([0-9;]*)m\002?') class AnsiState(object): def __init__(self,bold=False,inverse=False,color=u"white",background=u"black",backgroundbold=False): - self.bold=bold - self.inverse=inverse - self.color=color - self.background=background - self.backgroundbold=backgroundbold + self.bold = bold + self.inverse = inverse + self.color = color + self.background = background + self.backgroundbold = backgroundbold - trtable={u"black":0,u"red":4,u"green":2,u"yellow":6,u"blue":1,u"magenta":5,u"cyan":3,u"white":7} - revtable=dict(zip(trtable.values(),trtable.keys())) + trtable = {u"black":0, u"red":4, u"green":2, u"yellow":6, + u"blue":1, u"magenta":5, u"cyan":3, u"white":7} + revtable = dict(zip(trtable.values(),trtable.keys())) def get_winattr(self): - attr=0 + attr = 0 if self.bold: - attr|=0x0008 + attr |= 0x0008 if self.backgroundbold: - attr|=0x0080 + attr |= 0x0080 if self.inverse: - attr|=0x4000 - attr|=self.trtable[self.color] - attr|=(self.trtable[self.background]<<4) + attr |= 0x4000 + attr |= self.trtable[self.color] + attr |= (self.trtable[self.background] << 4) return attr - def set_winattr(self,attr): - self.bold=bool(attr&0x0008) - self.backgroundbold=bool(attr&0x0080) - self.inverse=bool(attr&0x4000) - self.color=self.revtable[attr&0x0007] - self.background=self.revtable[(attr&0x0070)>>4] + def set_winattr(self, attr): + self.bold = bool(attr & 0x0008) + self.backgroundbold = bool(attr & 0x0080) + self.inverse = bool(attr & 0x4000) + self.color = self.revtable[attr & 0x0007] + self.background = self.revtable[(attr & 0x0070) >> 4] winattr=property(get_winattr,set_winattr) def __repr__(self): - return u'AnsiState(bold=%s,inverse=%s,color=%9s,background=%9s,backgroundbold=%s)# 0x%x'%(self.bold, - self.inverse, - '"%s"'%self.color, - '"%s"'%self.background, - self.backgroundbold, - self.winattr) + return u'AnsiState(bold=%s,inverse=%s,color=%9s,' \ + u'background=%9s,backgroundbold=%s)# 0x%x'% \ + (self.bold, self.inverse, '"%s"'%self.color, + '"%s"'%self.background, self.backgroundbold, + self.winattr) def copy(self): - x=AnsiState() - x.bold=self.bold - x.inverse=self.inverse - x.color=self.color - x.background=self.background - x.backgroundbold=self.backgroundbold + x = AnsiState() + x.bold = self.bold + x.inverse = self.inverse + x.color = self.color + x.background = self.background + x.backgroundbold = self.backgroundbold return x -defaultstate=AnsiState(False,False,u"white") -trtable={0:u"black",1:u"red",2:u"green",3:u"yellow",4:u"blue",5:u"magenta",6:u"cyan",7:u"white"} +defaultstate = AnsiState(False,False,u"white") + +trtable = {0:u"black", 1:u"red", 2:u"green", 3:u"yellow", + 4:u"blue", 5:u"magenta", 6:u"cyan", 7:u"white"} class AnsiWriter(object): - def __init__(self,default=defaultstate): - if isinstance(defaultstate,AnsiState): - self.defaultstate=default + def __init__(self, default=defaultstate): + if isinstance(defaultstate, AnsiState): + self.defaultstate = default else: self.defaultstate=AnsiState() - self.defaultstate.winattr=defaultstate + self.defaultstate.winattr = defaultstate def write_color(self,text, attr=None): @@ -70,21 +72,21 @@ class AnsiWriter(object): return the number of characters written. ''' if isinstance(attr,AnsiState): - defaultstate=attr + defaultstate = attr elif attr is None: #use attribute form initial console attr = self.defaultstate.copy() else: - defaultstate=AnsiState() - defaultstate.winattr=attr - attr=defaultstate + defaultstate = AnsiState() + defaultstate.winattr = attr + attr = defaultstate chunks = terminal_escape.split(text) n = 0 # count the characters we actually write, omitting the escapes res=[] for chunk in chunks: m = escape_parts.match(chunk) if m: - parts=m.group(1).split(u";") - if len(parts)==1 and parts[0]==u"0": + parts = m.group(1).split(u";") + if len(parts) == 1 and parts[0] == u"0": attr = self.defaultstate.copy() continue for part in parts: @@ -96,29 +98,29 @@ class AnsiWriter(object): elif part == u"1": # switch on bold (i.e. intensify foreground color) attr.bold=True elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color - attr.color = trtable[int(part)-30] + attr.color = trtable[int(part) - 30] elif len(part) == 2 and u"40" <= part <= u"47": # set background color - attr.color = trtable[int(part)-40] + attr.color = trtable[int(part) - 40] continue n += len(chunk) if True: - res.append((attr.copy(),chunk)) + res.append((attr.copy(), chunk)) return n,res def parse_color(self,text, attr=None): - n,res=self.write_color(text,attr) - return n,[attr.winattr for attr,text in res] + n,res=self.write_color(text, attr) + return n, [attr.winattr for attr, text in res] -def write_color(text,attr=None): - a=AnsiWriter(defaultstate) - return a.write_color(text,attr) +def write_color(text, attr=None): + a = AnsiWriter(defaultstate) + return a.write_color(text, attr) def write_color_old( text, attr=None): u'''write text at current cursor position and interpret color escapes. return the number of characters written. ''' - res=[] + res = [] chunks = terminal_escape.split(text) n = 0 # count the characters we actually write, omitting the escapes if attr is None:#use attribute from initial console @@ -138,14 +140,14 @@ def write_color_old( text, attr=None): # we have to mirror bits attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2) elif len(part) == 2 and u"40" <= part <= u"47": # set background color - part = int(part)-40 + part = int(part) - 40 # we have to mirror bits attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2) # ignore blink, underline and anything we don't understand continue n += len(chunk) if chunk: - res.append((u"0x%x"%attr,chunk)) + res.append((u"0x%x"%attr, chunk)) return res diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index b3a19c8..2ec16d2 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -156,14 +156,14 @@ funcs = [ ] # I don't want events for these keys, they are just a bother for my application -key_modifiers = { VK_SHIFT:1, - VK_CONTROL:1, - VK_MENU:1, # alt key - 0x5b:1, # windows key +key_modifiers = { VK_SHIFT : 1, + VK_CONTROL : 1, + VK_MENU : 1, # alt key + 0x5b : 1, # windows key } -def split_block(text,size=1000): - return [text[start:start+size] for start in range(0, len(text), size)] +def split_block(text, size=1000): + return [text[start:start + size] for start in range(0, len(text), size)] @@ -184,8 +184,9 @@ class Console(object): #self.AllocConsole() if newbuffer: - self.hout = self.CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, - 0, None, 1, None) + self.hout = self.CreateConsoleScreenBuffer( + GENERIC_READ | GENERIC_WRITE, + 0, None, 1, None) self.SetConsoleActiveScreenBuffer(self.hout) else: self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE) @@ -199,10 +200,9 @@ class Console(object): self.attr = info.wAttributes self.saveattr = info.wAttributes # remember the initial colors - self.defaultstate=AnsiState() - self.defaultstate.winattr=info.wAttributes - self.ansiwriter=AnsiWriter(self.defaultstate) -# self.ansiwriter.defaultstate.bold=False + self.defaultstate = AnsiState() + self.defaultstate.winattr = info.wAttributes + self.ansiwriter = AnsiWriter(self.defaultstate) background = self.attr & 0xf0 for escape in self.escape_to_color: @@ -212,8 +212,10 @@ class Console(object): self.softspace = 0 # this is for using it as a file-like object self.serial = 0 - self.pythondll = CDLL(u'python%s%s' % (sys.version[0], sys.version[2])) - self.inputHookPtr = c_int.from_address(addressof(self.pythondll.PyOS_InputHook)).value + self.pythondll = \ + CDLL(u'python%s%s' % (sys.version[0], sys.version[2])) + self.inputHookPtr = \ + c_int.from_address(addressof(self.pythondll.PyOS_InputHook)).value setattr(Console, u'PyMem_Malloc', self.pythondll.PyMem_Malloc) def __del__(self): @@ -232,7 +234,8 @@ class Console(object): return top,bot def fixcoord(self, x, y): - u'''Return a long with x and y packed inside, also handle negative x and y.''' + u'''Return a long with x and y packed inside, + also handle negative x and y.''' if x < 0 or y < 0: info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) @@ -240,8 +243,8 @@ class Console(object): x = info.srWindow.Right - x y = info.srWindow.Bottom + y - # this is a hack! ctypes won't pass structures but COORD is just like a - # long, so this works. + # this is a hack! ctypes won't pass structures but COORD is + # just like a long, so this works. return c_int(y << 16 | x) def pos(self, x=None, y=None): @@ -251,11 +254,12 @@ class Console(object): self.GetConsoleScreenBufferInfo(self.hout, byref(info)) return (info.dwCursorPosition.X, info.dwCursorPosition.Y) else: - return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y)) + return self.SetConsoleCursorPosition(self.hout, + self.fixcoord(x, y)) def home(self): u'''Move to home.''' - self.pos(0,0) + self.pos(0, 0) # Map ANSI color escape sequences into Windows Console Attributes @@ -312,7 +316,7 @@ class Console(object): elif chunk[0] == u'\r': # carriage return x = 0 elif chunk[0] == u'\t': # tab - x = 8*(int(x/8)+1) + x = 8 * (int(x / 8) + 1) if x > w: # newline x -= w y += 1 @@ -342,25 +346,27 @@ class Console(object): def write_color(self, text, attr=None): text = ensure_unicode(text) - n,res= self.ansiwriter.write_color(text,attr) + n, res= self.ansiwriter.write_color(text, attr) junk = c_int(0) for attr,chunk in res: log(u"console.attr:%s"%unicode(attr)) log(u"console.chunk:%s"%unicode(chunk)) self.SetConsoleTextAttribute(self.hout, attr.winattr) for short_chunk in split_block(chunk): - self.WriteConsoleW(self.hout, short_chunk, len(short_chunk), byref(junk), None) + self.WriteConsoleW(self.hout, short_chunk, + len(short_chunk), byref(junk), None) return n def write_plain(self, text, attr=None): u'''write text at current cursor position.''' - log(u'write("%s", %s)' %(text,attr)) + log(u'write("%s", %s)' %(text, attr)) if attr is None: attr = self.attr n = c_int(0) self.SetConsoleTextAttribute(self.hout, attr) for short_chunk in split_block(chunk): - self.WriteConsoleW(self.hout, ensure_unicode(short_chunk), len(short_chunk), byref(junk), None) + self.WriteConsoleW(self.hout, ensure_unicode(short_chunk), + len(short_chunk), byref(junk), None) return len(text) #This function must be used to ensure functioning with EMACS @@ -368,7 +374,7 @@ class Console(object): if os.environ.has_key(u"EMACS"): def write_color(self, text, attr=None): junk = c_int(0) - self.WriteFile(self.hout, text, len(text), byref(junk),None) + self.WriteFile(self.hout, text, len(text), byref(junk), None) return len(text) write_plain = write_color @@ -399,8 +405,10 @@ class Console(object): w = info.dwSize.X n = c_int(0) for y in range(info.dwSize.Y): - self.FillConsoleOutputAttribute(self.hout, attr, w, self.fixcoord(0, y), byref(n)) - self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), w, self.fixcoord(0, y), byref(n)) + self.FillConsoleOutputAttribute(self.hout, attr, + w, self.fixcoord(0, y), byref(n)) + self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), + w, self.fixcoord(0, y), byref(n)) self.attr = attr @@ -411,16 +419,17 @@ class Console(object): pos = self.fixcoord(x, y) n = c_int(0) - self.WriteConsoleOutputCharacterW(self.hout, text, len(text), pos, byref(n)) + self.WriteConsoleOutputCharacterW(self.hout, text, + len(text), pos, byref(n)) self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n)) def clear_to_end_of_window(self): - top,bot=self._get_top_bot() - pos=self.pos() - w,h=self.size() - self.rectangle( (pos[0],pos[1],w,pos[1]+1)) - if pos[1] w: # newline x -= w y += 1 @@ -183,10 +185,12 @@ class Console(object): y = h - 1 return scroll - trtable={0:color.Black,4:color.DarkRed,2:color.DarkGreen,6:color.DarkYellow, - 1:color.DarkBlue,5:color.DarkMagenta,3:color.DarkCyan,7:color.Gray, - 8:color.DarkGray,4+8:color.Red,2+8:color.Green,6+8:color.Yellow, - 1+8:color.Blue,5+8:color.Magenta,3+8:color.Cyan,7+8:color.White} + trtable = {0 : color.Black, 4 : color.DarkRed, 2 : color.DarkGreen, + 6 : color.DarkYellow, 1 : color.DarkBlue, 5 : color.DarkMagenta, + 3 : color.DarkCyan, 7 : color.Gray, 8 : color.DarkGray, + 4+8 : color.Red, 2+8 : color.Green, 6+8 : color.Yellow, + 1+8 : color.Blue, 5+8 : color.Magenta,3+8 : color.Cyan, + 7+8 : color.White} def write_color(self, text, attr=None): '''write text at current cursor position and interpret color escapes. @@ -196,31 +200,30 @@ class Console(object): log(u'write_color("%s", %s)' % (text, attr)) chunks = self.terminal_escape.split(text) log(u'chunks=%s' % repr(chunks)) - bg=self.savebg + bg = self.savebg n = 0 # count the characters we actually write, omitting the escapes if attr is None:#use attribute from initial console attr = self.attr try: - fg=self.trtable[(0x000f&attr)] - bg=self.trtable[(0x00f0&attr)>>4] + fg = self.trtable[(0x000f&attr)] + bg = self.trtable[(0x00f0&attr)>>4] except TypeError: - fg=attr + fg = attr for chunk in chunks: m = self.escape_parts.match(chunk) if m: log(m.group(1)) - attr=ansicolor.get(m.group(1),self.attr) + attr = ansicolor.get(m.group(1), self.attr) n += len(chunk) - System.Console.ForegroundColor=fg - System.Console.BackgroundColor=bg - #self.WriteConsoleA(self.hout, chunk, len(chunk), byref(junk), None) + System.Console.ForegroundColor = fg + System.Console.BackgroundColor = bg System.Console.Write(chunk) return n def write_plain(self, text, attr=None): u'''write text at current cursor position.''' - log(u'write("%s", %s)' %(text,attr)) + log(u'write("%s", %s)' %(text, attr)) if attr is None: attr = self.attr n = c_int(0) @@ -254,92 +257,87 @@ class Console(object): def text(self, x, y, text, attr=None): u'''Write text at the given position.''' - self.pos(x,y) - self.write_color(text,attr) + self.pos(x, y) + self.write_color(text, attr) def clear_to_end_of_window(self): - oldtop=self.WindowTop - lastline=self.WindowTop+System.Console.WindowHeight - pos=self.pos() - w,h=self.size() - length=w-pos[0]+min((lastline-pos[1]-1),5)*w-1 - self.write_color(length*u" ") + oldtop = self.WindowTop + lastline = self.WindowTop+System.Console.WindowHeight + pos = self.pos() + w, h = self.size() + length = w - pos[0] + min((lastline - pos[1] - 1), 5) * w - 1 + self.write_color(length * u" ") self.pos(*pos) - self.WindowTop=oldtop + self.WindowTop = oldtop def rectangle(self, rect, attr=None, fill=u' '): u'''Fill Rectangle.''' - pass - oldtop=self.WindowTop - oldpos=self.pos() + oldtop = self.WindowTop + oldpos = self.pos() #raise NotImplementedError x0, y0, x1, y1 = rect if attr is None: attr = self.attr if fill: - rowfill=fill[:1]*abs(x1-x0) + rowfill = fill[:1] * abs(x1 - x0) else: - rowfill=u' '*abs(x1-x0) + rowfill = u' ' * abs(x1 - x0) for y in range(y0, y1): - System.Console.SetCursorPosition(x0,y) - self.write_color(rowfill,attr) + System.Console.SetCursorPosition(x0, y) + self.write_color(rowfill, attr) self.pos(*oldpos) def scroll(self, rect, dx, dy, attr=None, fill=' '): u'''Scroll a rectangle.''' - pass raise NotImplementedError def scroll_window(self, lines): u'''Scroll the window by the indicated number of lines.''' - top=self.WindowTop+lines - if top<0: - top=0 - if top+System.Console.WindowHeight>System.Console.BufferHeight: - top=System.Console.BufferHeight - self.WindowTop=top + top = self.WindowTop + lines + if top < 0: + top = 0 + if top + System.Console.WindowHeight > System.Console.BufferHeight: + top = System.Console.BufferHeight + self.WindowTop = top def getkeypress(self): u'''Return next key press event from the queue, ignoring others.''' - ck=System.ConsoleKey + ck = System.ConsoleKey while 1: e = System.Console.ReadKey(True) if e.Key == System.ConsoleKey.PageDown: #PageDown self.scroll_window(12) elif e.Key == System.ConsoleKey.PageUp:#PageUp self.scroll_window(-12) - elif str(e.KeyChar)==u"\000":#Drop deadkeys + elif str(e.KeyChar) == u"\000":#Drop deadkeys log(u"Deadkey: %s"%e) - return event(self,e) - pass + return event(self, e) else: - return event(self,e) + return event(self, e) def title(self, txt=None): u'''Set/get title.''' if txt: - System.Console.Title=txt + System.Console.Title = txt else: return System.Console.Title def size(self, width=None, height=None): u'''Set/get window size.''' - sc=System.Console - - + sc = System.Console if width is not None and height is not None: - sc.BufferWidth,sc.BufferHeight=width,height + sc.BufferWidth, sc.BufferHeight = width,height else: - return sc.BufferWidth,sc.BufferHeight + return sc.BufferWidth, sc.BufferHeight if width is not None and height is not None: - sc.WindowWidth,sc.WindowHeight=width,height + sc.WindowWidth, sc.WindowHeight = width,height else: - return sc.WindowWidth-1,sc.WindowHeight-1 + return sc.WindowWidth - 1, sc.WindowHeight - 1 def cursor(self, visible=True, size=None): u'''Set cursor on or off.''' - System.Console.CursorVisible=visible + System.Console.CursorVisible = visible def bell(self): System.Console.Beep() @@ -362,22 +360,22 @@ class event(Event): self.char = str(input.KeyChar) self.keycode = input.Key self.state = input.Modifiers - log(u"%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar)) - self.type="KeyRelease" + log(u"%s,%s,%s"%(input.Modifiers, input.Key, input.KeyChar)) + self.type = "KeyRelease" self.keysym = make_keysym(self.keycode) self.keyinfo = make_KeyPress(self.char, self.state, self.keycode) def make_event_from_keydescr(keydescr): def input(): return 1 - input.KeyChar=u"a" - input.Key=System.ConsoleKey.A - input.Modifiers=System.ConsoleModifiers.Shift - input.next_serial=input - e=event(input,input) + input.KeyChar = u"a" + input.Key = System.ConsoleKey.A + input.Modifiers = System.ConsoleModifiers.Shift + input.next_serial = input + e = event(input,input) del input.next_serial - keyinfo=make_KeyPress_from_keydescr(keydescr) - e.keyinfo=keyinfo + keyinfo = make_KeyPress_from_keydescr(keydescr) + e.keyinfo = keyinfo return e CTRL_C_EVENT=make_event_from_keydescr(u"Control-c") @@ -385,21 +383,21 @@ CTRL_C_EVENT=make_event_from_keydescr(u"Control-c") def install_readline(hook): def hook_wrap(): try: - res=hook() + res = hook() except KeyboardInterrupt,x: #this exception does not seem to be caught - res=u"" + res = u"" except EOFError: return None - if res[-1:]==u"\n": + if res[-1:] == u"\n": return res[:-1] else: return res class IronPythonWrapper(IronPythonConsole.IConsole): - def ReadLine(self,autoIndentSize): + def ReadLine(self, autoIndentSize): return hook_wrap() - def Write(self,text, style): + def Write(self, text, style): System.Console.Write(text) - def WriteLine(self,text, style): + def WriteLine(self, text, style): System.Console.WriteLine(text) IronPythonConsole.PythonCommandLine.MyConsole = IronPythonWrapper() @@ -416,11 +414,11 @@ if __name__ == u'__main__': c.title(u"Testing console") # c.bell() print - print u"size",c.size() + print u"size", c.size() print u' some printed output' for i in range(10): - e=c.getkeypress() - print e.Key,chr(e.KeyChar),ord(e.KeyChar),e.Modifiers + e = c.getkeypress() + print e.Key, chr(e.KeyChar), ord(e.KeyChar), e.Modifiers del c System.Console.Clear() From 0e8e0c22e3cf57951d5c1e6c81567de7e78f7cca Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Wed, 12 Nov 2008 22:23:08 +0100 Subject: [PATCH 22/26] Ensure unicode from completions in logmessage --- pyreadline/modes/basemode.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pyreadline/modes/basemode.py b/pyreadline/modes/basemode.py index c5596ef..c5b118a 100644 --- a/pyreadline/modes/basemode.py +++ b/pyreadline/modes/basemode.py @@ -190,7 +190,7 @@ class BaseMode(object): self.begidx += 1 break text = ensure_str(u''.join(buf[self.begidx:self.endidx])) - log(u'complete text="%s"' % text) + log(u'complete text="%s"' % ensure_unicode(text)) i = 0 while 1: try: @@ -202,7 +202,7 @@ class BaseMode(object): completions.append(r) else: break - log(u'text completions=<%s>' % completions) + log(u'text completions=<%s>' % map(ensure_unicode, completions)) if not completions: # get the filename to complete while self.begidx > 0: @@ -211,7 +211,7 @@ class BaseMode(object): self.begidx += 1 break text = ensure_str(u''.join(buf[self.begidx:self.endidx])) - log(u'file complete text="%s"' % text) + log(u'file complete text="%s"' % ensure_unicode(text)) completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*')) if self.mark_directories == u'on': mc = [] @@ -221,7 +221,7 @@ class BaseMode(object): else: mc.append(f) completions = mc - log(u'fnames=<%s>' % completions) + log(u'fnames=<%s>' % map(ensure_unicode, completions)) return completions From ece97cb36e8f8af2197d2b82e1a964fad76b3926 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Wed, 12 Nov 2008 22:31:13 +0100 Subject: [PATCH 23/26] Reformatted pyreadline/keysyms/*.py --- pyreadline/console/console.py | 14 ++-- pyreadline/keysyms/__init__.py | 14 ++-- pyreadline/keysyms/common.py | 95 ++++++++++++------------ pyreadline/keysyms/ironpython_keysyms.py | 37 +++++---- pyreadline/keysyms/keysyms.py | 12 +-- 5 files changed, 85 insertions(+), 87 deletions(-) diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index 2ec16d2..9c645a6 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -16,20 +16,20 @@ This was modeled after the C extension of the same name by Fredrik Lundh. import sys,os import traceback import re -from pyreadline.logger import log -from pyreadline.unicode_helper import ensure_unicode,ensure_str + import pyreadline.unicode_helper as unicode_helper + +from pyreadline.logger import log +from pyreadline.unicode_helper import ensure_unicode, ensure_str +from pyreadline.keysyms import make_KeyPress +from pyreadline.console.ansi import AnsiState,AnsiWriter + try: from ctypes import * from _ctypes import call_function except ImportError: raise ImportError(u"You need ctypes to run this code") -# my code -from pyreadline.keysyms import make_KeyPress -from pyreadline.console.ansi import AnsiState,AnsiWriter - - def nolog(string): pass diff --git a/pyreadline/keysyms/__init__.py b/pyreadline/keysyms/__init__.py index 8c3ef5e..ae3aec2 100644 --- a/pyreadline/keysyms/__init__.py +++ b/pyreadline/keysyms/__init__.py @@ -1,20 +1,20 @@ import sys -success=False -in_ironpython=u"IronPython" in sys.version +success = False +in_ironpython = u"IronPython" in sys.version if in_ironpython: try: from ironpython_keysyms import * - success=True - except ImportError,x: + success = True + except ImportError, x: raise else: try: from keysyms import * - success=True - except ImportError,x: + success = True + except ImportError, x: pass if not success: - raise ImportError(u"Could not import keysym for local pythonversion",x) \ No newline at end of file + raise ImportError(u"Could not import keysym for local pythonversion", x) \ No newline at end of file diff --git a/pyreadline/keysyms/common.py b/pyreadline/keysyms/common.py index d1a6266..df43ec7 100644 --- a/pyreadline/keysyms/common.py +++ b/pyreadline/keysyms/common.py @@ -15,67 +15,68 @@ except NameError: from pyreadline.unicode_helper import ensure_unicode -validkey =set([u'cancel', u'backspace', u'tab', u'clear', - u'return', u'shift_l', u'control_l', u'alt_l', - u'pause', u'caps_lock', u'escape', u'space', - u'prior', u'next', u'end', u'home', - u'left', u'up', u'right', u'down', - u'select', u'print', u'execute', u'snapshot', - u'insert', u'delete', u'help', u'f1', - u'f2', u'f3', u'f4', u'f5', - u'f6', u'f7', u'f8', u'f9', - u'f10', u'f11', u'f12', u'f13', - u'f14', u'f15', u'f16', u'f17', - u'f18', u'f19', u'f20', u'f21', - u'f22', u'f23', u'f24', u'num_lock', - u'scroll_lock', u'vk_apps', u'vk_processkey',u'vk_attn', - u'vk_crsel', u'vk_exsel', u'vk_ereof', u'vk_play', - u'vk_zoom', u'vk_noname', u'vk_pa1', u'vk_oem_clear', - u'numpad0', u'numpad1', u'numpad2', u'numpad3', - u'numpad4', u'numpad5', u'numpad6', u'numpad7', - u'numpad8', u'numpad9', u'divide', u'multiply', - u'add', u'subtract', u'vk_decimal']) +validkey =set([u'cancel', u'backspace', u'tab', u'clear', + u'return', u'shift_l', u'control_l', u'alt_l', + u'pause', u'caps_lock', u'escape', u'space', + u'prior', u'next', u'end', u'home', + u'left', u'up', u'right', u'down', + u'select', u'print', u'execute', u'snapshot', + u'insert', u'delete', u'help', u'f1', + u'f2', u'f3', u'f4', u'f5', + u'f6', u'f7', u'f8', u'f9', + u'f10', u'f11', u'f12', u'f13', + u'f14', u'f15', u'f16', u'f17', + u'f18', u'f19', u'f20', u'f21', + u'f22', u'f23', u'f24', u'num_lock', + u'scroll_lock', u'vk_apps', u'vk_processkey',u'vk_attn', + u'vk_crsel', u'vk_exsel', u'vk_ereof', u'vk_play', + u'vk_zoom', u'vk_noname', u'vk_pa1', u'vk_oem_clear', + u'numpad0', u'numpad1', u'numpad2', u'numpad3', + u'numpad4', u'numpad5', u'numpad6', u'numpad7', + u'numpad8', u'numpad9', u'divide', u'multiply', + u'add', u'subtract', u'vk_decimal']) -escape_sequence_to_special_key={u"\\e[a":u"up", u"\\e[b":u"down", u"del":u"delete"} +escape_sequence_to_special_key = {u"\\e[a" : u"up", u"\\e[b" : u"down", u"del" : u"delete"} class KeyPress(object): - def __init__(self,char="",shift=False,control=False,meta=False,keyname=u""): + def __init__(self, char="", shift=False, control=False, meta=False,keyname=u""): if control or meta or shift: - char=char.upper() - self.info=dict(char=char, - shift=shift, - control=control, - meta=meta, - keyname=keyname) + char = char.upper() + self.info = dict(char=char, + shift=shift, + control=control, + meta=meta, + keyname=keyname) def create(name): def get(self): return self.info[name] - def set(self,value): - self.info[name]=value - return property(get,set) - char=create(u"char") - shift=create(u"shift") - control=create(u"control") - meta=create(u"meta") - keyname=create(u"keyname") + + def set(self, value): + self.info[name] = value + return property(get, set) + char = create(u"char") + shift = create(u"shift") + control = create(u"control") + meta = create(u"meta") + keyname = create(u"keyname") def __repr__(self): - return u"(%s,%s,%s,%s)"%tuple(map(ensure_unicode,self.tuple())) + return u"(%s,%s,%s,%s)"%tuple(map(ensure_unicode, self.tuple())) def tuple(self): if self.keyname: - return (self.control,self.meta,self.shift,self.keyname) + return (self.control, self.meta, self.shift, self.keyname) else: if self.control or self.meta or self.shift: - return (self.control,self.meta,self.shift,self.char.upper()) + return (self.control, self.meta, self.shift, self.char.upper()) else: - return (self.control,self.meta,self.shift,self.char) + return (self.control, self.meta, self.shift, self.char) def make_KeyPress_from_keydescr(keydescr): - keyinfo=KeyPress() - if len(keydescr)>2 and keydescr[:1]==u'"' and keydescr[-1:]==u'"': - keydescr=keydescr[1:-1] + keyinfo = KeyPress() + if len(keydescr) > 2 and keydescr[:1] == u'"' and keydescr[-1:] == u'"': + keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() @@ -105,14 +106,14 @@ def make_KeyPress_from_keydescr(keydescr): else: if len(keydescr) > 1: if keydescr.strip().lower() in validkey: - keyinfo.keyname=keydescr.strip().lower() - keyinfo.char="" + keyinfo.keyname = keydescr.strip().lower() + keyinfo.char = "" else: raise IndexError(u"Not a valid key: '%s'"%keydescr) else: - keyinfo.char=keydescr + keyinfo.char = keydescr return keyinfo -if __name__==u"__main__": +if __name__ == u"__main__": import startup \ No newline at end of file diff --git a/pyreadline/keysyms/ironpython_keysyms.py b/pyreadline/keysyms/ironpython_keysyms.py index be387f2..783940c 100644 --- a/pyreadline/keysyms/ironpython_keysyms.py +++ b/pyreadline/keysyms/ironpython_keysyms.py @@ -7,12 +7,12 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** import System -from common import validkey,KeyPress,make_KeyPress_from_keydescr +from common import validkey, KeyPress, make_KeyPress_from_keydescr -c32=System.ConsoleKey -Shift=System.ConsoleModifiers.Shift -Control=System.ConsoleModifiers.Control -Alt=System.ConsoleModifiers.Alt +c32 = System.ConsoleKey +Shift = System.ConsoleModifiers.Shift +Control = System.ConsoleModifiers.Control +Alt = System.ConsoleModifiers.Alt # table for translating virtual keys to X windows key symbols code2sym_map = {#c32.CANCEL: u'Cancel', c32.Backspace: u'BackSpace', @@ -181,25 +181,22 @@ def keyseq_to_keyinfo(keyseq): return res[0] def make_keyinfo(keycode, state): -# control = (state & (4+8)) != 0 -# meta = (state & (1+2)) != 0 -# shift = (state & 0x10) != 0 - control=False - meta=False - shift=False + control = False + meta =False + shift = False return (control, meta, shift, keycode) -def make_KeyPress(char,state,keycode): +def make_KeyPress(char, state, keycode): - shift=bool(int(state)&int(Shift)) - control=bool(int(state)&int(Control)) - meta=bool(int(state)&int(Alt)) - keyname=code2sym_map.get(keycode,u"").lower() + shift = bool(int(state) & int(Shift)) + control = bool(int(state) & int(Control)) + meta = bool(int(state) & int(Alt)) + keyname = code2sym_map.get(keycode, u"").lower() if control and meta: #equivalent to altgr so clear flags - control=False - meta=False + control = False + meta = False elif control: - char=str(keycode) - return KeyPress(char,shift,control,meta,keyname) + char = str(keycode) + return KeyPress(char, shift, control, meta, keyname) diff --git a/pyreadline/keysyms/keysyms.py b/pyreadline/keysyms/keysyms.py index ee77186..fd7d0c7 100644 --- a/pyreadline/keysyms/keysyms.py +++ b/pyreadline/keysyms/keysyms.py @@ -12,7 +12,7 @@ from ctypes import windll import ctypes # table for translating virtual keys to X windows key symbols -from common import validkey,KeyPress,make_KeyPress_from_keydescr +from common import validkey, KeyPress, make_KeyPress_from_keydescr code2sym_map = {c32.VK_CANCEL: u'cancel', c32.VK_BACK: u'backspace', @@ -117,15 +117,15 @@ def make_KeyPress(char, state, keycode): meta = (state & (1+2)) != 0 shift = (state & 0x10) != 0 if control and not meta:#Matches ctrl- chords should pass keycode as char - char=chr(keycode) + char = chr(keycode) elif control and meta: #Matches alt gr and should just pass on char - control=False - meta=False + control = False + meta = False try: keyname=code2sym_map[keycode] except KeyError: - keyname=u"" - out=KeyPress(char, shift, control, meta, keyname) + keyname = u"" + out = KeyPress(char, shift, control, meta, keyname) return out if __name__==u"__main__": From f08b5b1c5a6adc9e507a45b09f37997aa766f43c Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Wed, 12 Nov 2008 22:56:56 +0100 Subject: [PATCH 24/26] reformatting pyreadline/lineeditor/*.py --- pyreadline/lineeditor/history.py | 128 ++--- pyreadline/lineeditor/lineobj.py | 686 +++++++++++++-------------- pyreadline/lineeditor/wordmatcher.py | 105 ++-- 3 files changed, 465 insertions(+), 454 deletions(-) diff --git a/pyreadline/lineeditor/history.py b/pyreadline/lineeditor/history.py index 15a25c8..0ee9d71 100644 --- a/pyreadline/lineeditor/history.py +++ b/pyreadline/lineeditor/history.py @@ -5,11 +5,11 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -import re,operator,string,sys,os +import re, operator,string, sys,os -from pyreadline.unicode_helper import ensure_unicode,ensure_str +from pyreadline.unicode_helper import ensure_unicode, ensure_str if u"pyreadline" in sys.modules: - pyreadline= sys.modules[u"pyreadline"] + pyreadline = sys.modules[u"pyreadline"] else: import pyreadline @@ -22,37 +22,37 @@ class EscapeHistory(exceptions.Exception): from pyreadline.logger import log -_ignore_leading_spaces=False +_ignore_leading_spaces = False class LineHistory(object): def __init__(self): - self.history=[] - self._history_length=100 - self._history_cursor=0 - self.history_filename=os.path.expanduser('~/.history') #Cannot expand unicode strings correctly on python2.4 - self.lastcommand=None - self.query=u"" + self.history = [] + self._history_length = 100 + self._history_cursor = 0 + self.history_filename = os.path.expanduser('~/.history') #Cannot expand unicode strings correctly on python2.4 + self.lastcommand = None + self.query = u"" def get_history_length(self): - value=self._history_length + value = self._history_length log(u"get_history_length:%d"%value) return value - def set_history_length(self,value): - log(u"set_history_length: old:%d new:%d"%(self._history_length,value)) - self._history_length=value + def set_history_length(self, value): + log(u"set_history_length: old:%d new:%d"%(self._history_length, value)) + self._history_length = value def get_history_cursor(self): - value=self._history_cursor + value = self._history_cursor log(u"get_history_cursor:%d"%value) return value - def set_history_cursor(self,value): - log(u"set_history_cursor: old:%d new:%d"%(self._history_cursor,value)) - self._history_cursor=value + def set_history_cursor(self, value): + log(u"set_history_cursor: old:%d new:%d"%(self._history_cursor, value)) + self._history_cursor = value - history_length=property(get_history_length,set_history_length) - history_cursor=property(get_history_cursor,set_history_cursor) + history_length = property(get_history_length, set_history_length) + history_cursor = property(get_history_cursor, set_history_cursor) def clear_history(self): u'''Clear readline history.''' @@ -62,7 +62,7 @@ class LineHistory(object): def read_history_file(self, filename=None): u'''Load a readline history file.''' if filename is None: - filename=self.history_filename + filename = self.history_filename try: for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip()))) @@ -70,10 +70,10 @@ class LineHistory(object): self.history = [] self.history_cursor = 0 - def write_history_file(self, filename=None): + def write_history_file(self, filename = None): u'''Save a readline history file.''' if filename is None: - filename=self.history_filename + filename = self.history_filename fp = open(filename, u'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_text())) @@ -91,19 +91,19 @@ class LineHistory(object): self.history.append(line) self.history_cursor = len(self.history) - def previous_history(self,current): # (C-p) + def previous_history(self, current): # (C-p) u'''Move back through the history list, fetching the previous command. ''' - if self.history_cursor==len(self.history): + if self.history_cursor == len(self.history): self.history.append(current.copy()) #do not use add_history since we do not want to increment cursor if self.history_cursor > 0: self.history_cursor -= 1 current.set_line(self.history[self.history_cursor].get_line_text()) - current.point=lineobj.EndOfLine + current.point = lineobj.EndOfLine - def next_history(self,current): # (C-n) + def next_history(self, current): # (C-n) u'''Move forward through the history list, fetching the next command. ''' - if self.history_cursor < len(self.history)-1: + if self.history_cursor < len(self.history) - 1: self.history_cursor += 1 current.set_line(self.history[self.history_cursor].get_line_text()) @@ -113,33 +113,41 @@ class LineHistory(object): if len(self.history) > 0: self.l_buffer = self.history[0] - def end_of_history(self,current): # (M->) + def end_of_history(self, current): # (M->) u'''Move to the end of the input history, i.e., the line currently being entered.''' - self.history_cursor=len(self.history) + self.history_cursor = len(self.history) current.set_line(self.history[-1].get_line_text()) - def reverse_search_history(self,searchfor,startpos=None): + def reverse_search_history(self, searchfor, startpos=None): if startpos is None: - startpos=self.history_cursor + startpos = self.history_cursor if _ignore_leading_spaces: - res=[(idx,line.lstrip()) for idx,line in enumerate(self.history[startpos:0:-1]) if line.lstrip().startswith(searchfor.lstrip())] + res = [(idx, line.lstrip()) + for idx, line in enumerate(self.history[startpos:0:-1]) + if line.lstrip().startswith(searchfor.lstrip())] else: - res=[(idx,line) for idx,line in enumerate(self.history[startpos:0:-1]) if line.startswith(searchfor)] + res = [(idx, line) + for idx, line in enumerate(self.history[startpos:0:-1]) + if line.startswith(searchfor)] if res: - self.history_cursor-=res[0][0] + self.history_cursor -= res[0][0] return res[0][1].get_line_text() return u"" - def forward_search_history(self,searchfor,startpos=None): + def forward_search_history(self, searchfor, startpos=None): if startpos is None: - startpos=self.history_cursor + startpos = self.history_cursor if _ignore_leading_spaces: - res=[(idx,line.lstrip()) for idx,line in enumerate(self.history[startpos:]) if line.lstrip().startswith(searchfor.lstrip())] + res = [(idx, line.lstrip()) + for idx, line in enumerate(self.history[startpos:]) + if line.lstrip().startswith(searchfor.lstrip())] else: - res=[(idx,line) for idx,line in enumerate(self.history[startpos:]) if line.startswith(searchfor)] + res = [(idx, line) + for idx, line in enumerate(self.history[startpos:]) + if line.startswith(searchfor)] if res: - self.history_cursor+=res[0][0] + self.history_cursor += res[0][0] return res[0][1].get_line_text() return u"" @@ -148,51 +156,57 @@ class LineHistory(object): if (self.lastcommand != self.history_search_forward and self.lastcommand != self.history_search_backward): self.query = u''.join(partial[0:partial.point].get_line_text()) - hcstart=max(self.history_cursor,0) + hcstart = max(self.history_cursor,0) hc = self.history_cursor + direction while (direction < 0 and hc >= 0) or (direction > 0 and hc < len(self.history)): h = self.history[hc] if not self.query: self.history_cursor = hc - result=lineobj.ReadLineTextBuffer(h,point=len(h.get_line_text())) + result = lineobj.ReadLineTextBuffer(h, point=len(h.get_line_text())) return result elif (h.get_line_text().startswith(self.query) and (h != partial.get_line_text())): self.history_cursor = hc - result=lineobj.ReadLineTextBuffer(h,point=partial.point) + result = lineobj.ReadLineTextBuffer(h, point=partial.point) return result hc += direction else: - if len(self.history)==0: + if len(self.history) == 0: pass - elif hc>=len(self.history) and not self.query: - self.history_cursor=len(self.history) - return lineobj.ReadLineTextBuffer(u"",point=0) - elif self.history[max(min(hcstart,len(self.history)-1),0)].get_line_text().startswith(self.query) and self.query: - return lineobj.ReadLineTextBuffer(self.history[max(min(hcstart,len(self.history)-1),0)],point=partial.point) + elif hc >= len(self.history) and not self.query: + self.history_cursor = len(self.history) + return lineobj.ReadLineTextBuffer(u"", point=0) + elif self.history[max(min(hcstart, len(self.history) - 1), 0)]\ + .get_line_text().startswith(self.query) and self.query: + return lineobj.ReadLineTextBuffer(self.history\ + [max(min(hcstart, len(self.history) - 1),0)], + point = partial.point) else: - return lineobj.ReadLineTextBuffer(partial,point=partial.point) - return lineobj.ReadLineTextBuffer(self.query,point=min(len(self.query),partial.point)) + return lineobj.ReadLineTextBuffer(partial, + point=partial.point) + return lineobj.ReadLineTextBuffer(self.query, + point=min(len(self.query), + partial.point)) except IndexError: raise - def history_search_forward(self,partial): # () + def history_search_forward(self, partial): # () u'''Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' - q= self._search(1,partial) + q= self._search(1, partial) return q - def history_search_backward(self,partial): # () + def history_search_backward(self, partial): # () u'''Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' - q= self._search(-1,partial) + q= self._search(-1, partial) return q if __name__==u"__main__": - q=LineHistory() - RL=lineobj.ReadLineTextBuffer + q = LineHistory() + RL = lineobj.ReadLineTextBuffer q.add_history(RL(u"aaaa")) q.add_history(RL(u"aaba")) q.add_history(RL(u"aaca")) diff --git a/pyreadline/lineeditor/lineobj.py b/pyreadline/lineeditor/lineobj.py index 9b3ab0f..4347ffb 100644 --- a/pyreadline/lineeditor/lineobj.py +++ b/pyreadline/lineeditor/lineobj.py @@ -5,14 +5,14 @@ # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** -import re,operator,sys +import re, operator, sys import wordmatcher import pyreadline.clipboard as clipboard from pyreadline.logger import log from pyreadline.unicode_helper import ensure_unicode -kill_ring_to_clipboard=False #set to true to copy every addition to kill ring to clipboard +kill_ring_to_clipboard = False #set to true to copy every addition to kill ring to clipboard class NotAWordError(IndexError): @@ -20,180 +20,182 @@ class NotAWordError(IndexError): def quote_char(c): - if ord(c)>0: + if ord(c) > 0: return c ############## Line positioner ######################## class LinePositioner(object): - def __call__(self,line): + def __call__(self, line): NotImplementedError(u"Base class !!!") class NextChar(LinePositioner): - def __call__(self,line): - if line.point0: - return line.point-1 + def __call__(self, line): + if line.point > 0: + return line.point - 1 else: return line.point -PrevChar=PrevChar() +PrevChar = PrevChar() class NextWordStart(LinePositioner): - def __call__(self,line): - return line.next_start_segment(line.line_buffer,line.is_word_token)[line.point] -NextWordStart=NextWordStart() + def __call__(self, line): + return line.next_start_segment(line.line_buffer, line.is_word_token)[line.point] +NextWordStart = NextWordStart() class NextWordEnd(LinePositioner): - def __call__(self,line): - return line.next_end_segment(line.line_buffer,line.is_word_token)[line.point] -NextWordEnd=NextWordEnd() + def __call__(self, line): + return line.next_end_segment(line.line_buffer, line.is_word_token)[line.point] +NextWordEnd = NextWordEnd() class PrevWordStart(LinePositioner): - def __call__(self,line): - return line.prev_start_segment(line.line_buffer,line.is_word_token)[line.point] -PrevWordStart=PrevWordStart() + def __call__(self, line): + return line.prev_start_segment(line.line_buffer, line.is_word_token)[line.point] +PrevWordStart = PrevWordStart() class WordStart(LinePositioner): - def __call__(self,line): - if line.is_word_token(line.get_line_text()[Point(line):Point(line)+1]): - if Point(line)>0 and line.is_word_token(line.get_line_text()[Point(line)-1:Point(line)]): + def __call__(self, line): + if line.is_word_token(line.get_line_text()[Point(line):Point(line) + 1]): + if Point(line) > 0 and line.is_word_token(line.get_line_text()[Point(line) - 1:Point(line)]): return PrevWordStart(line) else: return line.point else: raise NotAWordError(u"Point is not in a word") -WordStart=WordStart() +WordStart = WordStart() class WordEnd(LinePositioner): - def __call__(self,line): - if line.is_word_token(line.get_line_text()[Point(line):Point(line)+1]): - if line.is_word_token(line.get_line_text()[Point(line)+1:Point(line)+2]): + def __call__(self, line): + if line.is_word_token(line.get_line_text()[Point(line):Point(line) + 1]): + if line.is_word_token(line.get_line_text()[Point(line) + 1:Point(line) + 2]): return NextWordEnd(line) else: return line.point else: raise NotAWordError(u"Point is not in a word") -WordEnd=WordEnd() +WordEnd = WordEnd() class PrevWordEnd(LinePositioner): - def __call__(self,line): - return line.prev_end_segment(line.line_buffer,line.is_word_token)[line.point] -PrevWordEnd=PrevWordEnd() + def __call__(self, line): + return line.prev_end_segment(line.line_buffer, line.is_word_token)[line.point] +PrevWordEnd = PrevWordEnd() class PrevSpace(LinePositioner): - def __call__(self,line): - point=line.point - if line[point-1:point].get_line_text()==u" ": - while point>0 and line[point-1:point].get_line_text()==u" ": - point-=1 - while point>0 and line[point-1:point].get_line_text()!=u" ": - point-=1 + def __call__(self, line): + point = line.point + if line[point - 1:point].get_line_text() == u" ": + while point > 0 and line[point - 1:point].get_line_text() == u" ": + point -= 1 + while point > 0 and line[point - 1:point].get_line_text() != u" ": + point -= 1 return point -PrevSpace=PrevSpace() +PrevSpace = PrevSpace() class StartOfLine(LinePositioner): - def __call__(self,line): + def __call__(self, line): return 0 -StartOfLine=StartOfLine() +StartOfLine = StartOfLine() class EndOfLine(LinePositioner): - def __call__(self,line): + def __call__(self, line): return len(line.line_buffer) -EndOfLine=EndOfLine() +EndOfLine = EndOfLine() class Point(LinePositioner): - def __call__(self,line): + def __call__(self, line): return line.point -Point=Point() +Point = Point() class Mark(LinePositioner): - def __call__(self,line): + def __call__(self, line): return line.mark -Mark=Mark() +k = Mark() -all_positioners=[(value.__class__.__name__,value) for key,value in globals().items() if isinstance(value,LinePositioner)] +all_positioners = [(value.__class__.__name__, value) + for key, value in globals().items() + if isinstance(value, LinePositioner)] all_positioners.sort() ############### LineSlice ################# class LineSlice(object): - def __call__(self,line): + def __call__(self, line): NotImplementedError(u"Base class !!!") class CurrentWord(LineSlice): - def __call__(self,line): - return slice(WordStart(line),WordEnd(line),None) -CurrentWord=CurrentWord() + def __call__(self, line): + return slice(WordStart(line), WordEnd(line), None) +CurrentWord = CurrentWord() class NextWord(LineSlice): - def __call__(self,line): - work=TextLine(line) - work.point=NextWordStart - start=work.point - stop=NextWordEnd(work) - return slice(start,stop) -NextWord=NextWord() + def __call__(self, line): + work = TextLine(line) + work.point = NextWordStart + start = work.point + stop = NextWordEnd(work) + return slice(start, stop) +NextWord = NextWord() class PrevWord(LineSlice): - def __call__(self,line): - work=TextLine(line) - work.point=PrevWordEnd - stop=work.point - start=PrevWordStart(work) - return slice(start,stop) -PrevWord=PrevWord() + def __call__(self, line): + work = TextLine(line) + work.point = PrevWordEnd + stop = work.point + start = PrevWordStart(work) + return slice(start, stop) +PrevWord = PrevWord() class PointSlice(LineSlice): - def __call__(self,line): - return slice(Point(line),Point(line)+1,None) -PointSlice=PointSlice() + def __call__(self, line): + return slice(Point(line), Point(line) + 1, None) +PointSlice = PointSlice() ############### TextLine ###################### class TextLine(object): - def __init__(self,txtstr,point=None,mark=None): - self.line_buffer=[] - self._point=0 - self.mark=-1 - self.undo_stack=[] - self.overwrite=False - if isinstance(txtstr,TextLine): #copy - self.line_buffer=txtstr.line_buffer[:] + def __init__(self, txtstr, point = None, mark = None): + self.line_buffer = [] + self._point = 0 + self.mark = -1 + self.undo_stack = [] + self.overwrite = False + if isinstance(txtstr, TextLine): #copy + self.line_buffer = txtstr.line_buffer[:] if point is None: - self.point=txtstr.point + self.point = txtstr.point else: - self.point=point + self.point = point if mark is None: - self.mark=txtstr.mark + self.mark = txtstr.mark else: - self.mark=mark + self.mark = mark else: self._insert_text(txtstr) if point is None: - self.point=0 + self.point = 0 else: - self.point=point + self.point = point if mark is None: - self.mark=-1 + self.mark = -1 else: - self.mark=mark + self.mark = mark - self.is_word_token=wordmatcher.is_word_token - self.next_start_segment=wordmatcher.next_start_segment - self.next_end_segment=wordmatcher.next_end_segment - self.prev_start_segment=wordmatcher.prev_start_segment - self.prev_end_segment=wordmatcher.prev_end_segment + self.is_word_token = wordmatcher.is_word_token + self.next_start_segment = wordmatcher.next_start_segment + self.next_end_segment = wordmatcher.next_end_segment + self.prev_start_segment = wordmatcher.prev_start_segment + self.prev_end_segment = wordmatcher.prev_end_segment def push_undo(self): ltext = self.get_line_text() @@ -213,47 +215,47 @@ class TextLine(object): def set_top_undo(self): if self.undo_stack: - undo=self.undo_stack[-1] - self.line_buffer=undo.line_buffer - self.point=undo.point - self.mark=undo.mark + undo = self.undo_stack[-1] + self.line_buffer = undo.line_buffer + self.point = undo.point + self.mark = undo.mark else: pass def __repr__(self): - return u'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer,self.point,self.mark) + return u'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer, self.point, self.mark) def copy(self): return self.__class__(self) def set_point(self,value): - if isinstance(value,LinePositioner): - value=value(self) + if isinstance(value, LinePositioner): + value = value(self) assert (value <= len(self.line_buffer)) - if value>len(self.line_buffer): - value=len(self.line_buffer) - self._point=value + if value > len(self.line_buffer): + value = len(self.line_buffer) + self._point = value def get_point(self): return self._point - point=property(get_point,set_point) + point = property(get_point, set_point) - def visible_line_width(self,position=Point): + def visible_line_width(self, position = Point): """Return the visible width of the text in line buffer up to position.""" extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD]) - return len(self[:position].quoted_text())+self[:position].line_buffer.count(u"\t")*7 + extra_char_width + return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u"\t")*7 + extra_char_width def quoted_text(self): quoted = [ quote_char(c) for c in self.line_buffer ] self.line_char_width = [ len(c) for c in quoted ] - return u''.join(map(ensure_unicode,quoted)) + return u''.join(map(ensure_unicode, quoted)) def get_line_text(self): - buf=self.line_buffer - buf=map(ensure_unicode,buf) + buf = self.line_buffer + buf = map(ensure_unicode, buf) return u''.join(buf) - def set_line(self, text, cursor=None): + def set_line(self, text, cursor = None): self.line_buffer = [ c for c in str(text) ] if cursor is None: self.point = len(self.line_buffer) @@ -268,148 +270,150 @@ class TextLine(object): self.point = len(self.line_buffer) def _insert_text(self, text, argument=1): - text=text*argument + text = text * argument if self.overwrite: for c in text: #if self.point: - self.line_buffer[self.point]= c + self.line_buffer[self.point] = c self.point += 1 else: for c in text: self.line_buffer.insert(self.point, c) self.point += 1 - def __getitem__(self,key): + def __getitem__(self, key): #Check if key is LineSlice, convert to regular slice #and continue processing - if isinstance(key,LineSlice): - key=key(self) - if isinstance(key,slice): + if isinstance(key, LineSlice): + key = key(self) + if isinstance(key, slice): if key.step is None: pass else: raise Error if key.start is None: - start=StartOfLine(self) + start = StartOfLine(self) elif isinstance(key.start,LinePositioner): - start=key.start(self) + start = key.start(self) else: - start=key.start + start = key.start if key.stop is None: - stop=EndOfLine(self) - elif isinstance(key.stop,LinePositioner): - stop=key.stop(self) + stop = EndOfLine(self) + elif isinstance(key.stop, LinePositioner): + stop = key.stop(self) else: - stop=key.stop - return self.__class__(self.line_buffer[start:stop],point=0) - elif isinstance(key,LinePositioner): + stop = key.stop + return self.__class__(self.line_buffer[start:stop], point=0) + elif isinstance(key, LinePositioner): return self.line_buffer[key(self)] - elif isinstance(key,tuple): + elif isinstance(key, tuple): raise IndexError(u"Cannot use step in line buffer indexing") #Multiple slice not allowed else: # return TextLine(self.line_buffer[key]) return self.line_buffer[key] - def __delitem__(self,key): - point=self.point - if isinstance(key,LineSlice): - key=key(self) - if isinstance(key,slice): - start=key.start - stop=key.stop - if isinstance(start,LinePositioner): - start=start(self) + def __delitem__(self, key): + point = self.point + if isinstance(key, LineSlice): + key = key(self) + if isinstance(key, slice): + start = key.start + stop = key.stop + if isinstance(start, LinePositioner): + start = start(self) elif start is None: start=0 - if isinstance(stop,LinePositioner): - stop=stop(self) + if isinstance(stop, LinePositioner): + stop = stop(self) elif stop is None: - stop=EndOfLine(self) - elif isinstance(key,LinePositioner): - start=key(self) - stop=start+1 + stop = EndOfLine(self) + elif isinstance(key, LinePositioner): + start = key(self) + stop = start + 1 else: - start=key - stop=key+1 - prev=self.line_buffer[:start] - rest=self.line_buffer[stop:] - self.line_buffer=prev+rest - if point>stop: - self.point=point-(stop-start) - elif point>=start and point <=stop: - self.point=start + start = key + stop = key + 1 + prev = self.line_buffer[:start] + rest = self.line_buffer[stop:] + self.line_buffer = prev + rest + if point > stop: + self.point = point - (stop - start) + elif point >= start and point <= stop: + self.point = start - def __setitem__(self,key,value): - if isinstance(key,LineSlice): - key=key(self) - if isinstance(key,slice): - start=key.start - stop=key.stop - elif isinstance(key,LinePositioner): - start=key(self) - stop=start+1 + def __setitem__(self, key, value): + if isinstance(key, LineSlice): + key = key(self) + if isinstance(key, slice): + start = key.start + stop = key.stop + elif isinstance(key, LinePositioner): + start = key(self) + stop = start + 1 else: - start=key - stop=key+1 - prev=self.line_buffer[:start] - value=self.__class__(value).line_buffer - rest=self.line_buffer[stop:] - out=prev+value+rest - if len(out)>=len(self): - self.point=len(self) - self.line_buffer=out + start = key + stop = key + 1 + prev = self.line_buffer[:start] + value = self.__class__(value).line_buffer + rest = self.line_buffer[stop:] + out = prev + value + rest + if len(out) >= len(self): + self.point = len(self) + self.line_buffer = out def __len__(self): return len(self.line_buffer) def upper(self): - self.line_buffer=[x.upper() for x in self.line_buffer] + self.line_buffer = [x.upper() for x in self.line_buffer] return self def lower(self): - self.line_buffer=[x.lower() for x in self.line_buffer] + self.line_buffer = [x.lower() for x in self.line_buffer] return self def capitalize(self): - self.set_line(self.get_line_text().capitalize(),self.point) + self.set_line(self.get_line_text().capitalize(), self.point) return self - def startswith(self,txt): + def startswith(self, txt): return self.get_line_text().startswith(txt) - def endswith(self,txt): + def endswith(self, txt): return self.get_line_text().endswith(txt) - def __contains__(self,txt): + def __contains__(self, txt): return txt in self.get_line_text() -lines=[TextLine(u"abc"), - TextLine(u"abc def"), - TextLine(u"abc def ghi"), - TextLine(u" abc def "), - ] -l=lines[2] -l.point=5 +lines = [TextLine(u"abc"), + TextLine(u"abc def"), + TextLine(u"abc def ghi"), + TextLine(u" abc def "), + ] +l = lines[2] +l.point = 5 class ReadLineTextBuffer(TextLine): - def __init__(self,txtstr,point=None,mark=None): - super(ReadLineTextBuffer,self).__init__(txtstr,point,mark) - self.enable_win32_clipboard=True - self.selection_mark=-1 - self.enable_selection=True - self.kill_ring=[] + def __init__(self,txtstr, point = None, mark = None): + super(ReadLineTextBuffer, self).__init__(txtstr, point, mark) + self.enable_win32_clipboard = True + self.selection_mark = -1 + self.enable_selection = True + self.kill_ring = [] def __repr__(self): - return u'ReadLineTextBuffer("%s",point=%s,mark=%s,selection_mark=%s)'%(self.line_buffer,self.point,self.mark,self.selection_mark) + return u'ReadLineTextBuffer'\ + u'("%s",point=%s,mark=%s,selection_mark=%s)'%\ + (self.line_buffer, self.point, self.mark,self.selection_mark) def insert_text(self, char, argument=1): self.delete_selection() - self.selection_mark=-1 + self.selection_mark = -1 self._insert_text(char, argument) def to_clipboard(self): @@ -419,242 +423,239 @@ class ReadLineTextBuffer(TextLine): ######### Movement def beginning_of_line(self): - self.selection_mark=-1 - self.point=StartOfLine + self.selection_mark = -1 + self.point = StartOfLine def end_of_line(self): - self.selection_mark=-1 - self.point=EndOfLine + self.selection_mark = -1 + self.point = EndOfLine - def forward_char(self,argument=1): - if argument<0: + def forward_char(self,argument = 1): + if argument < 0: self.backward_char(-argument) - self.selection_mark=-1 + self.selection_mark = -1 for x in range(argument): - self.point=NextChar + self.point = NextChar - def backward_char(self,argument=1): - if argument<0: + def backward_char(self, argument=1): + if argument < 0: self.forward_char(-argument) - self.selection_mark=-1 + self.selection_mark = -1 for x in range(argument): - self.point=PrevChar + self.point = PrevChar def forward_word(self,argument=1): if argument<0: self.backward_word(-argument) self.selection_mark=-1 for x in range(argument): - self.point=NextWordStart + self.point = NextWordStart - def backward_word(self,argument=1): - if argument<0: + def backward_word(self, argument=1): + if argument < 0: self.forward_word(-argument) - self.selection_mark=-1 + self.selection_mark = -1 for x in range(argument): - self.point=PrevWordStart + self.point = PrevWordStart - def forward_word_end(self,argument=1): - if argument<0: + def forward_word_end(self, argument=1): + if argument < 0: self.backward_word_end(-argument) - self.selection_mark=-1 + self.selection_mark = -1 for x in range(argument): - self.point=NextWordEnd + self.point = NextWordEnd - def backward_word_end(self,argument=1): - if argument<0: + def backward_word_end(self, argument=1): + if argument < 0: self.forward_word_end(-argument) - self.selection_mark=-1 + self.selection_mark = -1 for x in range(argument): - self.point=NextWordEnd + self.point = NextWordEnd ######### Movement select def beginning_of_line_extend_selection(self): - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point - self.point=StartOfLine + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point + self.point = StartOfLine def end_of_line_extend_selection(self): - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point - self.point=EndOfLine + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point + self.point = EndOfLine def forward_char_extend_selection(self,argument=1): - if argument<0: + if argument < 0: self.backward_char_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=NextChar + self.point = NextChar - def backward_char_extend_selection(self,argument=1): - if argument<0: + def backward_char_extend_selection(self, argument=1): + if argument < 0: self.forward_char_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=PrevChar + self.point = PrevChar - def forward_word_extend_selection(self,argument=1): - if argument<0: + def forward_word_extend_selection(self, argument=1): + if argument < 0: self.backward_word_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=NextWordStart + self.point = NextWordStart - def backward_word_extend_selection(self,argument=1): - if argument<0: + def backward_word_extend_selection(self, argument=1): + if argument < 0: self.forward_word_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=PrevWordStart + self.point = PrevWordStart - def forward_word_end_extend_selection(self,argument=1): - if argument<0: + def forward_word_end_extend_selection(self, argument=1): + if argument < 0: self.backward_word_end_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=NextWordEnd + self.point = NextWordEnd - def backward_word_end_extend_selection(self,argument=1): - if argument<0: + def backward_word_end_extend_selection(self, argument=1): + if argument < 0: self.forward_word_end_extend_selection(-argument) - if self.enable_selection and self.selection_mark<0: - self.selection_mark=self.point + if self.enable_selection and self.selection_mark < 0: + self.selection_mark = self.point for x in range(argument): - self.point=PrevWordEnd + self.point = PrevWordEnd ######### delete def delete_selection(self): - if self.enable_selection and self.selection_mark>=0: - if self.selection_mark= 0: + if self.selection_mark < self.point: del self[self.selection_mark:self.point] - self.selection_mark=-1 + self.selection_mark = -1 else: del self[self.point:self.selection_mark] - self.selection_mark=-1 + self.selection_mark = -1 return True else: - self.selection_mark=-1 + self.selection_mark = -1 return False - def delete_char(self,argument=1): - if argument<0: + def delete_char(self, argument=1): + if argument < 0: self.backward_delete_char(-argument) if self.delete_selection(): - argument-=1 + argument -= 1 for x in range(argument): del self[Point] - def backward_delete_char(self,argument=1): - if argument<0: + def backward_delete_char(self, argument=1): + if argument < 0: self.delete_char(-argument) if self.delete_selection(): - argument-=1 + argument -= 1 for x in range(argument): - if self.point>0: + if self.point > 0: self.backward_char() self.delete_char() - def forward_delete_word(self,argument=1): - if argument<0: + def forward_delete_word(self, argument=1): + if argument < 0: self.backward_delete_word(-argument) if self.delete_selection(): - argument-=1 + argument -= 1 for x in range(argument): del self[Point:NextWordStart] - def backward_delete_word(self,argument=1): - if argument<0: + def backward_delete_word(self, argument=1): + if argument < 0: self.forward_delete_word(-argument) if self.delete_selection(): - argument-=1 + argument -= 1 for x in range(argument): del self[PrevWordStart:Point] def delete_current_word(self): if not self.delete_selection(): del self[CurrentWord] - self.selection_mark=-1 + self.selection_mark =- 1 def delete_horizontal_space(self): if self[Point] in " \t": del self[PrevWordEnd:NextWordStart] - self.selection_mark=-1 + self.selection_mark = -1 ######### Case def upcase_word(self): - p=self.point + p = self.point try: - self[CurrentWord]=self[CurrentWord].upper() - self.point=p + self[CurrentWord] = self[CurrentWord].upper() + self.point = p except NotAWordError: pass def downcase_word(self): - p=self.point + p = self.point try: - self[CurrentWord]=self[CurrentWord].lower() - self.point=p + self[CurrentWord] = self[CurrentWord].lower() + self.point = p except NotAWordError: pass def capitalize_word(self): - p=self.point + p = self.point try: - self[CurrentWord]=self[CurrentWord].capitalize() - self.point=p + self[CurrentWord] = self[CurrentWord].capitalize() + self.point = p except NotAWordError: pass ########### Transpose def transpose_chars(self): - p2=Point(self) - if p2==0: + p2 = Point(self) + if p2 == 0: return - elif p2==len(self): - p2=p2-1 - p1=p2-1 - self[p2],self[p1]=self[p1],self[p2] - self.point=p2+1 + elif p2 == len(self): + p2 = p2 - 1 + p1 = p2 - 1 + self[p2], self[p1] = self[p1], self[p2] + self.point = p2 + 1 def transpose_words(self): - word1=TextLine(self) - word2=TextLine(self) - if self.point==len(self): - word2.point=PrevWordStart - word1.point=PrevWordStart(word2) + word1 = TextLine(self) + word2 = TextLine(self) + if self.point == len(self): + word2.point = PrevWordStart + word1.point = PrevWordStart(word2) else: - word1.point=PrevWordStart - word2.point=NextWordStart - stop1=NextWordEnd(word1) - stop2=NextWordEnd(word2) - start1=word1.point - start2=word2.point - self[start2:stop2]=word1[Point:NextWordEnd] - self[start1:stop1]=word2[Point:NextWordEnd] - self.point=stop2 + word1.point = PrevWordStart + word2.point = NextWordStart + stop1 = NextWordEnd(word1) + stop2 = NextWordEnd(word2) + start1 = word1.point + start2 = word2.point + self[start2:stop2] = word1[Point:NextWordEnd] + self[start1:stop1] = word2[Point:NextWordEnd] + self.point = stop2 ############ Kill def kill_line(self): - #self[self.point:].to_clipboard() self.add_to_kill_ring(self[self.point:]) del self.line_buffer[self.point:] def kill_whole_line(self): - #self[:].to_clipboard() self.add_to_kill_ring(self[:]) del self[:] def backward_kill_line(self): - #self[StartOfLine:Point].to_clipboard() del self[StartOfLine:Point] def unix_line_discard(self): @@ -663,27 +664,24 @@ class ReadLineTextBuffer(TextLine): def kill_word(self): """Kills to next word ending""" - #self[Point:NextWordEnd].to_clipboard() del self[Point:NextWordEnd] def backward_kill_word(self): """Kills to next word ending""" - #self[PrevWordStart:Point].to_clipboard() if not self.delete_selection(): del self[PrevWordStart:Point] - self.selection_mark=-1 + self.selection_mark = -1 def forward_kill_word(self): """Kills to next word ending""" - #self[Point:NextWordEnd].to_clipboard() if not self.delete_selection(): del self[Point:NextWordEnd] - self.selection_mark=-1 + self.selection_mark = -1 def unix_word_rubout(self): if not self.delete_selection(): del self[PrevSpace:Point] - self.selection_mark=-1 + self.selection_mark = -1 def kill_region(self): pass @@ -707,7 +705,7 @@ class ReadLineTextBuffer(TextLine): ############## Mark def set_mark(self): - self.mark=self.point + self.mark = self.point def exchange_point_and_mark(self): pass @@ -716,25 +714,25 @@ class ReadLineTextBuffer(TextLine): def copy_region_to_clipboard(self): # () u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard: - mark=min(self.mark,len(self.line_buffer)) - cursor=min(self.point,len(self.line_buffer)) - if self.mark==-1: + mark = min(self.mark, len(self.line_buffer)) + cursor = min(self.point, len(self.line_buffer)) + if self.mark == -1: return - begin=min(cursor,mark) - end=max(cursor,mark) - toclipboard=u"".join(self.line_buffer[begin:end]) + begin = min(cursor, mark) + end = max(cursor, mark) + toclipboard = u"".join(self.line_buffer[begin:end]) clipboard.SetClipboardText(toclipboard) def copy_selection_to_clipboard(self): # () u'''Copy the text in the region to the windows clipboard.''' - if self.enable_win32_clipboard and self.enable_selection and self.selection_mark>=0: - selection_mark=min(self.selection_mark,len(self.line_buffer)) - cursor=min(self.point,len(self.line_buffer)) - if self.selection_mark==-1: + if self.enable_win32_clipboard and self.enable_selection and self.selection_mark >= 0: + selection_mark = min(self.selection_mark,len(self.line_buffer)) + cursor = min(self.point,len(self.line_buffer)) + if self.selection_mark == -1: return - begin=min(cursor,selection_mark) - end=max(cursor,selection_mark) - toclipboard=u"".join(self.line_buffer[begin:end]) + begin = min(cursor, selection_mark) + end = max(cursor, selection_mark) + toclipboard = u"".join(self.line_buffer[begin:end]) clipboard.SetClipboardText(toclipboard) @@ -746,7 +744,7 @@ class ReadLineTextBuffer(TextLine): ############## Kill ring def add_to_kill_ring(self,txt): - self.kill_ring=[txt] + self.kill_ring = [txt] if kill_ring_to_clipboard: clipboard.SetClipboardText(txt.get_line_text()) @@ -757,45 +755,45 @@ class ReadLineTextBuffer(TextLine): ################################################################## -q=ReadLineTextBuffer(u"asff asFArw ewrWErhg",point=8) -q=TextLine(u"asff asFArw ewrWErhg",point=8) +q = ReadLineTextBuffer(u"asff asFArw ewrWErhg", point=8) +q = TextLine(u"asff asFArw ewrWErhg", point=8) -def show_pos(buff,pos,chr=u"."): - l=len(buff.line_buffer) +def show_pos(buff, pos, chr = u"."): + l = len(buff.line_buffer) def choice(bool): if bool: return chr else: return u" " - return u"".join([choice(pos==idx) for idx in range(l+1)]) + return u"".join([choice(pos==idx) for idx in range(l + 1)]) -def test_positioner(buff,points,positioner): - print (u" %s "%positioner.__class__.__name__).center(40,u"-") - buffstr=buff.line_buffer +def test_positioner(buff, points, positioner): + print (u" %s "%positioner.__class__.__name__).center(40, u"-") + buffstr = buff.line_buffer print u'"%s"'%(buffstr) for point in points: - b=TextLine(buff,point=point) - out=[u" "]*(len(buffstr)+1) - pos=positioner(b) - if pos==point: - out[pos]=u"&" + b = TextLine(buff, point = point) + out=[u" "] * (len(buffstr) + 1) + pos = positioner(b) + if pos == point: + out[pos] = u"&" else: - out[point]=u"." - out[pos]=u"^" + out[point] = u"." + out[pos] = u"^" print u'"%s"'%(u"".join(out)) -if __name__=="__main__": +if __name__ == "__main__": - print u'%-15s "%s"'%(u"Position",q.get_line_text()) - print u'%-15s "%s"'%(u"Point",show_pos(q,q.point)) + print u'%-15s "%s"'%(u"Position", q.get_line_text()) + print u'%-15s "%s"'%(u"Point", show_pos(q, q.point)) - for name,positioner in all_positioners: - pos=positioner(q) + for name, positioner in all_positioners: + pos = positioner(q) [] - print u'%-15s "%s"'%(name,show_pos(q,pos,u"^")) + print u'%-15s "%s"'%(name, show_pos(q, pos, u"^")) - l=ReadLineTextBuffer(u"kjjk asads asad") - l.point=EndOfLine + l = ReadLineTextBuffer(u"kjjk asads asad") + l.point = EndOfLine diff --git a/pyreadline/lineeditor/wordmatcher.py b/pyreadline/lineeditor/wordmatcher.py index 9bb8b28..7454516 100644 --- a/pyreadline/lineeditor/wordmatcher.py +++ b/pyreadline/lineeditor/wordmatcher.py @@ -6,50 +6,50 @@ # the file COPYING, distributed as part of this software. #***************************************************************************** -import re,operator +import re, operator -def str_find_all(str,ch): - result=[] - index=0 - while index>=0: - index=str.find(ch,index) - if index>=0: +def str_find_all(str, ch): + result = [] + index = 0 + while index >= 0: + index = str.find(ch, index) + if index >= 0: result.append(index) - index+=1 + index += 1 return result -word_pattern=re.compile(u"(x*)") +word_pattern = re.compile(u"(x*)") -def markwords(str,iswordfun): - markers={True:u"x",False:u"o"} +def markwords(str, iswordfun): + markers = {True : u"x", False : u"o"} return "".join([markers[iswordfun(ch)] for ch in str]) -def split_words(str,iswordfun): - return [x for x in word_pattern.split(markwords(str,iswordfun)) if x !=u""] +def split_words(str, iswordfun): + return [x for x in word_pattern.split(markwords(str,iswordfun)) if x != u""] -def mark_start_segment(str,is_segment): +def mark_start_segment(str, is_segment): def mark_start(s): - if s[0:1]==u"x": - return u"s"+s[1:] + if s[0:1] == u"x": + return u"s" + s[1:] else: return s - return u"".join(map(mark_start,split_words(str,is_segment))) + return u"".join(map(mark_start, split_words(str, is_segment))) -def mark_end_segment(str,is_segment): +def mark_end_segment(str, is_segment): def mark_start(s): - if s[0:1]==u"x": - return s[:-1]+u"s" + if s[0:1] == u"x": + return s[:-1] + u"s" else: return s - return u"".join(map(mark_start,split_words(str,is_segment))) + return u"".join(map(mark_start, split_words(str, is_segment))) -def mark_start_segment_index(str,is_segment): - return str_find_all(mark_start_segment(str,is_segment),u"s") +def mark_start_segment_index(str, is_segment): + return str_find_all(mark_start_segment(str, is_segment), u"s") -def mark_end_segment_index(str,is_segment): - return [x+1 for x in str_find_all(mark_end_segment(str,is_segment),u"s")] +def mark_end_segment_index(str, is_segment): + return [x + 1 for x in str_find_all(mark_end_segment(str, is_segment), u"s")] ################ Following are used in lineobj ########################### @@ -58,46 +58,45 @@ def is_word_token(str): return not is_non_word_token(str) def is_non_word_token(str): - if len(str)!=1 or str in u" \t\n": + if len(str) != 1 or str in u" \t\n": return True else: return False -def next_start_segment(str,is_segment): - str=u"".join(str) - result=[] - for start in mark_start_segment_index(str,is_segment): - result[len(result):start]=[start for x in range(start-len(result))] - result[len(result):len(str)]=[len(str) for x in range(len(str)-len(result)+1)] +def next_start_segment(str, is_segment): + str = u"".join(str) + result = [] + for start in mark_start_segment_index(str, is_segment): + result[len(result):start] = [start for x in range(start - len(result))] + result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)] return result -def next_end_segment(str,is_segment): - str=u"".join(str) - result=[] - for start in mark_end_segment_index(str,is_segment): - result[len(result):start]=[start for x in range(start-len(result))] - result[len(result):len(str)]=[len(str) for x in range(len(str)-len(result)+1)] +def next_end_segment(str, is_segment): + str = u"".join(str) + result = [] + for start in mark_end_segment_index(str, is_segment): + result[len(result):start] = [start for x in range(start - len(result))] + result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)] return result -def prev_start_segment(str,is_segment): - str=u"".join(str) - result=[] - prev=0 - for start in mark_start_segment_index(str,is_segment): - result[len(result):start+1]=[prev for x in range(start-len(result)+1)] +def prev_start_segment(str, is_segment): + str = u"".join(str) + result = [] + prev = 0 + for start in mark_start_segment_index(str, is_segment): + result[len(result):start+1] = [prev for x in range(start - len(result) + 1)] prev=start - result[len(result):len(str)]=[prev for x in range(len(str)-len(result)+1)] + result[len(result):len(str)] = [prev for x in range(len(str) - len(result) + 1)] return result -def prev_end_segment(str,is_segment): - str=u"".join(str) - result=[] - prev=0 - for start in mark_end_segment_index(str,is_segment): - result[len(result):start+1]=[prev for x in range(start-len(result)+1)] +def prev_end_segment(str, is_segment): + str = u"".join(str) + result = [] + prev = 0 + for start in mark_end_segment_index(str, is_segment): + result[len(result):start + 1] = [prev for x in range(start - len(result) + 1)] prev=start - result[len(result):len(str)]=[len(str) for x in range(len(str)-len(result)+1)] + result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)] return result - From 87da34ebf2225a2b7e8ba21a411ee05b3c807ea2 Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Sun, 11 Jan 2009 17:53:31 +0100 Subject: [PATCH 25/26] Add some ensure_unicode, ensure_str. --- pyreadline/console/console.py | 3 +++ pyreadline/test/lineeditor_test.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index 9c645a6..6c9af69 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -359,6 +359,7 @@ class Console(object): def write_plain(self, text, attr=None): u'''write text at current cursor position.''' + text = ensure_unicode(text) log(u'write("%s", %s)' %(text, attr)) if attr is None: attr = self.attr @@ -373,6 +374,7 @@ class Console(object): #Emacs sets the EMACS environment variable if os.environ.has_key(u"EMACS"): def write_color(self, text, attr=None): + text = ensure_str(text) junk = c_int(0) self.WriteFile(self.hout, text, len(text), byref(junk), None) return len(text) @@ -380,6 +382,7 @@ class Console(object): # make this class look like a file object def write(self, text): + text = ensure_unicode(text) log(u'write("%s")' % text) return self.write_color(text) diff --git a/pyreadline/test/lineeditor_test.py b/pyreadline/test/lineeditor_test.py index 5ae1f3a..3b1c9a5 100644 --- a/pyreadline/test/lineeditor_test.py +++ b/pyreadline/test/lineeditor_test.py @@ -387,4 +387,4 @@ def get_mark_pos(mstr): if __name__ == u'__main__': unittest.main() - l=lineobj.ReadLineTextBuffer(u"First Second Third") \ No newline at end of file + l=lineobj.ReadLineTextBuffer(u"First Second Third") From 6081024aaa5b455bd4c730992809d5f2f6fec05e Mon Sep 17 00:00:00 2001 From: Jorgen Stenarson Date: Tue, 6 Oct 2009 19:36:27 +0200 Subject: [PATCH 26/26] Fix for incremental search. Ctrl-S only generates events on key release events --- pyreadline/console/console.py | 15 +++++++------ pyreadline/keysyms/common.py | 10 ++++++++- pyreadline/modes/emacs.py | 42 ++++++++++++++++++----------------- pyreadline/rlmain.py | 9 ++++---- 4 files changed, 43 insertions(+), 33 deletions(-) diff --git a/pyreadline/console/console.py b/pyreadline/console/console.py index 6c9af69..2204003 100644 --- a/pyreadline/console/console.py +++ b/pyreadline/console/console.py @@ -21,7 +21,7 @@ import pyreadline.unicode_helper as unicode_helper from pyreadline.logger import log from pyreadline.unicode_helper import ensure_unicode, ensure_str -from pyreadline.keysyms import make_KeyPress +from pyreadline.keysyms import make_KeyPress, KeyPress from pyreadline.console.ansi import AnsiState,AnsiWriter try: @@ -33,7 +33,7 @@ except ImportError: def nolog(string): pass -log=nolog +log = nolog # some constants we need @@ -500,7 +500,6 @@ class Console(object): byref(Cevent), 1, byref(count)) if status and count.value == 1: e = event(self, Cevent) - log(u"console.get %s"%ensure_unicode(e.keyinfo)) return e def getkeypress(self): @@ -508,17 +507,18 @@ class Console(object): while 1: e = self.get() if e.type == u'KeyPress' and e.keycode not in key_modifiers: - log(u"console.getleypress %s"%e) - if e.keyinfo.keyname == 'next': + log(u"console.getkeypress %s"%e) + if e.keyinfo.keyname == u'next': self.scroll_window(12) - elif e.keyinfo.keyname == 'prior': + elif e.keyinfo.keyname == u'prior': self.scroll_window(-12) else: return e elif ((e.type == u'KeyRelease') and - (e.keyinfo == (True, False, False, 83))): + (e.keyinfo == KeyPress('S', False, True, False, 'S'))): log(u"getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type)) return e + def getchar(self): u'''Get next character from queue.''' @@ -650,6 +650,7 @@ class event(Event): self.type = u"Menu" self.state = input.Event.MenuEvent.dwCommandId + def getconsole(buffer=1): """Get a console handle. diff --git a/pyreadline/keysyms/common.py b/pyreadline/keysyms/common.py index df43ec7..d76b356 100644 --- a/pyreadline/keysyms/common.py +++ b/pyreadline/keysyms/common.py @@ -39,7 +39,7 @@ validkey =set([u'cancel', u'backspace', u'tab', u'clear', escape_sequence_to_special_key = {u"\\e[a" : u"up", u"\\e[b" : u"down", u"del" : u"delete"} class KeyPress(object): - def __init__(self, char="", shift=False, control=False, meta=False,keyname=u""): + def __init__(self, char=u"", shift=False, control=False, meta=False, keyname=u""): if control or meta or shift: char = char.upper() self.info = dict(char=char, @@ -73,6 +73,14 @@ class KeyPress(object): else: return (self.control, self.meta, self.shift, self.char) + def __eq__(self, other): + if isinstance(other, KeyPress): + s = self.tuple() + o = other.tuple() + return s == o + else: + return False + def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == u'"' and keydescr[-1:] == u'"': diff --git a/pyreadline/modes/emacs.py b/pyreadline/modes/emacs.py index 77074b4..dcf35ba 100644 --- a/pyreadline/modes/emacs.py +++ b/pyreadline/modes/emacs.py @@ -30,51 +30,51 @@ class IncrementalSearchPromptMode(object): pass def _process_incremental_search_keyevent(self, keyinfo): - keytuple=keyinfo.tuple() - log(u"IncrementalSearchPromptMode %s %s"%(keyinfo,keytuple)) + keytuple = keyinfo.tuple() + log(u"IncrementalSearchPromptMode %s %s"%(keyinfo, keytuple)) if keyinfo.keyname == u'backspace': self.subsearch_query = self.subsearch_query[:-1] if len(self.subsearch_query) > 0: self.line=self.subsearch_fun(self.subsearch_query) else: self._bell() - self.line="" #empty query means no search result + self.line = "" #empty query means no search result elif keyinfo.keyname in [u'return', u'escape']: self._bell() - self.prompt=self.subsearch_oldprompt - self.process_keyevent_queue=self.process_keyevent_queue[:-1] - self._history.history_cursor=len(self._history.history) + self.prompt = self.subsearch_oldprompt + self.process_keyevent_queue = self.process_keyevent_queue[:-1] + self._history.history_cursor = len(self._history.history) if keyinfo.keyname == u'escape': self.l_buffer.set_line(self.subsearch_old_line) return False elif keyinfo.keyname: pass - elif keytuple==self.subsearch_init_event: + elif keytuple == self.subsearch_init_event: self._history.history_cursor += self.subsearch_direction - self.line=self.subsearch_fun(self.subsearch_query) - elif keyinfo.control==False and keyinfo.meta==False : + self.line = self.subsearch_fun(self.subsearch_query) + elif keyinfo.control == False and keyinfo.meta == False : self.subsearch_query += keyinfo.char self.line=self.subsearch_fun(self.subsearch_query) else: pass - self.prompt=self.subsearch_prompt%self.subsearch_query + self.prompt = self.subsearch_prompt%self.subsearch_query self.l_buffer.set_line(self.line) def _init_incremental_search(self, searchfun, direction, init_event): u"""Initialize search prompt """ - self.subsearch_init_event=init_event.tuple() - self.subsearch_direction=direction + self.subsearch_init_event = init_event.tuple() + self.subsearch_direction = direction self.subsearch_query = u'' self.subsearch_fun = searchfun self.subsearch_old_line = self.l_buffer.get_line_text() self.process_keyevent_queue.append(self._process_incremental_search_keyevent) - self.subsearch_oldprompt=self.prompt + self.subsearch_oldprompt = self.prompt if (self.previous_func != self.history_search_forward and - self.previous_func != self.history_search_backward): + self.previous_func != self.history_search_backward): self.subsearch_query = u''.join(self.l_buffer[0:Point].get_line_text()) @@ -82,11 +82,13 @@ class IncrementalSearchPromptMode(object): self.subsearch_prompt = u"reverse-i-search`%s': " else: self.subsearch_prompt = u"forward-i-search`%s': " - self.prompt=self.subsearch_prompt%"" + + self.prompt = self.subsearch_prompt%"" + if self.subsearch_query: - self.line=self._process_search_keyevent(init_event) + self.line = self._process_incremental_search_keyevent(init_event) else: - self.line=u"" + self.line = u"" class SearchPromptMode(object): def __init__(self, rlobj): @@ -125,10 +127,10 @@ class SearchPromptMode(object): def _init_non_i_search(self, direction): self.non_inc_direction = direction self.non_inc_query = u"" - self.non_inc_oldprompt=self.prompt - self.non_inc_oldline=self.l_buffer.copy() + self.non_inc_oldprompt = self.prompt + self.non_inc_oldline = self.l_buffer.copy() self.l_buffer.reset_line() - self.prompt=self.non_inc_oldprompt+u":" + self.prompt = self.non_inc_oldprompt + u":" self.process_keyevent_queue.append(self._process_non_incremental_search_keyevent) def non_incremental_reverse_search_history(self, e): # (M-p) diff --git a/pyreadline/rlmain.py b/pyreadline/rlmain.py index cd213a8..c47e1ac 100644 --- a/pyreadline/rlmain.py +++ b/pyreadline/rlmain.py @@ -174,10 +174,9 @@ class BaseReadline(object): def get_completer(self): u'''Get the completer function. - ''' - - log(u'get_completer') - return self.mode.completer + ''' + log(u'get_completer') + return self.mode.completer def get_begidx(self): u'''Get the beginning index of the readline tab-completion scope.''' @@ -193,7 +192,7 @@ class BaseReadline(object): def get_completer_delims(self): u'''Get the readline word delimiters for tab-completion.''' - return self.mode.completer_delims + return self.mode.completer_delims.encode("ascii") def set_startup_hook(self, function=None): u'''Set or remove the startup_hook function.