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 -