mstrch0c 2017-04-14 11:05:51 +02:00
commit bc8ff5f44a
6520 changed files with 426985 additions and 0 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
import clr
clr.AddReferenceByPartialName(u"System.Windows.Forms")
import System.Windows.Forms.Clipboard as cb
def GetClipboardText():
text = ""
if cb.ContainsText():
text = cb.GetText()
return text
def SetClipboardText(text):
cb.SetText(text)
if __name__ == u'__main__':
txt = GetClipboardText() # display last text clipped
print txt

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
mybuffer = u""
def GetClipboardText():
return mybuffer
def SetClipboardText(text):
global mybuffer
mybuffer = text

View file

@ -0,0 +1,88 @@
#Bind keys for exit (keys only work on empty lines
#disable_readline(True) #Disable pyreadline completely.
debug_output("off") #"on" saves log info to./pyreadline_debug_log.txt
#"on_nologfile" only enables print warning messages
bind_exit_key("Control-d")
bind_exit_key("Control-z")
#Commands for moving
bind_key("Home", "beginning_of_line")
bind_key("End", "end_of_line")
bind_key("Left", "backward_char")
bind_key("Control-b", "backward_char")
bind_key("Right", "forward_char")
bind_key("Control-f", "forward_char")
bind_key("Alt-f", "forward_word")
bind_key("Alt-b", "backward_word")
bind_key("Clear", "clear_screen")
bind_key("Control-l", "clear_screen")
bind_key("Control-a", "beginning_of_line")
bind_key("Control-e", "end_of_line")
#bind_key("Control-l", "redraw_current_line")
#Commands for Manipulating the History
bind_key("Return", "accept_line")
bind_key("Control-p", "previous_history")
bind_key("Control-n", "next_history")
bind_key("Up", "history_search_backward")
bind_key("Down", "history_search_forward")
bind_key("Alt-<", "beginning_of_history")
bind_key("Alt->", "end_of_history")
bind_key("Control-r", "reverse_search_history")
bind_key("Control-s", "forward_search_history")
bind_key("Alt-p", "non_incremental_reverse_search_history")
bind_key("Alt-n", "non_incremental_forward_search_history")
bind_key("Control-z", "undo")
bind_key("Control-_", "undo")
#Commands for Changing Text
bind_key("Delete", "delete_char")
bind_key("Control-d", "delete_char")
bind_key("BackSpace", "backward_delete_char")
#bind_key("Control-Shift-v", "quoted_insert")
bind_key("Control-space", "self_insert")
bind_key("Control-BackSpace", "backward_delete_word")
#Killing and Yanking
bind_key("Control-k", "kill_line")
bind_key("Control-shift-k", "kill_whole_line")
bind_key("Escape", "kill_whole_line")
bind_key("Meta-d", "kill_word")
bind_key("Control-w", "unix_word_rubout")
#bind_key("Control-Delete", "forward_kill_word")
#Copy paste
bind_key("Shift-Right", "forward_char_extend_selection")
bind_key("Shift-Left", "backward_char_extend_selection")
bind_key("Shift-Control-Right", "forward_word_extend_selection")
bind_key("Shift-Control-Left", "backward_word_extend_selection")
bind_key("Control-m", "set_mark")
bind_key("Control-Shift-x", "copy_selection_to_clipboard")
#bind_key("Control-c", "copy_selection_to_clipboard") #Needs allow_ctrl_c(True) below to be uncommented
bind_key("Control-q", "copy_region_to_clipboard")
bind_key('Control-Shift-v', "paste_mulitline_code")
bind_key("Control-x", "cut_selection_to_clipboard")
bind_key("Control-v", "paste")
bind_key("Control-y", "yank")
bind_key("Alt-v", "ipython_paste")
#Unbinding keys:
#un_bind_key("Home")
#Other
bell_style("none") #modes: none, audible, visible(not implemented)
show_all_if_ambiguous("on")
mark_directories("on")
completer_delims(" \t\n\"\\'`@$><=;|&{(?")
complete_filesystem("off")
debug_output("off")
#allow_ctrl_c(True) #(Allows use of ctrl-c as copy key, still propagate keyboardinterrupt when not waiting for input)
history_filename("~/.pythonhistory")
history_length(200) #value of -1 means no limit
#set_mode("vi") #will cause following bind_keys to bind to vi mode as well as activate vi mode
#ctrl_c_tap_time_interval(0.3)

View file

@ -0,0 +1,30 @@
# -*- coding: UTF-8 -*-
# Example snippet to use in a PYTHONSTARTUP file
try:
import pyreadline.rlmain
#pyreadline.rlmain.config_path=r"c:\xxx\pyreadlineconfig.ini"
import readline,atexit
import pyreadline.unicode_helper
#
#
#Normally the codepage for pyreadline is set to be sys.stdout.encoding
#if you need to change this uncomment the following line
#pyreadline.unicode_helper.pyreadline_codepage="utf8"
except ImportError:
print "Module readline not available."
else:
#import tab completion functionality
import rlcompleter
#Override completer from rlcompleter to disable automatic ( on callable
completer_obj = rlcompleter.Completer()
def nop(val, word):
return word
completer_obj._callable_postfix = nop
readline.set_completer(completer_obj.complete)
#activate tab completion
readline.parse_and_bind("tab: complete")
readline.read_history_file()
atexit.register(readline.write_history_file)
del readline,rlcompleter,atexit

Binary file not shown.

View file

@ -0,0 +1,190 @@
# -*- coding: ISO-8859-1 -*-
import re,sys,os
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=u"white",background=u"black",backgroundbold=False):
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()))
def get_winattr(self):
attr = 0
if self.bold:
attr |= 0x0008
if self.backgroundbold:
attr |= 0x0080
if self.inverse:
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]
winattr=property(get_winattr,set_winattr)
def __repr__(self):
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
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"}
class AnsiWriter(object):
def __init__(self, default=defaultstate):
if isinstance(defaultstate, AnsiState):
self.defaultstate = default
else:
self.defaultstate=AnsiState()
self.defaultstate.winattr = defaultstate
def write_color(self,text, attr=None):
u'''write text at current cursor position and interpret color escapes.
return the number of characters written.
'''
if isinstance(attr,AnsiState):
defaultstate = attr
elif attr is None: #use attribute form initial console
attr = self.defaultstate.copy()
else:
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":
attr = self.defaultstate.copy()
continue
for part in parts:
if part == u"0": # No text attribute
attr = self.defaultstate.copy()
attr.bold=False
elif part == u"7": # switch on reverse
attr.inverse=True
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]
elif len(part) == 2 and u"40" <= part <= u"47": # set background color
attr.backgroundcolor = trtable[int(part) - 40]
continue
n += len(chunk)
if True:
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]
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 = []
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
attr = 15
for chunk in chunks:
m = escape_parts.match(chunk)
if m:
for part in m.group(1).split(u";"):
if part == u"0": # No text attribute
attr = 0
elif part == u"7": # switch on reverse
attr |= 0x4000
if part == u"1": # switch on bold (i.e. intensify foreground color)
attr |= 0x08
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 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)
# ignore blink, underline and anything we don't understand
continue
n += len(chunk)
if 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__==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))
pprint (write_color_old(s))
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=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=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__==u"__main__":
import console
import pprint
pprint=pprint.pprint
c=console.Console()
c.write_color(u"dhsjdhs")
c.write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:")
print
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))

Binary file not shown.

View file

@ -0,0 +1,16 @@
FOREGROUND_BLUE = 0x0001
FOREGROUND_GREEN = 0x0002
FOREGROUND_RED = 0x0004
FOREGROUND_INTENSITY = 0x0008
BACKGROUND_BLUE = 0x0010
BACKGROUND_GREEN = 0x0020
BACKGROUND_RED = 0x0040
BACKGROUND_INTENSITY = 0x0080
COMMON_LVB_LEADING_BYTE = 0x0100
COMMON_LVB_TRAILING_BYTE = 0x0200
COMMON_LVB_GRID_HORIZONTAL= 0x0400
COMMON_LVB_GRID_LVERTICAL = 0x0800
COMMON_LVB_GRID_RVERTICAL = 0x1000
COMMON_LVB_REVERSE_VIDEO = 0x2000
COMMON_LVB_UNDERSCORE = 0x4000

View file

@ -0,0 +1,52 @@
class baseconsole:
def __init__(self):
pass
def bell(self):
raise NotImplementedError
def pos(self, x=None, y=None):
u'''Move or query the window cursor.'''
raise NotImplementedError
def size(self):
raise NotImplementedError
def rectangle(self, rect, attr=None, fill=u' '):
u'''Fill Rectangle.'''
raise NotImplementedError
def write_scrolling(self, text, attr=None):
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
scroll amount. For example, I remember the cursor position of the
prompt so that I can redraw the line but if the window scrolls,
the remembered position is off.
This variant of write tries to keep track of the cursor position
so that it will know when the screen buffer is scrolled. It
returns the number of lines that the buffer scrolled.
'''
raise NotImplementedError
def getkeypress(self):
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=' '):
u'''Fill the entire screen.'''
raise NotImplementedError
def isatty(self):
return True
def flush(self):
pass

Binary file not shown.

View file

@ -0,0 +1,424 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2003-2006 Gary Bishop.
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
u'''Cursor control and color for the .NET console.
'''
#
# Ironpython requires a patch to work do:
#
# In file PythonCommandLine.cs patch line:
# class PythonCommandLine
# {
# to:
# public class PythonCommandLine
# {
#
#
#
# primitive debug printing that won't interfere with the screen
import clr,sys
clr.AddReferenceToFileAndPath(sys.executable)
import IronPythonConsole
import sys
import re
import os
import System
from event import Event
from pyreadline.logger import log
from pyreadline.keysyms import \
make_keysym, make_keyinfo, make_KeyPress, make_KeyPress_from_keydescr
from pyreadline.console.ansi import AnsiState
color = System.ConsoleColor
ansicolor={u"0;30": color.Black,
u"0;31": color.DarkRed,
u"0;32": color.DarkGreen,
u"0;33": color.DarkYellow,
u"0;34": color.DarkBlue,
u"0;35": color.DarkMagenta,
u"0;36": color.DarkCyan,
u"0;37": color.DarkGray,
u"1;30": color.Gray,
u"1;31": color.Red,
u"1;32": color.Green,
u"1;33": color.Yellow,
u"1;34": color.Blue,
u"1;35": color.Magenta,
u"1;36": color.Cyan,
u"1;37": color.White
}
winattr = {u"black" : 0, u"darkgray" : 0+8,
u"darkred" : 4, u"red" : 4+8,
u"darkgreen" : 2, u"green" : 2+8,
u"darkyellow" : 6, u"yellow" : 6+8,
u"darkblue" : 1, u"blue" : 1+8,
u"darkmagenta" : 5, u"magenta" : 5+8,
u"darkcyan" : 3, u"cyan" : 3+8,
u"gray" : 7, u"white" : 7+8}
class Console(object):
u'''Console driver for Windows.
'''
def __init__(self, newbuffer=0):
u'''Initialize the Console object.
newbuffer=1 will allocate a new buffer so the old content will be restored
on exit.
'''
self.serial = 0
self.attr = System.Console.ForegroundColor
self.saveattr = winattr[str(System.Console.ForegroundColor).lower()]
self.savebg = System.Console.BackgroundColor
log(u'initial attr=%s' % self.attr)
def _get(self):
top = System.Console.WindowTop
log(u"WindowTop:%s"%top)
return top
def _set(self, value):
top = System.Console.WindowTop
log(u"Set WindowTop:old:%s,new:%s"%(top, value))
WindowTop = property(_get, _set)
del _get, _set
def __del__(self):
u'''Cleanup the console when finished.'''
# I don't think this ever gets called
pass
def pos(self, x=None, y=None):
u'''Move or query the window cursor.'''
if x is not None:
System.Console.CursorLeft=x
else:
x = System.Console.CursorLeft
if y is not None:
System.Console.CursorTop=y
else:
y = System.Console.CursorTop
return x, y
def home(self):
u'''Move to home.'''
self.pos(0, 0)
# Map ANSI color escape sequences into Windows Console Attributes
terminal_escape = re.compile(u'(\001?\033\\[[0-9;]*m\002?)')
escape_parts = re.compile(u'\001?\033\\[([0-9;]*)m\002?')
# This pattern should match all characters that change the cursor position differently
# than a normal character.
motion_char_re = re.compile(u'([\n\r\t\010\007])')
def write_scrolling(self, text, attr=None):
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
scroll amount. For example, I remember the cursor position of the
prompt so that I can redraw the line but if the window scrolls,
the remembered position is off.
This variant of write tries to keep track of the cursor position
so that it will know when the screen buffer is scrolled. It
returns the number of lines that the buffer scrolled.
'''
x, y = self.pos()
w, h = self.size()
scroll = 0 # the result
# split the string into ordinary characters and funny characters
chunks = self.motion_char_re.split(text)
for chunk in chunks:
n = self.write_color(chunk, attr)
if len(chunk) == 1: # the funny characters will be alone
if chunk[0] == u'\n': # newline
x = 0
y += 1
elif chunk[0] == u'\r': # carriage return
x = 0
elif chunk[0] == u'\t': # tab
x = 8 * (int(x / 8) + 1)
if x > w: # newline
x -= w
y += 1
elif chunk[0] == u'\007': # bell
pass
elif chunk[0] == u'\010':
x -= 1
if x < 0:
y -= 1 # backed up 1 line
else: # ordinary character
x += 1
if x == w: # wrap
x = 0
y += 1
if y == h: # scroll
scroll += 1
y = h - 1
else: # chunk of ordinary characters
x += n
l = int(x / w) # lines we advanced
x = x % w # new x value
y += l
if y >= h: # scroll
scroll += y - h + 1
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}
def write_color(self, text, attr=None):
'''write text at current cursor position and interpret color escapes.
return the number of characters written.
'''
log(u'write_color("%s", %s)' % (text, attr))
chunks = self.terminal_escape.split(text)
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
attr = self.attr
try:
fg = self.trtable[(0x000f&attr)]
bg = self.trtable[(0x00f0&attr)>>4]
except TypeError:
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)
n += len(chunk)
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))
if attr is None:
attr = self.attr
n = c_int(0)
self.SetConsoleTextAttribute(self.hout, attr)
self.WriteConsoleA(self.hout, text, len(text), byref(n), None)
return len(text)
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)
return len(text)
write_plain = write_color
# make this class look like a file object
def write(self, text):
log(u'write("%s")' % text)
return self.write_color(text)
#write = write_scrolling
def isatty(self):
return True
def flush(self):
pass
def page(self, attr=None, fill=u' '):
u'''Fill the entire screen.'''
System.Console.Clear()
def text(self, x, y, text, attr=None):
u'''Write text at the given position.'''
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" ")
self.pos(*pos)
self.WindowTop = oldtop
def rectangle(self, rect, attr=None, fill=u' '):
u'''Fill Rectangle.'''
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)
else:
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=' '):
u'''Scroll a rectangle.'''
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
def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
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
log(u"Deadkey: %s"%e)
return event(self, e)
else:
return event(self, e)
def title(self, txt=None):
u'''Set/get title.'''
if 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
if width is not None and height is not None:
sc.BufferWidth, sc.BufferHeight = width,height
else:
return sc.BufferWidth, sc.BufferHeight
if width is not None and height is not None:
sc.WindowWidth, sc.WindowHeight = width,height
else:
return sc.WindowWidth - 1, sc.WindowHeight - 1
def cursor(self, visible=True, size=None):
u'''Set cursor on or off.'''
System.Console.CursorVisible = visible
def bell(self):
System.Console.Beep()
def next_serial(self):
u'''Get next event serial number.'''
self.serial += 1
return self.serial
class event(Event):
u'''Represent events from the console.'''
def __init__(self, console, input):
u'''Initialize an event from the Windows input structure.'''
self.type = u'??'
self.serial = console.next_serial()
self.width = 0
self.height = 0
self.x = 0
self.y = 0
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"
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)
del input.next_serial
keyinfo = make_KeyPress_from_keydescr(keydescr)
e.keyinfo = keyinfo
return e
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 = u""
except EOFError:
return None
if res[-1:] == u"\n":
return res[:-1]
else:
return res
class IronPythonWrapper(IronPythonConsole.IConsole):
def ReadLine(self, autoIndentSize):
return hook_wrap()
def Write(self, text, style):
System.Console.Write(text)
def WriteLine(self, text, style):
System.Console.WriteLine(text)
IronPythonConsole.PythonCommandLine.MyConsole = IronPythonWrapper()
if __name__ == u'__main__':
import time, sys
c = Console(0)
sys.stdout = c
sys.stderr = c
c.page()
c.pos(5, 10)
c.write(u'hi there')
c.title(u"Testing console")
# c.bell()
print
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
del c
System.Console.Clear()

Binary file not shown.

View file

@ -0,0 +1,18 @@
import sys,textwrap
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__]
def get_rest(rl):
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"")
return out

View file

@ -0,0 +1,20 @@
import sys
success = False
in_ironpython = u"IronPython" in sys.version
if in_ironpython:
try:
from ironpython_keysyms import *
success = True
except ImportError, x:
raise
else:
try:
from keysyms import *
success = True
except ImportError, x:
pass
if not success:
raise ImportError(u"Could not import keysym for local pythonversion", x)

View file

@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2003-2006 Gary Bishop.
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
# table for translating virtual keys to X windows key symbols
try:
set
except NameError:
from sets import Set as set
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'])
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=u"", 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)
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 __repr__(self):
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)
else:
if self.control or self.meta or self.shift:
return (self.control, self.meta, self.shift, self.char.upper())
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'"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith(u'control-'):
keyinfo.control = True
keydescr = keydescr[8:]
elif lkeyname.startswith(u'ctrl-'):
keyinfo.control = True
keydescr = keydescr[5:]
elif keydescr.lower().startswith(u'\\c-'):
keyinfo.control = True
keydescr = keydescr[3:]
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(u'meta-'):
keyinfo.meta = True
keydescr = keydescr[5:]
elif lkeyname.startswith(u'alt-'):
keyinfo.meta = True
keydescr = keydescr[4:]
elif lkeyname.startswith(u'shift-'):
keyinfo.shift = True
keydescr = keydescr[6:]
else:
if len(keydescr) > 1:
if keydescr.strip().lower() in validkey:
keyinfo.keyname = keydescr.strip().lower()
keyinfo.char = ""
else:
raise IndexError(u"Not a valid key: '%s'"%keydescr)
else:
keyinfo.char = keydescr
return keyinfo
if __name__ == u"__main__":
import startup

View file

@ -0,0 +1,202 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2003-2006 Gary Bishop.
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
import System
from common import validkey, KeyPress, make_KeyPress_from_keydescr
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',
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
def make_keysym(keycode):
try:
sym = code2sym_map[keycode]
except KeyError:
sym = u''
return sym
sym2code_map = {}
for code,sym in code2sym_map.iteritems():
sym2code_map[sym.lower()] = code
def key_text_to_keyinfo(keytext):
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:
return keyname_to_keyinfo(keytext)
def char_to_keyinfo(char, control=False, meta=False, shift=False):
vk = (ord(char))
if vk & 0xffff == 0xffff:
print u'VkKeyScan("%s") = %x' % (char, vk)
raise ValueError, u'bad key'
if vk & 0x100:
shift = True
if vk & 0x200:
control = True
if vk & 0x400:
meta = True
return (control, meta, shift, vk & 0xff)
def keyname_to_keyinfo(keyname):
control = False
meta = False
shift = False
while 1:
lkeyname = keyname.lower()
if lkeyname.startswith(u'control-'):
control = True
keyname = keyname[8:]
elif lkeyname.startswith(u'ctrl-'):
control = True
keyname = keyname[5:]
elif lkeyname.startswith(u'meta-'):
meta = True
keyname = keyname[5:]
elif lkeyname.startswith(u'alt-'):
meta = True
keyname = keyname[4:]
elif lkeyname.startswith(u'shift-'):
shift = True
keyname = keyname[6:]
else:
if len(keyname) > 1:
return (control, meta, shift, sym2code_map.get(keyname.lower(),u" "))
else:
return char_to_keyinfo(keyname, control, meta, shift)
def keyseq_to_keyinfo(keyseq):
res = []
control = False
meta = False
shift = False
while 1:
if keyseq.startswith(u'\\C-'):
control = True
keyseq = keyseq[3:]
elif keyseq.startswith(u'\\M-'):
meta = True
keyseq = keyseq[3:]
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:
res.append(char_to_keyinfo(keyseq[0], control, meta, shift))
control = meta = shift = False
keyseq = keyseq[1:]
else:
return res[0]
def make_keyinfo(keycode, state):
control = False
meta =False
shift = False
return (control, meta, shift, 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()
if control and meta: #equivalent to altgr so clear flags
control = False
meta = False
elif control:
char = str(keycode)
return KeyPress(char, shift, control, meta, keyname)

View file

@ -0,0 +1,133 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2003-2006 Gary Bishop.
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# 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
from common import validkey, KeyPress, make_KeyPress_from_keydescr
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
def char_to_keyinfo(char, control=False, meta=False, shift=False):
k=KeyPress()
vk = VkKeyScan(ord(char))
if vk & 0xffff == 0xffff:
print u'VkKeyScan("%s") = %x' % (char, vk)
raise ValueError, u'bad key'
if vk & 0x100:
k.shift = True
if vk & 0x200:
k.control = True
if vk & 0x400:
k.meta = True
k.char=chr(vk & 0xff)
return k
def make_KeyPress(char, state, keycode):
control = (state & (4+8)) != 0
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)
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 = u""
out = KeyPress(char, shift, control, meta, keyname)
return out
if __name__==u"__main__":
import startup

View file

@ -0,0 +1,171 @@
#This file contains constants that are normally found in win32all
#But included here to avoid the dependency
VK_LBUTTON=1
VK_RBUTTON=2
VK_CANCEL=3
VK_MBUTTON=4
VK_XBUTTON1=5
VK_XBUTTON2=6
VK_BACK=8
VK_TAB=9
VK_CLEAR=12
VK_RETURN=13
VK_SHIFT=16
VK_CONTROL=17
VK_MENU=18
VK_PAUSE=19
VK_CAPITAL=20
VK_KANA=0x15
VK_HANGEUL=0x15
VK_HANGUL=0x15
VK_JUNJA=0x17
VK_FINAL=0x18
VK_HANJA=0x19
VK_KANJI=0x19
VK_ESCAPE=0x1B
VK_CONVERT=0x1C
VK_NONCONVERT=0x1D
VK_ACCEPT=0x1E
VK_MODECHANGE=0x1F
VK_SPACE=32
VK_PRIOR=33
VK_NEXT=34
VK_END=35
VK_HOME=36
VK_LEFT=37
VK_UP=38
VK_RIGHT=39
VK_DOWN=40
VK_SELECT=41
VK_PRINT=42
VK_EXECUTE=43
VK_SNAPSHOT=44
VK_INSERT=45
VK_DELETE=46
VK_HELP=47
VK_LWIN=0x5B
VK_RWIN=0x5C
VK_APPS=0x5D
VK_SLEEP=0x5F
VK_NUMPAD0=0x60
VK_NUMPAD1=0x61
VK_NUMPAD2=0x62
VK_NUMPAD3=0x63
VK_NUMPAD4=0x64
VK_NUMPAD5=0x65
VK_NUMPAD6=0x66
VK_NUMPAD7=0x67
VK_NUMPAD8=0x68
VK_NUMPAD9=0x69
VK_MULTIPLY=0x6A
VK_ADD=0x6B
VK_SEPARATOR=0x6C
VK_SUBTRACT=0x6D
VK_DECIMAL=0x6E
VK_DIVIDE=0x6F
VK_F1=0x70
VK_F2=0x71
VK_F3=0x72
VK_F4=0x73
VK_F5=0x74
VK_F6=0x75
VK_F7=0x76
VK_F8=0x77
VK_F9=0x78
VK_F10=0x79
VK_F11=0x7A
VK_F12=0x7B
VK_F13=0x7C
VK_F14=0x7D
VK_F15=0x7E
VK_F16=0x7F
VK_F17=0x80
VK_F18=0x81
VK_F19=0x82
VK_F20=0x83
VK_F21=0x84
VK_F22=0x85
VK_F23=0x86
VK_F24=0x87
VK_NUMLOCK=0x90
VK_SCROLL=0x91
VK_LSHIFT=0xA0
VK_RSHIFT=0xA1
VK_LCONTROL=0xA2
VK_RCONTROL=0xA3
VK_LMENU=0xA4
VK_RMENU=0xA5
VK_BROWSER_BACK=0xA6
VK_BROWSER_FORWARD=0xA7
VK_BROWSER_REFRESH=0xA8
VK_BROWSER_STOP=0xA9
VK_BROWSER_SEARCH=0xAA
VK_BROWSER_FAVORITES=0xAB
VK_BROWSER_HOME=0xAC
VK_VOLUME_MUTE=0xAD
VK_VOLUME_DOWN=0xAE
VK_VOLUME_UP=0xAF
VK_MEDIA_NEXT_TRACK=0xB0
VK_MEDIA_PREV_TRACK=0xB1
VK_MEDIA_STOP=0xB2
VK_MEDIA_PLAY_PAUSE=0xB3
VK_LAUNCH_MAIL=0xB4
VK_LAUNCH_MEDIA_SELECT=0xB5
VK_LAUNCH_APP1=0xB6
VK_LAUNCH_APP2=0xB7
VK_OEM_1=0xBA
VK_OEM_PLUS=0xBB
VK_OEM_COMMA=0xBC
VK_OEM_MINUS=0xBD
VK_OEM_PERIOD=0xBE
VK_OEM_2=0xBF
VK_OEM_3=0xC0
VK_OEM_4=0xDB
VK_OEM_5=0xDC
VK_OEM_6=0xDD
VK_OEM_7=0xDE
VK_OEM_8=0xDF
VK_OEM_102=0xE2
VK_PROCESSKEY=0xE5
VK_PACKET=0xE7
VK_ATTN=0xF6
VK_CRSEL=0xF7
VK_EXSEL=0xF8
VK_EREOF=0xF9
VK_PLAY=0xFA
VK_ZOOM=0xFB
VK_NONAME=0xFC
VK_PA1=0xFD
VK_OEM_CLEAR=0xFE
CF_TEXT=1
CF_BITMAP=2
CF_METAFILEPICT=3
CF_SYLK=4
CF_DIF=5
CF_TIFF=6
CF_OEMTEXT=7
CF_DIB=8
CF_PALETTE=9
CF_PENDATA=10
CF_RIFF=11
CF_WAVE=12
CF_UNICODETEXT=13
CF_ENHMETAFILE=14
CF_HDROP=15
CF_LOCALE=16
CF_MAX=17
CF_OWNERDISPLAY=128
CF_DSPTEXT=129
CF_DSPBITMAP=130
CF_DSPMETAFILEPICT=131
CF_DSPENHMETAFILE=142
CF_PRIVATEFIRST=512
CF_PRIVATELAST=767
CF_GDIOBJFIRST=768
CF_GDIOBJLAST=1023
GPTR=64
GHND=66

View file

@ -0,0 +1,264 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# 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
from pyreadline.unicode_helper import ensure_unicode, ensure_str
if u"pyreadline" in sys.modules:
pyreadline = sys.modules[u"pyreadline"]
else:
import pyreadline
import lineobj
import exceptions
class EscapeHistory(exceptions.Exception):
pass
from pyreadline.logger import log
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.last_search_for = u""
def get_current_history_length(self):
u'''Return the number of lines currently in the history.
(This is different from get_history_length(), which returns
the maximum number of lines that will be written to a history file.)'''
value = len(self.history)
log(u"get_current_history_length:%d"%value)
return value
def get_history_length(self):
u'''Return the desired length of the history file. Negative values imply
unlimited history file size.'''
value = self._history_length
log(u"get_history_length:%d"%value)
return value
def get_history_item(self, index):
u'''Return the current contents of history item at index (starts with index 1).'''
item = self.history[index - 1]
log(u"get_history_item: index:%d item:%r"%(index, item))
return item.get_line_text()
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
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
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.'''
self.history[:] = []
self.history_cursor = 0
def read_history_file(self, filename=None):
u'''Load a readline history file.'''
if filename is None:
filename = self.history_filename
try:
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):
u'''Save a readline history file.'''
if filename is None:
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()))
fp.write(u'\n')
fp.close()
def add_history(self, line):
u'''Append a line to the history buffer, as if it was the last line typed.'''
if not hasattr(line, "get_line_text"):
line = lineobj.ReadLineTextBuffer(line)
if not line.get_line_text():
pass
elif len(self.history) > 0 and self.history[-1].get_line_text() == line.get_line_text():
pass
else:
self.history.append(line)
self.history_cursor = len(self.history)
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):
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
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:
self.history_cursor += 1
current.set_line(self.history[self.history_cursor].get_line_text())
def beginning_of_history(self): # (M-<)
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->)
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())
def reverse_search_history(self, searchfor, startpos=None):
if startpos is None:
startpos = self.history_cursor
origpos = startpos
result = lineobj.ReadLineTextBuffer("")
for idx, line in list(enumerate(self.history))[startpos:0:-1]:
if searchfor in line:
startpos = idx
break
#If we get a new search without change in search term it means
#someone pushed ctrl-r and we should find the next match
if self.last_search_for == searchfor and startpos > 0:
startpos -= 1
for idx, line in list(enumerate(self.history))[startpos:0:-1]:
if searchfor in line:
startpos = idx
break
if self.history:
result = self.history[startpos].get_line_text()
else:
result = u""
self.history_cursor = startpos
self.last_search_for = searchfor
log(u"reverse_search_history: old:%d new:%d result:%r"%(origpos, self.history_cursor, result))
return result
def forward_search_history(self, searchfor, startpos=None):
if startpos is None:
startpos = min(self.history_cursor, max(0, self.get_current_history_length()-1))
origpos = startpos
result = lineobj.ReadLineTextBuffer("")
for idx, line in list(enumerate(self.history))[startpos:]:
if searchfor in line:
startpos = idx
break
#If we get a new search without change in search term it means
#someone pushed ctrl-r and we should find the next match
if self.last_search_for == searchfor and startpos < self.get_current_history_length()-1:
startpos += 1
for idx, line in list(enumerate(self.history))[startpos:]:
if searchfor in line:
startpos = idx
break
if self.history:
result = self.history[startpos].get_line_text()
else:
result = u""
self.history_cursor = startpos
self.last_search_for = searchfor
return result
def _search(self, direction, partial):
try:
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)
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()))
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)
return result
hc += direction
else:
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)
else:
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): # ()
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): # ()
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__==u"__main__":
import pdb
q = LineHistory()
r = LineHistory()
s = LineHistory()
RL = lineobj.ReadLineTextBuffer
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"))
r.add_history(RL(u"ako"))

View file

@ -0,0 +1,799 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# 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 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
class NotAWordError(IndexError):
pass
def quote_char(c):
if ord(c) > 0:
return c
############## Line positioner ########################
class LinePositioner(object):
def __call__(self, line):
NotImplementedError(u"Base class !!!")
class NextChar(LinePositioner):
def __call__(self, line):
if line.point < len(line.line_buffer):
return line.point + 1
else:
return line.point
NextChar = NextChar()
class PrevChar(LinePositioner):
def __call__(self, line):
if line.point > 0:
return line.point - 1
else:
return line.point
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()
class NextWordEnd(LinePositioner):
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()
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)]):
return PrevWordStart(line)
else:
return line.point
else:
raise NotAWordError(u"Point is not in a word")
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]):
return NextWordEnd(line)
else:
return line.point
else:
raise NotAWordError(u"Point is not in a word")
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()
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
return point
PrevSpace = PrevSpace()
class StartOfLine(LinePositioner):
def __call__(self, line):
return 0
StartOfLine = StartOfLine()
class EndOfLine(LinePositioner):
def __call__(self, line):
return len(line.line_buffer)
EndOfLine = EndOfLine()
class Point(LinePositioner):
def __call__(self, line):
return line.point
Point = Point()
class Mark(LinePositioner):
def __call__(self, line):
return line.mark
k = Mark()
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):
NotImplementedError(u"Base class !!!")
class CurrentWord(LineSlice):
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()
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()
class PointSlice(LineSlice):
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[:]
if point is None:
self.point = txtstr.point
else:
self.point = point
if mark is None:
self.mark = txtstr.mark
else:
self.mark = mark
else:
self._insert_text(txtstr)
if point is None:
self.point = 0
else:
self.point = point
if mark is None:
self.mark = -1
else:
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
def push_undo(self):
ltext = self.get_line_text()
if self.undo_stack and ltext == self.undo_stack[-1].get_line_text():
self.undo_stack[-1].point = self.point
else:
self.undo_stack.append(self.copy())
def pop_undo(self):
if len(self.undo_stack) >= 2:
self.undo_stack.pop()
self.set_top_undo()
self.undo_stack.pop()
else:
self.reset_line()
self.undo_stack = []
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
else:
pass
def __repr__(self):
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)
assert (value <= len(self.line_buffer))
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)
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
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))
def get_line_text(self):
buf = self.line_buffer
buf = map(ensure_unicode, buf)
return u''.join(buf)
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)
else:
self.point = cursor
def reset_line(self):
self.line_buffer = []
self.point = 0
def end_of_line(self):
self.point = len(self.line_buffer)
def _insert_text(self, text, argument=1):
text = text * argument
if self.overwrite:
for c in text:
#if self.point:
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):
#Check if key is LineSlice, convert to regular slice
#and continue processing
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)
elif isinstance(key.start,LinePositioner):
start = key.start(self)
else:
start = key.start
if key.stop is None:
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):
return self.line_buffer[key(self)]
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)
elif start is None:
start=0
if isinstance(stop, LinePositioner):
stop = stop(self)
elif stop is None:
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
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
def __len__(self):
return len(self.line_buffer)
def upper(self):
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]
return self
def capitalize(self):
self.set_line(self.get_line_text().capitalize(), self.point)
return self
def startswith(self, txt):
return self.get_line_text().startswith(txt)
def endswith(self, txt):
return self.get_line_text().endswith(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
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 __repr__(self):
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._insert_text(char, argument)
def to_clipboard(self):
if self.enable_win32_clipboard:
clipboard.set_clipboard_text(self.get_line_text())
######### Movement
def beginning_of_line(self):
self.selection_mark = -1
self.point = StartOfLine
def end_of_line(self):
self.selection_mark = -1
self.point = EndOfLine
def forward_char(self,argument = 1):
if argument < 0:
self.backward_char(-argument)
self.selection_mark = -1
for x in range(argument):
self.point = NextChar
def backward_char(self, argument=1):
if argument < 0:
self.forward_char(-argument)
self.selection_mark = -1
for x in range(argument):
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
def backward_word(self, argument=1):
if argument < 0:
self.forward_word(-argument)
self.selection_mark = -1
for x in range(argument):
self.point = PrevWordStart
def forward_word_end(self, argument=1):
if argument < 0:
self.backward_word_end(-argument)
self.selection_mark = -1
for x in range(argument):
self.point = NextWordEnd
def backward_word_end(self, argument=1):
if argument < 0:
self.forward_word_end(-argument)
self.selection_mark = -1
for x in range(argument):
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
def end_of_line_extend_selection(self):
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:
self.backward_char_extend_selection(-argument)
if self.enable_selection and self.selection_mark < 0:
self.selection_mark = self.point
for x in range(argument):
self.point = NextChar
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
for x in range(argument):
self.point = PrevChar
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
for x in range(argument):
self.point = NextWordStart
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
for x in range(argument):
self.point = PrevWordStart
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
for x in range(argument):
self.point = NextWordEnd
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
for x in range(argument):
self.point = PrevWordEnd
######### delete
def delete_selection(self):
if self.enable_selection and self.selection_mark >= 0:
if self.selection_mark < self.point:
del self[self.selection_mark:self.point]
self.selection_mark = -1
else:
del self[self.point:self.selection_mark]
self.selection_mark = -1
return True
else:
self.selection_mark = -1
return False
def delete_char(self, argument=1):
if argument < 0:
self.backward_delete_char(-argument)
if self.delete_selection():
argument -= 1
for x in range(argument):
del self[Point]
def backward_delete_char(self, argument=1):
if argument < 0:
self.delete_char(-argument)
if self.delete_selection():
argument -= 1
for x in range(argument):
if self.point > 0:
self.backward_char()
self.delete_char()
def forward_delete_word(self, argument=1):
if argument < 0:
self.backward_delete_word(-argument)
if self.delete_selection():
argument -= 1
for x in range(argument):
del self[Point:NextWordStart]
def backward_delete_word(self, argument=1):
if argument < 0:
self.forward_delete_word(-argument)
if self.delete_selection():
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
def delete_horizontal_space(self):
if self[Point] in " \t":
del self[PrevWordEnd:NextWordStart]
self.selection_mark = -1
######### Case
def upcase_word(self):
p = self.point
try:
self[CurrentWord] = self[CurrentWord].upper()
self.point = p
except NotAWordError:
pass
def downcase_word(self):
p = self.point
try:
self[CurrentWord] = self[CurrentWord].lower()
self.point = p
except NotAWordError:
pass
def capitalize_word(self):
p = self.point
try:
self[CurrentWord] = self[CurrentWord].capitalize()
self.point = p
except NotAWordError:
pass
########### Transpose
def transpose_chars(self):
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
def transpose_words(self):
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
############ Kill
def kill_line(self):
self.add_to_kill_ring(self[self.point:])
del self.line_buffer[self.point:]
def kill_whole_line(self):
self.add_to_kill_ring(self[:])
del self[:]
def backward_kill_line(self):
del self[StartOfLine:Point]
def unix_line_discard(self):
del self[StartOfLine:Point]
pass
def kill_word(self):
"""Kills to next word ending"""
del self[Point:NextWordEnd]
def backward_kill_word(self):
"""Kills to next word ending"""
if not self.delete_selection():
del self[PrevWordStart:Point]
self.selection_mark = -1
def forward_kill_word(self):
"""Kills to next word ending"""
if not self.delete_selection():
del self[Point:NextWordEnd]
self.selection_mark = -1
def unix_word_rubout(self):
if not self.delete_selection():
del self[PrevSpace:Point]
self.selection_mark = -1
def kill_region(self):
pass
def copy_region_as_kill(self):
pass
def copy_backward_word(self):
pass
def copy_forward_word(self):
pass
def yank(self):
self.paste_from_kill_ring()
def yank_pop(self):
pass
############## Mark
def set_mark(self):
self.mark = self.point
def exchange_point_and_mark(self):
pass
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:
return
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:
return
begin = min(cursor, selection_mark)
end = max(cursor, selection_mark)
toclipboard = u"".join(self.line_buffer[begin:end])
clipboard.SetClipboardText(toclipboard)
def cut_selection_to_clipboard(self): # ()
self.copy_selection_to_clipboard()
self.delete_selection()
############## Paste
############## Kill ring
def add_to_kill_ring(self,txt):
self.kill_ring = [txt]
if kill_ring_to_clipboard:
clipboard.SetClipboardText(txt.get_line_text())
def paste_from_kill_ring(self):
if self.kill_ring:
self.insert_text(self.kill_ring[0])
##################################################################
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 choice(bool):
if bool:
return chr
else:
return u" "
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
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"&"
else:
out[point] = u"."
out[pos] = u"^"
print u'"%s"'%(u"".join(out))
if __name__ == "__main__":
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 u'%-15s "%s"'%(name, show_pos(q, pos, u"^"))
l = ReadLineTextBuffer(u"kjjk asads asad")
l.point = EndOfLine

View file

@ -0,0 +1,102 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# 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
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
return result
word_pattern = re.compile(u"(x*)")
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 mark_start_segment(str, is_segment):
def mark_start(s):
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)))
def mark_end_segment(str, is_segment):
def mark_start(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)))
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")]
################ Following are used in lineobj ###########################
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":
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)]
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)]
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)]
prev=start
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)]
prev=start
result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)]
return result

Binary file not shown.

View file

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
import cPickle
import logging
import logging.handlers
import SocketServer
import struct,socket
try:
import msvcrt
except ImportError:
msvcrt = None
print u"problem"
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()
return q
return u""
singleline=False
def main():
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((u"", port))
s.settimeout(1)
while 1:
try:
data, addr = s.recvfrom(100000)
print data,
except socket.timeout:
key = check_key().lower()
if u"q" == key:
print u"Quitting logserver"
break
elif u"c" == key:
print u"\n" * 100
if __name__ == u"__main__":
main()

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Michael Graz. <mgraz@plan10.com>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
from pyreadline.modes.emacs import *
from pyreadline import keysyms
from pyreadline.lineeditor import lineobj
from pyreadline.keysyms.common import make_KeyPress_from_keydescr
import unittest
class MockReadline:
def __init__ (self):
self.l_buffer=lineobj.ReadLineTextBuffer(u"")
self._history=history.LineHistory()
def add_history (self, line):
self._history.add_history (lineobj.TextLine (line))
def _print_prompt (self):
pass
def _bell (self):
pass
def insert_text(self, string):
u'''Insert text into the command line.'''
self.l_buffer.insert_text(string)
class MockConsole:
def __init__ (self):
self.bell_count = 0
self.text = ''
def size (self):
return (1, 1)
def cursor(self, visible=None, size=None):
pass
def bell (self):
self.bell_count += 1
def write (self, text):
self.text += text
class Event:
def __init__ (self, char):
if char==u"escape":
self.char=u'\x1b'
elif char==u"backspace":
self.char=u'\x08'
elif char==u"tab":
self.char=u'\t'
elif char==u"space":
self.char=u' '
else:
self.char = char
def keytext_to_keyinfo_and_event (keytext):
keyinfo = keysyms.common.make_KeyPress_from_keydescr (keytext)
if len(keytext) == 3 and keytext[0] == u'"' and keytext[2] == u'"':
event = Event (keytext[1])
else:
event = Event (keyinfo.tuple() [3])
return keyinfo, event
#override runTests from from main in unittest to remove sys.exit call
class Tester(unittest.TestProgram):
def runTests(self):
if self.testRunner is None:
self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity)
result = self.testRunner.run(self.test)
# sys.exit(not result.wasSuccessful())

View file

@ -0,0 +1,400 @@
# -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2006 Michael Graz. <mgraz@plan10.com>
# Copyright (C) 2006 Michael Graz. <mgraz@plan10.com>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
import sys, unittest
import pdb
sys.path.append (u'../..')
from pyreadline.modes.emacs import *
from pyreadline import keysyms
from pyreadline.lineeditor import lineobj
from common import *
from pyreadline.logger import log
import pyreadline.logger as logger
logger.sock_silent=True
logger.show_event=[u"debug"]
#----------------------------------------------------------------------
class EmacsModeTest (EmacsMode):
tested_commands={}
def __init__ (self):
EmacsMode.__init__ (self, MockReadline())
self.mock_console = MockConsole ()
self.init_editing_mode (None)
self.lst_completions = []
self.completer = self.mock_completer
self.completer_delims = u' u'
self.tabstop = 4
self.mark_directories=False
self.show_all_if_ambiguous=False
def get_mock_console (self):
return self.mock_console
console = property (get_mock_console)
def _set_line (self, text):
self.l_buffer.set_line (text)
def get_line (self):
return self.l_buffer.get_line_text ()
line = property (get_line)
def get_line_cursor (self):
return self.l_buffer.point
line_cursor = property (get_line_cursor)
def input (self, keytext):
if keytext[0:1] == 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:
keyinfo, event = keytext_to_keyinfo_and_event (key)
dispatch_func = self.key_dispatch.get(keyinfo.tuple(),self.self_insert)
self.tested_commands[dispatch_func.__name__]=dispatch_func
log(u"keydisp: %s %s"%( key,dispatch_func.__name__))
dispatch_func (event)
self.previous_func=dispatch_func
def accept_line (self, e):
if EmacsMode.accept_line (self, e):
# simulate return
# self.add_history (self.line)
self.l_buffer.reset_line ()
def mock_completer (self, text, state):
return self.lst_completions [state]
#----------------------------------------------------------------------
class TestsKeyinfo (unittest.TestCase):
def test_keyinfo (self):
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)
class TestsMovement (unittest.TestCase):
def test_cursor (self):
r = EmacsModeTest ()
self.assertEqual (r.line, u'')
r.input(u'"First Second Third"')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Control-a')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 0)
r.input(u'Control-e')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Home')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 0)
r.input(u'Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 1)
r.input(u'Ctrl-f')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 2)
r.input(u'Ctrl-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 5)
r.input(u'Ctrl-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 12)
r.input(u'Ctrl-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Ctrl-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Ctrl-Left')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 13)
r.input(u'Ctrl-Left')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 6)
r.input(u'Ctrl-Left')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 0)
r.input(u'Ctrl-Left')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 0)
class TestsDelete (unittest.TestCase):
def test_delete (self):
r = EmacsModeTest ()
self.assertEqual (r.line, u'')
r.input(u'"First Second Third"')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Delete')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Left')
r.input(u'Left')
r.input(u'Delete')
self.assertEqual (r.line, u'First Second Thid')
self.assertEqual (r.line_cursor, 16)
r.input(u'Delete')
self.assertEqual (r.line, u'First Second Thi')
self.assertEqual (r.line_cursor, 16)
r.input(u'Backspace')
self.assertEqual (r.line, u'First Second Th')
self.assertEqual (r.line_cursor, 15)
r.input(u'Home')
r.input(u'Right')
r.input(u'Right')
self.assertEqual (r.line, u'First Second Th')
self.assertEqual (r.line_cursor, 2)
r.input(u'Backspace')
self.assertEqual (r.line, u'Frst Second Th')
self.assertEqual (r.line_cursor, 1)
r.input(u'Backspace')
self.assertEqual (r.line, u'rst Second Th')
self.assertEqual (r.line_cursor, 0)
r.input(u'Backspace')
self.assertEqual (r.line, u'rst Second Th')
self.assertEqual (r.line_cursor, 0)
r.input(u'Escape')
self.assertEqual (r.line, u'')
self.assertEqual (r.line_cursor, 0)
def test_delete_word (self):
r = EmacsModeTest ()
self.assertEqual (r.line, u'')
r.input(u'"First Second Third"')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
r.input(u'Control-Backspace')
self.assertEqual (r.line, u'First Second ')
self.assertEqual (r.line_cursor, 13)
r.input(u'Backspace')
r.input(u'Left')
r.input(u'Left')
self.assertEqual (r.line, u'First Second')
self.assertEqual (r.line_cursor, 10)
r.input(u'Control-Backspace')
self.assertEqual (r.line, u'First nd')
self.assertEqual (r.line_cursor, 6)
r.input(u'Escape')
self.assertEqual (r.line, u'')
self.assertEqual (r.line_cursor, 0)
r.input(u'"First Second Third"')
r.input(u'Home')
r.input(u'Right')
r.input(u'Right')
r.input(u'Control-Delete')
self.assertEqual (r.line, u'FiSecond Third')
self.assertEqual (r.line_cursor, 2)
r.input(u'Control-Delete')
self.assertEqual (r.line, u'FiThird')
self.assertEqual (r.line_cursor, 2)
r.input(u'Control-Delete')
self.assertEqual (r.line, u'Fi')
self.assertEqual (r.line_cursor, 2)
r.input(u'Control-Delete')
self.assertEqual (r.line, u'Fi')
self.assertEqual (r.line_cursor, 2)
r.input(u'Escape')
self.assertEqual (r.line, u'')
self.assertEqual (r.line_cursor, 0)
class TestsSelectionMovement (unittest.TestCase):
def test_cursor (self):
r = EmacsModeTest ()
self.assertEqual (r.line, u'')
r.input(u'"First Second Third"')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 18)
self.assertEqual (r.l_buffer.selection_mark, -1)
r.input(u'Home')
r.input(u'Shift-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 1)
self.assertEqual (r.l_buffer.selection_mark, 0)
r.input(u'Shift-Control-Right')
self.assertEqual (r.line, u'First Second Third')
self.assertEqual (r.line_cursor, 5)
self.assertEqual (r.l_buffer.selection_mark, 0)
r.input(u'"a"')
self.assertEqual (r.line, u'a Second Third')
self.assertEqual (r.line_cursor, 1)
self.assertEqual (r.l_buffer.selection_mark, -1)
r.input(u'Shift-End')
self.assertEqual (r.line, u'a Second Third')
self.assertEqual (r.line_cursor, 14)
self.assertEqual (r.l_buffer.selection_mark, 1)
r.input(u'Delete')
self.assertEqual (r.line, u'a')
self.assertEqual (r.line_cursor, 1)
self.assertEqual (r.l_buffer.selection_mark, -1)
class TestsHistory (unittest.TestCase):
def test_history_1 (self):
r = EmacsModeTest ()
r.add_history (u'aa')
r.add_history (u'bbb')
self.assertEqual (r.line, u'')
r.input (u'Up')
self.assertEqual (r.line, u'bbb')
self.assertEqual (r.line_cursor, 3)
r.input (u'Up')
self.assertEqual (r.line, u'aa')
self.assertEqual (r.line_cursor, 2)
r.input (u'Up')
self.assertEqual (r.line, u'aa')
self.assertEqual (r.line_cursor, 2)
r.input (u'Down')
self.assertEqual (r.line, u'bbb')
self.assertEqual (r.line_cursor, 3)
r.input (u'Down')
self.assertEqual (r.line, u'')
self.assertEqual (r.line_cursor, 0)
def test_history_2 (self):
r = EmacsModeTest ()
r.add_history (u'aaaa')
r.add_history (u'aaba')
r.add_history (u'aaca')
r.add_history (u'akca')
r.add_history (u'bbb')
r.add_history (u'ako')
self.assert_line(r,'',0)
r.input (u'"a"')
r.input (u'Up')
self.assert_line(r,'ako',1)
r.input (u'Up')
self.assert_line(r,'akca',1)
r.input (u'Up')
self.assert_line(r,'aaca',1)
r.input (u'Up')
self.assert_line(r,'aaba',1)
r.input (u'Up')
self.assert_line(r,'aaaa',1)
r.input (u'Right')
self.assert_line(r,'aaaa',2)
r.input (u'Down')
self.assert_line(r,'aaba',2)
r.input (u'Down')
self.assert_line(r,'aaca',2)
r.input (u'Down')
self.assert_line(r,'aaca',2)
r.input (u'Left')
r.input (u'Left')
r.input (u'Down')
r.input (u'Down')
self.assert_line(r,'bbb',3)
r.input (u'Left')
self.assert_line(r,'bbb',2)
r.input (u'Down')
self.assert_line(r,'bbb',2)
r.input (u'Up')
self.assert_line(r,'bbb',2)
def test_history_3 (self):
r = EmacsModeTest ()
r.add_history (u'aaaa')
r.add_history (u'aaba')
r.add_history (u'aaca')
r.add_history (u'akca')
r.add_history (u'bbb')
r.add_history (u'ako')
self.assert_line(r,'',0)
r.input (u'')
r.input (u'Up')
self.assert_line(r,'ako',3)
r.input (u'Down')
self.assert_line(r,'',0)
r.input (u'Up')
self.assert_line(r,'ako',3)
def test_history_3 (self):
r = EmacsModeTest ()
r.add_history (u'aaaa')
r.add_history (u'aaba')
r.add_history (u'aaca')
r.add_history (u'akca')
r.add_history (u'bbb')
r.add_history (u'ako')
self.assert_line(r,'',0)
r.input (u'k')
r.input (u'Up')
self.assert_line(r,'k',1)
def test_complete (self):
import rlcompleter
logger.sock_silent = False
log("-" * 50)
r = EmacsModeTest()
completerobj = rlcompleter.Completer()
def _nop(val, word):
return word
completerobj._callable_postfix = _nop
r.completer = completerobj.complete
r._bind_key("tab", r.complete)
r.input(u'"exi(ksdjksjd)"')
r.input(u'Control-a')
r.input(u'Right')
r.input(u'Right')
r.input(u'Right')
r.input(u'Tab')
self.assert_line(r, u"exit(ksdjksjd)", 4)
r.input(u'Escape')
r.input(u'"exi"')
r.input(u'Control-a')
r.input(u'Right')
r.input(u'Right')
r.input(u'Right')
r.input(u'Tab')
self.assert_line(r, u"exit", 4)
def assert_line(self,r,line,cursor):
self.assertEqual (r.line, line)
self.assertEqual (r.line_cursor, cursor)
#----------------------------------------------------------------------
# utility functions
#----------------------------------------------------------------------
if __name__ == u'__main__':
Tester()
tested=EmacsModeTest.tested_commands.keys()
tested.sort()
# print " Tested functions ".center(60,"-")
# print "\n".join(tested)
# print
all_funcs=dict([(x.__name__,x) for x in EmacsModeTest().key_dispatch.values()])
all_funcs=all_funcs.keys()
not_tested=[x for x in all_funcs if x not in tested]
not_tested.sort()
print " Not tested functions ".center(60,"-")
print "\n".join(not_tested)

View file

@ -0,0 +1,148 @@
# -*- coding: UTF-8 -*-
# Copyright (C) 2007 Jörgen Stenarson. <>
import sys, unittest
sys.path.append (u'../..')
#from pyreadline.modes.vi import *
#from pyreadline import keysyms
from pyreadline.lineeditor import lineobj
from pyreadline.lineeditor.history import LineHistory
import pyreadline.lineeditor.history as history
import pyreadline.logger
pyreadline.logger.sock_silent=False
from pyreadline.logger import log
#----------------------------------------------------------------------
#----------------------------------------------------------------------
RL=lineobj.ReadLineTextBuffer
class Test_prev_next_history(unittest.TestCase):
t = u"test text"
def setUp(self):
self.q = q = LineHistory()
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):
hist = self.q
assert hist.history_cursor == 6
l = RL(u"")
hist.previous_history(l)
assert l.get_line_text() == u"ako"
hist.previous_history(l)
assert l.get_line_text() == u"bbb"
hist.previous_history(l)
assert l.get_line_text() == u"akca"
hist.previous_history(l)
assert l.get_line_text() == u"aaca"
hist.previous_history(l)
assert l.get_line_text() == u"aaba"
hist.previous_history(l)
assert l.get_line_text() == u"aaaa"
hist.previous_history(l)
assert l.get_line_text() == u"aaaa"
def test_next_history (self):
hist=self.q
hist.beginning_of_history()
assert hist.history_cursor==0
l=RL(u"")
hist.next_history(l)
assert l.get_line_text()==u"aaba"
hist.next_history(l)
assert l.get_line_text()==u"aaca"
hist.next_history(l)
assert l.get_line_text()==u"akca"
hist.next_history(l)
assert l.get_line_text()==u"bbb"
hist.next_history(l)
assert l.get_line_text()==u"ako"
hist.next_history(l)
assert l.get_line_text()==u"ako"
class Test_prev_next_history(unittest.TestCase):
t = u"test text"
def setUp(self):
self.q = q = LineHistory()
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):
q = LineHistory()
for x in [u"aaaa",u"aaba",u"aaca",u" aacax",u"akca",u"bbb",u"ako"]:
q.add_history(RL(x))
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):
q = LineHistory()
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(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
class Test_history_search_incr_fwd_backwd(unittest.TestCase):
def setUp(self):
self.q = q = LineHistory()
for x in [u"aaaa",u"aaba",u"aaca",u"akca",u"bbb",u"ako"]:
q.add_history(RL(x))
def test_backward_1(self):
q = self.q
self.assertEqual(q.reverse_search_history(u"b"), u"bbb")
self.assertEqual(q.reverse_search_history(u"b"), u"aaba")
self.assertEqual(q.reverse_search_history(u"bb"), u"aaba")
def test_backward_2(self):
q = self.q
self.assertEqual(q.reverse_search_history(u"a"), u"ako")
self.assertEqual(q.reverse_search_history(u"aa"), u"aaca")
self.assertEqual(q.reverse_search_history(u"a"), u"aaca")
self.assertEqual(q.reverse_search_history(u"ab"), u"aaba")
def test_forward_1(self):
q = self.q
self.assertEqual(q.forward_search_history(u"a"), u"ako")
def test_forward_2(self):
q = self.q
q.history_cursor = 0
self.assertEqual(q.forward_search_history(u"a"), u"aaaa")
self.assertEqual(q.forward_search_history(u"a"), u"aaba")
self.assertEqual(q.forward_search_history(u"ak"), u"akca")
self.assertEqual(q.forward_search_history(u"akl"), u"akca")
self.assertEqual(q.forward_search_history(u"ak"), u"akca")
self.assertEqual(q.forward_search_history(u"ako"), u"ako")
class Test_empty_history_search_incr_fwd_backwd(unittest.TestCase):
def setUp(self):
self.q = q = LineHistory()
def test_backward_1(self):
q = self.q
self.assertEqual(q.reverse_search_history(u"b"), u"")
def test_forward_1(self):
q = self.q
self.assertEqual(q.forward_search_history(u"a"), u"")
#----------------------------------------------------------------------
# utility functions
#----------------------------------------------------------------------
if __name__ == u'__main__':
unittest.main()
l=lineobj.ReadLineTextBuffer(u"First Second Third")

View file

@ -0,0 +1,390 @@
# Copyright (C) 2006 Michael Graz. <mgraz@plan10.com>
import sys, unittest
sys.path.append (u'../..')
#from pyreadline.modes.vi import *
#from pyreadline import keysyms
from pyreadline.lineeditor import lineobj
#----------------------------------------------------------------------
#----------------------------------------------------------------------
class Test_copy (unittest.TestCase):
def test_copy1 (self):
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(u"first second",point=5)
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)
class Test_linepos (unittest.TestCase):
t="test text"
def test_NextChar (self):
t=self.t
l=lineobj.ReadLineTextBuffer(t)
for i in range(len(t)):
self.assertEqual(i,l.point)
l.point=lineobj.NextChar
#advance past end of buffer
l.point=lineobj.NextChar
self.assertEqual(len(t),l.point)
def test_PrevChar (self):
t=self.t
l=lineobj.ReadLineTextBuffer(t,point=len(t))
for i in range(len(t)):
self.assertEqual(len(t)-i,l.point)
l.point=lineobj.PrevChar
#advance past beginning of buffer
l.point=lineobj.PrevChar
self.assertEqual(0,l.point)
def test_EndOfLine (self):
t=self.t
l=lineobj.ReadLineTextBuffer(t,point=len(t))
for i in range(len(t)):
l.point=i
l.point=lineobj.EndOfLine
self.assertEqual(len(t),l.point)
def test_StartOfLine (self):
t=self.t
l=lineobj.ReadLineTextBuffer(t,point=len(t))
for i in range(len(t)):
l.point=i
l.point=lineobj.StartOfLine
self.assertEqual(0,l.point)
class Tests_linepos2(Test_linepos):
t="kajkj"
class Tests_linepos3(Test_linepos):
t=""
class Test_movement (unittest.TestCase):
def test_NextChar (self):
cmd=lineobj.NextChar
tests=[
# u"First"
(cmd,
u"First",
u"# u",
u" # u"),
(cmd,
u"First",
u" # u",
u" #"),
(cmd,
u"First",
u" #",
u" #"),
]
for cmd,text,init_point,expected_point in tests:
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_PrevChar (self):
cmd=lineobj.PrevChar
tests=[
# u"First"
(cmd,
u"First",
u" #",
u" # u"),
(cmd,
u"First",
u" # u",
u"# u"),
(cmd,
u"First",
u"# u",
u"# u"),
]
for cmd,text,init_point,expected_point in tests:
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_PrevWordStart (self):
cmd=lineobj.PrevWordStart
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u" #",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u"# u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_NextWordStart (self):
cmd=lineobj.NextWordStart
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_NextWordEnd (self):
cmd=lineobj.NextWordEnd
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_PrevWordEnd (self):
cmd=lineobj.PrevWordEnd
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u" #",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u"# u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_WordEnd_1 (self):
cmd=lineobj.WordEnd
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u" # u"),
(cmd,
u"First Second Third",
u" # u",
u" # u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_WordEnd_2 (self):
cmd=lineobj.WordEnd
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u" # u"),
(cmd,
u"First Second Third",
u" # u"),
(cmd,
u"First Second Third",
u" #"),
]
for cmd,text,init_point in tests:
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
self.assertRaises(lineobj.NotAWordError,cmd,l)
def test_WordStart_1 (self):
cmd=lineobj.WordStart
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u"# u"),
(cmd,
u"First Second Third",
u" # u",
u"# u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_WordStart_2 (self):
cmd=lineobj.WordStart
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u" # u"),
(cmd,
u"First Second Third",
u" # u"),
(cmd,
u"First Second Third",
u" #"),
]
for cmd,text,init_point in tests:
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
self.assertRaises(lineobj.NotAWordError,cmd,l)
def test_StartOfLine (self):
cmd=lineobj.StartOfLine
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u"# u"),
(cmd,
u"First Second Third",
u" # u",
u"# u"),
(cmd,
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))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_EndOfLine (self):
cmd=lineobj.EndOfLine
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
u"# u",
u" #"),
(cmd,
u"First Second Third",
u" # u",
u" #"),
(cmd,
u"First Second Third",
u" #",
u" #"),
]
for cmd,text,init_point,expected_point in tests:
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
l.point=cmd
self.assertEqual(get_point_pos(expected_point),l.point)
def test_Point(self):
cmd=lineobj.Point
tests=[
# u"First Second Third"
(cmd,
u"First Second Third",
0),
(cmd,
u"First Second Third",
12),
(cmd,
u"First Second Third",
18),
]
for cmd,text,p in tests:
l=lineobj.ReadLineTextBuffer(text,p)
self.assertEqual(p,cmd(l))
#----------------------------------------------------------------------
# utility functions
def get_point_pos(pstr):
return pstr.index(u"#")
def get_mark_pos(mstr):
try:
return mstr.index(u"#")
except ValueError:
return -1
#----------------------------------------------------------------------
if __name__ == u'__main__':
unittest.main()
l=lineobj.ReadLineTextBuffer(u"First Second Third")

File diff suppressed because it is too large Load diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.