Changeset 1877

Show
Ignore:
Timestamp:
11/03/06 16:39:12 (2 years ago)
Author:
jstenar
Message:

pyreadline-refactor: improved support for ironpython. Seems quite ok now. Also another bug fix in history search

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • pyreadline/branches/refactor/pyreadline/clipboard/__init__.py

    r1419 r1877  
     1import sys 
    12success=False 
     3in_ironpython=sys.version.startswith("IronPython") 
    24 
    3 try: 
    4     from clipboard import GetClipboardText,SetClipboardText 
    5     success=True 
    6 except ImportError: 
     5if in_ironpython: 
    76    try: 
    87        from ironpython_clipboard import GetClipboardText,SetClipboardText 
     
    109    except ImportError: 
    1110        pass 
    12      
     11else: 
     12    try: 
     13        from clipboard import GetClipboardText,SetClipboardText 
     14        success=True 
     15    except ImportError: 
     16        pass     
    1317     
    1418     
  • pyreadline/branches/refactor/pyreadline/console/__init__.py

    r1419 r1877  
    1 import glob 
     1import glob,sys 
    22 
    33success=False 
     4in_ironpython=sys.version.startswith("IronPython") 
    45 
    5 try: 
    6     from console import * 
    7     success=True 
    8 except ImportError: 
    9  
     6if in_ironpython: 
    107    try: 
    118        from ironpython_console import * 
     9        success=True 
     10    except ImportError: 
     11        raise 
     12else: 
     13    try: 
     14        from console import * 
    1215        success=True 
    1316    except ImportError: 
  • pyreadline/branches/refactor/pyreadline/console/console.py

    r1843 r1877  
    210210        self.FreeConsole() 
    211211 
     212    def _get_top_bot(self): 
     213        info = CONSOLE_SCREEN_BUFFER_INFO() 
     214        self.GetConsoleScreenBufferInfo(self.hout, byref(info)) 
     215        rect = info.srWindow 
     216        top = rect.Top  
     217        bot = rect.Bottom  
     218        return top,bot 
     219 
    212220    def fixcoord(self, x, y): 
    213221        '''Return a long with x and y packed inside, also handle negative x and y.''' 
     
    280288        w, h = self.size() 
    281289        scroll = 0 # the result 
    282  
    283290        # split the string into ordinary characters and funny characters 
    284291        chunks = self.motion_char_re.split(text) 
     
    345352 
    346353    def write_color(self, text, attr=None): 
    347         log_sock(text) 
    348         log_sock("%s"%attr) 
    349354        n,res= self.ansiwriter.write_color(text,attr) 
    350355        junk = c_int(0) 
    351356        for attr,chunk in res: 
    352             log_sock("%s:%s"%(attr,chunk)) 
    353357            log(str(attr)) 
    354358            log(str(chunk)) 
     
    410414        self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n)) 
    411415 
     416    def clear_to_end_of_window(self): 
     417        top,bot=self._get_top_bot() 
     418        pos=self.pos() 
     419        w,h=self.size() 
     420        self.rectangle( (pos[0],pos[1],w,pos[1]+1)) 
     421        if pos[1]<bot: 
     422            self.rectangle((0,pos[1]+1,w,bot+1)) 
     423 
    412424    def rectangle(self, rect, attr=None, fill=' '): 
    413425        '''Fill Rectangle.''' 
     426        log_sock("rect:%s"%[rect]) 
    414427        x0, y0, x1, y1 = rect 
    415428        n = c_int(0) 
     
    446459        h = bot - top 
    447460        maxbot = info.dwSize.Y-1 
    448         log('sw: lines=%d mb=%d top=%d bot=%d' % (lines,maxbot,top,bot)) 
    449461        if top < 0: 
    450462            top = 0 
     
    492504            elif e.type == 'KeyRelease' and e.keyinfo==(True, False, False, 83): 
    493505                log("getKeypress:%s,%s,%s"%(e.keyinfo,e.keycode,e.type)) 
    494 #                log_sock(str(e)) 
    495506                return e 
    496507                 
  • pyreadline/branches/refactor/pyreadline/console/ironpython_console.py

    r1419 r1877  
    1010''' 
    1111 
     12# 
     13# Ironpython requires a patch to work do: 
     14# 
     15# In file PythonCommandLine.cs patch line:      
     16#    class PythonCommandLine 
     17#    { 
     18 
     19# to: 
     20#    public class PythonCommandLine 
     21#    { 
     22# 
     23# 
     24# 
     25 
     26 
    1227# primitive debug printing that won't interfere with the screen 
    1328 
     
    2439 
    2540from event import Event 
    26 from pyreadline.logger import log 
     41from pyreadline.logger import log,log_sock 
    2742 
    2843#print "Codepage",System.Console.InputEncoding.CodePage 
    29 from pyreadline.keysyms import make_keysym, make_keyinfo,make_KeyPress 
    30  
     44from pyreadline.keysyms import make_keysym, make_keyinfo,make_KeyPress,make_KeyPress_from_keydescr 
     45from pyreadline.console.ansi import AnsiState 
    3146color=System.ConsoleColor 
    3247 
    33 ansicolor={ 
     48ansicolor={"0;30": color.Black, 
    3449           "0;31": color.DarkRed, 
    3550           "0;32": color.DarkGreen, 
     
    3954           "0;36": color.DarkCyan, 
    4055           "0;37": color.DarkGray, 
     56           "1;30": color.Gray, 
    4157           "1;31": color.Red, 
    4258           "1;32": color.Green, 
     
    4864          } 
    4965 
     66winattr={"black":0,"darkgray":0+8, 
     67         "darkred":4,"red":4+8, 
     68         "darkgreen":2,"green":2+8, 
     69         "darkyellow":6,"yellow":6+8, 
     70         "darkblue":1,"blue":1+8, 
     71         "darkmagenta":5, "magenta":5+8, 
     72         "darkcyan":3,"cyan":3+8, 
     73         "gray":7,"white":7+8} 
     74 
    5075class Console(object): 
    5176    '''Console driver for Windows. 
     
    6186        self.serial=0 
    6287        self.attr = System.Console.ForegroundColor 
    63         self.saveattr = System.Console.ForegroundColor 
     88        self.saveattr = winattr[str(System.Console.ForegroundColor).lower()] 
     89        self.savebg=System.Console.BackgroundColor 
    6490        log('initial attr=%s' % self.attr) 
     91        log_sock("%s"%self.saveattr) 
     92 
     93    def _get(self): 
     94        top=System.Console.WindowTop 
     95        log_sock("WindowTop:%s"%top,"console") 
     96        return top 
     97    def _set(self,value): 
     98        top=System.Console.WindowTop 
     99        log_sock("Set WindowTop:old:%s,new:%s"%(top,value),"console") 
     100    WindowTop=property(_get,_set) 
     101    del _get,_set 
    65102 
    66103    def __del__(self): 
    67104        '''Cleanup the console when finished.''' 
    68105        # I don't think this ever gets called 
    69         self.SetConsoleTextAttribute(self.hout, self.saveattr) 
    70         self.SetConsoleMode(self.hin, self.inmode) 
    71         self.FreeConsole() 
     106        pass 
    72107 
    73108    def pos(self, x=None, y=None): 
     
    154189        return scroll 
    155190 
     191    trtable={0:color.Black,4:color.DarkRed,2:color.DarkGreen,6:color.DarkYellow, 
     192             1:color.DarkBlue,5:color.DarkMagenta,3:color.DarkCyan,7:color.Gray, 
     193             8:color.DarkGray,4+8:color.Red,2+8:color.Green,6+8:color.Yellow, 
     194             1+8:color.Blue,5+8:color.Magenta,3+8:color.Cyan,7+8:color.White} 
     195 
    156196    def write_color(self, text, attr=None): 
    157197        '''write text at current cursor position and interpret color escapes. 
     
    162202        chunks = self.terminal_escape.split(text) 
    163203        log('chunks=%s' % repr(chunks)) 
     204        bg=self.savebg 
    164205        n = 0 # count the characters we actually write, omitting the escapes 
    165206        if attr is None:#use attribute from initial console 
    166207            attr = self.attr 
     208        try: 
     209            fg=self.trtable[(0x000f&attr)] 
     210            bg=self.trtable[(0x00f0&attr)>>4] 
     211        except TypeError: 
     212            fg=attr 
     213             
    167214        for chunk in chunks: 
    168215            m = self.escape_parts.match(chunk) 
     
    171218                attr=ansicolor.get(m.group(1),self.attr) 
    172219            n += len(chunk) 
    173             log('attr=%s' % attr) 
    174             System.Console.ForegroundColor=attr 
     220            System.Console.ForegroundColor=fg 
     221            System.Console.BackgroundColor=bg 
    175222            #self.WriteConsoleA(self.hout, chunk, len(chunk), byref(junk), None) 
    176223            System.Console.Write(chunk) 
     
    216263        self.write_color(text,attr) 
    217264 
     265    def clear_to_end_of_window(self): 
     266        oldtop=self.WindowTop 
     267        lastline=self.WindowTop+System.Console.WindowHeight 
     268        pos=self.pos() 
     269        w,h=self.size() 
     270        length=w-pos[0]+min((lastline-pos[1]-1),5)*w-1 
     271        self.write_color(length*" ") 
     272        self.pos(*pos) 
     273        self.WindowTop=oldtop 
     274         
    218275    def rectangle(self, rect, attr=None, fill=' '): 
    219276        '''Fill Rectangle.''' 
    220277        pass 
     278        oldtop=self.WindowTop 
     279        oldpos=self.pos() 
    221280        #raise NotImplementedError 
    222281        x0, y0, x1, y1 = rect 
     
    230289                System.Console.SetCursorPosition(x0,y) 
    231290                self.write_color(rowfill,attr) 
     291        self.pos(*oldpos) 
    232292 
    233293    def scroll(self, rect, dx, dy, attr=None, fill=' '): 
     
    238298    def scroll_window(self, lines): 
    239299        '''Scroll the window by the indicated number of lines.''' 
    240         top=System.Console.WindowTop+lines 
     300        top=self.WindowTop+lines 
    241301        if top<0: 
    242302            top=0 
    243303        if top+System.Console.WindowHeight>System.Console.BufferHeight: 
    244304            top=System.Console.BufferHeight 
    245         System.Console.WindowTop=top 
     305        self.WindowTop=top 
    246306 
    247307    def getkeypress(self): 
     
    249309        ck=System.ConsoleKey 
    250310        while 1: 
    251             e = System.Console.ReadKey(True) 
     311            try: 
     312                e = System.Console.ReadKey(True) 
     313            except KeyboardInterrupt: 
     314                return CTRL_C_EVENT     
    252315            if e.Key == System.ConsoleKey.PageDown: #PageDown 
    253316                self.scroll_window(12) 
     
    255318                self.scroll_window(-12) 
    256319            elif str(e.KeyChar)=="\000":#Drop deadkeys 
     320                log_sock("Deadkey: %s"%e) 
     321                return event(self,e) 
    257322                pass 
    258323            else: 
     
    269334        '''Set/get window size.''' 
    270335        sc=System.Console 
     336         
     337     
     338        if width is not None and height is not None: 
     339            sc.BufferWidth,sc.BufferHeight=width,height 
     340        else: 
     341            return sc.BufferWidth,sc.BufferHeight 
     342 
    271343        if width is not None and height is not None: 
    272344            sc.WindowWidth,sc.WindowHeight=width,height 
    273345        else: 
    274             return sc.WindowWidth,sc.WindowHeight 
     346            return sc.WindowWidth-1,sc.WindowHeight-1 
    275347     
    276348    def cursor(self, visible=True, size=None): 
     
    299371        self.keycode = input.Key 
    300372        self.state = input.Modifiers 
    301          
     373        log_sock("%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar),"console") 
    302374        self.type="KeyRelease" 
    303  
    304375        self.keysym = make_keysym(self.keycode) 
    305376        self.keyinfo = make_KeyPress(self.char, self.state, self.keycode) 
    306377 
     378def make_event_from_keydescr(keydescr): 
     379    def input(): 
     380        return 1 
     381    input.KeyChar="a" 
     382    input.Key=System.ConsoleKey.A 
     383    input.Modifiers=System.ConsoleModifiers.Shift 
     384    input.next_serial=input 
     385    e=event(input,input) 
     386    del input.next_serial 
     387    keyinfo=make_KeyPress_from_keydescr(keydescr) 
     388    e.keyinfo=keyinfo 
     389    return e 
     390 
     391CTRL_C_EVENT=make_event_from_keydescr("Control-c") 
    307392 
    308393def install_readline(hook): 
     
    344429    del c 
    345430 
    346 System.Console.Clear() 
     431    System.Console.Clear() 
  • pyreadline/branches/refactor/pyreadline/keysyms/ironpython_keysyms.py

    r1419 r1877  
    99import System 
    1010from common import validkey,KeyPress,make_KeyPress_from_keydescr 
    11  
     11from pyreadline.logger import log_sock 
    1212c32=System.ConsoleKey 
    1313Shift=System.ConsoleModifiers.Shift 
     
    197197    meta=bool(int(state)&int(Alt)) 
    198198    keyname=code2sym_map.get(keycode,"").lower() 
    199     if control: 
     199    log_sock("make key %s %s %s %s"%(shift,control,meta,keycode),"keysyms") 
     200    if control and meta: #equivalent to altgr so clear flags 
     201        control=False 
     202        meta=False     
     203    elif control: 
    200204        char=str(keycode) 
    201205    return KeyPress(char,shift,control,meta,keyname) 
  • pyreadline/branches/refactor/pyreadline/lineeditor/history.py

    r1843 r1877  
    5959            filename=self.history_filename 
    6060        try: 
    61             for line in open(filename, 'rt'): 
     61            for line in open(filename, 'r'): 
    6262                self.add_history(lineobj.ReadLineTextBuffer(line.rstrip())) 
    6363        except IOError: 
     
    180180 
    181181    def _search(self, direction, partial): 
    182         if (self.lastcommand != self.history_search_forward and 
    183                 self.lastcommand != self.history_search_backward): 
    184             self.query = ''.join(partial[0:partial.point].get_line_text()) 
    185         hcstart=max(self.history_cursor,0)  
    186         hc = self.history_cursor + direction 
    187         while (direction < 0 and hc >= 0) or (direction > 0 and hc < len(self.history)): 
    188             h = self.history[hc] 
    189             if not self.query: 
    190                 self.history_cursor = hc 
    191                 result=lineobj.ReadLineTextBuffer(h,point=len(h.get_line_text())) 
    192                 return result 
    193             elif h.get_line_text().startswith(self.query) and h != partial.get_line_text(): 
    194                 self.history_cursor = hc 
    195                 result=lineobj.ReadLineTextBuffer(h,point=partial.point) 
    196                 return result 
    197             hc += direction 
    198         else: 
    199             if len(self.history)==0: 
    200                 pass  
    201             elif hc>=len(self.history) and not self.query: 
    202                 self.history_cursor=len(self.history) 
    203                 return lineobj.ReadLineTextBuffer("",point=0) 
    204             elif self.history[hcstart].get_line_text().startswith(self.query) and self.query: 
    205                 return lineobj.ReadLineTextBuffer(self.history[hcstart],point=partial.point) 
    206             else:                 
    207                 return lineobj.ReadLineTextBuffer(partial,point=partial.point) 
    208             return lineobj.ReadLineTextBuffer(self.query,point=min(len(self.query),partial.point)) 
     182        try: 
     183            if (self.lastcommand != self.history_search_forward and 
     184                    self.lastcommand != self.history_search_backward): 
     185                self.query = ''.join(partial[0:partial.point].get_line_text()) 
     186            hcstart=max(self.history_cursor,0)  
     187            log_sock("hcstart %s"%hcstart) 
     188            hc = self.history_cursor + direction 
     189            while (direction < 0 and hc >= 0) or (direction > 0 and hc < len(self.history)): 
     190                h = self.history[hc] 
     191                if not self.query: 
     192                    self.history_cursor = hc 
     193                    result=lineobj.ReadLineTextBuffer(h,point=len(h.get_line_text())) 
     194                    return result 
     195                elif h.get_line_text().startswith(self.query) and h != partial.get_line_text(): 
     196                    self.history_cursor = hc 
     197                    result=lineobj.ReadLineTextBuffer(h,point=partial.point) 
     198                    return result 
     199                hc += direction 
     200            else: 
     201                if len(self.history)==0: 
     202                    pass  
     203                elif hc>=len(self.history) and not self.query: 
     204                    self.history_cursor=len(self.history) 
     205                    return lineobj.ReadLineTextBuffer("",point=0) 
     206                elif self.history[max(min(hcstart,len(self.history)-1),0)].get_line_text().startswith(self.query) and self.query: 
     207                    return lineobj.ReadLineTextBuffer(self.history[max(min(hcstart,len(self.history)-1),0)],point=partial.point) 
     208                else:                 
     209                    return lineobj.ReadLineTextBuffer(partial,point=partial.point) 
     210                return lineobj.ReadLineTextBuffer(self.query,point=min(len(self.query),partial.point)) 
     211        except IndexError: 
     212            log_sock("hcstart:%s %s"%(hcstart,len(self.history))) 
     213            raise 
    209214 
    210215    def history_search_forward(self,partial): # () 
     
    219224        between the start of the current line and the point. This is a 
    220225        non-incremental search. By default, this command is unbound.''' 
     226         
    221227        q= self._search(-1,partial) 
    222228        return q 
  • pyreadline/branches/refactor/pyreadline/logger.py

    r1836 r1877  
    2727logsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
    2828 
    29 show_event=["keypress","bound_function","bind_key"
     29show_event=["keypress","bound_function","bind_key","console"
    3030show_event=["bound_function"] 
    3131 
    32 sock_silent=Fals
     32sock_silent=Tru
    3333 
    3434def log_sock(s,event_type=None): 
     
    4444 
    4545     
    46 log_sock("Starting pyreadline") 
  • pyreadline/branches/refactor/pyreadline/modes/basemode.py

    r1843 r1877  
    77#  the file COPYING, distributed as part of this software. 
    88#***************************************************************************** 
    9 import os,re,math,glob 
     9import os,re,math,glob,sys 
    1010import pyreadline.logger as logger 
    1111from   pyreadline.logger import log 
     
    1515import pyreadline.clipboard as clipboard 
    1616from pyreadline.error import ReadlineError,GetSetError 
     17in_ironpython=sys.version.startswith("IronPython") 
    1718 
    1819class BaseMode(object): 
     
    174175                    self.console.write(completions[i].ljust(wmax+1)) 
    175176            self.console.write('\n') 
     177        if in_ironpython: 
     178            self.prompt=sys.ps1 
    176179        self._print_prompt() 
    177180 
  • pyreadline/branches/refactor/pyreadline/modes/emacs.py

    r1834 r1877  
    77#  the file COPYING, distributed as part of this software. 
    88#***************************************************************************** 
    9 import os 
     9import os,sys 
    1010import pyreadline.logger as logger 
    1111from   pyreadline.logger import log,log_sock 
     
    2222     
    2323    return "(%s,%s,%s,%s,%x)"%k 
     24in_ironpython=sys.version.startswith("IronPython") 
     25 
    2426 
    2527class EmacsMode(basemode.BaseMode): 
     
    2931        self._keylog=(lambda x,y: None) 
    3032        self.previous_func=None 
    31         self.prompt="
     33        self.prompt=">>>
    3234    def __repr__(self): 
    3335        return "<EmacsMode>" 
     
    106108            c.write('\r\n') 
    107109        else: 
    108             self._readline_from_keyboard() 
     110            try: 
     111                self._readline_from_keyboard() 
     112            except EOFError: 
     113                if in_ironpython: 
     114                    return None 
     115                else: 
     116                    raise 
    109117            c.write('\r\n') 
    110118 
  • pyreadline/branches/refactor/pyreadline/rlmain.py

    r1843 r1877  
    2929 
    3030from modes import editingmodes 
     31 
     32in_ironpython=sys.version.startswith("IronPython") 
     33if in_ironpython:#ironpython does not provide a prompt string to readline 
     34    import System     
     35    default_prompt=">>> " 
     36else: 
     37    default_prompt="" 
     38 
    3139 
    3240def quote_char(c): 
     
    4856        self.prompt_color = None 
    4957        self.command_color = None 
    50         self.selection_color =0x00f0 
     58        self.selection_color = self.console.saveattr<<4 
    5159        self.key_dispatch = {} 
    5260        self.previous_func = None 
     
    271279        x, y = c.pos() 
    272280        w, h = c.size() 
    273         c.rectangle((x, y, w, y+1)) 
     281        c.rectangle((x, y, w+1, y+1)) 
    274282        c.rectangle((0, y+1, w, min(y+3,h))) 
    275283 
     
    279287        w, h = c.size() 
    280288        xc += self.l_buffer.visible_line_width() 
    281         while(xc > w): 
     289        while(xc >= w): 
    282290            xc -= w 
    283291            yc += 1 
     
    286294    def _print_prompt(self): 
    287295        c = self.console 
    288         log('prompt="%s"' % repr(self.prompt)) 
    289296        x, y = c.pos() 
     297         
    290298        n = c.write_scrolling(self.prompt, self.prompt_color) 
    291299        self.prompt_begin_pos = (x, y - n) 
     
    314322        else: 
    315323            n = c.write_scrolling(ltext, self.command_color) 
    316              
    317324        self._update_prompt_pos(n) 
    318         self._clear_after() 
     325        if hasattr(c,"clear_to_end_of_window"): #Work around function for ironpython due  
     326            c.clear_to_end_of_window()          #to System.Console's lack of FillFunction 
     327        else: 
     328            self._clear_after() 
    319329        self._set_cursor() 
    320330     
     
    330340        def bind_key(key,name): 
    331341            log("bind %s %s"%(key,name)) 
    332             log_sock("bindkey: %s %s"%(key,name),"bind_key") 
    333342            if hasattr(modes[mode],name): 
    334          #       print "can bind",key,name 
    335343                modes[mode]._bind_key(key,getattr(modes[mode],name)) 
    336344            else: 
  • pyreadline/branches/refactor/pyreadline/test/emacs_test.py

    r1843 r1877  
    304304        r.input ('Up') 
    305305        self.assert_line(r,'ako',3) 
     306 
     307    def test_history_3 (self): 
     308        r = EmacsModeTest () 
     309        r.add_history ('aaaa') 
     310        r.add_history ('aaba') 
     311        r.add_history ('aaca') 
     312        r.add_history ('akca') 
     313        r.add_history ('bbb') 
     314        r.add_history ('ako') 
     315        self.assert_line(r,'',0) 
     316        r.input ('k') 
     317        r.input ('Up') 
     318        self.assert_line(r,'k',1) 
    306319 
    307320