mirror of
https://github.com/wassname/pyreadline.git
synced 2026-06-27 16:10:38 +08:00
Adding __future__ imports to all files
This commit is contained in:
@@ -6,6 +6,8 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
import unicode_helper, logger, clipboard, lineeditor, modes, console
|
||||
from rlmain import *
|
||||
import rlmain
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
from . import unicode_helper, logger, clipboard, lineeditor, modes, console
|
||||
from .rlmain import *
|
||||
from . import rlmain
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import sys
|
||||
success = True
|
||||
in_ironpython = u"IronPython" in sys.version
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
if in_ironpython:
|
||||
try:
|
||||
from ironpython_clipboard import GetClipboardText, SetClipboardText
|
||||
from .ironpython_clipboard import GetClipboardText, SetClipboardText
|
||||
except ImportError:
|
||||
from no_clipboard import GetClipboardText, SetClipboardText
|
||||
from .no_clipboard import GetClipboardText, SetClipboardText
|
||||
|
||||
else:
|
||||
try:
|
||||
from win32_clipboard import GetClipboardText, SetClipboardText
|
||||
from .win32_clipboard import GetClipboardText, SetClipboardText
|
||||
except ImportError:
|
||||
from no_clipboard import GetClipboardText, SetClipboardText
|
||||
from .no_clipboard import GetClipboardText, SetClipboardText
|
||||
|
||||
|
||||
def send_data(lists):
|
||||
@@ -22,15 +23,15 @@ def set_clipboard_text(toclipboard):
|
||||
SetClipboardText(str(toclipboard))
|
||||
|
||||
def make_tab(lists):
|
||||
if hasattr(lists, u"tolist"):
|
||||
if hasattr(lists, "tolist"):
|
||||
lists = lists.tolist()
|
||||
ut = []
|
||||
for rad in lists:
|
||||
if type(rad) in [list, tuple]:
|
||||
ut.append(u"\t".join([u"%s"%x for x in rad]))
|
||||
ut.append("\t".join(["%s"%x for x in rad]))
|
||||
else:
|
||||
ut.append(u"%s"%rad)
|
||||
return u"\n".join(ut)
|
||||
ut.append("%s"%rad)
|
||||
return "\n".join(ut)
|
||||
|
||||
def make_list_of_list(txt):
|
||||
def make_num(x):
|
||||
@@ -47,8 +48,8 @@ def make_list_of_list(txt):
|
||||
return x
|
||||
ut = []
|
||||
flag = False
|
||||
for rad in [x for x in txt.split(u"\r\n") if x != u""]:
|
||||
raden=[make_num(x) for x in rad.split(u"\t")]
|
||||
for rad in [x for x in txt.split("\r\n") if x != ""]:
|
||||
raden=[make_num(x) for x in rad.split("\t")]
|
||||
if str in map(type,raden):
|
||||
flag = True
|
||||
ut.append(raden)
|
||||
@@ -56,17 +57,17 @@ def make_list_of_list(txt):
|
||||
|
||||
|
||||
def get_clipboard_text_and_convert(paste_list=False):
|
||||
u"""Get txt from clipboard. if paste_list==True the convert tab separated
|
||||
"""Get txt from clipboard. if paste_list==True the convert tab separated
|
||||
data to list of lists. Enclose list of list in array() if all elements are
|
||||
numeric"""
|
||||
txt = GetClipboardText()
|
||||
if txt:
|
||||
if paste_list and u"\t" in txt:
|
||||
if paste_list and "\t" in txt:
|
||||
array, flag = make_list_of_list(txt)
|
||||
if flag:
|
||||
txt = repr(array)
|
||||
else:
|
||||
txt = u"array(%s)"%repr(array)
|
||||
txt = u"".join([c for c in txt if c not in u" \t\r\n"])
|
||||
txt = "array(%s)"%repr(array)
|
||||
txt = "".join([c for c in txt if c not in " \t\r\n"])
|
||||
return txt
|
||||
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import clr
|
||||
clr.AddReferenceByPartialName(u"System.Windows.Forms")
|
||||
clr.AddReferenceByPartialName("System.Windows.Forms")
|
||||
import System.Windows.Forms.Clipboard as cb
|
||||
|
||||
def GetClipboardText():
|
||||
@@ -19,9 +20,9 @@ def GetClipboardText():
|
||||
def SetClipboardText(text):
|
||||
cb.SetText(text)
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
txt = GetClipboardText() # display last text clipped
|
||||
print txt
|
||||
print(txt)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
|
||||
mybuffer = u""
|
||||
mybuffer = ""
|
||||
|
||||
def GetClipboardText():
|
||||
return mybuffer
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
# hence this contribution.
|
||||
#
|
||||
###################################################################################
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
from ctypes import *
|
||||
from pyreadline.keysyms.winconstants import CF_TEXT, GHND
|
||||
@@ -80,7 +81,7 @@ def getformatname(format):
|
||||
return buffer.value
|
||||
|
||||
def GetClipboardText():
|
||||
text = u""
|
||||
text = ""
|
||||
if OpenClipboard(0):
|
||||
hClipMem = GetClipboardData(CF_TEXT)
|
||||
if hClipMem:
|
||||
@@ -103,6 +104,6 @@ def SetClipboardText(text):
|
||||
SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))
|
||||
CloseClipboard()
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
txt = GetClipboardText() # display last text clipped
|
||||
print txt
|
||||
print(txt)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#Bind keys for exit (keys only work on empty lines
|
||||
#disable_readline(True) #Disable pyreadline completely.
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
debug_output("off") #"on" saves log info to./pyreadline_debug_log.txt
|
||||
#"on_nologfile" only enables print warning messages
|
||||
bind_exit_key("Control-d")
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Example snippet to use in a PYTHONSTARTUP file
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
try:
|
||||
import pyreadline.rlmain
|
||||
#pyreadline.rlmain.config_path=r"c:\xxx\pyreadlineconfig.ini"
|
||||
import readline,atexit
|
||||
import readline, atexit
|
||||
import pyreadline.unicode_helper
|
||||
#
|
||||
#
|
||||
@@ -11,7 +12,7 @@ try:
|
||||
#if you need to change this uncomment the following line
|
||||
#pyreadline.unicode_helper.pyreadline_codepage="utf8"
|
||||
except ImportError:
|
||||
print "Module readline not available."
|
||||
print("Module readline not available.")
|
||||
else:
|
||||
#import tab completion functionality
|
||||
import rlcompleter
|
||||
@@ -27,4 +28,4 @@ else:
|
||||
readline.parse_and_bind("tab: complete")
|
||||
readline.read_history_file()
|
||||
atexit.register(readline.write_history_file)
|
||||
del readline,rlcompleter,atexit
|
||||
del readline, rlcompleter, atexit
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import glob,sys
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import glob, sys
|
||||
|
||||
success = False
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
|
||||
if in_ironpython:
|
||||
try:
|
||||
from ironpython_console import *
|
||||
from .ironpython_console import *
|
||||
success = True
|
||||
except ImportError:
|
||||
raise
|
||||
else:
|
||||
try:
|
||||
from console import *
|
||||
from .console import *
|
||||
success = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
+45
-44
@@ -1,20 +1,21 @@
|
||||
# -*- coding: ISO-8859-1 -*-
|
||||
import re,sys,os
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
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?')
|
||||
terminal_escape = re.compile('(\001?\033\\[[0-9;]*m\002?)')
|
||||
escape_parts = re.compile('\001?\033\\[([0-9;]*)m\002?')
|
||||
|
||||
|
||||
class AnsiState(object):
|
||||
def __init__(self,bold=False,inverse=False,color=u"white",background=u"black",backgroundbold=False):
|
||||
def __init__(self, bold=False, inverse=False, color="white", background="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}
|
||||
trtable = {"black":0, "red":4, "green":2, "yellow":6,
|
||||
"blue":1, "magenta":5, "cyan":3, "white":7}
|
||||
revtable = dict(zip(trtable.values(),trtable.keys()))
|
||||
def get_winattr(self):
|
||||
attr = 0
|
||||
@@ -35,10 +36,10 @@ class AnsiState(object):
|
||||
self.color = self.revtable[attr & 0x0007]
|
||||
self.background = self.revtable[(attr & 0x0070) >> 4]
|
||||
|
||||
winattr=property(get_winattr,set_winattr)
|
||||
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'% \
|
||||
return 'AnsiState(bold=%s,inverse=%s,color=%9s,' \
|
||||
'background=%9s,backgroundbold=%s)# 0x%x'% \
|
||||
(self.bold, self.inverse, '"%s"'%self.color,
|
||||
'"%s"'%self.background, self.backgroundbold,
|
||||
self.winattr)
|
||||
@@ -52,10 +53,10 @@ class AnsiState(object):
|
||||
x.backgroundbold = self.backgroundbold
|
||||
return x
|
||||
|
||||
defaultstate = AnsiState(False,False,u"white")
|
||||
defaultstate = AnsiState(False, False, "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"}
|
||||
trtable = {0:"black", 1:"red", 2:"green", 3:"yellow",
|
||||
4:"blue", 5:"magenta", 6:"cyan", 7:"white"}
|
||||
|
||||
class AnsiWriter(object):
|
||||
def __init__(self, default=defaultstate):
|
||||
@@ -67,7 +68,7 @@ class AnsiWriter(object):
|
||||
|
||||
|
||||
def write_color(self,text, attr=None):
|
||||
u'''write text at current cursor position and interpret color escapes.
|
||||
'''write text at current cursor position and interpret color escapes.
|
||||
|
||||
return the number of characters written.
|
||||
'''
|
||||
@@ -85,21 +86,21 @@ class AnsiWriter(object):
|
||||
for chunk in chunks:
|
||||
m = escape_parts.match(chunk)
|
||||
if m:
|
||||
parts = m.group(1).split(u";")
|
||||
if len(parts) == 1 and parts[0] == u"0":
|
||||
parts = m.group(1).split(";")
|
||||
if len(parts) == 1 and parts[0] == "0":
|
||||
attr = self.defaultstate.copy()
|
||||
continue
|
||||
for part in parts:
|
||||
if part == u"0": # No text attribute
|
||||
if part == "0": # No text attribute
|
||||
attr = self.defaultstate.copy()
|
||||
attr.bold=False
|
||||
elif part == u"7": # switch on reverse
|
||||
elif part == "7": # switch on reverse
|
||||
attr.inverse=True
|
||||
elif part == u"1": # switch on bold (i.e. intensify foreground color)
|
||||
elif part == "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
|
||||
elif len(part) == 2 and "30" <= part <= "37": # set foreground color
|
||||
attr.color = trtable[int(part) - 30]
|
||||
elif len(part) == 2 and u"40" <= part <= u"47": # set background color
|
||||
elif len(part) == 2 and "40" <= part <= "47": # set background color
|
||||
attr.backgroundcolor = trtable[int(part) - 40]
|
||||
continue
|
||||
n += len(chunk)
|
||||
@@ -108,7 +109,7 @@ class AnsiWriter(object):
|
||||
return n,res
|
||||
|
||||
def parse_color(self,text, attr=None):
|
||||
n,res=self.write_color(text, attr)
|
||||
n, res = self.write_color(text, attr)
|
||||
return n, [attr.winattr for attr, text in res]
|
||||
|
||||
def write_color(text, attr=None):
|
||||
@@ -116,7 +117,7 @@ def write_color(text, attr=None):
|
||||
return a.write_color(text, attr)
|
||||
|
||||
def write_color_old( text, attr=None):
|
||||
u'''write text at current cursor position and interpret color escapes.
|
||||
'''write text at current cursor position and interpret color escapes.
|
||||
|
||||
return the number of characters written.
|
||||
'''
|
||||
@@ -128,18 +129,18 @@ def write_color_old( text, attr=None):
|
||||
for chunk in chunks:
|
||||
m = escape_parts.match(chunk)
|
||||
if m:
|
||||
for part in m.group(1).split(u";"):
|
||||
if part == u"0": # No text attribute
|
||||
for part in m.group(1).split(";"):
|
||||
if part == "0": # No text attribute
|
||||
attr = 0
|
||||
elif part == u"7": # switch on reverse
|
||||
elif part == "7": # switch on reverse
|
||||
attr |= 0x4000
|
||||
if part == u"1": # switch on bold (i.e. intensify foreground color)
|
||||
if part == "1": # switch on bold (i.e. intensify foreground color)
|
||||
attr |= 0x08
|
||||
elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
|
||||
elif len(part) == 2 and "30" <= part <= "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
|
||||
elif len(part) == 2 and "40" <= part <= "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)
|
||||
@@ -147,44 +148,44 @@ def write_color_old( text, attr=None):
|
||||
continue
|
||||
n += len(chunk)
|
||||
if chunk:
|
||||
res.append((u"0x%x"%attr, chunk))
|
||||
res.append(("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":
|
||||
if __name__ == "__main__x":
|
||||
import pprint
|
||||
pprint=pprint.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"
|
||||
s = "\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"
|
||||
s = "\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"
|
||||
s = "\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m"
|
||||
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"
|
||||
s = "\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m"
|
||||
pprint (write_color(s))
|
||||
pprint (write_color_old(s))
|
||||
|
||||
|
||||
if __name__==u"__main__":
|
||||
if __name__ == "__main__":
|
||||
import console
|
||||
import pprint
|
||||
pprint=pprint.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]:")
|
||||
c = console.Console()
|
||||
c.write_color("dhsjdhs")
|
||||
c.write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:")
|
||||
print
|
||||
pprint (write_color(u"\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
|
||||
pprint (write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
|
||||
|
||||
if __name__==u"__main__x":
|
||||
if __name__ == "__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 = pprint.pprint
|
||||
s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
|
||||
pprint (write_color(s))
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
# 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 Windows console.
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
'''Cursor control and color for the Windows console.
|
||||
|
||||
This was modeled after the C extension of the same name by Fredrik Lundh.
|
||||
'''
|
||||
@@ -22,7 +23,7 @@ import pyreadline.unicode_helper as unicode_helper
|
||||
from pyreadline.logger import log
|
||||
from pyreadline.unicode_helper import ensure_unicode, ensure_str
|
||||
from pyreadline.keysyms import make_KeyPress, KeyPress
|
||||
from pyreadline.console.ansi import AnsiState,AnsiWriter
|
||||
from pyreadline.console.ansi import AnsiState, AnsiWriter
|
||||
|
||||
try:
|
||||
import ctypes.util
|
||||
@@ -30,7 +31,7 @@ try:
|
||||
from _ctypes import call_function
|
||||
from ctypes.wintypes import *
|
||||
except ImportError:
|
||||
raise ImportError(u"You need ctypes to run this code")
|
||||
raise ImportError("You need ctypes to run this code")
|
||||
|
||||
if sys.version_info < (2, 6):
|
||||
bytes = str
|
||||
@@ -173,12 +174,12 @@ def split_block(text, size=1000):
|
||||
|
||||
|
||||
class Console(object):
|
||||
u'''Console driver for Windows.
|
||||
'''Console driver for Windows.
|
||||
|
||||
'''
|
||||
|
||||
def __init__(self, newbuffer=0):
|
||||
u'''Initialize the Console object.
|
||||
'''Initialize the Console object.
|
||||
|
||||
newbuffer=1 will allocate a new buffer so the old content will be restored
|
||||
on exit.
|
||||
@@ -212,20 +213,20 @@ class Console(object):
|
||||
for escape in self.escape_to_color:
|
||||
if self.escape_to_color[escape] is not None:
|
||||
self.escape_to_color[escape] |= background
|
||||
log(u'initial attr=%x' % self.attr)
|
||||
log('initial attr=%x' % self.attr)
|
||||
self.softspace = 0 # this is for using it as a file-like object
|
||||
self.serial = 0
|
||||
|
||||
self.pythondll = \
|
||||
CDLL(u'python%s%s' % (sys.version[0], sys.version[2]))
|
||||
CDLL('python%s%s' % (sys.version[0], sys.version[2]))
|
||||
self.pythondll.PyMem_Malloc.restype = c_size_t
|
||||
self.pythondll.PyMem_Malloc.argtypes = [c_size_t]
|
||||
self.inputHookPtr = \
|
||||
c_void_p.from_address(addressof(self.pythondll.PyOS_InputHook)).value
|
||||
setattr(Console, u'PyMem_Malloc', self.pythondll.PyMem_Malloc)
|
||||
setattr(Console, 'PyMem_Malloc', self.pythondll.PyMem_Malloc)
|
||||
|
||||
def __del__(self):
|
||||
u'''Cleanup the console when finished.'''
|
||||
'''Cleanup the console when finished.'''
|
||||
# I don't think this ever gets called
|
||||
self.SetConsoleTextAttribute(self.hout, self.saveattr)
|
||||
self.SetConsoleMode(self.hin, self.inmode)
|
||||
@@ -240,7 +241,7 @@ class Console(object):
|
||||
return top,bot
|
||||
|
||||
def fixcoord(self, x, y):
|
||||
u'''Return a long with x and y packed inside,
|
||||
'''Return a long with x and y packed inside,
|
||||
also handle negative x and y.'''
|
||||
if x < 0 or y < 0:
|
||||
info = CONSOLE_SCREEN_BUFFER_INFO()
|
||||
@@ -254,7 +255,7 @@ class Console(object):
|
||||
return c_int(y << 16 | x)
|
||||
|
||||
def pos(self, x=None, y=None):
|
||||
u'''Move or query the window cursor.'''
|
||||
'''Move or query the window cursor.'''
|
||||
if x is None:
|
||||
info = CONSOLE_SCREEN_BUFFER_INFO()
|
||||
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
||||
@@ -264,30 +265,30 @@ class Console(object):
|
||||
self.fixcoord(x, y))
|
||||
|
||||
def home(self):
|
||||
u'''Move to home.'''
|
||||
'''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?')
|
||||
escape_to_color = { u'0;30': 0x0, #black
|
||||
u'0;31': 0x4, #red
|
||||
u'0;32': 0x2, #green
|
||||
u'0;33': 0x4+0x2, #brown?
|
||||
u'0;34': 0x1, #blue
|
||||
u'0;35': 0x1+0x4, #purple
|
||||
u'0;36': 0x2+0x4, #cyan
|
||||
u'0;37': 0x1+0x2+0x4, #grey
|
||||
u'1;30': 0x1+0x2+0x4, #dark gray
|
||||
u'1;31': 0x4+0x8, #red
|
||||
u'1;32': 0x2+0x8, #light green
|
||||
u'1;33': 0x4+0x2+0x8, #yellow
|
||||
u'1;34': 0x1+0x8, #light blue
|
||||
u'1;35': 0x1+0x4+0x8, #light purple
|
||||
u'1;36': 0x1+0x2+0x8, #light cyan
|
||||
u'1;37': 0x1+0x2+0x4+0x8, #white
|
||||
u'0': None,
|
||||
terminal_escape = re.compile('(\001?\033\\[[0-9;]+m\002?)')
|
||||
escape_parts = re.compile('\001?\033\\[([0-9;]+)m\002?')
|
||||
escape_to_color = { '0;30': 0x0, #black
|
||||
'0;31': 0x4, #red
|
||||
'0;32': 0x2, #green
|
||||
'0;33': 0x4+0x2, #brown?
|
||||
'0;34': 0x1, #blue
|
||||
'0;35': 0x1+0x4, #purple
|
||||
'0;36': 0x2+0x4, #cyan
|
||||
'0;37': 0x1+0x2+0x4, #grey
|
||||
'1;30': 0x1+0x2+0x4, #dark gray
|
||||
'1;31': 0x4+0x8, #red
|
||||
'1;32': 0x2+0x8, #light green
|
||||
'1;33': 0x4+0x2+0x8, #yellow
|
||||
'1;34': 0x1+0x8, #light blue
|
||||
'1;35': 0x1+0x4+0x8, #light purple
|
||||
'1;36': 0x1+0x2+0x8, #light cyan
|
||||
'1;37': 0x1+0x2+0x4+0x8, #white
|
||||
'0': None,
|
||||
}
|
||||
|
||||
# This pattern should match all characters that change the cursor position differently
|
||||
@@ -295,7 +296,7 @@ class Console(object):
|
||||
motion_char_re = re.compile('([\n\r\t\010\007])'.encode('ascii'))
|
||||
|
||||
def write_scrolling(self, text, attr=None):
|
||||
u'''write text at current cursor position while watching for scrolling.
|
||||
'''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
|
||||
@@ -316,19 +317,19 @@ class Console(object):
|
||||
for chunk in chunks:
|
||||
n = self.write_color(chunk, attr)
|
||||
if len(chunk) == 1: # the funny characters will be alone
|
||||
if chunk[0] == u'\n': # newline
|
||||
if chunk[0] == '\n': # newline
|
||||
x = 0
|
||||
y += 1
|
||||
elif chunk[0] == u'\r': # carriage return
|
||||
elif chunk[0] == '\r': # carriage return
|
||||
x = 0
|
||||
elif chunk[0] == u'\t': # tab
|
||||
elif chunk[0] == '\t': # tab
|
||||
x = 8 * (int(x / 8) + 1)
|
||||
if x > w: # newline
|
||||
x -= w
|
||||
y += 1
|
||||
elif chunk[0] == u'\007': # bell
|
||||
elif chunk[0] == '\007': # bell
|
||||
pass
|
||||
elif chunk[0] == u'\010':
|
||||
elif chunk[0] == '\010':
|
||||
x -= 1
|
||||
if x < 0:
|
||||
y -= 1 # backed up 1 line
|
||||
@@ -355,8 +356,8 @@ class Console(object):
|
||||
n, res= self.ansiwriter.write_color(text, attr)
|
||||
junk = DWORD(0)
|
||||
for attr,chunk in res:
|
||||
log(u"console.attr:%s"%unicode(attr))
|
||||
log(u"console.chunk:%s"%unicode(chunk))
|
||||
log("console.attr:%s"%unicode(attr))
|
||||
log("console.chunk:%s"%unicode(chunk))
|
||||
self.SetConsoleTextAttribute(self.hout, attr.winattr)
|
||||
for short_chunk in split_block(chunk):
|
||||
self.WriteConsoleW(self.hout, short_chunk,
|
||||
@@ -364,9 +365,9 @@ class Console(object):
|
||||
return n
|
||||
|
||||
def write_plain(self, text, attr=None):
|
||||
u'''write text at current cursor position.'''
|
||||
'''write text at current cursor position.'''
|
||||
text = ensure_unicode(text)
|
||||
log(u'write("%s", %s)' %(text, attr))
|
||||
log('write("%s", %s)' %(text, attr))
|
||||
if attr is None:
|
||||
attr = self.attr
|
||||
junk = DWORD(0)
|
||||
@@ -378,7 +379,7 @@ class Console(object):
|
||||
|
||||
#This function must be used to ensure functioning with EMACS
|
||||
#Emacs sets the EMACS environment variable
|
||||
if os.environ.has_key(u"EMACS"):
|
||||
if os.environ.has_key("EMACS"):
|
||||
def write_color(self, text, attr=None):
|
||||
text = ensure_str(text)
|
||||
junk = DWORD(0)
|
||||
@@ -389,7 +390,7 @@ class Console(object):
|
||||
# make this class look like a file object
|
||||
def write(self, text):
|
||||
text = ensure_unicode(text)
|
||||
log(u'write("%s")' % text)
|
||||
log('write("%s")' % text)
|
||||
return self.write_color(text)
|
||||
|
||||
#write = write_scrolling
|
||||
@@ -400,8 +401,8 @@ class Console(object):
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def page(self, attr=None, fill=u' '):
|
||||
u'''Fill the entire screen.'''
|
||||
def page(self, attr=None, fill=' '):
|
||||
'''Fill the entire screen.'''
|
||||
if attr is None:
|
||||
attr = self.attr
|
||||
if len(fill) != 1:
|
||||
@@ -422,7 +423,7 @@ class Console(object):
|
||||
self.attr = attr
|
||||
|
||||
def text(self, x, y, text, attr=None):
|
||||
u'''Write text at the given position.'''
|
||||
'''Write text at the given position.'''
|
||||
if attr is None:
|
||||
attr = self.attr
|
||||
|
||||
@@ -440,8 +441,8 @@ class Console(object):
|
||||
if pos[1] < bot:
|
||||
self.rectangle((0, pos[1] + 1, w, bot + 1))
|
||||
|
||||
def rectangle(self, rect, attr=None, fill=u' '):
|
||||
u'''Fill Rectangle.'''
|
||||
def rectangle(self, rect, attr=None, fill=' '):
|
||||
'''Fill Rectangle.'''
|
||||
x0, y0, x1, y1 = rect
|
||||
n = DWORD(0)
|
||||
if attr is None:
|
||||
@@ -454,7 +455,7 @@ class Console(object):
|
||||
pos, byref(n))
|
||||
|
||||
def scroll(self, rect, dx, dy, attr=None, fill=' '):
|
||||
u'''Scroll a rectangle.'''
|
||||
'''Scroll a rectangle.'''
|
||||
if attr is None:
|
||||
attr = self.attr
|
||||
x0, y0, x1, y1 = rect
|
||||
@@ -468,11 +469,11 @@ class Console(object):
|
||||
byref(source), dest, byref(style))
|
||||
|
||||
def scroll_window(self, lines):
|
||||
u'''Scroll the window by the indicated number of lines.'''
|
||||
'''Scroll the window by the indicated number of lines.'''
|
||||
info = CONSOLE_SCREEN_BUFFER_INFO()
|
||||
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
||||
rect = info.srWindow
|
||||
log(u'sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
|
||||
log('sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
|
||||
top = rect.Top + lines
|
||||
bot = rect.Bottom + lines
|
||||
h = bot - top
|
||||
@@ -489,12 +490,12 @@ class Console(object):
|
||||
nrect.Bottom = bot
|
||||
nrect.Left = rect.Left
|
||||
nrect.Right = rect.Right
|
||||
log(u'sn: top=%d bot=%d' % (top, bot))
|
||||
log('sn: top=%d bot=%d' % (top, bot))
|
||||
r=self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
|
||||
log(u'r=%d' % r)
|
||||
log('r=%d' % r)
|
||||
|
||||
def get(self):
|
||||
u'''Get next event from queue.'''
|
||||
'''Get next event from queue.'''
|
||||
inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
|
||||
|
||||
Cevent = INPUT_RECORD()
|
||||
@@ -509,25 +510,25 @@ class Console(object):
|
||||
return e
|
||||
|
||||
def getkeypress(self):
|
||||
u'''Return next key press event from the queue, ignoring others.'''
|
||||
'''Return next key press event from the queue, ignoring others.'''
|
||||
while 1:
|
||||
e = self.get()
|
||||
if e.type == u'KeyPress' and e.keycode not in key_modifiers:
|
||||
log(u"console.getkeypress %s"%e)
|
||||
if e.keyinfo.keyname == u'next':
|
||||
if e.type == 'KeyPress' and e.keycode not in key_modifiers:
|
||||
log("console.getkeypress %s"%e)
|
||||
if e.keyinfo.keyname == 'next':
|
||||
self.scroll_window(12)
|
||||
elif e.keyinfo.keyname == u'prior':
|
||||
elif e.keyinfo.keyname == 'prior':
|
||||
self.scroll_window(-12)
|
||||
else:
|
||||
return e
|
||||
elif ((e.type == u'KeyRelease') and
|
||||
elif ((e.type == 'KeyRelease') and
|
||||
(e.keyinfo == KeyPress('S', False, True, False, 'S'))):
|
||||
log(u"getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type))
|
||||
log("getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type))
|
||||
return e
|
||||
|
||||
|
||||
def getchar(self):
|
||||
u'''Get next character from queue.'''
|
||||
'''Get next character from queue.'''
|
||||
|
||||
Cevent = INPUT_RECORD()
|
||||
count = DWORD(0)
|
||||
@@ -544,7 +545,7 @@ class Console(object):
|
||||
return sym
|
||||
|
||||
def peek(self):
|
||||
u'''Check event queue.'''
|
||||
'''Check event queue.'''
|
||||
Cevent = INPUT_RECORD()
|
||||
count = DWORD(0)
|
||||
status = self.PeekConsoleInputW(self.hin,
|
||||
@@ -553,7 +554,7 @@ class Console(object):
|
||||
return event(self, Cevent)
|
||||
|
||||
def title(self, txt=None):
|
||||
u'''Set/get title.'''
|
||||
'''Set/get title.'''
|
||||
if txt:
|
||||
self.SetConsoleTitleW(txt)
|
||||
else:
|
||||
@@ -563,7 +564,7 @@ class Console(object):
|
||||
return buffer.value[:n]
|
||||
|
||||
def size(self, width=None, height=None):
|
||||
u'''Set/get window size.'''
|
||||
'''Set/get window size.'''
|
||||
info = CONSOLE_SCREEN_BUFFER_INFO()
|
||||
status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
||||
if not status:
|
||||
@@ -581,7 +582,7 @@ class Console(object):
|
||||
return (info.dwSize.X, info.dwSize.Y)
|
||||
|
||||
def cursor(self, visible=None, size=None):
|
||||
u'''Set cursor on or off.'''
|
||||
'''Set cursor on or off.'''
|
||||
info = CONSOLE_CURSOR_INFO()
|
||||
if self.GetConsoleCursorInfo(self.hout, byref(info)):
|
||||
if visible is not None:
|
||||
@@ -591,10 +592,10 @@ class Console(object):
|
||||
self.SetConsoleCursorInfo(self.hout, byref(info))
|
||||
|
||||
def bell(self):
|
||||
self.write(u'\007')
|
||||
self.write('\007')
|
||||
|
||||
def next_serial(self):
|
||||
u'''Get next event serial number.'''
|
||||
'''Get next event serial number.'''
|
||||
self.serial += 1
|
||||
return self.serial
|
||||
|
||||
@@ -673,32 +674,32 @@ Console.WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, c_void_p] #HANDLE
|
||||
|
||||
|
||||
|
||||
from event import Event
|
||||
from .event import Event
|
||||
|
||||
VkKeyScan = windll.user32.VkKeyScanA
|
||||
|
||||
|
||||
class event(Event):
|
||||
u'''Represent events from the console.'''
|
||||
'''Represent events from the console.'''
|
||||
def __init__(self, console, input):
|
||||
'''Initialize an event from the Windows input structure.'''
|
||||
self.type = u'??'
|
||||
self.type = '??'
|
||||
self.serial = console.next_serial()
|
||||
self.width = 0
|
||||
self.height = 0
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.char = u''
|
||||
self.char = ''
|
||||
self.keycode = 0
|
||||
self.keysym = u'??'
|
||||
self.keysym = '??'
|
||||
self.keyinfo = None # a tuple with (control, meta, shift, keycode) for dispatch
|
||||
self.width = None
|
||||
|
||||
if input.EventType == KEY_EVENT:
|
||||
if input.Event.KeyEvent.bKeyDown:
|
||||
self.type = u"KeyPress"
|
||||
self.type = "KeyPress"
|
||||
else:
|
||||
self.type = u"KeyRelease"
|
||||
self.type = "KeyRelease"
|
||||
self.char = input.Event.KeyEvent.uChar.UnicodeChar
|
||||
self.keycode = input.Event.KeyEvent.wVirtualKeyCode
|
||||
self.state = input.Event.KeyEvent.dwControlKeyState
|
||||
@@ -706,23 +707,23 @@ class event(Event):
|
||||
|
||||
elif input.EventType == MOUSE_EVENT:
|
||||
if input.Event.MouseEvent.dwEventFlags & MOUSE_MOVED:
|
||||
self.type = u"Motion"
|
||||
self.type = "Motion"
|
||||
else:
|
||||
self.type = u"Button"
|
||||
self.type = "Button"
|
||||
self.x = input.Event.MouseEvent.dwMousePosition.X
|
||||
self.y = input.Event.MouseEvent.dwMousePosition.Y
|
||||
self.state = input.Event.MouseEvent.dwButtonState
|
||||
elif input.EventType == WINDOW_BUFFER_SIZE_EVENT:
|
||||
self.type = u"Configure"
|
||||
self.type = "Configure"
|
||||
self.width = input.Event.WindowBufferSizeEvent.dwSize.X
|
||||
self.height = input.Event.WindowBufferSizeEvent.dwSize.Y
|
||||
elif input.EventType == FOCUS_EVENT:
|
||||
if input.Event.FocusEvent.bSetFocus:
|
||||
self.type = u"FocusIn"
|
||||
self.type = "FocusIn"
|
||||
else:
|
||||
self.type = u"FocusOut"
|
||||
self.type = "FocusOut"
|
||||
elif input.EventType == MENU_EVENT:
|
||||
self.type = u"Menu"
|
||||
self.type = "Menu"
|
||||
self.state = input.Event.MenuEvent.dwCommandId
|
||||
|
||||
|
||||
@@ -760,23 +761,23 @@ readline_hook = None # the python hook goes here
|
||||
readline_ref = None # reference to the c-callable to keep it alive
|
||||
|
||||
def hook_wrapper_23(stdin, stdout, prompt):
|
||||
u'''Wrap a Python readline so it behaves like GNU readline.'''
|
||||
'''Wrap a Python readline so it behaves like GNU readline.'''
|
||||
try:
|
||||
# call the Python hook
|
||||
res = ensure_str(readline_hook(prompt))
|
||||
# make sure it returned the right sort of thing
|
||||
if res and not isinstance(res, bytes):
|
||||
raise TypeError, u'readline must return a string.'
|
||||
raise TypeError, 'readline must return a string.'
|
||||
except KeyboardInterrupt:
|
||||
# GNU readline returns 0 on keyboard interrupt
|
||||
return 0
|
||||
except EOFError:
|
||||
# It returns an empty string on EOF
|
||||
res = u''
|
||||
res = ''
|
||||
except:
|
||||
print >>sys.stderr, u'Readline internal error'
|
||||
print('Readline internal error', file=sys.stderr)
|
||||
traceback.print_exc()
|
||||
res = u'\n'
|
||||
res = '\n'
|
||||
# we have to make a copy because the caller expects to free the result
|
||||
n = len(res)
|
||||
p = Console.PyMem_Malloc(n + 1)
|
||||
@@ -784,23 +785,23 @@ def hook_wrapper_23(stdin, stdout, prompt):
|
||||
return p
|
||||
|
||||
def hook_wrapper(prompt):
|
||||
u'''Wrap a Python readline so it behaves like GNU readline.'''
|
||||
'''Wrap a Python readline so it behaves like GNU readline.'''
|
||||
try:
|
||||
# call the Python hook
|
||||
res = ensure_str(readline_hook(prompt))
|
||||
# make sure it returned the right sort of thing
|
||||
if res and not isinstance(res, bytes):
|
||||
raise TypeError, u'readline must return a string.'
|
||||
raise TypeError, 'readline must return a string.'
|
||||
except KeyboardInterrupt:
|
||||
# GNU readline returns 0 on keyboard interrupt
|
||||
return 0
|
||||
except EOFError:
|
||||
# It returns an empty string on EOF
|
||||
res = u''
|
||||
res = ''
|
||||
except:
|
||||
print >>sys.stderr, u'Readline internal error'
|
||||
print('Readline internal error', file=sys.stderr)
|
||||
traceback.print_exc()
|
||||
res = u'\n'
|
||||
res = '\n'
|
||||
# we have to make a copy because the caller expects to free the result
|
||||
p = _strdup(res)
|
||||
return p
|
||||
@@ -835,11 +836,11 @@ if __name__ == '__main__':
|
||||
sys.stdout = c
|
||||
sys.stderr = c
|
||||
c.page()
|
||||
print p("d"), p("D")
|
||||
print(p("d"), p("D"))
|
||||
c.pos(5, 10)
|
||||
c.write('hi there')
|
||||
print 'some printed output'
|
||||
print('some printed output')
|
||||
for i in range(10):
|
||||
q = c.getkeypress()
|
||||
print q
|
||||
print(q)
|
||||
del c
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
FOREGROUND_BLUE = 0x0001
|
||||
FOREGROUND_GREEN = 0x0002
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
class baseconsole:
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
class baseconsole(object):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@@ -6,18 +8,18 @@ class baseconsole:
|
||||
raise NotImplementedError
|
||||
|
||||
def pos(self, x=None, y=None):
|
||||
u'''Move or query the window cursor.'''
|
||||
'''Move or query the window cursor.'''
|
||||
raise NotImplementedError
|
||||
|
||||
def size(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def rectangle(self, rect, attr=None, fill=u' '):
|
||||
u'''Fill Rectangle.'''
|
||||
def rectangle(self, rect, attr=None, fill=' '):
|
||||
'''Fill Rectangle.'''
|
||||
raise NotImplementedError
|
||||
|
||||
def write_scrolling(self, text, attr=None):
|
||||
u'''write text at current cursor position while watching for scrolling.
|
||||
'''write text at current cursor position while watching for scrolling.
|
||||
|
||||
If the window scrolls because you are at the bottom of the screen
|
||||
buffer, all positions that you are storing will be shifted by the
|
||||
@@ -33,14 +35,14 @@ class baseconsole:
|
||||
raise NotImplementedError
|
||||
|
||||
def getkeypress(self):
|
||||
u'''Return next key press event from the queue, ignoring others.'''
|
||||
'''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.'''
|
||||
'''Fill the entire screen.'''
|
||||
raise NotImplementedError
|
||||
|
||||
def isatty(self):
|
||||
|
||||
+14
-14
@@ -1,27 +1,27 @@
|
||||
class Event(object):
|
||||
u'''Represent events from the console.'''
|
||||
'''Represent events from the console.'''
|
||||
def __init__(self, console, input):
|
||||
pass
|
||||
|
||||
def __repr__(self):
|
||||
u'''Display an event for debugging.'''
|
||||
if self.type in [u'KeyPress', u'KeyRelease']:
|
||||
'''Display an event for debugging.'''
|
||||
if self.type in ['KeyPress', 'KeyRelease']:
|
||||
chr = self.char
|
||||
if ord(chr)<ord(u"A"):
|
||||
chr = u"?"
|
||||
s = u"%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % \
|
||||
if ord(chr) < ord("A"):
|
||||
chr = "?"
|
||||
s = "%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % \
|
||||
(self.type, chr, ord(self.char), self.keysym, self.keycode, self.keycode,
|
||||
self.state, self.keyinfo)
|
||||
elif self.type in [u'Motion', u'Button']:
|
||||
s = u'%s x=%d y=%d state=%x' % (self.type, self.x, self.y, self.state)
|
||||
elif self.type == u'Configure':
|
||||
s = u'%s w=%d h=%d' % (self.type, self.width, self.height)
|
||||
elif self.type in [u'FocusIn', u'FocusOut']:
|
||||
elif self.type in ['Motion', 'Button']:
|
||||
s = '%s x=%d y=%d state=%x' % (self.type, self.x, self.y, self.state)
|
||||
elif self.type == 'Configure':
|
||||
s = '%s w=%d h=%d' % (self.type, self.width, self.height)
|
||||
elif self.type in ['FocusIn', 'FocusOut']:
|
||||
s = self.type
|
||||
elif self.type == u'Menu':
|
||||
s = u'%s state=%x' % (self.type, self.state)
|
||||
elif self.type == 'Menu':
|
||||
s = '%s state=%x' % (self.type, self.state)
|
||||
else:
|
||||
s = u'unknown event type'
|
||||
s = 'unknown event type'
|
||||
return s
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
# 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.
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
'''Cursor control and color for the .NET console.
|
||||
'''
|
||||
|
||||
#
|
||||
@@ -42,40 +44,40 @@ from pyreadline.keysyms import \
|
||||
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
|
||||
ansicolor={"0;30": color.Black,
|
||||
"0;31": color.DarkRed,
|
||||
"0;32": color.DarkGreen,
|
||||
"0;33": color.DarkYellow,
|
||||
"0;34": color.DarkBlue,
|
||||
"0;35": color.DarkMagenta,
|
||||
"0;36": color.DarkCyan,
|
||||
"0;37": color.DarkGray,
|
||||
"1;30": color.Gray,
|
||||
"1;31": color.Red,
|
||||
"1;32": color.Green,
|
||||
"1;33": color.Yellow,
|
||||
"1;34": color.Blue,
|
||||
"1;35": color.Magenta,
|
||||
"1;36": color.Cyan,
|
||||
"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}
|
||||
winattr = {"black" : 0, "darkgray" : 0+8,
|
||||
"darkred" : 4, "red" : 4+8,
|
||||
"darkgreen" : 2, "green" : 2+8,
|
||||
"darkyellow" : 6, "yellow" : 6+8,
|
||||
"darkblue" : 1, "blue" : 1+8,
|
||||
"darkmagenta" : 5, "magenta" : 5+8,
|
||||
"darkcyan" : 3, "cyan" : 3+8,
|
||||
"gray" : 7, "white" : 7+8}
|
||||
|
||||
class Console(object):
|
||||
u'''Console driver for Windows.
|
||||
'''Console driver for Windows.
|
||||
|
||||
'''
|
||||
|
||||
def __init__(self, newbuffer=0):
|
||||
u'''Initialize the Console object.
|
||||
'''Initialize the Console object.
|
||||
|
||||
newbuffer=1 will allocate a new buffer so the old content will be restored
|
||||
on exit.
|
||||
@@ -84,27 +86,27 @@ class Console(object):
|
||||
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)
|
||||
log('initial attr=%s' % self.attr)
|
||||
|
||||
def _get(self):
|
||||
top = System.Console.WindowTop
|
||||
log(u"WindowTop:%s"%top)
|
||||
log("WindowTop:%s"%top)
|
||||
return top
|
||||
|
||||
def _set(self, value):
|
||||
top = System.Console.WindowTop
|
||||
log(u"Set WindowTop:old:%s,new:%s"%(top, value))
|
||||
log("Set WindowTop:old:%s,new:%s"%(top, value))
|
||||
|
||||
WindowTop = property(_get, _set)
|
||||
del _get, _set
|
||||
|
||||
def __del__(self):
|
||||
u'''Cleanup the console when finished.'''
|
||||
'''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.'''
|
||||
'''Move or query the window cursor.'''
|
||||
if x is not None:
|
||||
System.Console.CursorLeft=x
|
||||
else:
|
||||
@@ -116,20 +118,20 @@ class Console(object):
|
||||
return x, y
|
||||
|
||||
def home(self):
|
||||
u'''Move to home.'''
|
||||
'''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?')
|
||||
terminal_escape = re.compile('(\001?\033\\[[0-9;]*m\002?)')
|
||||
escape_parts = re.compile('\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])')
|
||||
motion_char_re = re.compile('([\n\r\t\010\007])')
|
||||
|
||||
def write_scrolling(self, text, attr=None):
|
||||
u'''write text at current cursor position while watching for scrolling.
|
||||
'''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
|
||||
@@ -151,19 +153,19 @@ class Console(object):
|
||||
for chunk in chunks:
|
||||
n = self.write_color(chunk, attr)
|
||||
if len(chunk) == 1: # the funny characters will be alone
|
||||
if chunk[0] == u'\n': # newline
|
||||
if chunk[0] == '\n': # newline
|
||||
x = 0
|
||||
y += 1
|
||||
elif chunk[0] == u'\r': # carriage return
|
||||
elif chunk[0] == '\r': # carriage return
|
||||
x = 0
|
||||
elif chunk[0] == u'\t': # tab
|
||||
elif chunk[0] == '\t': # tab
|
||||
x = 8 * (int(x / 8) + 1)
|
||||
if x > w: # newline
|
||||
x -= w
|
||||
y += 1
|
||||
elif chunk[0] == u'\007': # bell
|
||||
elif chunk[0] == '\007': # bell
|
||||
pass
|
||||
elif chunk[0] == u'\010':
|
||||
elif chunk[0] == '\010':
|
||||
x -= 1
|
||||
if x < 0:
|
||||
y -= 1 # backed up 1 line
|
||||
@@ -197,9 +199,9 @@ class Console(object):
|
||||
|
||||
return the number of characters written.
|
||||
'''
|
||||
log(u'write_color("%s", %s)' % (text, attr))
|
||||
log('write_color("%s", %s)' % (text, attr))
|
||||
chunks = self.terminal_escape.split(text)
|
||||
log(u'chunks=%s' % repr(chunks))
|
||||
log('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
|
||||
@@ -222,8 +224,8 @@ class Console(object):
|
||||
return n
|
||||
|
||||
def write_plain(self, text, attr=None):
|
||||
u'''write text at current cursor position.'''
|
||||
log(u'write("%s", %s)' %(text, attr))
|
||||
'''write text at current cursor position.'''
|
||||
log('write("%s", %s)' %(text, attr))
|
||||
if attr is None:
|
||||
attr = self.attr
|
||||
n = c_int(0)
|
||||
@@ -231,7 +233,7 @@ class Console(object):
|
||||
self.WriteConsoleA(self.hout, text, len(text), byref(n), None)
|
||||
return len(text)
|
||||
|
||||
if os.environ.has_key(u"EMACS"):
|
||||
if os.environ.has_key("EMACS"):
|
||||
def write_color(self, text, attr=None):
|
||||
junk = c_int(0)
|
||||
self.WriteFile(self.hout, text, len(text), byref(junk), None)
|
||||
@@ -240,7 +242,7 @@ class Console(object):
|
||||
|
||||
# make this class look like a file object
|
||||
def write(self, text):
|
||||
log(u'write("%s")' % text)
|
||||
log('write("%s")' % text)
|
||||
return self.write_color(text)
|
||||
|
||||
#write = write_scrolling
|
||||
@@ -251,12 +253,12 @@ class Console(object):
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def page(self, attr=None, fill=u' '):
|
||||
u'''Fill the entire screen.'''
|
||||
def page(self, attr=None, fill=' '):
|
||||
'''Fill the entire screen.'''
|
||||
System.Console.Clear()
|
||||
|
||||
def text(self, x, y, text, attr=None):
|
||||
u'''Write text at the given position.'''
|
||||
'''Write text at the given position.'''
|
||||
self.pos(x, y)
|
||||
self.write_color(text, attr)
|
||||
|
||||
@@ -266,12 +268,12 @@ class Console(object):
|
||||
pos = self.pos()
|
||||
w, h = self.size()
|
||||
length = w - pos[0] + min((lastline - pos[1] - 1), 5) * w - 1
|
||||
self.write_color(length * u" ")
|
||||
self.write_color(length * " ")
|
||||
self.pos(*pos)
|
||||
self.WindowTop = oldtop
|
||||
|
||||
def rectangle(self, rect, attr=None, fill=u' '):
|
||||
u'''Fill Rectangle.'''
|
||||
def rectangle(self, rect, attr=None, fill=' '):
|
||||
'''Fill Rectangle.'''
|
||||
oldtop = self.WindowTop
|
||||
oldpos = self.pos()
|
||||
#raise NotImplementedError
|
||||
@@ -281,18 +283,18 @@ class Console(object):
|
||||
if fill:
|
||||
rowfill = fill[:1] * abs(x1 - x0)
|
||||
else:
|
||||
rowfill = u' ' * abs(x1 - x0)
|
||||
rowfill = ' ' * 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.'''
|
||||
'''Scroll a rectangle.'''
|
||||
raise NotImplementedError
|
||||
|
||||
def scroll_window(self, lines):
|
||||
u'''Scroll the window by the indicated number of lines.'''
|
||||
'''Scroll the window by the indicated number of lines.'''
|
||||
top = self.WindowTop + lines
|
||||
if top < 0:
|
||||
top = 0
|
||||
@@ -301,7 +303,7 @@ class Console(object):
|
||||
self.WindowTop = top
|
||||
|
||||
def getkeypress(self):
|
||||
u'''Return next key press event from the queue, ignoring others.'''
|
||||
'''Return next key press event from the queue, ignoring others.'''
|
||||
ck = System.ConsoleKey
|
||||
while 1:
|
||||
e = System.Console.ReadKey(True)
|
||||
@@ -309,21 +311,21 @@ class Console(object):
|
||||
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)
|
||||
elif str(e.KeyChar) == "\000":#Drop deadkeys
|
||||
log("Deadkey: %s"%e)
|
||||
return event(self, e)
|
||||
else:
|
||||
return event(self, e)
|
||||
|
||||
def title(self, txt=None):
|
||||
u'''Set/get title.'''
|
||||
'''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.'''
|
||||
'''Set/get window size.'''
|
||||
sc = System.Console
|
||||
if width is not None and height is not None:
|
||||
sc.BufferWidth, sc.BufferHeight = width,height
|
||||
@@ -336,22 +338,22 @@ class Console(object):
|
||||
return sc.WindowWidth - 1, sc.WindowHeight - 1
|
||||
|
||||
def cursor(self, visible=True, size=None):
|
||||
u'''Set cursor on or off.'''
|
||||
'''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.'''
|
||||
'''Get next event serial number.'''
|
||||
self.serial += 1
|
||||
return self.serial
|
||||
|
||||
class event(Event):
|
||||
u'''Represent events from the console.'''
|
||||
'''Represent events from the console.'''
|
||||
def __init__(self, console, input):
|
||||
u'''Initialize an event from the Windows input structure.'''
|
||||
self.type = u'??'
|
||||
'''Initialize an event from the Windows input structure.'''
|
||||
self.type = '??'
|
||||
self.serial = console.next_serial()
|
||||
self.width = 0
|
||||
self.height = 0
|
||||
@@ -360,7 +362,7 @@ class event(Event):
|
||||
self.char = str(input.KeyChar)
|
||||
self.keycode = input.Key
|
||||
self.state = input.Modifiers
|
||||
log(u"%s,%s,%s"%(input.Modifiers, input.Key, input.KeyChar))
|
||||
log("%s,%s,%s"%(input.Modifiers, input.Key, input.KeyChar))
|
||||
self.type = "KeyRelease"
|
||||
self.keysym = make_keysym(self.keycode)
|
||||
self.keyinfo = make_KeyPress(self.char, self.state, self.keycode)
|
||||
@@ -368,7 +370,7 @@ class event(Event):
|
||||
def make_event_from_keydescr(keydescr):
|
||||
def input():
|
||||
return 1
|
||||
input.KeyChar = u"a"
|
||||
input.KeyChar = "a"
|
||||
input.Key = System.ConsoleKey.A
|
||||
input.Modifiers = System.ConsoleModifiers.Shift
|
||||
input.next_serial = input
|
||||
@@ -378,17 +380,17 @@ def make_event_from_keydescr(keydescr):
|
||||
e.keyinfo = keyinfo
|
||||
return e
|
||||
|
||||
CTRL_C_EVENT=make_event_from_keydescr(u"Control-c")
|
||||
CTRL_C_EVENT=make_event_from_keydescr("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""
|
||||
res = ""
|
||||
except EOFError:
|
||||
return None
|
||||
if res[-1:] == u"\n":
|
||||
if res[-1:] == "\n":
|
||||
return res[:-1]
|
||||
else:
|
||||
return res
|
||||
@@ -403,22 +405,22 @@ def install_readline(hook):
|
||||
|
||||
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__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.write('hi there')
|
||||
c.title("Testing console")
|
||||
# c.bell()
|
||||
print
|
||||
print u"size", c.size()
|
||||
print u' some printed output'
|
||||
print()
|
||||
print("size", c.size())
|
||||
print(' some printed output')
|
||||
for i in range(10):
|
||||
e = c.getkeypress()
|
||||
print e.Key, chr(e.KeyChar), ord(e.KeyChar), e.Modifiers
|
||||
print(e.Key, chr(e.KeyChar), ord(e.KeyChar), e.Modifiers)
|
||||
del c
|
||||
|
||||
System.Console.Clear()
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
|
||||
class ReadlineError(Exception):
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
u'''
|
||||
'''
|
||||
Example script using the callback interface of readline.
|
||||
|
||||
:author: strank
|
||||
'''
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
__docformat__ = u"restructuredtext en"
|
||||
__docformat__ = "restructuredtext en"
|
||||
|
||||
import sys
|
||||
import os
|
||||
@@ -13,7 +14,8 @@ import time
|
||||
import readline
|
||||
|
||||
import msvcrt
|
||||
from pyreadline.rlmain import rl
|
||||
from readline import rl
|
||||
import readline
|
||||
|
||||
prompting = True
|
||||
count = 0
|
||||
@@ -21,33 +23,33 @@ maxlines = 10
|
||||
|
||||
|
||||
def main():
|
||||
readline.callback_handler_install(u'Starting test, please do type:' + os.linesep, lineReceived)
|
||||
readline.callback_handler_install('Starting test, please do type:' + os.linesep, lineReceived)
|
||||
index = 0
|
||||
start = int(time.time())
|
||||
while prompting:
|
||||
# demonstrate that async stuff is possible:
|
||||
if start + index < time.time():
|
||||
rl.console.title(u"NON-BLOCKING: %d" % index)
|
||||
rl.console.title("NON-BLOCKING: %d" % index)
|
||||
index += 1
|
||||
# ugly busy waiting/polling on windows, using 'select' on Unix: (or use twisted)
|
||||
if msvcrt.kbhit():
|
||||
readline.callback_read_char()
|
||||
print u"Done, index =", index
|
||||
print("Done, index =", index)
|
||||
|
||||
|
||||
def lineReceived(line):
|
||||
global count, prompting
|
||||
count += 1
|
||||
print u"Got line: %s" % line
|
||||
print("Got line: %s" % line)
|
||||
if count > maxlines:
|
||||
prompting = False
|
||||
readline.callback_handler_remove()
|
||||
else:
|
||||
readline.callback_handler_install(u'Got %s of %s, more typing please:' % (count, maxlines)
|
||||
readline.callback_handler_install('Got %s of %s, more typing please:' % (count, maxlines)
|
||||
+ os.linesep, lineReceived)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
|
||||
"""
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
from pyreadline.rlmain import BaseReadline
|
||||
from pyreadline.keysyms.common import KeyPress
|
||||
import pyreadline.logger as log
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import sys,textwrap
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import sys, textwrap
|
||||
|
||||
rlmain = sys.modules[u"pyreadline.rlmain"]
|
||||
rlmain = sys.modules["pyreadline.rlmain"]
|
||||
rl = rlmain.rl
|
||||
|
||||
def get_doc(rl):
|
||||
@@ -13,6 +14,6 @@ def get_rest(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"")
|
||||
out.append("\n".join(textwrap.wrap(doc, 80, initial_indent=" ")))
|
||||
out.append("")
|
||||
return out
|
||||
@@ -1,7 +1,10 @@
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import sys
|
||||
|
||||
success = False
|
||||
in_ironpython = u"IronPython" in sys.version
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
from . import winconstants
|
||||
|
||||
if in_ironpython:
|
||||
try:
|
||||
@@ -11,10 +14,10 @@ if in_ironpython:
|
||||
raise
|
||||
else:
|
||||
try:
|
||||
from keysyms import *
|
||||
from .keysyms import *
|
||||
success = True
|
||||
except ImportError, x:
|
||||
pass
|
||||
|
||||
if not success:
|
||||
raise ImportError(u"Could not import keysym for local pythonversion", x)
|
||||
raise ImportError("Could not import keysym for local pythonversion", x)
|
||||
@@ -7,6 +7,7 @@
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
# table for translating virtual keys to X windows key symbols
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
try:
|
||||
set
|
||||
@@ -15,31 +16,31 @@ except NameError:
|
||||
|
||||
from pyreadline.unicode_helper import ensure_unicode
|
||||
|
||||
validkey =set([u'cancel', u'backspace', u'tab', u'clear',
|
||||
u'return', u'shift_l', u'control_l', u'alt_l',
|
||||
u'pause', u'caps_lock', u'escape', u'space',
|
||||
u'prior', u'next', u'end', u'home',
|
||||
u'left', u'up', u'right', u'down',
|
||||
u'select', u'print', u'execute', u'snapshot',
|
||||
u'insert', u'delete', u'help', u'f1',
|
||||
u'f2', u'f3', u'f4', u'f5',
|
||||
u'f6', u'f7', u'f8', u'f9',
|
||||
u'f10', u'f11', u'f12', u'f13',
|
||||
u'f14', u'f15', u'f16', u'f17',
|
||||
u'f18', u'f19', u'f20', u'f21',
|
||||
u'f22', u'f23', u'f24', u'num_lock',
|
||||
u'scroll_lock', u'vk_apps', u'vk_processkey',u'vk_attn',
|
||||
u'vk_crsel', u'vk_exsel', u'vk_ereof', u'vk_play',
|
||||
u'vk_zoom', u'vk_noname', u'vk_pa1', u'vk_oem_clear',
|
||||
u'numpad0', u'numpad1', u'numpad2', u'numpad3',
|
||||
u'numpad4', u'numpad5', u'numpad6', u'numpad7',
|
||||
u'numpad8', u'numpad9', u'divide', u'multiply',
|
||||
u'add', u'subtract', u'vk_decimal'])
|
||||
validkey =set(['cancel', 'backspace', 'tab', 'clear',
|
||||
'return', 'shift_l', 'control_l', 'alt_l',
|
||||
'pause', 'caps_lock', 'escape', 'space',
|
||||
'prior', 'next', 'end', 'home',
|
||||
'left', 'up', 'right', 'down',
|
||||
'select', 'print', 'execute', 'snapshot',
|
||||
'insert', 'delete', 'help', 'f1',
|
||||
'f2', 'f3', 'f4', 'f5',
|
||||
'f6', 'f7', 'f8', 'f9',
|
||||
'f10', 'f11', 'f12', 'f13',
|
||||
'f14', 'f15', 'f16', 'f17',
|
||||
'f18', 'f19', 'f20', 'f21',
|
||||
'f22', 'f23', 'f24', 'num_lock',
|
||||
'scroll_lock', 'vk_apps', 'vk_processkey','vk_attn',
|
||||
'vk_crsel', 'vk_exsel', 'vk_ereof', 'vk_play',
|
||||
'vk_zoom', 'vk_noname', 'vk_pa1', 'vk_oem_clear',
|
||||
'numpad0', 'numpad1', 'numpad2', 'numpad3',
|
||||
'numpad4', 'numpad5', 'numpad6', 'numpad7',
|
||||
'numpad8', 'numpad9', 'divide', 'multiply',
|
||||
'add', 'subtract', 'vk_decimal'])
|
||||
|
||||
escape_sequence_to_special_key = {u"\\e[a" : u"up", u"\\e[b" : u"down", u"del" : u"delete"}
|
||||
escape_sequence_to_special_key = {"\\e[a" : "up", "\\e[b" : "down", "del" : "delete"}
|
||||
|
||||
class KeyPress(object):
|
||||
def __init__(self, char=u"", shift=False, control=False, meta=False, keyname=u""):
|
||||
def __init__(self, char="", shift=False, control=False, meta=False, keyname=""):
|
||||
if control or meta or shift:
|
||||
char = char.upper()
|
||||
self.info = dict(char=char,
|
||||
@@ -55,14 +56,14 @@ class KeyPress(object):
|
||||
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")
|
||||
char = create("char")
|
||||
shift = create("shift")
|
||||
control = create("control")
|
||||
meta = create("meta")
|
||||
keyname = create("keyname")
|
||||
|
||||
def __repr__(self):
|
||||
return u"(%s,%s,%s,%s)"%tuple(map(ensure_unicode, self.tuple()))
|
||||
return "(%s,%s,%s,%s)"%tuple(map(ensure_unicode, self.tuple()))
|
||||
|
||||
def tuple(self):
|
||||
if self.keyname:
|
||||
@@ -83,32 +84,32 @@ class KeyPress(object):
|
||||
|
||||
def make_KeyPress_from_keydescr(keydescr):
|
||||
keyinfo = KeyPress()
|
||||
if len(keydescr) > 2 and keydescr[:1] == u'"' and keydescr[-1:] == u'"':
|
||||
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
|
||||
keydescr = keydescr[1:-1]
|
||||
|
||||
while 1:
|
||||
lkeyname = keydescr.lower()
|
||||
if lkeyname.startswith(u'control-'):
|
||||
if lkeyname.startswith('control-'):
|
||||
keyinfo.control = True
|
||||
keydescr = keydescr[8:]
|
||||
elif lkeyname.startswith(u'ctrl-'):
|
||||
elif lkeyname.startswith('ctrl-'):
|
||||
keyinfo.control = True
|
||||
keydescr = keydescr[5:]
|
||||
elif keydescr.lower().startswith(u'\\c-'):
|
||||
elif keydescr.lower().startswith('\\c-'):
|
||||
keyinfo.control = True
|
||||
keydescr = keydescr[3:]
|
||||
elif keydescr.lower().startswith(u'\\m-'):
|
||||
elif keydescr.lower().startswith('\\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-'):
|
||||
elif lkeyname.startswith('meta-'):
|
||||
keyinfo.meta = True
|
||||
keydescr = keydescr[5:]
|
||||
elif lkeyname.startswith(u'alt-'):
|
||||
elif lkeyname.startswith('alt-'):
|
||||
keyinfo.meta = True
|
||||
keydescr = keydescr[4:]
|
||||
elif lkeyname.startswith(u'shift-'):
|
||||
elif lkeyname.startswith('shift-'):
|
||||
keyinfo.shift = True
|
||||
keydescr = keydescr[6:]
|
||||
else:
|
||||
@@ -117,11 +118,11 @@ def make_KeyPress_from_keydescr(keydescr):
|
||||
keyinfo.keyname = keydescr.strip().lower()
|
||||
keyinfo.char = ""
|
||||
else:
|
||||
raise IndexError(u"Not a valid key: '%s'"%keydescr)
|
||||
raise IndexError("Not a valid key: '%s'"%keydescr)
|
||||
else:
|
||||
keyinfo.char = keydescr
|
||||
return keyinfo
|
||||
|
||||
if __name__ == u"__main__":
|
||||
if __name__ == "__main__":
|
||||
import startup
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import System
|
||||
from common import validkey, KeyPress, make_KeyPress_from_keydescr
|
||||
|
||||
@@ -14,85 +15,85 @@ Shift = System.ConsoleModifiers.Shift
|
||||
Control = System.ConsoleModifiers.Control
|
||||
Alt = System.ConsoleModifiers.Alt
|
||||
# table for translating virtual keys to X windows key symbols
|
||||
code2sym_map = {#c32.CANCEL: 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'
|
||||
code2sym_map = {#c32.CANCEL: 'Cancel',
|
||||
c32.Backspace: 'BackSpace',
|
||||
c32.Tab: 'Tab',
|
||||
c32.Clear: 'Clear',
|
||||
c32.Enter: 'Return',
|
||||
# c32.Shift: 'Shift_L',
|
||||
# c32.Control: 'Control_L',
|
||||
# c32.Menu: 'Alt_L',
|
||||
c32.Pause: 'Pause',
|
||||
# c32.Capital: 'Caps_Lock',
|
||||
c32.Escape: 'Escape',
|
||||
# c32.Space: 'space',
|
||||
c32.PageUp: 'Prior',
|
||||
c32.PageDown: 'Next',
|
||||
c32.End: 'End',
|
||||
c32.Home: 'Home',
|
||||
c32.LeftArrow: 'Left',
|
||||
c32.UpArrow: 'Up',
|
||||
c32.RightArrow: 'Right',
|
||||
c32.DownArrow: 'Down',
|
||||
c32.Select: 'Select',
|
||||
c32.Print: 'Print',
|
||||
c32.Execute: 'Execute',
|
||||
# c32.Snapshot: 'Snapshot',
|
||||
c32.Insert: 'Insert',
|
||||
c32.Delete: 'Delete',
|
||||
c32.Help: 'Help',
|
||||
c32.F1: 'F1',
|
||||
c32.F2: 'F2',
|
||||
c32.F3: 'F3',
|
||||
c32.F4: 'F4',
|
||||
c32.F5: 'F5',
|
||||
c32.F6: 'F6',
|
||||
c32.F7: 'F7',
|
||||
c32.F8: 'F8',
|
||||
c32.F9: 'F9',
|
||||
c32.F10: 'F10',
|
||||
c32.F11: 'F11',
|
||||
c32.F12: 'F12',
|
||||
c32.F13: 'F13',
|
||||
c32.F14: 'F14',
|
||||
c32.F15: 'F15',
|
||||
c32.F16: 'F16',
|
||||
c32.F17: 'F17',
|
||||
c32.F18: 'F18',
|
||||
c32.F19: 'F19',
|
||||
c32.F20: 'F20',
|
||||
c32.F21: 'F21',
|
||||
c32.F22: 'F22',
|
||||
c32.F23: 'F23',
|
||||
c32.F24: 'F24',
|
||||
# c32.Numlock: 'Num_Lock,',
|
||||
# c32.Scroll: 'Scroll_Lock',
|
||||
# c32.Apps: 'VK_APPS',
|
||||
# c32.ProcesskeY: 'VK_PROCESSKEY',
|
||||
# c32.Attn: 'VK_ATTN',
|
||||
# c32.Crsel: 'VK_CRSEL',
|
||||
# c32.Exsel: 'VK_EXSEL',
|
||||
# c32.Ereof: 'VK_EREOF',
|
||||
# c32.Play: 'VK_PLAY',
|
||||
# c32.Zoom: 'VK_ZOOM',
|
||||
# c32.Noname: 'VK_NONAME',
|
||||
# c32.Pa1: 'VK_PA1',
|
||||
c32.OemClear: 'VK_OEM_CLEAR',
|
||||
c32.NumPad0: 'NUMPAD0',
|
||||
c32.NumPad1: 'NUMPAD1',
|
||||
c32.NumPad2: 'NUMPAD2',
|
||||
c32.NumPad3: 'NUMPAD3',
|
||||
c32.NumPad4: 'NUMPAD4',
|
||||
c32.NumPad5: 'NUMPAD5',
|
||||
c32.NumPad6: 'NUMPAD6',
|
||||
c32.NumPad7: 'NUMPAD7',
|
||||
c32.NumPad8: 'NUMPAD8',
|
||||
c32.NumPad9: 'NUMPAD9',
|
||||
c32.Divide: 'Divide',
|
||||
c32.Multiply: 'Multiply',
|
||||
c32.Add: 'Add',
|
||||
c32.Subtract: 'Subtract',
|
||||
c32.Decimal: 'VK_DECIMAL'
|
||||
}
|
||||
|
||||
# function to handle the mapping
|
||||
@@ -100,7 +101,7 @@ def make_keysym(keycode):
|
||||
try:
|
||||
sym = code2sym_map[keycode]
|
||||
except KeyError:
|
||||
sym = u''
|
||||
sym = ''
|
||||
return sym
|
||||
|
||||
sym2code_map = {}
|
||||
@@ -108,7 +109,7 @@ 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'''
|
||||
'''Convert a GNU readline style textual description of a key to keycode with modifiers'''
|
||||
if keytext.startswith('"'): # "
|
||||
return keyseq_to_keyinfo(keytext[1:-1])
|
||||
else:
|
||||
@@ -118,8 +119,8 @@ def key_text_to_keyinfo(keytext):
|
||||
def char_to_keyinfo(char, control=False, meta=False, shift=False):
|
||||
vk = (ord(char))
|
||||
if vk & 0xffff == 0xffff:
|
||||
print u'VkKeyScan("%s") = %x' % (char, vk)
|
||||
raise ValueError, u'bad key'
|
||||
print('VkKeyScan("%s") = %x' % (char, vk))
|
||||
raise ValueError, 'bad key'
|
||||
if vk & 0x100:
|
||||
shift = True
|
||||
if vk & 0x200:
|
||||
@@ -135,24 +136,24 @@ def keyname_to_keyinfo(keyname):
|
||||
|
||||
while 1:
|
||||
lkeyname = keyname.lower()
|
||||
if lkeyname.startswith(u'control-'):
|
||||
if lkeyname.startswith('control-'):
|
||||
control = True
|
||||
keyname = keyname[8:]
|
||||
elif lkeyname.startswith(u'ctrl-'):
|
||||
elif lkeyname.startswith('ctrl-'):
|
||||
control = True
|
||||
keyname = keyname[5:]
|
||||
elif lkeyname.startswith(u'meta-'):
|
||||
elif lkeyname.startswith('meta-'):
|
||||
meta = True
|
||||
keyname = keyname[5:]
|
||||
elif lkeyname.startswith(u'alt-'):
|
||||
elif lkeyname.startswith('alt-'):
|
||||
meta = True
|
||||
keyname = keyname[4:]
|
||||
elif lkeyname.startswith(u'shift-'):
|
||||
elif lkeyname.startswith('shift-'):
|
||||
shift = True
|
||||
keyname = keyname[6:]
|
||||
else:
|
||||
if len(keyname) > 1:
|
||||
return (control, meta, shift, sym2code_map.get(keyname.lower(),u" "))
|
||||
return (control, meta, shift, sym2code_map.get(keyname.lower()," "))
|
||||
else:
|
||||
return char_to_keyinfo(keyname, control, meta, shift)
|
||||
|
||||
@@ -163,14 +164,14 @@ def keyseq_to_keyinfo(keyseq):
|
||||
shift = False
|
||||
|
||||
while 1:
|
||||
if keyseq.startswith(u'\\C-'):
|
||||
if keyseq.startswith('\\C-'):
|
||||
control = True
|
||||
keyseq = keyseq[3:]
|
||||
elif keyseq.startswith(u'\\M-'):
|
||||
elif keyseq.startswith('\\M-'):
|
||||
meta = True
|
||||
keyseq = keyseq[3:]
|
||||
elif keyseq.startswith(u'\\e'):
|
||||
res.append(char_to_keyinfo(u'\033', control, meta, shift))
|
||||
elif keyseq.startswith('\\e'):
|
||||
res.append(char_to_keyinfo('\033', control, meta, shift))
|
||||
control = meta = shift = False
|
||||
keyseq = keyseq[2:]
|
||||
elif len(keyseq) >= 1:
|
||||
@@ -192,7 +193,7 @@ def make_KeyPress(char, state, keycode):
|
||||
shift = bool(int(state) & int(Shift))
|
||||
control = bool(int(state) & int(Control))
|
||||
meta = bool(int(state) & int(Alt))
|
||||
keyname = code2sym_map.get(keycode, u"").lower()
|
||||
keyname = code2sym_map.get(keycode, "").lower()
|
||||
if control and meta: #equivalent to altgr so clear flags
|
||||
control = False
|
||||
meta = False
|
||||
|
||||
@@ -6,93 +6,94 @@
|
||||
# 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 __future__ import print_function, unicode_literals, absolute_import
|
||||
from . 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
|
||||
from .common import KeyPress
|
||||
|
||||
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'
|
||||
code2sym_map = {c32.VK_CANCEL: 'cancel',
|
||||
c32.VK_BACK: 'backspace',
|
||||
c32.VK_TAB: 'tab',
|
||||
c32.VK_CLEAR: 'clear',
|
||||
c32.VK_RETURN: 'return',
|
||||
c32.VK_SHIFT: 'shift_l',
|
||||
c32.VK_CONTROL: 'control_l',
|
||||
c32.VK_MENU: 'alt_l',
|
||||
c32.VK_PAUSE: 'pause',
|
||||
c32.VK_CAPITAL: 'caps_lock',
|
||||
c32.VK_ESCAPE: 'escape',
|
||||
c32.VK_SPACE: 'space',
|
||||
c32.VK_PRIOR: 'prior',
|
||||
c32.VK_NEXT: 'next',
|
||||
c32.VK_END: 'end',
|
||||
c32.VK_HOME: 'home',
|
||||
c32.VK_LEFT: 'left',
|
||||
c32.VK_UP: 'up',
|
||||
c32.VK_RIGHT: 'right',
|
||||
c32.VK_DOWN: 'down',
|
||||
c32.VK_SELECT: 'select',
|
||||
c32.VK_PRINT: 'print',
|
||||
c32.VK_EXECUTE: 'execute',
|
||||
c32.VK_SNAPSHOT: 'snapshot',
|
||||
c32.VK_INSERT: 'insert',
|
||||
c32.VK_DELETE: 'delete',
|
||||
c32.VK_HELP: 'help',
|
||||
c32.VK_F1: 'f1',
|
||||
c32.VK_F2: 'f2',
|
||||
c32.VK_F3: 'f3',
|
||||
c32.VK_F4: 'f4',
|
||||
c32.VK_F5: 'f5',
|
||||
c32.VK_F6: 'f6',
|
||||
c32.VK_F7: 'f7',
|
||||
c32.VK_F8: 'f8',
|
||||
c32.VK_F9: 'f9',
|
||||
c32.VK_F10: 'f10',
|
||||
c32.VK_F11: 'f11',
|
||||
c32.VK_F12: 'f12',
|
||||
c32.VK_F13: 'f13',
|
||||
c32.VK_F14: 'f14',
|
||||
c32.VK_F15: 'f15',
|
||||
c32.VK_F16: 'f16',
|
||||
c32.VK_F17: 'f17',
|
||||
c32.VK_F18: 'f18',
|
||||
c32.VK_F19: 'f19',
|
||||
c32.VK_F20: 'f20',
|
||||
c32.VK_F21: 'f21',
|
||||
c32.VK_F22: 'f22',
|
||||
c32.VK_F23: 'f23',
|
||||
c32.VK_F24: 'f24',
|
||||
c32.VK_NUMLOCK: 'num_lock,',
|
||||
c32.VK_SCROLL: 'scroll_lock',
|
||||
c32.VK_APPS: 'vk_apps',
|
||||
c32.VK_PROCESSKEY: 'vk_processkey',
|
||||
c32.VK_ATTN: 'vk_attn',
|
||||
c32.VK_CRSEL: 'vk_crsel',
|
||||
c32.VK_EXSEL: 'vk_exsel',
|
||||
c32.VK_EREOF: 'vk_ereof',
|
||||
c32.VK_PLAY: 'vk_play',
|
||||
c32.VK_ZOOM: 'vk_zoom',
|
||||
c32.VK_NONAME: 'vk_noname',
|
||||
c32.VK_PA1: 'vk_pa1',
|
||||
c32.VK_OEM_CLEAR: 'vk_oem_clear',
|
||||
c32.VK_NUMPAD0: 'numpad0',
|
||||
c32.VK_NUMPAD1: 'numpad1',
|
||||
c32.VK_NUMPAD2: 'numpad2',
|
||||
c32.VK_NUMPAD3: 'numpad3',
|
||||
c32.VK_NUMPAD4: 'numpad4',
|
||||
c32.VK_NUMPAD5: 'numpad5',
|
||||
c32.VK_NUMPAD6: 'numpad6',
|
||||
c32.VK_NUMPAD7: 'numpad7',
|
||||
c32.VK_NUMPAD8: 'numpad8',
|
||||
c32.VK_NUMPAD9: 'numpad9',
|
||||
c32.VK_DIVIDE: 'divide',
|
||||
c32.VK_MULTIPLY: 'multiply',
|
||||
c32.VK_ADD: 'add',
|
||||
c32.VK_SUBTRACT: 'subtract',
|
||||
c32.VK_DECIMAL: 'vk_decimal'
|
||||
}
|
||||
|
||||
VkKeyScan = windll.user32.VkKeyScanA
|
||||
@@ -101,8 +102,8 @@ 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'
|
||||
print('VkKeyScan("%s") = %x' % (char, vk))
|
||||
raise ValueError, 'bad key'
|
||||
if vk & 0x100:
|
||||
k.shift = True
|
||||
if vk & 0x200:
|
||||
@@ -124,10 +125,10 @@ def make_KeyPress(char, state, keycode):
|
||||
try:
|
||||
keyname=code2sym_map[keycode]
|
||||
except KeyError:
|
||||
keyname = u""
|
||||
keyname = ""
|
||||
out = KeyPress(char, shift, control, meta, keyname)
|
||||
return out
|
||||
|
||||
if __name__==u"__main__":
|
||||
if __name__ == "__main__":
|
||||
import startup
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#This file contains constants that are normally found in win32all
|
||||
#But included here to avoid the dependency
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
VK_LBUTTON=1
|
||||
VK_RBUTTON=2
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
# 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 __future__ import print_function, unicode_literals, absolute_import
|
||||
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"]
|
||||
if "pyreadline" in sys.modules:
|
||||
pyreadline = sys.modules["pyreadline"]
|
||||
else:
|
||||
import pyreadline
|
||||
|
||||
import lineobj
|
||||
from . import lineobj
|
||||
|
||||
class EscapeHistory(Exception):
|
||||
pass
|
||||
@@ -28,67 +29,67 @@ class LineHistory(object):
|
||||
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""
|
||||
self.query = ""
|
||||
self.last_search_for = ""
|
||||
|
||||
def get_current_history_length(self):
|
||||
u'''Return the number of lines currently in the history.
|
||||
'''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)
|
||||
log("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
|
||||
'''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)
|
||||
log("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).'''
|
||||
'''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))
|
||||
log("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))
|
||||
log("set_history_length: old:%d new:%d"%(self._history_length, value))
|
||||
self._history_length = value
|
||||
|
||||
def get_history_cursor(self):
|
||||
value = self._history_cursor
|
||||
log(u"get_history_cursor:%d"%value)
|
||||
log("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))
|
||||
log("set_history_cursor: old:%d new:%d"%(self._history_cursor, value))
|
||||
self._history_cursor = value
|
||||
|
||||
history_length = property(get_history_length, set_history_length)
|
||||
history_cursor = property(get_history_cursor, set_history_cursor)
|
||||
|
||||
def clear_history(self):
|
||||
u'''Clear readline history.'''
|
||||
'''Clear readline history.'''
|
||||
self.history[:] = []
|
||||
self.history_cursor = 0
|
||||
|
||||
def read_history_file(self, filename=None):
|
||||
u'''Load a readline history file.'''
|
||||
'''Load a readline history file.'''
|
||||
if filename is None:
|
||||
filename = self.history_filename
|
||||
try:
|
||||
for line in open(filename, u'r'):
|
||||
for line in open(filename, '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.'''
|
||||
'''Save a readline history file.'''
|
||||
if filename is None:
|
||||
filename = self.history_filename
|
||||
fp = open(filename, u'wb')
|
||||
fp = open(filename, 'wb')
|
||||
for line in self.history[-self.history_length:]:
|
||||
fp.write(ensure_str(line.get_line_text()))
|
||||
fp.write('\n'.encode('ascii'))
|
||||
@@ -96,7 +97,7 @@ class LineHistory(object):
|
||||
|
||||
|
||||
def add_history(self, line):
|
||||
u'''Append a line to the history buffer, as if it was the last line typed.'''
|
||||
'''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():
|
||||
@@ -108,7 +109,7 @@ class LineHistory(object):
|
||||
self.history_cursor = len(self.history)
|
||||
|
||||
def previous_history(self, current): # (C-p)
|
||||
u'''Move back through the history list, fetching the previous command. '''
|
||||
'''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
|
||||
|
||||
@@ -118,19 +119,19 @@ class LineHistory(object):
|
||||
current.point = lineobj.EndOfLine
|
||||
|
||||
def next_history(self, current): # (C-n)
|
||||
u'''Move forward through the history list, fetching the next command. '''
|
||||
'''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.'''
|
||||
'''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
|
||||
'''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())
|
||||
@@ -159,10 +160,10 @@ class LineHistory(object):
|
||||
if self.history:
|
||||
result = self.history[startpos].get_line_text()
|
||||
else:
|
||||
result = u""
|
||||
result = ""
|
||||
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))
|
||||
log("reverse_search_history: old:%d new:%d result:%r"%(origpos, self.history_cursor, result))
|
||||
return result
|
||||
|
||||
def forward_search_history(self, searchfor, startpos=None):
|
||||
@@ -189,7 +190,7 @@ class LineHistory(object):
|
||||
if self.history:
|
||||
result = self.history[startpos].get_line_text()
|
||||
else:
|
||||
result = u""
|
||||
result = ""
|
||||
self.history_cursor = startpos
|
||||
self.last_search_for = searchfor
|
||||
return result
|
||||
@@ -198,7 +199,7 @@ class LineHistory(object):
|
||||
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())
|
||||
self.query = ''.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)):
|
||||
@@ -217,7 +218,7 @@ class LineHistory(object):
|
||||
pass
|
||||
elif hc >= len(self.history) and not self.query:
|
||||
self.history_cursor = len(self.history)
|
||||
return lineobj.ReadLineTextBuffer(u"", point=0)
|
||||
return lineobj.ReadLineTextBuffer("", 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\
|
||||
@@ -233,30 +234,30 @@ class LineHistory(object):
|
||||
raise
|
||||
|
||||
def history_search_forward(self, partial): # ()
|
||||
u'''Search forward through the history for the string of characters
|
||||
'''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
|
||||
'''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__":
|
||||
if __name__ == "__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"))
|
||||
q.add_history(RL("aaaa"))
|
||||
q.add_history(RL("aaba"))
|
||||
q.add_history(RL("aaca"))
|
||||
q.add_history(RL("akca"))
|
||||
q.add_history(RL("bbb"))
|
||||
q.add_history(RL("ako"))
|
||||
r.add_history(RL("ako"))
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import re, operator, sys
|
||||
|
||||
import wordmatcher
|
||||
from . import wordmatcher
|
||||
import pyreadline.clipboard as clipboard
|
||||
from pyreadline.logger import log
|
||||
from pyreadline.unicode_helper import ensure_unicode, biter
|
||||
@@ -27,7 +28,7 @@ def quote_char(c):
|
||||
|
||||
class LinePositioner(object):
|
||||
def __call__(self, line):
|
||||
NotImplementedError(u"Base class !!!")
|
||||
NotImplementedError("Base class !!!")
|
||||
|
||||
class NextChar(LinePositioner):
|
||||
def __call__(self, line):
|
||||
@@ -69,7 +70,7 @@ class WordStart(LinePositioner):
|
||||
else:
|
||||
return line.point
|
||||
else:
|
||||
raise NotAWordError(u"Point is not in a word")
|
||||
raise NotAWordError("Point is not in a word")
|
||||
WordStart = WordStart()
|
||||
|
||||
class WordEnd(LinePositioner):
|
||||
@@ -80,7 +81,7 @@ class WordEnd(LinePositioner):
|
||||
else:
|
||||
return line.point
|
||||
else:
|
||||
raise NotAWordError(u"Point is not in a word")
|
||||
raise NotAWordError("Point is not in a word")
|
||||
WordEnd = WordEnd()
|
||||
|
||||
class PrevWordEnd(LinePositioner):
|
||||
@@ -91,10 +92,10 @@ 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" ":
|
||||
if line[point - 1:point].get_line_text() == " ":
|
||||
while point > 0 and line[point - 1:point].get_line_text() == " ":
|
||||
point -= 1
|
||||
while point > 0 and line[point - 1:point].get_line_text() != u" ":
|
||||
while point > 0 and line[point - 1:point].get_line_text() != " ":
|
||||
point -= 1
|
||||
return point
|
||||
PrevSpace = PrevSpace()
|
||||
@@ -129,7 +130,7 @@ all_positioners.sort()
|
||||
|
||||
class LineSlice(object):
|
||||
def __call__(self, line):
|
||||
NotImplementedError(u"Base class !!!")
|
||||
NotImplementedError("Base class !!!")
|
||||
|
||||
|
||||
class CurrentWord(LineSlice):
|
||||
@@ -223,7 +224,7 @@ class TextLine(object):
|
||||
pass
|
||||
|
||||
def __repr__(self):
|
||||
return u'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer, self.point, self.mark)
|
||||
return 'TextLine("%s",point=%s,mark=%s)'%(self.line_buffer, self.point, self.mark)
|
||||
|
||||
def copy(self):
|
||||
return self.__class__(self)
|
||||
@@ -243,17 +244,17 @@ class TextLine(object):
|
||||
def visible_line_width(self, position = Point):
|
||||
"""Return the visible width of the text in line buffer up to position."""
|
||||
extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD])
|
||||
return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u"\t")*7 + extra_char_width
|
||||
return len(self[:position].quoted_text()) + self[:position].line_buffer.count("\t")*7 + extra_char_width
|
||||
|
||||
def quoted_text(self):
|
||||
quoted = [ quote_char(c) for c in self.line_buffer ]
|
||||
self.line_char_width = [ len(c) for c in quoted ]
|
||||
return u''.join(map(ensure_unicode, quoted))
|
||||
return ''.join(map(ensure_unicode, quoted))
|
||||
|
||||
def get_line_text(self):
|
||||
buf = self.line_buffer
|
||||
buf = map(ensure_unicode, buf)
|
||||
return u''.join(buf)
|
||||
return ''.join(buf)
|
||||
|
||||
def set_line(self, text, cursor = None):
|
||||
self.line_buffer = [ c for c in str(text) ]
|
||||
@@ -307,7 +308,7 @@ class TextLine(object):
|
||||
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
|
||||
raise IndexError("Cannot use step in line buffer indexing") #Multiple slice not allowed
|
||||
else:
|
||||
# return TextLine(self.line_buffer[key])
|
||||
return self.line_buffer[key]
|
||||
@@ -387,10 +388,10 @@ class TextLine(object):
|
||||
return txt in self.get_line_text()
|
||||
|
||||
|
||||
lines = [TextLine(u"abc"),
|
||||
TextLine(u"abc def"),
|
||||
TextLine(u"abc def ghi"),
|
||||
TextLine(u" abc def "),
|
||||
lines = [TextLine("abc"),
|
||||
TextLine("abc def"),
|
||||
TextLine("abc def ghi"),
|
||||
TextLine(" abc def "),
|
||||
]
|
||||
l = lines[2]
|
||||
l.point = 5
|
||||
@@ -406,8 +407,8 @@ class ReadLineTextBuffer(TextLine):
|
||||
self.kill_ring = []
|
||||
|
||||
def __repr__(self):
|
||||
return u'ReadLineTextBuffer'\
|
||||
u'("%s",point=%s,mark=%s,selection_mark=%s)'%\
|
||||
return 'ReadLineTextBuffer'\
|
||||
'("%s",point=%s,mark=%s,selection_mark=%s)'%\
|
||||
(self.line_buffer, self.point, self.mark,self.selection_mark)
|
||||
|
||||
|
||||
@@ -712,7 +713,7 @@ class ReadLineTextBuffer(TextLine):
|
||||
|
||||
|
||||
def copy_region_to_clipboard(self): # ()
|
||||
u'''Copy the text in the region to the windows clipboard.'''
|
||||
'''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))
|
||||
@@ -720,11 +721,11 @@ class ReadLineTextBuffer(TextLine):
|
||||
return
|
||||
begin = min(cursor, mark)
|
||||
end = max(cursor, mark)
|
||||
toclipboard = u"".join(self.line_buffer[begin:end])
|
||||
toclipboard = "".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.'''
|
||||
'''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))
|
||||
@@ -732,7 +733,7 @@ class ReadLineTextBuffer(TextLine):
|
||||
return
|
||||
begin = min(cursor, selection_mark)
|
||||
end = max(cursor, selection_mark)
|
||||
toclipboard = u"".join(self.line_buffer[begin:end])
|
||||
toclipboard = "".join(self.line_buffer[begin:end])
|
||||
clipboard.SetClipboardText(toclipboard)
|
||||
|
||||
|
||||
@@ -755,45 +756,45 @@ class ReadLineTextBuffer(TextLine):
|
||||
|
||||
|
||||
##################################################################
|
||||
q = ReadLineTextBuffer(u"asff asFArw ewrWErhg", point=8)
|
||||
q = TextLine(u"asff asFArw ewrWErhg", point=8)
|
||||
q = ReadLineTextBuffer("asff asFArw ewrWErhg", point=8)
|
||||
q = TextLine("asff asFArw ewrWErhg", point=8)
|
||||
|
||||
def show_pos(buff, pos, chr = u"."):
|
||||
def show_pos(buff, pos, chr = "."):
|
||||
l = len(buff.line_buffer)
|
||||
def choice(bool):
|
||||
if bool:
|
||||
return chr
|
||||
else:
|
||||
return u" "
|
||||
return u"".join([choice(pos==idx) for idx in range(l + 1)])
|
||||
return " "
|
||||
return "".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"-")
|
||||
print((" %s "%positioner.__class__.__name__).center(40, "-"))
|
||||
buffstr = buff.line_buffer
|
||||
|
||||
print u'"%s"'%(buffstr)
|
||||
print('"%s"'%(buffstr))
|
||||
for point in points:
|
||||
b = TextLine(buff, point = point)
|
||||
out=[u" "] * (len(buffstr) + 1)
|
||||
out=[" "] * (len(buffstr) + 1)
|
||||
pos = positioner(b)
|
||||
if pos == point:
|
||||
out[pos] = u"&"
|
||||
out[pos] = "&"
|
||||
else:
|
||||
out[point] = u"."
|
||||
out[pos] = u"^"
|
||||
print u'"%s"'%(u"".join(out))
|
||||
out[point] = "."
|
||||
out[pos] = "^"
|
||||
print('"%s"'%("".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))
|
||||
print('%-15s "%s"'%("Position", q.get_line_text()))
|
||||
print('%-15s "%s"'%("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"^"))
|
||||
print('%-15s "%s"'%(name, show_pos(q, pos, "^")))
|
||||
|
||||
l = ReadLineTextBuffer(u"kjjk asads asad")
|
||||
l = ReadLineTextBuffer("kjjk asads asad")
|
||||
l.point = EndOfLine
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import re, operator
|
||||
|
||||
@@ -20,36 +21,36 @@ def str_find_all(str, ch):
|
||||
return result
|
||||
|
||||
|
||||
word_pattern = re.compile(u"(x*)")
|
||||
word_pattern = re.compile("(x*)")
|
||||
|
||||
def markwords(str, iswordfun):
|
||||
markers = {True : u"x", False : u"o"}
|
||||
markers = {True : "x", False : "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""]
|
||||
return [x for x in word_pattern.split(markwords(str,iswordfun)) if x != ""]
|
||||
|
||||
def mark_start_segment(str, is_segment):
|
||||
def mark_start(s):
|
||||
if s[0:1] == u"x":
|
||||
return u"s" + s[1:]
|
||||
if s[0:1] == "x":
|
||||
return "s" + s[1:]
|
||||
else:
|
||||
return s
|
||||
return u"".join(map(mark_start, split_words(str, is_segment)))
|
||||
return "".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"
|
||||
if s[0:1] == "x":
|
||||
return s[:-1] + "s"
|
||||
else:
|
||||
return s
|
||||
return u"".join(map(mark_start, split_words(str, is_segment)))
|
||||
return "".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")
|
||||
return str_find_all(mark_start_segment(str, is_segment), "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")]
|
||||
return [x + 1 for x in str_find_all(mark_end_segment(str, is_segment), "s")]
|
||||
|
||||
|
||||
################ Following are used in lineobj ###########################
|
||||
@@ -58,13 +59,13 @@ def is_word_token(str):
|
||||
return not is_non_word_token(str)
|
||||
|
||||
def is_non_word_token(str):
|
||||
if len(str) != 1 or str in u" \t\n":
|
||||
if len(str) != 1 or str in " \t\n":
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def next_start_segment(str, is_segment):
|
||||
str = u"".join(str)
|
||||
str = "".join(str)
|
||||
result = []
|
||||
for start in mark_start_segment_index(str, is_segment):
|
||||
result[len(result):start] = [start for x in range(start - len(result))]
|
||||
@@ -72,7 +73,7 @@ def next_start_segment(str, is_segment):
|
||||
return result
|
||||
|
||||
def next_end_segment(str, is_segment):
|
||||
str = u"".join(str)
|
||||
str = "".join(str)
|
||||
result = []
|
||||
for start in mark_end_segment_index(str, is_segment):
|
||||
result[len(result):start] = [start for x in range(start - len(result))]
|
||||
@@ -81,7 +82,7 @@ def next_end_segment(str, is_segment):
|
||||
|
||||
|
||||
def prev_start_segment(str, is_segment):
|
||||
str = u"".join(str)
|
||||
str = "".join(str)
|
||||
result = []
|
||||
prev = 0
|
||||
for start in mark_start_segment_index(str, is_segment):
|
||||
@@ -91,7 +92,7 @@ def prev_start_segment(str, is_segment):
|
||||
return result
|
||||
|
||||
def prev_end_segment(str, is_segment):
|
||||
str = u"".join(str)
|
||||
str = "".join(str)
|
||||
result = []
|
||||
prev = 0
|
||||
for start in mark_end_segment_index(str, is_segment):
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import socket, logging, logging.handlers
|
||||
from pyreadline.unicode_helper import ensure_str
|
||||
|
||||
host = u"localhost"
|
||||
host = "localhost"
|
||||
port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
|
||||
|
||||
|
||||
pyreadline_logger = logging.getLogger(u'PYREADLINE')
|
||||
pyreadline_logger = logging.getLogger('PYREADLINE')
|
||||
pyreadline_logger.setLevel(logging.DEBUG)
|
||||
pyreadline_logger.propagate = False
|
||||
formatter = logging.Formatter('%(message)s')
|
||||
@@ -64,7 +65,7 @@ def stop_file_log():
|
||||
file_handler = None
|
||||
|
||||
def stop_logging():
|
||||
log(u"STOPING LOG")
|
||||
log("STOPING LOG")
|
||||
stop_file_log()
|
||||
stop_socket_log()
|
||||
|
||||
|
||||
+14
-13
@@ -5,21 +5,22 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import cPickle
|
||||
import logging
|
||||
import logging.handlers
|
||||
import SocketServer
|
||||
import struct,socket
|
||||
import struct, socket
|
||||
|
||||
try:
|
||||
import msvcrt
|
||||
except ImportError:
|
||||
msvcrt = None
|
||||
print u"problem"
|
||||
print "problem"
|
||||
|
||||
|
||||
port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
|
||||
host = u'localhost'
|
||||
host = 'localhost'
|
||||
|
||||
def check_key():
|
||||
if msvcrt is None:
|
||||
@@ -28,18 +29,18 @@ def check_key():
|
||||
if msvcrt.kbhit() != 0:
|
||||
q = msvcrt.getch()
|
||||
return q
|
||||
return u""
|
||||
return ""
|
||||
|
||||
|
||||
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
|
||||
print "Starting TCP logserver on port:", port
|
||||
print "Press q to quit logserver", port
|
||||
print "Press c to clear screen", port
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
|
||||
s.bind((u"", port))
|
||||
s.bind(("", port))
|
||||
s.settimeout(1)
|
||||
while 1:
|
||||
try:
|
||||
@@ -47,11 +48,11 @@ def main():
|
||||
print data,
|
||||
except socket.timeout:
|
||||
key = check_key().lower()
|
||||
if u"q" == key:
|
||||
print u"Quitting logserver"
|
||||
if "q" == key:
|
||||
print "Quitting logserver"
|
||||
break
|
||||
elif u"c" == key:
|
||||
print u"\n" * 100
|
||||
elif "c" == key:
|
||||
print "\n" * 100
|
||||
|
||||
if __name__ == u"__main__":
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,6 @@
|
||||
__all__=["emacs","notemacs","vi"]
|
||||
import emacs,notemacs,vi
|
||||
editingmodes=[emacs.EmacsMode,notemacs.NotEmacsMode,vi.ViMode]
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
__all__=["emacs", "notemacs", "vi"]
|
||||
from . import emacs, notemacs, vi
|
||||
editingmodes = [emacs.EmacsMode, notemacs.NotEmacsMode, vi.ViMode]
|
||||
|
||||
#add check to ensure all modes have unique mode names
|
||||
@@ -6,7 +6,8 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
import os,re,math,glob,sys,time
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import os, re, math, glob, sys, time
|
||||
import pyreadline.logger as logger
|
||||
from pyreadline.logger import log
|
||||
from pyreadline.keysyms.common import make_KeyPress_from_keydescr
|
||||
@@ -15,10 +16,10 @@ import pyreadline.lineeditor.history as history
|
||||
import pyreadline.clipboard as clipboard
|
||||
from pyreadline.error import ReadlineError,GetSetError
|
||||
from pyreadline.unicode_helper import ensure_str, ensure_unicode
|
||||
in_ironpython=u"IronPython" in sys.version
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
|
||||
class BaseMode(object):
|
||||
mode=u"base"
|
||||
mode = "base"
|
||||
def __init__(self,rlobj):
|
||||
self.argument=0
|
||||
self.rlobj=rlobj
|
||||
@@ -28,10 +29,10 @@ class BaseMode(object):
|
||||
self.prevargument=None
|
||||
self.l_buffer=lineobj.ReadLineTextBuffer("")
|
||||
self._history=history.LineHistory()
|
||||
self.completer_delims = u" \t\n\"\\'`@$><=;|&{("
|
||||
self.show_all_if_ambiguous = u'off'
|
||||
self.mark_directories = u'on'
|
||||
self.complete_filesystem = u'off'
|
||||
self.completer_delims = " \t\n\"\\'`@$><=;|&{("
|
||||
self.show_all_if_ambiguous = 'off'
|
||||
self.mark_directories = 'on'
|
||||
self.complete_filesystem = 'off'
|
||||
self.completer = None
|
||||
self.begidx = 0
|
||||
self.endidx = 0
|
||||
@@ -41,7 +42,7 @@ class BaseMode(object):
|
||||
self.first_prompt = True
|
||||
self.cursor_size=25
|
||||
|
||||
self.prompt = u">>> "
|
||||
self.prompt = ">>> "
|
||||
|
||||
#Paste settings
|
||||
#assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n
|
||||
@@ -58,7 +59,7 @@ class BaseMode(object):
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return u"<BaseMode>"
|
||||
return "<BaseMode>"
|
||||
|
||||
def _gs(x):
|
||||
def g(self):
|
||||
@@ -81,29 +82,29 @@ class BaseMode(object):
|
||||
argument_reset=property(_argreset)
|
||||
|
||||
#used in readline
|
||||
ctrl_c_tap_time_interval=property(*_gs(u"ctrl_c_tap_time_interval"))
|
||||
allow_ctrl_c=property(*_gs(u"allow_ctrl_c"))
|
||||
_print_prompt=property(_g(u"_print_prompt"))
|
||||
_update_line=property(_g(u"_update_line"))
|
||||
console=property(_g(u"console"))
|
||||
prompt_begin_pos=property(_g(u"prompt_begin_pos"))
|
||||
prompt_end_pos=property(_g(u"prompt_end_pos"))
|
||||
ctrl_c_tap_time_interval=property(*_gs("ctrl_c_tap_time_interval"))
|
||||
allow_ctrl_c=property(*_gs("allow_ctrl_c"))
|
||||
_print_prompt=property(_g("_print_prompt"))
|
||||
_update_line=property(_g("_update_line"))
|
||||
console=property(_g("console"))
|
||||
prompt_begin_pos=property(_g("prompt_begin_pos"))
|
||||
prompt_end_pos=property(_g("prompt_end_pos"))
|
||||
|
||||
#used in completer _completions
|
||||
# completer_delims=property(*_gs("completer_delims"))
|
||||
_bell=property(_g(u"_bell"))
|
||||
bell_style=property(_g(u"bell_style"))
|
||||
_bell=property(_g("_bell"))
|
||||
bell_style=property(_g("bell_style"))
|
||||
|
||||
#used in emacs
|
||||
_clear_after=property(_g(u"_clear_after"))
|
||||
_update_prompt_pos=property(_g(u"_update_prompt_pos"))
|
||||
_clear_after=property(_g("_clear_after"))
|
||||
_update_prompt_pos=property(_g("_update_prompt_pos"))
|
||||
|
||||
#not used in basemode or emacs
|
||||
|
||||
def process_keyevent(self, keyinfo):
|
||||
raise NotImplementedError
|
||||
|
||||
def readline_setup(self, prompt=u''):
|
||||
def readline_setup(self, prompt=''):
|
||||
self.l_buffer.selection_mark=-1
|
||||
if self.first_prompt:
|
||||
self.first_prompt = False
|
||||
@@ -111,7 +112,7 @@ class BaseMode(object):
|
||||
try:
|
||||
self.startup_hook()
|
||||
except:
|
||||
print u'startup hook failed'
|
||||
print('startup hook failed')
|
||||
traceback.print_exc()
|
||||
|
||||
self.l_buffer.reset_line()
|
||||
@@ -121,7 +122,7 @@ class BaseMode(object):
|
||||
try:
|
||||
self.pre_input_hook()
|
||||
except:
|
||||
print u'pre_input_hook failed'
|
||||
print('pre_input_hook failed')
|
||||
traceback.print_exc()
|
||||
self.pre_input_hook = None
|
||||
|
||||
@@ -130,7 +131,7 @@ class BaseMode(object):
|
||||
|
||||
|
||||
def finalize(self):
|
||||
u"""Every bindable command should call this function for cleanup.
|
||||
"""Every bindable command should call this function for cleanup.
|
||||
Except those that want to set argument to a non-zero value.
|
||||
"""
|
||||
self.argument = 0
|
||||
@@ -142,12 +143,12 @@ class BaseMode(object):
|
||||
|
||||
#Create key bindings:
|
||||
def rl_settings_to_string(self):
|
||||
out=[u"%-20s: %s"%(u"show all if ambigous",self.show_all_if_ambiguous)]
|
||||
out.append(u"%-20s: %s"%(u"mark_directories",self.mark_directories))
|
||||
out.append(u"%-20s: %s"%(u"bell_style",self.bell_style))
|
||||
out.append(u"------------- key bindings ------------")
|
||||
tablepat=u"%-7s %-7s %-7s %-15s %-15s "
|
||||
out.append(tablepat%(u"Control",u"Meta",u"Shift",u"Keycode/char",u"Function"))
|
||||
out=["%-20s: %s"%("show all if ambigous",self.show_all_if_ambiguous)]
|
||||
out.append("%-20s: %s"%("mark_directories",self.mark_directories))
|
||||
out.append("%-20s: %s"%("bell_style",self.bell_style))
|
||||
out.append("------------- key bindings ------------")
|
||||
tablepat="%-7s %-7s %-7s %-15s %-15s "
|
||||
out.append(tablepat%("Control","Meta","Shift","Keycode/char","Function"))
|
||||
bindings=[(k[0],k[1],k[2],k[3],v.__name__) for k,v in self.key_dispatch.iteritems()]
|
||||
bindings.sort()
|
||||
for key in bindings:
|
||||
@@ -156,16 +157,16 @@ class BaseMode(object):
|
||||
|
||||
|
||||
def _bind_key(self, key, func):
|
||||
u"""setup the mapping from key to call the function."""
|
||||
"""setup the mapping from key to call the function."""
|
||||
if not callable(func):
|
||||
print u"Trying to bind non method to keystroke:%s,%s"%(key,func)
|
||||
raise ReadlineError(u"Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(self._bind_key)))
|
||||
print("Trying to bind non method to keystroke:%s,%s"%(key,func))
|
||||
raise ReadlineError("Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(self._bind_key)))
|
||||
keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
|
||||
log(u">>>%s -> %s<<<"%(keyinfo,func.__name__))
|
||||
log(">>>%s -> %s<<<"%(keyinfo,func.__name__))
|
||||
self.key_dispatch[keyinfo] = func
|
||||
|
||||
def _bind_exit_key(self, key):
|
||||
u"""setup the mapping from key to call the function."""
|
||||
"""setup the mapping from key to call the function."""
|
||||
keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
|
||||
self.exit_dispatch[keyinfo] = None
|
||||
|
||||
@@ -190,8 +191,8 @@ class BaseMode(object):
|
||||
if buf[self.begidx] in self.completer_delims:
|
||||
self.begidx += 1
|
||||
break
|
||||
text = ensure_str(u''.join(buf[self.begidx:self.endidx]))
|
||||
log(u'complete text="%s"' % ensure_unicode(text))
|
||||
text = ensure_str(''.join(buf[self.begidx:self.endidx]))
|
||||
log('complete text="%s"' % ensure_unicode(text))
|
||||
i = 0
|
||||
while 1:
|
||||
try:
|
||||
@@ -205,18 +206,18 @@ class BaseMode(object):
|
||||
completions.append(r)
|
||||
else:
|
||||
pass
|
||||
log(u'text completions=<%s>' % map(ensure_unicode, completions))
|
||||
log('text completions=<%s>' % map(ensure_unicode, completions))
|
||||
if (self.complete_filesystem == "on") and not completions:
|
||||
# get the filename to complete
|
||||
while self.begidx > 0:
|
||||
self.begidx -= 1
|
||||
if buf[self.begidx] in u' \t\n':
|
||||
if buf[self.begidx] in ' \t\n':
|
||||
self.begidx += 1
|
||||
break
|
||||
text = ensure_str(u''.join(buf[self.begidx:self.endidx]))
|
||||
log(u'file complete text="%s"' % ensure_unicode(text))
|
||||
text = ensure_str(''.join(buf[self.begidx:self.endidx]))
|
||||
log('file complete text="%s"' % ensure_unicode(text))
|
||||
completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*'.encode('ascii')))
|
||||
if self.mark_directories == u'on':
|
||||
if self.mark_directories == 'on':
|
||||
mc = []
|
||||
for f in completions:
|
||||
if os.path.isdir(f):
|
||||
@@ -224,32 +225,32 @@ class BaseMode(object):
|
||||
else:
|
||||
mc.append(f)
|
||||
completions = mc
|
||||
log(u'fnames=<%s>' % map(ensure_unicode, completions))
|
||||
log('fnames=<%s>' % map(ensure_unicode, completions))
|
||||
return completions
|
||||
|
||||
|
||||
def _display_completions(self, completions):
|
||||
if not completions:
|
||||
return
|
||||
self.console.write(u'\n')
|
||||
self.console.write('\n')
|
||||
wmax = max(map(len, completions))
|
||||
w, h = self.console.size()
|
||||
cols = max(1, int((w-1) / (wmax+1)))
|
||||
rows = int(math.ceil(float(len(completions)) / cols))
|
||||
for row in range(rows):
|
||||
s = u''
|
||||
s = ''
|
||||
for col in range(cols):
|
||||
i = col*rows + row
|
||||
if i < len(completions):
|
||||
self.console.write(completions[i].ljust(wmax+1))
|
||||
self.console.write(u'\n')
|
||||
self.console.write('\n')
|
||||
if in_ironpython:
|
||||
self.prompt=sys.ps1
|
||||
self._print_prompt()
|
||||
|
||||
|
||||
def complete(self, e): # (TAB)
|
||||
u"""Attempt to perform completion on the text before point. The
|
||||
"""Attempt to perform completion on the text before point. The
|
||||
actual completion performed is application-specific. The default is
|
||||
filename completion."""
|
||||
completions = self._get_completions()
|
||||
@@ -261,7 +262,7 @@ class BaseMode(object):
|
||||
self.l_buffer[self.begidx:self.endidx] = rep
|
||||
self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx)
|
||||
if len(completions) > 1:
|
||||
if self.show_all_if_ambiguous == u'on':
|
||||
if self.show_all_if_ambiguous == 'on':
|
||||
self._display_completions(completions)
|
||||
else:
|
||||
self._bell()
|
||||
@@ -270,13 +271,13 @@ class BaseMode(object):
|
||||
self.finalize()
|
||||
|
||||
def possible_completions(self, e): # (M-?)
|
||||
u"""List the possible completions of the text before point. """
|
||||
"""List the possible completions of the text before point. """
|
||||
completions = self._get_completions()
|
||||
self._display_completions(completions)
|
||||
self.finalize()
|
||||
|
||||
def insert_completions(self, e): # (M-*)
|
||||
u"""Insert all completions of the text before point that would have
|
||||
"""Insert all completions of the text before point that would have
|
||||
been generated by possible-completions."""
|
||||
completions = self._get_completions()
|
||||
b = self.begidx
|
||||
@@ -291,7 +292,7 @@ class BaseMode(object):
|
||||
self.finalize()
|
||||
|
||||
def menu_complete(self, e): # ()
|
||||
u"""Similar to complete, but replaces the word to be completed with a
|
||||
"""Similar to complete, but replaces the word to be completed with a
|
||||
single match from the list of possible completions. Repeated
|
||||
execution of menu-complete steps through the list of possible
|
||||
completions, inserting each match in turn. At the end of the list of
|
||||
@@ -306,95 +307,95 @@ class BaseMode(object):
|
||||
|
||||
|
||||
def insert_text(self, string):
|
||||
u"""Insert text into the command line."""
|
||||
"""Insert text into the command line."""
|
||||
self.l_buffer.insert_text(string, self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def beginning_of_line(self, e): # (C-a)
|
||||
u"""Move to the start of the current line. """
|
||||
"""Move to the start of the current line. """
|
||||
self.l_buffer.beginning_of_line()
|
||||
self.finalize()
|
||||
|
||||
def end_of_line(self, e): # (C-e)
|
||||
u"""Move to the end of the line. """
|
||||
"""Move to the end of the line. """
|
||||
self.l_buffer.end_of_line()
|
||||
self.finalize()
|
||||
|
||||
def forward_char(self, e): # (C-f)
|
||||
u"""Move forward a character. """
|
||||
"""Move forward a character. """
|
||||
self.l_buffer.forward_char(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_char(self, e): # (C-b)
|
||||
u"""Move back a character. """
|
||||
"""Move back a character. """
|
||||
self.l_buffer.backward_char(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def forward_word(self, e): # (M-f)
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.forward_word(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_word(self, e): # (M-b)
|
||||
u"""Move back to the start of the current or previous word. Words are
|
||||
"""Move back to the start of the current or previous word. Words are
|
||||
composed of letters and digits."""
|
||||
self.l_buffer.backward_word(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def forward_word_end(self, e): # ()
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.forward_word_end(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_word_end(self, e): # ()
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.backward_word_end(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
### Movement with extend selection
|
||||
def beginning_of_line_extend_selection(self, e): #
|
||||
u"""Move to the start of the current line. """
|
||||
"""Move to the start of the current line. """
|
||||
self.l_buffer.beginning_of_line_extend_selection()
|
||||
self.finalize()
|
||||
|
||||
def end_of_line_extend_selection(self, e): #
|
||||
u"""Move to the end of the line. """
|
||||
"""Move to the end of the line. """
|
||||
self.l_buffer.end_of_line_extend_selection()
|
||||
self.finalize()
|
||||
|
||||
def forward_char_extend_selection(self, e): #
|
||||
u"""Move forward a character. """
|
||||
"""Move forward a character. """
|
||||
self.l_buffer.forward_char_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_char_extend_selection(self, e): #
|
||||
u"""Move back a character. """
|
||||
"""Move back a character. """
|
||||
self.l_buffer.backward_char_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def forward_word_extend_selection(self, e): #
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.forward_word_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_word_extend_selection(self, e): #
|
||||
u"""Move back to the start of the current or previous word. Words are
|
||||
"""Move back to the start of the current or previous word. Words are
|
||||
composed of letters and digits."""
|
||||
self.l_buffer.backward_word_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def forward_word_end_extend_selection(self, e): #
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_word_end_extend_selection(self, e): #
|
||||
u"""Move forward to the end of the next word. Words are composed of
|
||||
"""Move forward to the end of the next word. Words are composed of
|
||||
letters and digits."""
|
||||
self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
|
||||
self.finalize()
|
||||
@@ -403,19 +404,19 @@ class BaseMode(object):
|
||||
######## Change case
|
||||
|
||||
def upcase_word(self, e): # (M-u)
|
||||
u"""Uppercase the current (or following) word. With a negative
|
||||
"""Uppercase the current (or following) word. With a negative
|
||||
argument, uppercase the previous word, but do not move the cursor."""
|
||||
self.l_buffer.upcase_word()
|
||||
self.finalize()
|
||||
|
||||
def downcase_word(self, e): # (M-l)
|
||||
u"""Lowercase the current (or following) word. With a negative
|
||||
"""Lowercase the current (or following) word. With a negative
|
||||
argument, lowercase the previous word, but do not move the cursor."""
|
||||
self.l_buffer.downcase_word()
|
||||
self.finalize()
|
||||
|
||||
def capitalize_word(self, e): # (M-c)
|
||||
u"""Capitalize the current (or following) word. With a negative
|
||||
"""Capitalize the current (or following) word. With a negative
|
||||
argument, capitalize the previous word, but do not move the cursor."""
|
||||
self.l_buffer.capitalize_word()
|
||||
self.finalize()
|
||||
@@ -423,17 +424,17 @@ class BaseMode(object):
|
||||
|
||||
########
|
||||
def clear_screen(self, e): # (C-l)
|
||||
u"""Clear the screen and redraw the current line, leaving the current
|
||||
"""Clear the screen and redraw the current line, leaving the current
|
||||
line at the top of the screen."""
|
||||
self.console.page()
|
||||
self.finalize()
|
||||
|
||||
def redraw_current_line(self, e): # ()
|
||||
u"""Refresh the current line. By default, this is unbound."""
|
||||
"""Refresh the current line. By default, this is unbound."""
|
||||
self.finalize()
|
||||
|
||||
def accept_line(self, e): # (Newline or Return)
|
||||
u"""Accept the line regardless of where the cursor is. If this line
|
||||
"""Accept the line regardless of where the cursor is. If this line
|
||||
is non-empty, it may be added to the history list for future recall
|
||||
with add_history(). If this line is a modified history line, the
|
||||
history line is restored to its original state."""
|
||||
@@ -441,37 +442,37 @@ class BaseMode(object):
|
||||
return True
|
||||
|
||||
def delete_char(self, e): # (C-d)
|
||||
u"""Delete the character at point. If point is at the beginning of
|
||||
"""Delete the character at point. If point is at the beginning of
|
||||
the line, there are no characters in the line, and the last
|
||||
character typed was not bound to delete-char, then return EOF."""
|
||||
self.l_buffer.delete_char(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_delete_char(self, e): # (Rubout)
|
||||
u"""Delete the character behind the cursor. A numeric argument means
|
||||
"""Delete the character behind the cursor. A numeric argument means
|
||||
to kill the characters instead of deleting them."""
|
||||
self.l_buffer.backward_delete_char(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def backward_delete_word(self, e): # (Control-Rubout)
|
||||
u"""Delete the character behind the cursor. A numeric argument means
|
||||
"""Delete the character behind the cursor. A numeric argument means
|
||||
to kill the characters instead of deleting them."""
|
||||
self.l_buffer.backward_delete_word(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def forward_delete_word(self, e): # (Control-Delete)
|
||||
u"""Delete the character behind the cursor. A numeric argument means
|
||||
"""Delete the character behind the cursor. A numeric argument means
|
||||
to kill the characters instead of deleting them."""
|
||||
self.l_buffer.forward_delete_word(self.argument_reset)
|
||||
self.finalize()
|
||||
|
||||
def delete_horizontal_space(self, e): # ()
|
||||
u"""Delete all spaces and tabs around point. By default, this is unbound. """
|
||||
"""Delete all spaces and tabs around point. By default, this is unbound. """
|
||||
self.l_buffer.delete_horizontal_space()
|
||||
self.finalize()
|
||||
|
||||
def self_insert(self, e): # (a, b, A, 1, !, ...)
|
||||
u"""Insert yourself. """
|
||||
"""Insert yourself. """
|
||||
if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys.
|
||||
self.insert_text(e.char)
|
||||
self.finalize()
|
||||
@@ -480,7 +481,7 @@ class BaseMode(object):
|
||||
# Paste from clipboard
|
||||
|
||||
def paste(self,e):
|
||||
u"""Paste windows clipboard.
|
||||
"""Paste windows clipboard.
|
||||
Assume single line strip other lines and end of line markers and trailing spaces""" #(Control-v)
|
||||
if self.enable_win32_clipboard:
|
||||
txt=clipboard.get_clipboard_text_and_convert(False)
|
||||
@@ -490,7 +491,7 @@ class BaseMode(object):
|
||||
self.finalize()
|
||||
|
||||
def paste_mulitline_code(self,e):
|
||||
u"""Paste windows clipboard as multiline code.
|
||||
"""Paste windows clipboard as multiline code.
|
||||
Removes any empty lines in the code"""
|
||||
reg=re.compile("\r?\n")
|
||||
if self.enable_win32_clipboard:
|
||||
@@ -508,7 +509,7 @@ class BaseMode(object):
|
||||
self.finalize()
|
||||
|
||||
def ipython_paste(self,e):
|
||||
u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is
|
||||
"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is
|
||||
True then try to convert tabseparated data to repr of list of lists or
|
||||
repr of array.
|
||||
If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space"""
|
||||
@@ -523,39 +524,39 @@ class BaseMode(object):
|
||||
|
||||
|
||||
def copy_region_to_clipboard(self, e): # ()
|
||||
u"""Copy the text in the region to the windows clipboard."""
|
||||
"""Copy the text in the region to the windows clipboard."""
|
||||
self.l_buffer.copy_region_to_clipboard()
|
||||
self.finalize()
|
||||
|
||||
def copy_selection_to_clipboard(self, e): # ()
|
||||
u"""Copy the text in the region to the windows clipboard."""
|
||||
"""Copy the text in the region to the windows clipboard."""
|
||||
self.l_buffer.copy_selection_to_clipboard()
|
||||
self.finalize()
|
||||
|
||||
def cut_selection_to_clipboard(self, e): # ()
|
||||
u"""Copy the text in the region to the windows clipboard."""
|
||||
"""Copy the text in the region to the windows clipboard."""
|
||||
self.l_buffer.cut_selection_to_clipboard()
|
||||
self.finalize()
|
||||
|
||||
def dump_functions(self, e): # ()
|
||||
u"""Print all of the functions and their key bindings to the Readline
|
||||
"""Print all of the functions and their key bindings to the Readline
|
||||
output stream. If a numeric argument is supplied, the output is
|
||||
formatted in such a way that it can be made part of an inputrc
|
||||
file. This command is unbound by default."""
|
||||
print
|
||||
print()
|
||||
txt="\n".join(self.rl_settings_to_string())
|
||||
print txt
|
||||
print(txt)
|
||||
self._print_prompt()
|
||||
self.finalize()
|
||||
|
||||
def commonprefix(m):
|
||||
u"Given a list of pathnames, returns the longest common leading component"
|
||||
if not m: return u''
|
||||
"Given a list of pathnames, returns the longest common leading component"
|
||||
if not m: return ''
|
||||
prefix = m[0]
|
||||
for item in m:
|
||||
for i in range(len(prefix)):
|
||||
if prefix[:i+1].lower() != item[:i+1].lower():
|
||||
prefix = prefix[:i]
|
||||
if i == 0: return u''
|
||||
if i == 0: return ''
|
||||
break
|
||||
return prefix
|
||||
|
||||
+166
-165
@@ -6,13 +6,14 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import os, sys, time
|
||||
import pyreadline.logger as logger
|
||||
from pyreadline.logger import log
|
||||
from pyreadline.lineeditor.lineobj import Point
|
||||
import pyreadline.lineeditor.lineobj as lineobj
|
||||
import pyreadline.lineeditor.history as history
|
||||
import basemode
|
||||
from . import basemode
|
||||
from pyreadline.unicode_helper import ensure_unicode
|
||||
|
||||
|
||||
@@ -21,9 +22,9 @@ def format(keyinfo):
|
||||
k = keyinfo + (-1,)
|
||||
else:
|
||||
k = keyinfo + (ord(keyinfo[-1]),)
|
||||
return u"(%s,%s,%s,%s,%x)"%k
|
||||
return "(%s,%s,%s,%s,%x)"%k
|
||||
|
||||
in_ironpython = u"IronPython" in sys.version
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
|
||||
|
||||
class IncrementalSearchPromptMode(object):
|
||||
@@ -43,31 +44,31 @@ class IncrementalSearchPromptMode(object):
|
||||
fwdtuples.append(ktuple)
|
||||
|
||||
|
||||
log(u"IncrementalSearchPromptMode %s %s"%(keyinfo, keytuple))
|
||||
if keyinfo.keyname == u'backspace':
|
||||
log("IncrementalSearchPromptMode %s %s"%(keyinfo, keytuple))
|
||||
if keyinfo.keyname == 'backspace':
|
||||
self.subsearch_query = self.subsearch_query[:-1]
|
||||
if len(self.subsearch_query) > 0:
|
||||
self.line = self.subsearch_fun(self.subsearch_query)
|
||||
else:
|
||||
self._bell()
|
||||
self.line = "" # empty query means no search result
|
||||
elif keyinfo.keyname in [u'return', u'escape']:
|
||||
elif keyinfo.keyname in ['return', 'escape']:
|
||||
self._bell()
|
||||
self.prompt = self.subsearch_oldprompt
|
||||
self.process_keyevent_queue = self.process_keyevent_queue[:-1]
|
||||
self._history.history_cursor = len(self._history.history)
|
||||
if keyinfo.keyname == u'escape':
|
||||
if keyinfo.keyname == 'escape':
|
||||
self.l_buffer.set_line(self.subsearch_old_line)
|
||||
return True
|
||||
elif keyinfo.keyname:
|
||||
pass
|
||||
elif keytuple in revtuples:
|
||||
self.subsearch_fun = self._history.reverse_search_history
|
||||
self.subsearch_prompt = u"reverse-i-search%d`%s': "
|
||||
self.subsearch_prompt = "reverse-i-search%d`%s': "
|
||||
self.line = self.subsearch_fun(self.subsearch_query)
|
||||
elif keytuple in fwdtuples:
|
||||
self.subsearch_fun = self._history.forward_search_history
|
||||
self.subsearch_prompt = u"forward-i-search%d`%s': "
|
||||
self.subsearch_prompt = "forward-i-search%d`%s': "
|
||||
self.line = self.subsearch_fun(self.subsearch_query)
|
||||
elif keyinfo.control == False and keyinfo.meta == False:
|
||||
self.subsearch_query += keyinfo.char
|
||||
@@ -78,10 +79,10 @@ class IncrementalSearchPromptMode(object):
|
||||
self.l_buffer.set_line(self.line)
|
||||
|
||||
def _init_incremental_search(self, searchfun, init_event):
|
||||
u"""Initialize search prompt
|
||||
"""Initialize search prompt
|
||||
"""
|
||||
log("init_incremental_search")
|
||||
self.subsearch_query = u''
|
||||
self.subsearch_query = ''
|
||||
self.subsearch_fun = searchfun
|
||||
self.subsearch_old_line = self.l_buffer.get_line_text()
|
||||
|
||||
@@ -95,16 +96,16 @@ class IncrementalSearchPromptMode(object):
|
||||
self.subsearch_query = self.l_buffer[0:Point].get_line_text()
|
||||
|
||||
if self.subsearch_fun == self.reverse_search_history:
|
||||
self.subsearch_prompt = u"reverse-i-search%d`%s': "
|
||||
self.subsearch_prompt = "reverse-i-search%d`%s': "
|
||||
else:
|
||||
self.subsearch_prompt = u"forward-i-search%d`%s': "
|
||||
self.subsearch_prompt = "forward-i-search%d`%s': "
|
||||
|
||||
self.prompt = self.subsearch_prompt%(self._history.history_cursor, "")
|
||||
|
||||
if self.subsearch_query:
|
||||
self.line = self._process_incremental_search_keyevent(init_event)
|
||||
else:
|
||||
self.line = u""
|
||||
self.line = ""
|
||||
|
||||
|
||||
class SearchPromptMode(object):
|
||||
@@ -113,12 +114,12 @@ class SearchPromptMode(object):
|
||||
|
||||
def _process_non_incremental_search_keyevent(self, keyinfo):
|
||||
keytuple = keyinfo.tuple()
|
||||
log(u"SearchPromptMode %s %s"%(keyinfo, keytuple))
|
||||
log("SearchPromptMode %s %s"%(keyinfo, keytuple))
|
||||
history = self._history
|
||||
|
||||
if keyinfo.keyname == u'backspace':
|
||||
if keyinfo.keyname == 'backspace':
|
||||
self.non_inc_query = self.non_inc_query[:-1]
|
||||
elif keyinfo.keyname in [u'return', u'escape']:
|
||||
elif keyinfo.keyname in ['return', 'escape']:
|
||||
if self.non_inc_query:
|
||||
if self.non_inc_direction == -1:
|
||||
res = history.reverse_search_history(self.non_inc_query)
|
||||
@@ -129,7 +130,7 @@ class SearchPromptMode(object):
|
||||
self.prompt = self.non_inc_oldprompt
|
||||
self.process_keyevent_queue = self.process_keyevent_queue[:-1]
|
||||
self._history.history_cursor = len(self._history.history)
|
||||
if keyinfo.keyname == u'escape':
|
||||
if keyinfo.keyname == 'escape':
|
||||
self.l_buffer = self.non_inc_oldline
|
||||
else:
|
||||
self.l_buffer.set_line(res)
|
||||
@@ -140,26 +141,26 @@ class SearchPromptMode(object):
|
||||
self.non_inc_query += keyinfo.char
|
||||
else:
|
||||
pass
|
||||
self.prompt = self.non_inc_oldprompt + u":" + self.non_inc_query
|
||||
self.prompt = self.non_inc_oldprompt + ":" + self.non_inc_query
|
||||
|
||||
def _init_non_i_search(self, direction):
|
||||
self.non_inc_direction = direction
|
||||
self.non_inc_query = u""
|
||||
self.non_inc_query = ""
|
||||
self.non_inc_oldprompt = self.prompt
|
||||
self.non_inc_oldline = self.l_buffer.copy()
|
||||
self.l_buffer.reset_line()
|
||||
self.prompt = self.non_inc_oldprompt + u":"
|
||||
self.prompt = self.non_inc_oldprompt + ":"
|
||||
queue = self.process_keyevent_queue
|
||||
queue.append(self._process_non_incremental_search_keyevent)
|
||||
|
||||
def non_incremental_reverse_search_history(self, e): # (M-p)
|
||||
u'''Search backward starting at the current line and moving up
|
||||
'''Search backward starting at the current line and moving up
|
||||
through the history as necessary using a non-incremental search for
|
||||
a string supplied by the user.'''
|
||||
return self._init_non_i_search(-1)
|
||||
|
||||
def non_incremental_forward_search_history(self, e): # (M-n)
|
||||
u'''Search forward starting at the current line and moving down
|
||||
'''Search forward starting at the current line and moving down
|
||||
through the the history as necessary using a non-incremental search
|
||||
for a string supplied by the user.'''
|
||||
return self._init_non_i_search(1)
|
||||
@@ -174,24 +175,24 @@ class DigitArgumentMode(object):
|
||||
pass
|
||||
|
||||
def _process_digit_argument_keyevent(self, keyinfo):
|
||||
log(u"DigitArgumentMode.keyinfo %s"%keyinfo)
|
||||
log("DigitArgumentMode.keyinfo %s"%keyinfo)
|
||||
keytuple = keyinfo.tuple()
|
||||
log(u"DigitArgumentMode.keytuple %s %s"%(keyinfo, keytuple))
|
||||
log("DigitArgumentMode.keytuple %s %s"%(keyinfo, keytuple))
|
||||
if keyinfo.keyname in ['return']:
|
||||
self.prompt = self._digit_argument_oldprompt
|
||||
self.process_keyevent_queue = self.process_keyevent_queue[:-1]
|
||||
return True
|
||||
elif keyinfo.keyname:
|
||||
pass
|
||||
elif (keyinfo.char in u"0123456789" and
|
||||
elif (keyinfo.char in "0123456789" and
|
||||
keyinfo.control == False and
|
||||
keyinfo.meta == False):
|
||||
log(u"arg %s %s"%(self.argument, keyinfo.char))
|
||||
log("arg %s %s"%(self.argument, keyinfo.char))
|
||||
self.argument = self.argument * 10 + int(keyinfo.char)
|
||||
else:
|
||||
self.prompt = self._digit_argument_oldprompt
|
||||
raise LeaveModeTryNext
|
||||
self.prompt = u"(arg: %s) "%self.argument
|
||||
self.prompt = "(arg: %s) "%self.argument
|
||||
|
||||
def _init_digit_argument(self, keyinfo):
|
||||
"""Initialize search prompt
|
||||
@@ -205,11 +206,11 @@ class DigitArgumentMode(object):
|
||||
|
||||
if keyinfo.char == "-":
|
||||
self.argument = -1
|
||||
elif keyinfo.char in u"0123456789":
|
||||
elif keyinfo.char in "0123456789":
|
||||
self.argument = int(keyinfo.char)
|
||||
log(u"<%s> %s"%(self.argument, type(self.argument)))
|
||||
self.prompt = u"(arg: %s) "%self.argument
|
||||
log(u"arg-init %s %s"%(self.argument, keyinfo.char))
|
||||
log("<%s> %s"%(self.argument, type(self.argument)))
|
||||
self.prompt = "(arg: %s) "%self.argument
|
||||
log("arg-init %s %s"%(self.argument, keyinfo.char))
|
||||
|
||||
|
||||
class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
@@ -223,18 +224,18 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
DigitArgumentMode.__init__(self, rlobj)
|
||||
self._keylog = (lambda x, y: None)
|
||||
self.previous_func = None
|
||||
self.prompt = u">>> "
|
||||
self.prompt = ">>> "
|
||||
self._insert_verbatim = False
|
||||
self.next_meta = False # True to force meta on next character
|
||||
|
||||
self.process_keyevent_queue = [self._process_keyevent]
|
||||
|
||||
def __repr__(self):
|
||||
return u"<EmacsMode>"
|
||||
return "<EmacsMode>"
|
||||
|
||||
def add_key_logger(self, logfun):
|
||||
u"""logfun should be function that takes disp_fun and line_"""\
|
||||
u"""buffer object """
|
||||
"""logfun should be function that takes disp_fun and line_"""\
|
||||
"""buffer object """
|
||||
self._keylog = logfun
|
||||
|
||||
def process_keyevent(self, keyinfo):
|
||||
@@ -249,10 +250,10 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
return False
|
||||
|
||||
def _process_keyevent(self, keyinfo):
|
||||
u"""return True when line is final
|
||||
"""return True when line is final
|
||||
"""
|
||||
#Process exit keys. Only exit on empty line
|
||||
log(u"_process_keyevent <%s>"%keyinfo)
|
||||
log("_process_keyevent <%s>"%keyinfo)
|
||||
|
||||
def nop(e):
|
||||
pass
|
||||
@@ -269,7 +270,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
|
||||
if keytuple in self.exit_dispatch:
|
||||
pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer))
|
||||
log(u"exit_dispatch:<%s, %s>"%pars)
|
||||
log("exit_dispatch:<%s, %s>"%pars)
|
||||
if lineobj.EndOfLine(self.l_buffer) == 0:
|
||||
raise EOFError
|
||||
if keyinfo.keyname or keyinfo.control or keyinfo.meta:
|
||||
@@ -278,7 +279,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
default = self.self_insert
|
||||
dispatch_func = self.key_dispatch.get(keytuple, default)
|
||||
|
||||
log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func))
|
||||
log("readline from keyboard:<%s,%s>"%(keytuple, dispatch_func))
|
||||
|
||||
r = None
|
||||
if dispatch_func:
|
||||
@@ -291,38 +292,38 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
|
||||
######### History commands
|
||||
def previous_history(self, e): # (C-p)
|
||||
u'''Move back through the history list, fetching the previous
|
||||
'''Move back through the history list, fetching the previous
|
||||
command. '''
|
||||
self._history.previous_history(self.l_buffer)
|
||||
self.l_buffer.point = lineobj.EndOfLine
|
||||
self.finalize()
|
||||
|
||||
def next_history(self, e): # (C-n)
|
||||
u'''Move forward through the history list, fetching the next
|
||||
'''Move forward through the history list, fetching the next
|
||||
command. '''
|
||||
self._history.next_history(self.l_buffer)
|
||||
self.finalize()
|
||||
|
||||
def beginning_of_history(self, e): # (M-<)
|
||||
u'''Move to the first line in the history.'''
|
||||
'''Move to the first line in the history.'''
|
||||
self._history.beginning_of_history()
|
||||
self.finalize()
|
||||
|
||||
def end_of_history(self, e): # (M->)
|
||||
u'''Move to the end of the input history, i.e., the line currently
|
||||
'''Move to the end of the input history, i.e., the line currently
|
||||
being entered.'''
|
||||
self._history.end_of_history(self.l_buffer)
|
||||
self.finalize()
|
||||
|
||||
def reverse_search_history(self, e): # (C-r)
|
||||
u'''Search backward starting at the current line and moving up
|
||||
'''Search backward starting at the current line and moving up
|
||||
through the history as necessary. This is an incremental search.'''
|
||||
log("rev_search_history")
|
||||
self._init_incremental_search(self._history.reverse_search_history, e)
|
||||
self.finalize()
|
||||
|
||||
def forward_search_history(self, e): # (C-s)
|
||||
u'''Search forward starting at the current line and moving down
|
||||
'''Search forward starting at the current line and moving down
|
||||
through the the history as necessary. This is an incremental
|
||||
search.'''
|
||||
log("fwd_search_history")
|
||||
@@ -330,7 +331,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def history_search_forward(self, e): # ()
|
||||
u'''Search forward through the history for the string of characters
|
||||
'''Search forward through the history for the string of characters
|
||||
between the start of the current line and the point. This is a
|
||||
non-incremental search. By default, this command is unbound.'''
|
||||
if (self.previous_func and
|
||||
@@ -345,7 +346,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def history_search_backward(self, e): # ()
|
||||
u'''Search backward through the history for the string of characters
|
||||
'''Search backward through the history for the string of characters
|
||||
between the start of the current line and the point. This is a
|
||||
non-incremental search. By default, this command is unbound.'''
|
||||
if (self.previous_func and
|
||||
@@ -360,7 +361,7 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def yank_nth_arg(self, e): # (M-C-y)
|
||||
u'''Insert the first argument to the previous command (usually the
|
||||
'''Insert the first argument to the previous command (usually the
|
||||
second word on the previous line) at point. With an argument n,
|
||||
insert the nth word from the previous command (the words in the
|
||||
previous command begin with word 0). A negative argument inserts the
|
||||
@@ -368,33 +369,33 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def yank_last_arg(self, e): # (M-. or M-_)
|
||||
u'''Insert last argument to the previous command (the last word of
|
||||
'''Insert last argument to the previous command (the last word of
|
||||
the previous history entry). With an argument, behave exactly like
|
||||
yank-nth-arg. Successive calls to yank-last-arg move back through
|
||||
the history list, inserting the last argument of each line in turn.'''
|
||||
self.finalize()
|
||||
|
||||
def forward_backward_delete_char(self, e): # ()
|
||||
u'''Delete the character under the cursor, unless the cursor is at
|
||||
'''Delete the character under the cursor, unless the cursor is at
|
||||
the end of the line, in which case the character behind the cursor
|
||||
is deleted. By default, this is not bound to a key.'''
|
||||
self.finalize()
|
||||
|
||||
def quoted_insert(self, e): # (C-q or C-v)
|
||||
u'''Add the next character typed to the line verbatim. This is how to
|
||||
'''Add the next character typed to the line verbatim. This is how to
|
||||
insert key sequences like C-q, for example.'''
|
||||
self._insert_verbatim = True
|
||||
self.finalize()
|
||||
|
||||
def tab_insert(self, e): # (M-TAB)
|
||||
u'''Insert a tab character. '''
|
||||
'''Insert a tab character. '''
|
||||
cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
|
||||
ws = ' ' * (self.tabstop - (cursor % self.tabstop))
|
||||
self.insert_text(ws)
|
||||
self.finalize()
|
||||
|
||||
def transpose_chars(self, e): # (C-t)
|
||||
u'''Drag the character before the cursor forward over the character
|
||||
'''Drag the character before the cursor forward over the character
|
||||
at the cursor, moving the cursor forward as well. If the insertion
|
||||
point is at the end of the line, then this transposes the last two
|
||||
characters of the line. Negative arguments have no effect.'''
|
||||
@@ -402,14 +403,14 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def transpose_words(self, e): # (M-t)
|
||||
u'''Drag the word before point past the word after point, moving
|
||||
'''Drag the word before point past the word after point, moving
|
||||
point past that word as well. If the insertion point is at the end
|
||||
of the line, this transposes the last two words on the line.'''
|
||||
self.l_buffer.transpose_words()
|
||||
self.finalize()
|
||||
|
||||
def overwrite_mode(self, e): # ()
|
||||
u'''Toggle overwrite mode. With an explicit positive numeric
|
||||
'''Toggle overwrite mode. With an explicit positive numeric
|
||||
argument, switches to overwrite mode. With an explicit non-positive
|
||||
numeric argument, switches to insert mode. This command affects only
|
||||
emacs mode; vi mode does overwrite differently. Each call to
|
||||
@@ -420,30 +421,30 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def kill_line(self, e): # (C-k)
|
||||
u'''Kill the text from point to the end of the line. '''
|
||||
'''Kill the text from point to the end of the line. '''
|
||||
self.l_buffer.kill_line()
|
||||
self.finalize()
|
||||
|
||||
def backward_kill_line(self, e): # (C-x Rubout)
|
||||
u'''Kill backward to the beginning of the line. '''
|
||||
'''Kill backward to the beginning of the line. '''
|
||||
self.l_buffer.backward_kill_line()
|
||||
self.finalize()
|
||||
|
||||
def unix_line_discard(self, e): # (C-u)
|
||||
u'''Kill backward from the cursor to the beginning of the current
|
||||
'''Kill backward from the cursor to the beginning of the current
|
||||
line. '''
|
||||
# how is this different from backward_kill_line?
|
||||
self.l_buffer.unix_line_discard()
|
||||
self.finalize()
|
||||
|
||||
def kill_whole_line(self, e): # ()
|
||||
u'''Kill all characters on the current line, no matter where point
|
||||
'''Kill all characters on the current line, no matter where point
|
||||
is. By default, this is unbound.'''
|
||||
self.l_buffer.kill_whole_line()
|
||||
self.finalize()
|
||||
|
||||
def kill_word(self, e): # (M-d)
|
||||
u'''Kill from point to the end of the current word, or if between
|
||||
'''Kill from point to the end of the current word, or if between
|
||||
words, to the end of the next word. Word boundaries are the same as
|
||||
forward-word.'''
|
||||
self.l_buffer.kill_word()
|
||||
@@ -452,133 +453,133 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
forward_kill_word = kill_word
|
||||
|
||||
def backward_kill_word(self, e): # (M-DEL)
|
||||
u'''Kill the word behind point. Word boundaries are the same as
|
||||
'''Kill the word behind point. Word boundaries are the same as
|
||||
backward-word. '''
|
||||
self.l_buffer.backward_kill_word()
|
||||
self.finalize()
|
||||
|
||||
def unix_word_rubout(self, e): # (C-w)
|
||||
u'''Kill the word behind point, using white space as a word
|
||||
'''Kill the word behind point, using white space as a word
|
||||
boundary. The killed text is saved on the kill-ring.'''
|
||||
self.l_buffer.unix_word_rubout()
|
||||
self.finalize()
|
||||
|
||||
def kill_region(self, e): # ()
|
||||
u'''Kill the text in the current region. By default, this command is
|
||||
'''Kill the text in the current region. By default, this command is
|
||||
unbound. '''
|
||||
self.finalize()
|
||||
|
||||
def copy_region_as_kill(self, e): # ()
|
||||
u'''Copy the text in the region to the kill buffer, so it can be
|
||||
'''Copy the text in the region to the kill buffer, so it can be
|
||||
yanked right away. By default, this command is unbound.'''
|
||||
self.finalize()
|
||||
|
||||
def copy_backward_word(self, e): # ()
|
||||
u'''Copy the word before point to the kill buffer. The word
|
||||
'''Copy the word before point to the kill buffer. The word
|
||||
boundaries are the same as backward-word. By default, this command
|
||||
is unbound.'''
|
||||
self.finalize()
|
||||
|
||||
def copy_forward_word(self, e): # ()
|
||||
u'''Copy the word following point to the kill buffer. The word
|
||||
'''Copy the word following point to the kill buffer. The word
|
||||
boundaries are the same as forward-word. By default, this command is
|
||||
unbound.'''
|
||||
self.finalize()
|
||||
|
||||
def yank(self, e): # (C-y)
|
||||
u'''Yank the top of the kill ring into the buffer at point. '''
|
||||
'''Yank the top of the kill ring into the buffer at point. '''
|
||||
self.l_buffer.yank()
|
||||
self.finalize()
|
||||
|
||||
def yank_pop(self, e): # (M-y)
|
||||
u'''Rotate the kill-ring, and yank the new top. You can only do this
|
||||
'''Rotate the kill-ring, and yank the new top. You can only do this
|
||||
if the prior command is yank or yank-pop.'''
|
||||
self.l_buffer.yank_pop()
|
||||
self.finalize()
|
||||
|
||||
def delete_char_or_list(self, e): # ()
|
||||
u'''Deletes the character under the cursor if not at the beginning or
|
||||
'''Deletes the character under the cursor if not at the beginning or
|
||||
end of the line (like delete-char). If at the end of the line,
|
||||
behaves identically to possible-completions. This command is unbound
|
||||
by default.'''
|
||||
self.finalize()
|
||||
|
||||
def start_kbd_macro(self, e): # (C-x ()
|
||||
u'''Begin saving the characters typed into the current keyboard
|
||||
'''Begin saving the characters typed into the current keyboard
|
||||
macro. '''
|
||||
self.finalize()
|
||||
|
||||
def end_kbd_macro(self, e): # (C-x ))
|
||||
u'''Stop saving the characters typed into the current keyboard macro
|
||||
'''Stop saving the characters typed into the current keyboard macro
|
||||
and save the definition.'''
|
||||
self.finalize()
|
||||
|
||||
def call_last_kbd_macro(self, e): # (C-x e)
|
||||
u'''Re-execute the last keyboard macro defined, by making the
|
||||
'''Re-execute the last keyboard macro defined, by making the
|
||||
characters in the macro appear as if typed at the keyboard.'''
|
||||
self.finalize()
|
||||
|
||||
def re_read_init_file(self, e): # (C-x C-r)
|
||||
u'''Read in the contents of the inputrc file, and incorporate any
|
||||
'''Read in the contents of the inputrc file, and incorporate any
|
||||
bindings or variable assignments found there.'''
|
||||
self.finalize()
|
||||
|
||||
def abort(self, e): # (C-g)
|
||||
u'''Abort the current editing command and ring the terminals bell
|
||||
'''Abort the current editing command and ring the terminals bell
|
||||
(subject to the setting of bell-style).'''
|
||||
self._bell()
|
||||
self.finalize()
|
||||
|
||||
def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
|
||||
u'''If the metafied character x is lowercase, run the command that is
|
||||
'''If the metafied character x is lowercase, run the command that is
|
||||
bound to the corresponding uppercase character.'''
|
||||
self.finalize()
|
||||
|
||||
def prefix_meta(self, e): # (ESC)
|
||||
u'''Metafy the next character typed. This is for keyboards without a
|
||||
'''Metafy the next character typed. This is for keyboards without a
|
||||
meta key. Typing ESC f is equivalent to typing M-f. '''
|
||||
self.next_meta = True
|
||||
self.finalize()
|
||||
|
||||
def undo(self, e): # (C-_ or C-x C-u)
|
||||
u'''Incremental undo, separately remembered for each line.'''
|
||||
'''Incremental undo, separately remembered for each line.'''
|
||||
self.l_buffer.pop_undo()
|
||||
self.finalize()
|
||||
|
||||
def revert_line(self, e): # (M-r)
|
||||
u'''Undo all changes made to this line. This is like executing the
|
||||
'''Undo all changes made to this line. This is like executing the
|
||||
undo command enough times to get back to the beginning.'''
|
||||
self.finalize()
|
||||
|
||||
def tilde_expand(self, e): # (M-~)
|
||||
u'''Perform tilde expansion on the current word.'''
|
||||
'''Perform tilde expansion on the current word.'''
|
||||
self.finalize()
|
||||
|
||||
def set_mark(self, e): # (C-@)
|
||||
u'''Set the mark to the point. If a numeric argument is supplied, the
|
||||
'''Set the mark to the point. If a numeric argument is supplied, the
|
||||
mark is set to that position.'''
|
||||
self.l_buffer.set_mark()
|
||||
self.finalize()
|
||||
|
||||
def exchange_point_and_mark(self, e): # (C-x C-x)
|
||||
u'''Swap the point with the mark. The current cursor position is set
|
||||
'''Swap the point with the mark. The current cursor position is set
|
||||
to the saved position, and the old cursor position is saved as the
|
||||
mark.'''
|
||||
self.finalize()
|
||||
|
||||
def character_search(self, e): # (C-])
|
||||
u'''A character is read and point is moved to the next occurrence of
|
||||
'''A character is read and point is moved to the next occurrence of
|
||||
that character. A negative count searches for previous occurrences.'''
|
||||
self.finalize()
|
||||
|
||||
def character_search_backward(self, e): # (M-C-])
|
||||
u'''A character is read and point is moved to the previous occurrence
|
||||
'''A character is read and point is moved to the previous occurrence
|
||||
of that character. A negative count searches for subsequent
|
||||
occurrences.'''
|
||||
self.finalize()
|
||||
|
||||
def insert_comment(self, e): # (M-#)
|
||||
u'''Without a numeric argument, the value of the comment-begin
|
||||
'''Without a numeric argument, the value of the comment-begin
|
||||
variable is inserted at the beginning of the current line. If a
|
||||
numeric argument is supplied, this command acts as a toggle: if the
|
||||
characters at the beginning of the line do not match the value of
|
||||
@@ -588,27 +589,27 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
self.finalize()
|
||||
|
||||
def dump_variables(self, e): # ()
|
||||
u'''Print all of the settable variables and their values to the
|
||||
'''Print all of the settable variables and their values to the
|
||||
Readline output stream. If a numeric argument is supplied, the
|
||||
output is formatted in such a way that it can be made part of an
|
||||
inputrc file. This command is unbound by default.'''
|
||||
self.finalize()
|
||||
|
||||
def dump_macros(self, e): # ()
|
||||
u'''Print all of the Readline key sequences bound to macros and the
|
||||
'''Print all of the Readline key sequences bound to macros and the
|
||||
strings they output. If a numeric argument is supplied, the output
|
||||
is formatted in such a way that it can be made part of an inputrc
|
||||
file. This command is unbound by default.'''
|
||||
self.finalize()
|
||||
|
||||
def digit_argument(self, e): # (M-0, M-1, ... M--)
|
||||
u'''Add this digit to the argument already accumulating, or start a
|
||||
'''Add this digit to the argument already accumulating, or start a
|
||||
new argument. M-- starts a negative argument.'''
|
||||
self._init_digit_argument(e)
|
||||
#Should not finalize
|
||||
|
||||
def universal_argument(self, e): # ()
|
||||
u'''This is another way to specify an argument. If this command is
|
||||
'''This is another way to specify an argument. If this command is
|
||||
followed by one or more digits, optionally with a leading minus
|
||||
sign, those digits define the argument. If the command is followed
|
||||
by digits, executing universal-argument again ends the numeric
|
||||
@@ -623,100 +624,100 @@ class EmacsMode(DigitArgumentMode, IncrementalSearchPromptMode,
|
||||
|
||||
#Create key bindings:
|
||||
def init_editing_mode(self, e): # (C-e)
|
||||
u'''When in vi command mode, this causes a switch to emacs editing
|
||||
'''When in vi command mode, this causes a switch to emacs editing
|
||||
mode.'''
|
||||
self._bind_exit_key(u'Control-d')
|
||||
self._bind_exit_key(u'Control-z')
|
||||
self._bind_exit_key('Control-d')
|
||||
self._bind_exit_key('Control-z')
|
||||
|
||||
# I often accidentally hold the shift or control while typing space
|
||||
self._bind_key(u'space', self.self_insert)
|
||||
self._bind_key(u'Shift-space', self.self_insert)
|
||||
self._bind_key(u'Control-space', self.self_insert)
|
||||
self._bind_key(u'Return', self.accept_line)
|
||||
self._bind_key(u'Left', self.backward_char)
|
||||
self._bind_key(u'Control-b', self.backward_char)
|
||||
self._bind_key(u'Right', self.forward_char)
|
||||
self._bind_key(u'Control-f', self.forward_char)
|
||||
self._bind_key(u'Control-h', self.backward_delete_char)
|
||||
self._bind_key(u'BackSpace', self.backward_delete_char)
|
||||
self._bind_key(u'Control-BackSpace', self.backward_delete_word)
|
||||
self._bind_key('space', self.self_insert)
|
||||
self._bind_key('Shift-space', self.self_insert)
|
||||
self._bind_key('Control-space', self.self_insert)
|
||||
self._bind_key('Return', self.accept_line)
|
||||
self._bind_key('Left', self.backward_char)
|
||||
self._bind_key('Control-b', self.backward_char)
|
||||
self._bind_key('Right', self.forward_char)
|
||||
self._bind_key('Control-f', self.forward_char)
|
||||
self._bind_key('Control-h', self.backward_delete_char)
|
||||
self._bind_key('BackSpace', self.backward_delete_char)
|
||||
self._bind_key('Control-BackSpace', self.backward_delete_word)
|
||||
|
||||
self._bind_key(u'Home', self.beginning_of_line)
|
||||
self._bind_key(u'End', self.end_of_line)
|
||||
self._bind_key(u'Delete', self.delete_char)
|
||||
self._bind_key(u'Control-d', self.delete_char)
|
||||
self._bind_key(u'Clear', self.clear_screen)
|
||||
self._bind_key(u'Alt-f', self.forward_word)
|
||||
self._bind_key(u'Alt-b', self.backward_word)
|
||||
self._bind_key(u'Control-l', self.clear_screen)
|
||||
self._bind_key(u'Control-p', self.previous_history)
|
||||
self._bind_key(u'Up', self.history_search_backward)
|
||||
self._bind_key(u'Control-n', self.next_history)
|
||||
self._bind_key(u'Down', self.history_search_forward)
|
||||
self._bind_key(u'Control-a', self.beginning_of_line)
|
||||
self._bind_key(u'Control-e', self.end_of_line)
|
||||
self._bind_key(u'Alt-<', self.beginning_of_history)
|
||||
self._bind_key(u'Alt->', self.end_of_history)
|
||||
self._bind_key(u'Control-r', self.reverse_search_history)
|
||||
self._bind_key(u'Control-s', self.forward_search_history)
|
||||
self._bind_key(u'Control-Shift-r', self.forward_search_history)
|
||||
self._bind_key(u'Alt-p',
|
||||
self._bind_key('Home', self.beginning_of_line)
|
||||
self._bind_key('End', self.end_of_line)
|
||||
self._bind_key('Delete', self.delete_char)
|
||||
self._bind_key('Control-d', self.delete_char)
|
||||
self._bind_key('Clear', self.clear_screen)
|
||||
self._bind_key('Alt-f', self.forward_word)
|
||||
self._bind_key('Alt-b', self.backward_word)
|
||||
self._bind_key('Control-l', self.clear_screen)
|
||||
self._bind_key('Control-p', self.previous_history)
|
||||
self._bind_key('Up', self.history_search_backward)
|
||||
self._bind_key('Control-n', self.next_history)
|
||||
self._bind_key('Down', self.history_search_forward)
|
||||
self._bind_key('Control-a', self.beginning_of_line)
|
||||
self._bind_key('Control-e', self.end_of_line)
|
||||
self._bind_key('Alt-<', self.beginning_of_history)
|
||||
self._bind_key('Alt->', self.end_of_history)
|
||||
self._bind_key('Control-r', self.reverse_search_history)
|
||||
self._bind_key('Control-s', self.forward_search_history)
|
||||
self._bind_key('Control-Shift-r', self.forward_search_history)
|
||||
self._bind_key('Alt-p',
|
||||
self.non_incremental_reverse_search_history)
|
||||
self._bind_key(u'Alt-n',
|
||||
self._bind_key('Alt-n',
|
||||
self.non_incremental_forward_search_history)
|
||||
self._bind_key(u'Control-z', self.undo)
|
||||
self._bind_key(u'Control-_', self.undo)
|
||||
self._bind_key(u'Escape', self.kill_whole_line)
|
||||
self._bind_key(u'Meta-d', self.kill_word)
|
||||
self._bind_key(u'Control-Delete', self.forward_delete_word)
|
||||
self._bind_key(u'Control-w', self.unix_word_rubout)
|
||||
self._bind_key('Control-z', self.undo)
|
||||
self._bind_key('Control-_', self.undo)
|
||||
self._bind_key('Escape', self.kill_whole_line)
|
||||
self._bind_key('Meta-d', self.kill_word)
|
||||
self._bind_key('Control-Delete', self.forward_delete_word)
|
||||
self._bind_key('Control-w', self.unix_word_rubout)
|
||||
#self._bind_key('Control-Shift-v', self.quoted_insert)
|
||||
self._bind_key(u'Control-v', self.paste)
|
||||
self._bind_key(u'Alt-v', self.ipython_paste)
|
||||
self._bind_key(u'Control-y', self.yank)
|
||||
self._bind_key(u'Control-k', self.kill_line)
|
||||
self._bind_key(u'Control-m', self.set_mark)
|
||||
self._bind_key(u'Control-q', self.copy_region_to_clipboard)
|
||||
self._bind_key('Control-v', self.paste)
|
||||
self._bind_key('Alt-v', self.ipython_paste)
|
||||
self._bind_key('Control-y', self.yank)
|
||||
self._bind_key('Control-k', self.kill_line)
|
||||
self._bind_key('Control-m', self.set_mark)
|
||||
self._bind_key('Control-q', self.copy_region_to_clipboard)
|
||||
# self._bind_key('Control-shift-k', self.kill_whole_line)
|
||||
self._bind_key(u'Control-Shift-v', self.paste_mulitline_code)
|
||||
self._bind_key(u"Control-Right", self.forward_word_end)
|
||||
self._bind_key(u"Control-Left", self.backward_word)
|
||||
self._bind_key(u"Shift-Right",
|
||||
self._bind_key('Control-Shift-v', self.paste_mulitline_code)
|
||||
self._bind_key("Control-Right", self.forward_word_end)
|
||||
self._bind_key("Control-Left", self.backward_word)
|
||||
self._bind_key("Shift-Right",
|
||||
self.forward_char_extend_selection)
|
||||
self._bind_key(u"Shift-Left",
|
||||
self._bind_key("Shift-Left",
|
||||
self.backward_char_extend_selection)
|
||||
self._bind_key(u"Shift-Control-Right",
|
||||
self._bind_key("Shift-Control-Right",
|
||||
self.forward_word_end_extend_selection)
|
||||
self._bind_key(u"Shift-Control-Left",
|
||||
self._bind_key("Shift-Control-Left",
|
||||
self.backward_word_extend_selection)
|
||||
self._bind_key(u"Shift-Home",
|
||||
self._bind_key("Shift-Home",
|
||||
self.beginning_of_line_extend_selection)
|
||||
self._bind_key(u"Shift-End",
|
||||
self._bind_key("Shift-End",
|
||||
self.end_of_line_extend_selection)
|
||||
self._bind_key(u"numpad0", self.self_insert)
|
||||
self._bind_key(u"numpad1", self.self_insert)
|
||||
self._bind_key(u"numpad2", self.self_insert)
|
||||
self._bind_key(u"numpad3", self.self_insert)
|
||||
self._bind_key(u"numpad4", self.self_insert)
|
||||
self._bind_key(u"numpad5", self.self_insert)
|
||||
self._bind_key(u"numpad6", self.self_insert)
|
||||
self._bind_key(u"numpad7", self.self_insert)
|
||||
self._bind_key(u"numpad8", self.self_insert)
|
||||
self._bind_key(u"numpad9", self.self_insert)
|
||||
self._bind_key(u"add", self.self_insert)
|
||||
self._bind_key(u"subtract", self.self_insert)
|
||||
self._bind_key(u"multiply", self.self_insert)
|
||||
self._bind_key(u"divide", self.self_insert)
|
||||
self._bind_key(u"vk_decimal", self.self_insert)
|
||||
log(u"RUNNING INIT EMACS")
|
||||
self._bind_key("numpad0", self.self_insert)
|
||||
self._bind_key("numpad1", self.self_insert)
|
||||
self._bind_key("numpad2", self.self_insert)
|
||||
self._bind_key("numpad3", self.self_insert)
|
||||
self._bind_key("numpad4", self.self_insert)
|
||||
self._bind_key("numpad5", self.self_insert)
|
||||
self._bind_key("numpad6", self.self_insert)
|
||||
self._bind_key("numpad7", self.self_insert)
|
||||
self._bind_key("numpad8", self.self_insert)
|
||||
self._bind_key("numpad9", self.self_insert)
|
||||
self._bind_key("add", self.self_insert)
|
||||
self._bind_key("subtract", self.self_insert)
|
||||
self._bind_key("multiply", self.self_insert)
|
||||
self._bind_key("divide", self.self_insert)
|
||||
self._bind_key("vk_decimal", self.self_insert)
|
||||
log("RUNNING INIT EMACS")
|
||||
for i in range(0, 10):
|
||||
self._bind_key(u"alt-%d"%i, self.digit_argument)
|
||||
self._bind_key(u"alt--", self.digit_argument)
|
||||
self._bind_key("alt-%d"%i, self.digit_argument)
|
||||
self._bind_key("alt--", self.digit_argument)
|
||||
|
||||
|
||||
# make it case insensitive
|
||||
def commonprefix(m):
|
||||
u"Given a list of pathnames, returns the longest common leading component"
|
||||
"Given a list of pathnames, returns the longest common leading component"
|
||||
if not m:
|
||||
return ''
|
||||
prefix = m[0]
|
||||
@@ -725,6 +726,6 @@ def commonprefix(m):
|
||||
if prefix[:i + 1].lower() != item[:i + 1].lower():
|
||||
prefix = prefix[:i]
|
||||
if i == 0:
|
||||
return u''
|
||||
return ''
|
||||
break
|
||||
return prefix
|
||||
|
||||
+119
-118
@@ -6,20 +6,21 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import os
|
||||
import pyreadline.logger as logger
|
||||
from pyreadline.logger import log
|
||||
import pyreadline.lineeditor.lineobj as lineobj
|
||||
import pyreadline.lineeditor.history as history
|
||||
import basemode
|
||||
from . import basemode
|
||||
|
||||
class NotEmacsMode(basemode.BaseMode):
|
||||
mode=u"notemacs"
|
||||
mode="notemacs"
|
||||
def __init__(self,rlobj):
|
||||
super(NotEmacsMode,self).__init__(rlobj)
|
||||
|
||||
def __repr__(self):
|
||||
return u"<NotEmacsMode>"
|
||||
return "<NotEmacsMode>"
|
||||
|
||||
def _readline_from_keyboard(self):
|
||||
c=self.console
|
||||
@@ -37,7 +38,7 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
raise EOFError
|
||||
|
||||
dispatch_func = self.key_dispatch.get(event.keyinfo,self.self_insert)
|
||||
log(u"readline from keyboard:%s"%(event.keyinfo,))
|
||||
log("readline from keyboard:%s"%(event.keyinfo,))
|
||||
r = None
|
||||
if dispatch_func:
|
||||
r = dispatch_func(event)
|
||||
@@ -49,7 +50,7 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
break
|
||||
|
||||
def readline(self, prompt=''):
|
||||
u'''Try to act like GNU readline.'''
|
||||
'''Try to act like GNU readline.'''
|
||||
# handle startup_hook
|
||||
if self.first_prompt:
|
||||
self.first_prompt = False
|
||||
@@ -57,7 +58,7 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
try:
|
||||
self.startup_hook()
|
||||
except:
|
||||
print u'startup hook failed'
|
||||
print('startup hook failed')
|
||||
traceback.print_exc()
|
||||
|
||||
c = self.console
|
||||
@@ -69,64 +70,64 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
try:
|
||||
self.pre_input_hook()
|
||||
except:
|
||||
print u'pre_input_hook failed'
|
||||
print('pre_input_hook failed')
|
||||
traceback.print_exc()
|
||||
self.pre_input_hook = None
|
||||
|
||||
log(u"in readline: %s"%self.paste_line_buffer)
|
||||
log("in readline: %s"%self.paste_line_buffer)
|
||||
if len(self.paste_line_buffer)>0:
|
||||
self.l_buffer=lineobj.ReadlineTextBuffer(self.paste_line_buffer[0])
|
||||
self._update_line()
|
||||
self.paste_line_buffer=self.paste_line_buffer[1:]
|
||||
c.write(u'\r\n')
|
||||
c.write('\r\n')
|
||||
else:
|
||||
self._readline_from_keyboard()
|
||||
c.write(u'\r\n')
|
||||
c.write('\r\n')
|
||||
|
||||
self.add_history(self.l_buffer.copy())
|
||||
|
||||
log(u'returning(%s)' % self.l_buffer.get_line_text())
|
||||
log('returning(%s)' % self.l_buffer.get_line_text())
|
||||
return self.l_buffer.get_line_text() + '\n'
|
||||
|
||||
### Methods below here are bindable emacs functions
|
||||
|
||||
def beginning_of_line(self, e): # (C-a)
|
||||
u'''Move to the start of the current line. '''
|
||||
'''Move to the start of the current line. '''
|
||||
self.l_buffer.beginning_of_line()
|
||||
|
||||
def end_of_line(self, e): # (C-e)
|
||||
u'''Move to the end of the line. '''
|
||||
'''Move to the end of the line. '''
|
||||
self.l_buffer.end_of_line()
|
||||
|
||||
def forward_char(self, e): # (C-f)
|
||||
u'''Move forward a character. '''
|
||||
'''Move forward a character. '''
|
||||
self.l_buffer.forward_char()
|
||||
|
||||
def backward_char(self, e): # (C-b)
|
||||
u'''Move back a character. '''
|
||||
'''Move back a character. '''
|
||||
self.l_buffer.backward_char()
|
||||
|
||||
def forward_word(self, e): # (M-f)
|
||||
u'''Move forward to the end of the next word. Words are composed of
|
||||
'''Move forward to the end of the next word. Words are composed of
|
||||
letters and digits.'''
|
||||
self.l_buffer.forward_word()
|
||||
|
||||
def backward_word(self, e): # (M-b)
|
||||
u'''Move back to the start of the current or previous word. Words are
|
||||
'''Move back to the start of the current or previous word. Words are
|
||||
composed of letters and digits.'''
|
||||
self.l_buffer.backward_word()
|
||||
|
||||
def clear_screen(self, e): # (C-l)
|
||||
u'''Clear the screen and redraw the current line, leaving the current
|
||||
'''Clear the screen and redraw the current line, leaving the current
|
||||
line at the top of the screen.'''
|
||||
self.console.page()
|
||||
|
||||
def redraw_current_line(self, e): # ()
|
||||
u'''Refresh the current line. By default, this is unbound.'''
|
||||
'''Refresh the current line. By default, this is unbound.'''
|
||||
pass
|
||||
|
||||
def accept_line(self, e): # (Newline or Return)
|
||||
u'''Accept the line regardless of where the cursor is. If this line
|
||||
'''Accept the line regardless of where the cursor is. If this line
|
||||
is non-empty, it may be added to the history list for future recall
|
||||
with add_history(). If this line is a modified history line, the
|
||||
history line is restored to its original state.'''
|
||||
@@ -134,47 +135,47 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
|
||||
######### History commands
|
||||
def previous_history(self, e): # (C-p)
|
||||
u'''Move back through the history list, fetching the previous command. '''
|
||||
'''Move back through the history list, fetching the previous command. '''
|
||||
self._history.previous_history(self.l_buffer)
|
||||
|
||||
def next_history(self, e): # (C-n)
|
||||
u'''Move forward through the history list, fetching the next command. '''
|
||||
'''Move forward through the history list, fetching the next command. '''
|
||||
self._history.next_history(self.l_buffer)
|
||||
|
||||
def beginning_of_history(self, e): # (M-<)
|
||||
u'''Move to the first line in the history.'''
|
||||
'''Move to the first line in the history.'''
|
||||
self._history.beginning_of_history()
|
||||
|
||||
def end_of_history(self, e): # (M->)
|
||||
u'''Move to the end of the input history, i.e., the line currently
|
||||
'''Move to the end of the input history, i.e., the line currently
|
||||
being entered.'''
|
||||
self._history.end_of_history(self.l_buffer)
|
||||
|
||||
def _i_search(self, searchfun, direction, init_event):
|
||||
c = self.console
|
||||
line = self.get_line_buffer()
|
||||
query = u''
|
||||
query = ''
|
||||
hc_start = self._history.history_cursor #+ direction
|
||||
while 1:
|
||||
x, y = self.prompt_end_pos
|
||||
c.pos(0, y)
|
||||
if direction < 0:
|
||||
prompt = u'reverse-i-search'
|
||||
prompt = 'reverse-i-search'
|
||||
else:
|
||||
prompt = u'forward-i-search'
|
||||
prompt = 'forward-i-search'
|
||||
|
||||
scroll = c.write_scrolling(u"%s`%s': %s" % (prompt, query, line))
|
||||
scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line))
|
||||
self._update_prompt_pos(scroll)
|
||||
self._clear_after()
|
||||
|
||||
event = c.getkeypress()
|
||||
if event.keysym == u'BackSpace':
|
||||
if event.keysym == 'BackSpace':
|
||||
if len(query) > 0:
|
||||
query = query[:-1]
|
||||
self._history.history_cursor = hc_start
|
||||
else:
|
||||
self._bell()
|
||||
elif event.char in string.letters + string.digits + string.punctuation + u' ':
|
||||
elif event.char in string.letters + string.digits + string.punctuation + ' ':
|
||||
self._history.history_cursor = hc_start
|
||||
query += event.char
|
||||
elif event.keyinfo == init_event.keyinfo:
|
||||
@@ -182,7 +183,7 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
line=searchfun(query)
|
||||
pass
|
||||
else:
|
||||
if event.keysym != u'Return':
|
||||
if event.keysym != 'Return':
|
||||
self._bell()
|
||||
break
|
||||
line=searchfun(query)
|
||||
@@ -194,46 +195,46 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
self._history.history_cursor=len(self._history.history)
|
||||
|
||||
def reverse_search_history(self, e): # (C-r)
|
||||
u'''Search backward starting at the current line and moving up
|
||||
'''Search backward starting at the current line and moving up
|
||||
through the history as necessary. This is an incremental search.'''
|
||||
# print "HEJ"
|
||||
# print("HEJ")
|
||||
# self.console.bell()
|
||||
self._i_search(self._history.reverse_search_history, -1, e)
|
||||
|
||||
def forward_search_history(self, e): # (C-s)
|
||||
u'''Search forward starting at the current line and moving down
|
||||
'''Search forward starting at the current line and moving down
|
||||
through the the history as necessary. This is an incremental search.'''
|
||||
# print "HEJ"
|
||||
# print("HEJ")
|
||||
# self.console.bell()
|
||||
self._i_search(self._history.forward_search_history, 1, e)
|
||||
|
||||
|
||||
def non_incremental_reverse_search_history(self, e): # (M-p)
|
||||
u'''Search backward starting at the current line and moving up
|
||||
'''Search backward starting at the current line and moving up
|
||||
through the history as necessary using a non-incremental search for
|
||||
a string supplied by the user.'''
|
||||
self._history.non_incremental_reverse_search_history(self.l_buffer)
|
||||
|
||||
def non_incremental_forward_search_history(self, e): # (M-n)
|
||||
u'''Search forward starting at the current line and moving down
|
||||
'''Search forward starting at the current line and moving down
|
||||
through the the history as necessary using a non-incremental search
|
||||
for a string supplied by the user.'''
|
||||
self._history.non_incremental_reverse_search_history(self.l_buffer)
|
||||
|
||||
def history_search_forward(self, e): # ()
|
||||
u'''Search forward through the history for the string of characters
|
||||
'''Search forward through the history for the string of characters
|
||||
between the start of the current line and the point. This is a
|
||||
non-incremental search. By default, this command is unbound.'''
|
||||
self.l_buffer=self._history.history_search_forward(self.l_buffer)
|
||||
|
||||
def history_search_backward(self, e): # ()
|
||||
u'''Search backward through the history for the string of characters
|
||||
'''Search backward through the history for the string of characters
|
||||
between the start of the current line and the point. This is a
|
||||
non-incremental search. By default, this command is unbound.'''
|
||||
self.l_buffer=self._history.history_search_backward(self.l_buffer)
|
||||
|
||||
def yank_nth_arg(self, e): # (M-C-y)
|
||||
u'''Insert the first argument to the previous command (usually the
|
||||
'''Insert the first argument to the previous command (usually the
|
||||
second word on the previous line) at point. With an argument n,
|
||||
insert the nth word from the previous command (the words in the
|
||||
previous command begin with word 0). A negative argument inserts the
|
||||
@@ -241,76 +242,76 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
pass
|
||||
|
||||
def yank_last_arg(self, e): # (M-. or M-_)
|
||||
u'''Insert last argument to the previous command (the last word of
|
||||
'''Insert last argument to the previous command (the last word of
|
||||
the previous history entry). With an argument, behave exactly like
|
||||
yank-nth-arg. Successive calls to yank-last-arg move back through
|
||||
the history list, inserting the last argument of each line in turn.'''
|
||||
pass
|
||||
|
||||
def delete_char(self, e): # (C-d)
|
||||
u'''Delete the character at point. If point is at the beginning of
|
||||
'''Delete the character at point. If point is at the beginning of
|
||||
the line, there are no characters in the line, and the last
|
||||
character typed was not bound to delete-char, then return EOF.'''
|
||||
self.l_buffer.delete_char()
|
||||
|
||||
def backward_delete_char(self, e): # (Rubout)
|
||||
u'''Delete the character behind the cursor. A numeric argument means
|
||||
'''Delete the character behind the cursor. A numeric argument means
|
||||
to kill the characters instead of deleting them.'''
|
||||
self.l_buffer.backward_delete_char()
|
||||
|
||||
def forward_backward_delete_char(self, e): # ()
|
||||
u'''Delete the character under the cursor, unless the cursor is at
|
||||
'''Delete the character under the cursor, unless the cursor is at
|
||||
the end of the line, in which case the character behind the cursor
|
||||
is deleted. By default, this is not bound to a key.'''
|
||||
pass
|
||||
|
||||
def quoted_insert(self, e): # (C-q or C-v)
|
||||
u'''Add the next character typed to the line verbatim. This is how to
|
||||
'''Add the next character typed to the line verbatim. This is how to
|
||||
insert key sequences like C-q, for example.'''
|
||||
e = self.console.getkeypress()
|
||||
self.insert_text(e.char)
|
||||
|
||||
def tab_insert(self, e): # (M-TAB)
|
||||
u'''Insert a tab character. '''
|
||||
'''Insert a tab character. '''
|
||||
cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
|
||||
ws = ' ' * (self.tabstop - (cursor % self.tabstop))
|
||||
self.insert_text(ws)
|
||||
|
||||
def self_insert(self, e): # (a, b, A, 1, !, ...)
|
||||
u'''Insert yourself. '''
|
||||
'''Insert yourself. '''
|
||||
if ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys.
|
||||
self.insert_text(e.char)
|
||||
|
||||
def transpose_chars(self, e): # (C-t)
|
||||
u'''Drag the character before the cursor forward over the character
|
||||
'''Drag the character before the cursor forward over the character
|
||||
at the cursor, moving the cursor forward as well. If the insertion
|
||||
point is at the end of the line, then this transposes the last two
|
||||
characters of the line. Negative arguments have no effect.'''
|
||||
self.l_buffer.transpose_chars()
|
||||
|
||||
def transpose_words(self, e): # (M-t)
|
||||
u'''Drag the word before point past the word after point, moving
|
||||
'''Drag the word before point past the word after point, moving
|
||||
point past that word as well. If the insertion point is at the end
|
||||
of the line, this transposes the last two words on the line.'''
|
||||
self.l_buffer.transpose_words()
|
||||
|
||||
def upcase_word(self, e): # (M-u)
|
||||
u'''Uppercase the current (or following) word. With a negative
|
||||
'''Uppercase the current (or following) word. With a negative
|
||||
argument, uppercase the previous word, but do not move the cursor.'''
|
||||
self.l_buffer.upcase_word()
|
||||
|
||||
def downcase_word(self, e): # (M-l)
|
||||
u'''Lowercase the current (or following) word. With a negative
|
||||
'''Lowercase the current (or following) word. With a negative
|
||||
argument, lowercase the previous word, but do not move the cursor.'''
|
||||
self.l_buffer.downcase_word()
|
||||
|
||||
def capitalize_word(self, e): # (M-c)
|
||||
u'''Capitalize the current (or following) word. With a negative
|
||||
'''Capitalize the current (or following) word. With a negative
|
||||
argument, capitalize the previous word, but do not move the cursor.'''
|
||||
self.l_buffer.capitalize_word()
|
||||
|
||||
def overwrite_mode(self, e): # ()
|
||||
u'''Toggle overwrite mode. With an explicit positive numeric
|
||||
'''Toggle overwrite mode. With an explicit positive numeric
|
||||
argument, switches to overwrite mode. With an explicit non-positive
|
||||
numeric argument, switches to insert mode. This command affects only
|
||||
emacs mode; vi mode does overwrite differently. Each call to
|
||||
@@ -321,54 +322,54 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
pass
|
||||
|
||||
def kill_line(self, e): # (C-k)
|
||||
u'''Kill the text from point to the end of the line. '''
|
||||
'''Kill the text from point to the end of the line. '''
|
||||
self.l_buffer.kill_line()
|
||||
|
||||
def backward_kill_line(self, e): # (C-x Rubout)
|
||||
u'''Kill backward to the beginning of the line. '''
|
||||
'''Kill backward to the beginning of the line. '''
|
||||
self.l_buffer.backward_kill_line()
|
||||
|
||||
def unix_line_discard(self, e): # (C-u)
|
||||
u'''Kill backward from the cursor to the beginning of the current line. '''
|
||||
'''Kill backward from the cursor to the beginning of the current line. '''
|
||||
# how is this different from backward_kill_line?
|
||||
self.l_buffer.unix_line_discard()
|
||||
|
||||
def kill_whole_line(self, e): # ()
|
||||
u'''Kill all characters on the current line, no matter where point
|
||||
'''Kill all characters on the current line, no matter where point
|
||||
is. By default, this is unbound.'''
|
||||
self.l_buffer.kill_whole_line()
|
||||
|
||||
def kill_word(self, e): # (M-d)
|
||||
u'''Kill from point to the end of the current word, or if between
|
||||
'''Kill from point to the end of the current word, or if between
|
||||
words, to the end of the next word. Word boundaries are the same as
|
||||
forward-word.'''
|
||||
self.l_buffer.kill_word()
|
||||
|
||||
def backward_kill_word(self, e): # (M-DEL)
|
||||
u'''Kill the word behind point. Word boundaries are the same as
|
||||
'''Kill the word behind point. Word boundaries are the same as
|
||||
backward-word. '''
|
||||
self.l_buffer.backward_kill_word()
|
||||
|
||||
def unix_word_rubout(self, e): # (C-w)
|
||||
u'''Kill the word behind point, using white space as a word
|
||||
'''Kill the word behind point, using white space as a word
|
||||
boundary. The killed text is saved on the kill-ring.'''
|
||||
self.l_buffer.unix_word_rubout()
|
||||
|
||||
def delete_horizontal_space(self, e): # ()
|
||||
u'''Delete all spaces and tabs around point. By default, this is unbound. '''
|
||||
'''Delete all spaces and tabs around point. By default, this is unbound. '''
|
||||
pass
|
||||
|
||||
def kill_region(self, e): # ()
|
||||
u'''Kill the text in the current region. By default, this command is unbound. '''
|
||||
'''Kill the text in the current region. By default, this command is unbound. '''
|
||||
pass
|
||||
|
||||
def copy_region_as_kill(self, e): # ()
|
||||
u'''Copy the text in the region to the kill buffer, so it can be
|
||||
'''Copy the text in the region to the kill buffer, so it can be
|
||||
yanked right away. By default, this command is unbound.'''
|
||||
pass
|
||||
|
||||
def copy_region_to_clipboard(self, e): # ()
|
||||
u'''Copy the text in the region to the windows clipboard.'''
|
||||
'''Copy the text in the region to the windows clipboard.'''
|
||||
if self.enable_win32_clipboard:
|
||||
mark=min(self.l_buffer.mark,len(self.l_buffer.line_buffer))
|
||||
cursor=min(self.l_buffer.point,len(self.l_buffer.line_buffer))
|
||||
@@ -376,72 +377,72 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
return
|
||||
begin=min(cursor,mark)
|
||||
end=max(cursor,mark)
|
||||
toclipboard=u"".join(self.l_buffer.line_buffer[begin:end])
|
||||
toclipboard="".join(self.l_buffer.line_buffer[begin:end])
|
||||
clipboard.SetClipboardText(str(toclipboard))
|
||||
|
||||
def copy_backward_word(self, e): # ()
|
||||
u'''Copy the word before point to the kill buffer. The word
|
||||
'''Copy the word before point to the kill buffer. The word
|
||||
boundaries are the same as backward-word. By default, this command
|
||||
is unbound.'''
|
||||
pass
|
||||
|
||||
def copy_forward_word(self, e): # ()
|
||||
u'''Copy the word following point to the kill buffer. The word
|
||||
'''Copy the word following point to the kill buffer. The word
|
||||
boundaries are the same as forward-word. By default, this command is
|
||||
unbound.'''
|
||||
pass
|
||||
|
||||
def paste(self,e):
|
||||
u'''Paste windows clipboard'''
|
||||
'''Paste windows clipboard'''
|
||||
if self.enable_win32_clipboard:
|
||||
txt=clipboard.get_clipboard_text_and_convert(False)
|
||||
self.insert_text(txt)
|
||||
|
||||
def paste_mulitline_code(self,e):
|
||||
u'''Paste windows clipboard'''
|
||||
reg=re.compile(u"\r?\n")
|
||||
'''Paste windows clipboard'''
|
||||
reg=re.compile("\r?\n")
|
||||
if self.enable_win32_clipboard:
|
||||
txt=clipboard.get_clipboard_text_and_convert(False)
|
||||
t=reg.split(txt)
|
||||
t=[row for row in t if row.strip()!=u""] #remove empty lines
|
||||
if t!=[u""]:
|
||||
t=[row for row in t if row.strip()!=""] #remove empty lines
|
||||
if t!=[""]:
|
||||
self.insert_text(t[0])
|
||||
self.add_history(self.l_buffer.copy())
|
||||
self.paste_line_buffer=t[1:]
|
||||
log(u"multi: %s"%self.paste_line_buffer)
|
||||
log("multi: %s"%self.paste_line_buffer)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def ipython_paste(self,e):
|
||||
u'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
|
||||
'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
|
||||
True then try to convert tabseparated data to repr of list of lists or
|
||||
repr of array'''
|
||||
if self.enable_win32_clipboard:
|
||||
txt=clipboard.get_clipboard_text_and_convert(
|
||||
self.enable_ipython_paste_list_of_lists)
|
||||
if self.enable_ipython_paste_for_paths:
|
||||
if len(txt)<300 and (u"\t" not in txt) and (u"\n" not in txt):
|
||||
txt=txt.replace(u"\\", u"/").replace(u" ", ur"\ ")
|
||||
if len(txt)<300 and ("\t" not in txt) and ("\n" not in txt):
|
||||
txt=txt.replace("\\", "/").replace(" ", r"\ ")
|
||||
self.insert_text(txt)
|
||||
|
||||
def yank(self, e): # (C-y)
|
||||
u'''Yank the top of the kill ring into the buffer at point. '''
|
||||
'''Yank the top of the kill ring into the buffer at point. '''
|
||||
pass
|
||||
|
||||
def yank_pop(self, e): # (M-y)
|
||||
u'''Rotate the kill-ring, and yank the new top. You can only do this
|
||||
'''Rotate the kill-ring, and yank the new top. You can only do this
|
||||
if the prior command is yank or yank-pop.'''
|
||||
pass
|
||||
|
||||
|
||||
def digit_argument(self, e): # (M-0, M-1, ... M--)
|
||||
u'''Add this digit to the argument already accumulating, or start a
|
||||
'''Add this digit to the argument already accumulating, or start a
|
||||
new argument. M-- starts a negative argument.'''
|
||||
pass
|
||||
|
||||
def universal_argument(self, e): # ()
|
||||
u'''This is another way to specify an argument. If this command is
|
||||
'''This is another way to specify an argument. If this command is
|
||||
followed by one or more digits, optionally with a leading minus
|
||||
sign, those digits define the argument. If the command is followed
|
||||
by digits, executing universal-argument again ends the numeric
|
||||
@@ -455,83 +456,83 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
pass
|
||||
|
||||
def delete_char_or_list(self, e): # ()
|
||||
u'''Deletes the character under the cursor if not at the beginning or
|
||||
'''Deletes the character under the cursor if not at the beginning or
|
||||
end of the line (like delete-char). If at the end of the line,
|
||||
behaves identically to possible-completions. This command is unbound
|
||||
by default.'''
|
||||
pass
|
||||
|
||||
def start_kbd_macro(self, e): # (C-x ()
|
||||
u'''Begin saving the characters typed into the current keyboard macro. '''
|
||||
'''Begin saving the characters typed into the current keyboard macro. '''
|
||||
pass
|
||||
|
||||
def end_kbd_macro(self, e): # (C-x ))
|
||||
u'''Stop saving the characters typed into the current keyboard macro
|
||||
'''Stop saving the characters typed into the current keyboard macro
|
||||
and save the definition.'''
|
||||
pass
|
||||
|
||||
def call_last_kbd_macro(self, e): # (C-x e)
|
||||
u'''Re-execute the last keyboard macro defined, by making the
|
||||
'''Re-execute the last keyboard macro defined, by making the
|
||||
characters in the macro appear as if typed at the keyboard.'''
|
||||
pass
|
||||
|
||||
def re_read_init_file(self, e): # (C-x C-r)
|
||||
u'''Read in the contents of the inputrc file, and incorporate any
|
||||
'''Read in the contents of the inputrc file, and incorporate any
|
||||
bindings or variable assignments found there.'''
|
||||
pass
|
||||
|
||||
def abort(self, e): # (C-g)
|
||||
u'''Abort the current editing command and ring the terminals bell
|
||||
'''Abort the current editing command and ring the terminals bell
|
||||
(subject to the setting of bell-style).'''
|
||||
self._bell()
|
||||
|
||||
def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
|
||||
u'''If the metafied character x is lowercase, run the command that is
|
||||
'''If the metafied character x is lowercase, run the command that is
|
||||
bound to the corresponding uppercase character.'''
|
||||
pass
|
||||
|
||||
def prefix_meta(self, e): # (ESC)
|
||||
u'''Metafy the next character typed. This is for keyboards without a
|
||||
'''Metafy the next character typed. This is for keyboards without a
|
||||
meta key. Typing ESC f is equivalent to typing M-f. '''
|
||||
self.next_meta = True
|
||||
|
||||
def undo(self, e): # (C-_ or C-x C-u)
|
||||
u'''Incremental undo, separately remembered for each line.'''
|
||||
'''Incremental undo, separately remembered for each line.'''
|
||||
self.l_buffer.pop_undo()
|
||||
|
||||
def revert_line(self, e): # (M-r)
|
||||
u'''Undo all changes made to this line. This is like executing the
|
||||
'''Undo all changes made to this line. This is like executing the
|
||||
undo command enough times to get back to the beginning.'''
|
||||
pass
|
||||
|
||||
def tilde_expand(self, e): # (M-~)
|
||||
u'''Perform tilde expansion on the current word.'''
|
||||
'''Perform tilde expansion on the current word.'''
|
||||
pass
|
||||
|
||||
def set_mark(self, e): # (C-@)
|
||||
u'''Set the mark to the point. If a numeric argument is supplied, the
|
||||
'''Set the mark to the point. If a numeric argument is supplied, the
|
||||
mark is set to that position.'''
|
||||
self.l_buffer.set_mark()
|
||||
|
||||
def exchange_point_and_mark(self, e): # (C-x C-x)
|
||||
u'''Swap the point with the mark. The current cursor position is set
|
||||
'''Swap the point with the mark. The current cursor position is set
|
||||
to the saved position, and the old cursor position is saved as the
|
||||
mark.'''
|
||||
pass
|
||||
|
||||
def character_search(self, e): # (C-])
|
||||
u'''A character is read and point is moved to the next occurrence of
|
||||
'''A character is read and point is moved to the next occurrence of
|
||||
that character. A negative count searches for previous occurrences.'''
|
||||
pass
|
||||
|
||||
def character_search_backward(self, e): # (M-C-])
|
||||
u'''A character is read and point is moved to the previous occurrence
|
||||
'''A character is read and point is moved to the previous occurrence
|
||||
of that character. A negative count searches for subsequent
|
||||
occurrences.'''
|
||||
pass
|
||||
|
||||
def insert_comment(self, e): # (M-#)
|
||||
u'''Without a numeric argument, the value of the comment-begin
|
||||
'''Without a numeric argument, the value of the comment-begin
|
||||
variable is inserted at the beginning of the current line. If a
|
||||
numeric argument is supplied, this command acts as a toggle: if the
|
||||
characters at the beginning of the line do not match the value of
|
||||
@@ -541,21 +542,21 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
pass
|
||||
|
||||
def dump_functions(self, e): # ()
|
||||
u'''Print all of the functions and their key bindings to the Readline
|
||||
'''Print all of the functions and their key bindings to the Readline
|
||||
output stream. If a numeric argument is supplied, the output is
|
||||
formatted in such a way that it can be made part of an inputrc
|
||||
file. This command is unbound by default.'''
|
||||
pass
|
||||
|
||||
def dump_variables(self, e): # ()
|
||||
u'''Print all of the settable variables and their values to the
|
||||
'''Print all of the settable variables and their values to the
|
||||
Readline output stream. If a numeric argument is supplied, the
|
||||
output is formatted in such a way that it can be made part of an
|
||||
inputrc file. This command is unbound by default.'''
|
||||
pass
|
||||
|
||||
def dump_macros(self, e): # ()
|
||||
u'''Print all of the Readline key sequences bound to macros and the
|
||||
'''Print all of the Readline key sequences bound to macros and the
|
||||
strings they output. If a numeric argument is supplied, the output
|
||||
is formatted in such a way that it can be made part of an inputrc
|
||||
file. This command is unbound by default.'''
|
||||
@@ -565,38 +566,38 @@ class NotEmacsMode(basemode.BaseMode):
|
||||
#Create key bindings:
|
||||
|
||||
def init_editing_mode(self, e): # (C-e)
|
||||
u'''When in vi command mode, this causes a switch to emacs editing
|
||||
'''When in vi command mode, this causes a switch to emacs editing
|
||||
mode.'''
|
||||
|
||||
self._bind_exit_key(u'Control-d')
|
||||
self._bind_exit_key(u'Control-z')
|
||||
self._bind_exit_key('Control-d')
|
||||
self._bind_exit_key('Control-z')
|
||||
|
||||
# I often accidentally hold the shift or control while typing space
|
||||
self._bind_key(u'Shift-space', self.self_insert)
|
||||
self._bind_key(u'Control-space', self.self_insert)
|
||||
self._bind_key(u'Return', self.accept_line)
|
||||
self._bind_key(u'Left', self.backward_char)
|
||||
self._bind_key(u'Control-b', self.backward_char)
|
||||
self._bind_key(u'Right', self.forward_char)
|
||||
self._bind_key(u'Control-f', self.forward_char)
|
||||
self._bind_key(u'BackSpace', self.backward_delete_char)
|
||||
self._bind_key(u'Home', self.beginning_of_line)
|
||||
self._bind_key(u'End', self.end_of_line)
|
||||
self._bind_key(u'Delete', self.delete_char)
|
||||
self._bind_key(u'Control-d', self.delete_char)
|
||||
self._bind_key(u'Clear', self.clear_screen)
|
||||
self._bind_key('Shift-space', self.self_insert)
|
||||
self._bind_key('Control-space', self.self_insert)
|
||||
self._bind_key('Return', self.accept_line)
|
||||
self._bind_key('Left', self.backward_char)
|
||||
self._bind_key('Control-b', self.backward_char)
|
||||
self._bind_key('Right', self.forward_char)
|
||||
self._bind_key('Control-f', self.forward_char)
|
||||
self._bind_key('BackSpace', self.backward_delete_char)
|
||||
self._bind_key('Home', self.beginning_of_line)
|
||||
self._bind_key('End', self.end_of_line)
|
||||
self._bind_key('Delete', self.delete_char)
|
||||
self._bind_key('Control-d', self.delete_char)
|
||||
self._bind_key('Clear', self.clear_screen)
|
||||
|
||||
|
||||
# make it case insensitive
|
||||
def commonprefix(m):
|
||||
u"Given a list of pathnames, returns the longest common leading component"
|
||||
if not m: return u''
|
||||
"Given a list of pathnames, returns the longest common leading component"
|
||||
if not m: return ''
|
||||
prefix = m[0]
|
||||
for item in m:
|
||||
for i in range(len(prefix)):
|
||||
if prefix[:i+1].lower() != item[:i+1].lower():
|
||||
prefix = prefix[:i]
|
||||
if i == 0: return u''
|
||||
if i == 0: return ''
|
||||
break
|
||||
return prefix
|
||||
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import os
|
||||
import pyreadline.logger as logger
|
||||
from pyreadline.logger import log
|
||||
import pyreadline.lineeditor.lineobj as lineobj
|
||||
import pyreadline.lineeditor.history as history
|
||||
import basemode
|
||||
from . import basemode
|
||||
|
||||
class ViMode(basemode.BaseMode):
|
||||
mode="vi"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
"""Release data for the pyreadline project.
|
||||
|
||||
$Id$"""
|
||||
|
||||
+116
-115
@@ -6,11 +6,12 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
u''' an attempt to implement readline for Python in Python using ctypes'''
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
''' an attempt to implement readline for Python in Python using ctypes'''
|
||||
import sys,os,re,time
|
||||
from glob import glob
|
||||
|
||||
import release
|
||||
from . import release
|
||||
|
||||
import pyreadline.lineeditor.lineobj as lineobj
|
||||
import pyreadline.lineeditor.history as history
|
||||
@@ -20,16 +21,16 @@ import pyreadline.logger as logger
|
||||
|
||||
from pyreadline.keysyms.common import make_KeyPress_from_keydescr
|
||||
from pyreadline.unicode_helper import ensure_unicode
|
||||
from logger import log
|
||||
from modes import editingmodes
|
||||
from error import ReadlineError, GetSetError
|
||||
from .logger import log
|
||||
from .modes import editingmodes
|
||||
from .error import ReadlineError, GetSetError
|
||||
|
||||
in_ironpython = u"IronPython" in sys.version
|
||||
in_ironpython = "IronPython" in sys.version
|
||||
if in_ironpython:#ironpython does not provide a prompt string to readline
|
||||
import System
|
||||
default_prompt = u">>> "
|
||||
default_prompt = ">>> "
|
||||
else:
|
||||
default_prompt = u""
|
||||
default_prompt = ""
|
||||
import pdb
|
||||
|
||||
|
||||
@@ -37,10 +38,10 @@ class MockConsoleError(Exception):
|
||||
pass
|
||||
|
||||
class MockConsole(object):
|
||||
u"""object used during refactoring. Should raise errors when someone tries to use it.
|
||||
"""object used during refactoring. Should raise errors when someone tries to use it.
|
||||
"""
|
||||
def __setattr__(self, x):
|
||||
raise MockConsoleError(u"Should not try to get attributes from MockConsole")
|
||||
raise MockConsoleError("Should not try to get attributes from MockConsole")
|
||||
|
||||
def cursor(self, size=50):
|
||||
pass
|
||||
@@ -51,7 +52,7 @@ class BaseReadline(object):
|
||||
self.ctrl_c_tap_time_interval = 0.3
|
||||
|
||||
self.debug = False
|
||||
self.bell_style = u'none'
|
||||
self.bell_style = 'none'
|
||||
self.mark = -1
|
||||
self.console=MockConsole()
|
||||
self.disable_readline = False
|
||||
@@ -62,43 +63,43 @@ class BaseReadline(object):
|
||||
self.mode = self.editingmodes[0]
|
||||
|
||||
self.read_inputrc()
|
||||
log(u"\n".join(self.mode.rl_settings_to_string()))
|
||||
log("\n".join(self.mode.rl_settings_to_string()))
|
||||
|
||||
self.callback = None
|
||||
|
||||
def parse_and_bind(self, string):
|
||||
u'''Parse and execute single line of a readline init file.'''
|
||||
'''Parse and execute single line of a readline init file.'''
|
||||
try:
|
||||
log(u'parse_and_bind("%s")' % string)
|
||||
if string.startswith(u'#'):
|
||||
log('parse_and_bind("%s")' % string)
|
||||
if string.startswith('#'):
|
||||
return
|
||||
if string.startswith(u'set'):
|
||||
m = re.compile(ur'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string)
|
||||
if string.startswith('set'):
|
||||
m = re.compile(r'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string)
|
||||
if m:
|
||||
var_name = m.group(1)
|
||||
val = m.group(2)
|
||||
try:
|
||||
setattr(self.mode, var_name.replace(u'-',u'_'), val)
|
||||
setattr(self.mode, var_name.replace('-','_'), val)
|
||||
except AttributeError:
|
||||
log(u'unknown var="%s" val="%s"' % (var_name, val))
|
||||
log('unknown var="%s" val="%s"' % (var_name, val))
|
||||
else:
|
||||
log(u'bad set "%s"' % string)
|
||||
log('bad set "%s"' % string)
|
||||
return
|
||||
m = re.compile(ur'\s*(.+)\s*:\s*([-a-zA-Z]+)\s*$').match(string)
|
||||
m = re.compile(r'\s*(.+)\s*:\s*([-a-zA-Z]+)\s*$').match(string)
|
||||
if m:
|
||||
key = m.group(1)
|
||||
func_name = m.group(2)
|
||||
py_name = func_name.replace(u'-', u'_')
|
||||
py_name = func_name.replace('-', '_')
|
||||
try:
|
||||
func = getattr(self.mode, py_name)
|
||||
except AttributeError:
|
||||
log(u'unknown func key="%s" func="%s"' % (key, func_name))
|
||||
log('unknown func key="%s" func="%s"' % (key, func_name))
|
||||
if self.debug:
|
||||
print u'pyreadline parse_and_bind error, unknown function to bind: "%s"' % func_name
|
||||
print('pyreadline parse_and_bind error, unknown function to bind: "%s"' % func_name)
|
||||
return
|
||||
self.mode._bind_key(key, func)
|
||||
except:
|
||||
log(u'error')
|
||||
log('error')
|
||||
raise
|
||||
|
||||
def _set_prompt(self, prompt):
|
||||
@@ -111,37 +112,37 @@ class BaseReadline(object):
|
||||
|
||||
|
||||
def get_line_buffer(self):
|
||||
u'''Return the current contents of the line buffer.'''
|
||||
'''Return the current contents of the line buffer.'''
|
||||
return self.mode.l_buffer.get_line_text()
|
||||
|
||||
def insert_text(self, string):
|
||||
u'''Insert text into the command line.'''
|
||||
'''Insert text into the command line.'''
|
||||
self.mode.insert_text(string)
|
||||
|
||||
def read_init_file(self, filename=None):
|
||||
u'''Parse a readline initialization file. The default filename is the last filename used.'''
|
||||
log(u'read_init_file("%s")' % filename)
|
||||
'''Parse a readline initialization file. The default filename is the last filename used.'''
|
||||
log('read_init_file("%s")' % filename)
|
||||
|
||||
#History file book keeping methods (non-bindable)
|
||||
|
||||
def add_history(self, line):
|
||||
u'''Append a line to the history buffer, as if it was the last line typed.'''
|
||||
'''Append a line to the history buffer, as if it was the last line typed.'''
|
||||
self.mode._history.add_history(line)
|
||||
|
||||
def get_current_history_length(self ):
|
||||
u'''Return the number of lines currently in the history.
|
||||
'''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.)'''
|
||||
return self.mode._history.get_current_history_length()
|
||||
|
||||
def get_history_length(self ):
|
||||
u'''Return the desired length of the history file.
|
||||
'''Return the desired length of the history file.
|
||||
|
||||
Negative values imply unlimited history file size.'''
|
||||
return self.mode._history.get_history_length()
|
||||
|
||||
def set_history_length(self, length):
|
||||
u'''Set the number of lines to save in the history file.
|
||||
'''Set the number of lines to save in the history file.
|
||||
|
||||
write_history_file() uses this value to truncate the history file
|
||||
when saving. Negative values imply unlimited history file size.
|
||||
@@ -149,28 +150,28 @@ class BaseReadline(object):
|
||||
self.mode._history.set_history_length(length)
|
||||
|
||||
def get_history_item(self, index):
|
||||
u'''Return the current contents of history item at index.'''
|
||||
'''Return the current contents of history item at index.'''
|
||||
return self.mode._history.get_history_item(index)
|
||||
|
||||
def clear_history(self):
|
||||
u'''Clear readline history'''
|
||||
'''Clear readline history'''
|
||||
self.mode._history.clear_history()
|
||||
|
||||
def read_history_file(self, filename=None):
|
||||
u'''Load a readline history file. The default filename is ~/.history.'''
|
||||
'''Load a readline history file. The default filename is ~/.history.'''
|
||||
if filename is None:
|
||||
filename = self.mode._history.history_filename
|
||||
log(u"read_history_file from %s"%ensure_unicode(filename))
|
||||
log("read_history_file from %s"%ensure_unicode(filename))
|
||||
self.mode._history.read_history_file(filename)
|
||||
|
||||
def write_history_file(self, filename=None):
|
||||
u'''Save a readline history file. The default filename is ~/.history.'''
|
||||
'''Save a readline history file. The default filename is ~/.history.'''
|
||||
self.mode._history.write_history_file(filename)
|
||||
|
||||
#Completer functions
|
||||
|
||||
def set_completer(self, function=None):
|
||||
u'''Set or remove the completer function.
|
||||
'''Set or remove the completer function.
|
||||
|
||||
If function is specified, it will be used as the new completer
|
||||
function; if omitted or None, any completer function already
|
||||
@@ -179,36 +180,36 @@ class BaseReadline(object):
|
||||
non-string value. It should return the next possible completion
|
||||
starting with text.
|
||||
'''
|
||||
log(u'set_completer')
|
||||
log('set_completer')
|
||||
self.mode.completer = function
|
||||
|
||||
def get_completer(self):
|
||||
u'''Get the completer function.
|
||||
'''Get the completer function.
|
||||
'''
|
||||
log(u'get_completer')
|
||||
log('get_completer')
|
||||
return self.mode.completer
|
||||
|
||||
def get_begidx(self):
|
||||
u'''Get the beginning index of the readline tab-completion scope.'''
|
||||
'''Get the beginning index of the readline tab-completion scope.'''
|
||||
return self.mode.begidx
|
||||
|
||||
def get_endidx(self):
|
||||
u'''Get the ending index of the readline tab-completion scope.'''
|
||||
'''Get the ending index of the readline tab-completion scope.'''
|
||||
return self.mode.endidx
|
||||
|
||||
def set_completer_delims(self, string):
|
||||
u'''Set the readline word delimiters for tab-completion.'''
|
||||
'''Set the readline word delimiters for tab-completion.'''
|
||||
self.mode.completer_delims = string
|
||||
|
||||
def get_completer_delims(self):
|
||||
u'''Get the readline word delimiters for tab-completion.'''
|
||||
'''Get the readline word delimiters for tab-completion.'''
|
||||
if sys.version_info[0] < 3:
|
||||
return self.mode.completer_delims.encode("ascii")
|
||||
else:
|
||||
return self.mode.completer_delims
|
||||
|
||||
def set_startup_hook(self, function=None):
|
||||
u'''Set or remove the startup_hook function.
|
||||
'''Set or remove the startup_hook function.
|
||||
|
||||
If function is specified, it will be used as the new startup_hook
|
||||
function; if omitted or None, any hook function already installed is
|
||||
@@ -219,7 +220,7 @@ class BaseReadline(object):
|
||||
self.mode.startup_hook = function
|
||||
|
||||
def set_pre_input_hook(self, function=None):
|
||||
u'''Set or remove the pre_input_hook function.
|
||||
'''Set or remove the pre_input_hook function.
|
||||
|
||||
If function is specified, it will be used as the new pre_input_hook
|
||||
function; if omitted or None, any hook function already installed is
|
||||
@@ -239,7 +240,7 @@ class BaseReadline(object):
|
||||
# Standard call, not available for all implementations
|
||||
#
|
||||
|
||||
def readline(self, prompt=u''):
|
||||
def readline(self, prompt=''):
|
||||
raise NotImplementedError
|
||||
|
||||
#
|
||||
@@ -248,27 +249,27 @@ class BaseReadline(object):
|
||||
def process_keyevent(self, keyinfo):
|
||||
return self.mode.process_keyevent(keyinfo)
|
||||
|
||||
def readline_setup(self, prompt=u""):
|
||||
def readline_setup(self, prompt=""):
|
||||
return self.mode.readline_setup(prompt)
|
||||
|
||||
def keyboard_poll(self):
|
||||
return self.mode._readline_from_keyboard_poll()
|
||||
|
||||
def callback_handler_install(self, prompt, callback):
|
||||
u'''bool readline_callback_handler_install ( string prompt, callback callback)
|
||||
'''bool readline_callback_handler_install ( string prompt, callback callback)
|
||||
Initializes the readline callback interface and terminal, prints the prompt and returns immediately
|
||||
'''
|
||||
self.callback = callback
|
||||
self.readline_setup(prompt)
|
||||
|
||||
def callback_handler_remove(self):
|
||||
u'''Removes a previously installed callback handler and restores terminal settings'''
|
||||
'''Removes a previously installed callback handler and restores terminal settings'''
|
||||
self.callback = None
|
||||
|
||||
def callback_read_char(self):
|
||||
u'''Reads a character and informs the readline callback interface when a line is received'''
|
||||
'''Reads a character and informs the readline callback interface when a line is received'''
|
||||
if self.keyboard_poll():
|
||||
line = self.get_line_buffer() + u'\n'
|
||||
line = self.get_line_buffer() + '\n'
|
||||
# however there is another newline added by
|
||||
# self.mode.readline_setup(prompt) which is called by callback_handler_install
|
||||
# this differs from GNU readline
|
||||
@@ -291,7 +292,7 @@ class BaseReadline(object):
|
||||
elif hasattr(modes[mode], name):
|
||||
modes[mode]._bind_key(key, getattr(modes[mode], name))
|
||||
else:
|
||||
print u"Trying to bind unknown command '%s' to key '%s'"%(name, key)
|
||||
print("Trying to bind unknown command '%s' to key '%s'"%(name, key))
|
||||
|
||||
def un_bind_key(key):
|
||||
keyinfo = make_KeyPress_from_keydescr(key).tuple()
|
||||
@@ -323,7 +324,7 @@ class BaseReadline(object):
|
||||
self.mode._history.history_length = int(length)
|
||||
|
||||
def allow_ctrl_c(mode):
|
||||
log(u"allow_ctrl_c:%s:%s"%(self.allow_ctrl_c, mode))
|
||||
log("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c, mode))
|
||||
self.allow_ctrl_c = mode
|
||||
|
||||
def setbellstyle(mode):
|
||||
@@ -347,27 +348,27 @@ class BaseReadline(object):
|
||||
def enable_ipython_paste_for_paths(boolean):
|
||||
self.mode.enable_ipython_paste_for_paths = boolean
|
||||
|
||||
def debug_output(on, filename=u"pyreadline_debug_log.txt"): #Not implemented yet
|
||||
if on in [u"on", u"on_nologfile"]:
|
||||
def debug_output(on, filename="pyreadline_debug_log.txt"): #Not implemented yet
|
||||
if on in ["on", "on_nologfile"]:
|
||||
self.debug=True
|
||||
|
||||
if on == "on":
|
||||
logger.start_file_log(filename)
|
||||
logger.start_socket_log()
|
||||
logger.log(u"STARTING LOG")
|
||||
elif on == u"on_nologfile":
|
||||
logger.log("STARTING LOG")
|
||||
elif on == "on_nologfile":
|
||||
logger.start_socket_log()
|
||||
logger.log(u"STARTING LOG")
|
||||
logger.log("STARTING LOG")
|
||||
else:
|
||||
logger.log(u"STOPING LOG")
|
||||
logger.log("STOPING LOG")
|
||||
logger.stop_file_log()
|
||||
logger.stop_socket_log()
|
||||
|
||||
_color_trtable={u"black":0, u"darkred":4, u"darkgreen":2,
|
||||
u"darkyellow":6, u"darkblue":1, u"darkmagenta":5,
|
||||
u"darkcyan":3, u"gray":7, u"red":4+8,
|
||||
u"green":2+8, u"yellow":6+8, u"blue":1+8,
|
||||
u"magenta":5+8, u"cyan":3+8, u"white":7+8}
|
||||
_color_trtable={"black":0, "darkred":4, "darkgreen":2,
|
||||
"darkyellow":6, "darkblue":1, "darkmagenta":5,
|
||||
"darkcyan":3, "gray":7, "red":4+8,
|
||||
"green":2+8, "yellow":6+8, "blue":1+8,
|
||||
"magenta":5+8, "cyan":3+8, "white":7+8}
|
||||
|
||||
def set_prompt_color(color):
|
||||
self.prompt_color = self._color_trtable.get(color.lower(),7)
|
||||
@@ -375,30 +376,30 @@ class BaseReadline(object):
|
||||
def set_input_color(color):
|
||||
self.command_color=self._color_trtable.get(color.lower(),7)
|
||||
|
||||
loc = {u"branch":release.branch,
|
||||
u"version":release.version,
|
||||
u"mode":mode,
|
||||
u"modes":modes,
|
||||
u"set_mode":setmode,
|
||||
u"bind_key":bind_key,
|
||||
u"disable_readline":disable_readline,
|
||||
u"bind_exit_key":bind_exit_key,
|
||||
u"un_bind_key":un_bind_key,
|
||||
u"un_bind_exit_key":un_bind_exit_key,
|
||||
u"bell_style":setbellstyle,
|
||||
u"mark_directories":mark_directories,
|
||||
u"show_all_if_ambiguous":show_all_if_ambiguous,
|
||||
u"completer_delims":completer_delims,
|
||||
u"complete_filesystem":complete_filesystem,
|
||||
u"debug_output":debug_output,
|
||||
u"history_filename":sethistoryfilename,
|
||||
u"history_length":sethistorylength,
|
||||
u"set_prompt_color":set_prompt_color,
|
||||
u"set_input_color":set_input_color,
|
||||
u"allow_ctrl_c":allow_ctrl_c,
|
||||
u"ctrl_c_tap_time_interval":ctrl_c_tap_time_interval,
|
||||
u"kill_ring_to_clipboard":setkill_ring_to_clipboard,
|
||||
u"enable_ipython_paste_for_paths":enable_ipython_paste_for_paths,
|
||||
loc = {"branch":release.branch,
|
||||
"version":release.version,
|
||||
"mode":mode,
|
||||
"modes":modes,
|
||||
"set_mode":setmode,
|
||||
"bind_key":bind_key,
|
||||
"disable_readline":disable_readline,
|
||||
"bind_exit_key":bind_exit_key,
|
||||
"un_bind_key":un_bind_key,
|
||||
"un_bind_exit_key":un_bind_exit_key,
|
||||
"bell_style":setbellstyle,
|
||||
"mark_directories":mark_directories,
|
||||
"show_all_if_ambiguous":show_all_if_ambiguous,
|
||||
"completer_delims":completer_delims,
|
||||
"complete_filesystem":complete_filesystem,
|
||||
"debug_output":debug_output,
|
||||
"history_filename":sethistoryfilename,
|
||||
"history_length":sethistorylength,
|
||||
"set_prompt_color":set_prompt_color,
|
||||
"set_input_color":set_input_color,
|
||||
"allow_ctrl_c":allow_ctrl_c,
|
||||
"ctrl_c_tap_time_interval":ctrl_c_tap_time_interval,
|
||||
"kill_ring_to_clipboard":setkill_ring_to_clipboard,
|
||||
"enable_ipython_paste_for_paths":enable_ipython_paste_for_paths,
|
||||
}
|
||||
if os.path.isfile(inputrcpath):
|
||||
try:
|
||||
@@ -406,11 +407,11 @@ class BaseReadline(object):
|
||||
except Exception,x:
|
||||
raise
|
||||
import traceback
|
||||
print >>sys.stderr, u"Error reading .pyinputrc"
|
||||
filepath,lineno=traceback.extract_tb(sys.exc_traceback)[1][:2]
|
||||
print >>sys.stderr, u"Line: %s in file %s"%(lineno, filepath)
|
||||
print >>sys.stderr, x
|
||||
raise ReadlineError(u"Error reading .pyinputrc")
|
||||
print("Error reading .pyinputrc", file=sys.stderr)
|
||||
filepath, lineno = traceback.extract_tb(sys.exc_traceback)[1][:2]
|
||||
print("Line: %s in file %s"%(lineno, filepath), file=sys.stderr)
|
||||
print(x, file=sys.stderr)
|
||||
raise ReadlineError("Error reading .pyinputrc")
|
||||
|
||||
|
||||
|
||||
@@ -433,15 +434,15 @@ class Readline(BaseReadline):
|
||||
## Internal functions
|
||||
|
||||
def _bell(self):
|
||||
u'''ring the bell if requested.'''
|
||||
if self.bell_style == u'none':
|
||||
'''ring the bell if requested.'''
|
||||
if self.bell_style == 'none':
|
||||
pass
|
||||
elif self.bell_style == u'visible':
|
||||
raise NotImplementedError(u"Bellstyle visible is not implemented yet.")
|
||||
elif self.bell_style == u'audible':
|
||||
elif self.bell_style == 'visible':
|
||||
raise NotImplementedError("Bellstyle visible is not implemented yet.")
|
||||
elif self.bell_style == 'audible':
|
||||
self.console.bell()
|
||||
else:
|
||||
raise ReadlineError(u"Bellstyle %s unknown."%self.bell_style)
|
||||
raise ReadlineError("Bellstyle %s unknown."%self.bell_style)
|
||||
|
||||
def _clear_after(self):
|
||||
c = self.console
|
||||
@@ -502,7 +503,7 @@ class Readline(BaseReadline):
|
||||
n += 1
|
||||
|
||||
self._update_prompt_pos(n)
|
||||
if hasattr(c, u"clear_to_end_of_window"): #Work around function for ironpython due
|
||||
if hasattr(c, "clear_to_end_of_window"): #Work around function for ironpython due
|
||||
c.clear_to_end_of_window() #to System.Console's lack of FillFunction
|
||||
else:
|
||||
self._clear_after()
|
||||
@@ -514,10 +515,10 @@ class Readline(BaseReadline):
|
||||
|
||||
def callback_read_char(self):
|
||||
#Override base to get automatic newline
|
||||
u'''Reads a character and informs the readline callback interface when a line is received'''
|
||||
'''Reads a character and informs the readline callback interface when a line is received'''
|
||||
if self.keyboard_poll():
|
||||
line = self.get_line_buffer() + u'\n'
|
||||
self.console.write(u"\r\n")
|
||||
line = self.get_line_buffer() + '\n'
|
||||
self.console.write("\r\n")
|
||||
# however there is another newline added by
|
||||
# self.mode.readline_setup(prompt) which is called by callback_handler_install
|
||||
# this differs from GNU readline
|
||||
@@ -559,31 +560,31 @@ class Readline(BaseReadline):
|
||||
self._update_line()
|
||||
return result
|
||||
|
||||
def readline_setup(self, prompt=u''):
|
||||
def readline_setup(self, prompt=''):
|
||||
BaseReadline.readline_setup(self, prompt)
|
||||
self._print_prompt()
|
||||
self._update_line()
|
||||
|
||||
def readline(self, prompt=u''):
|
||||
def readline(self, prompt=''):
|
||||
self.readline_setup(prompt)
|
||||
self.ctrl_c_timeout = time.time()
|
||||
self._readline_from_keyboard()
|
||||
self.console.write(u'\r\n')
|
||||
log(u'returning(%s)' % self.get_line_buffer())
|
||||
return self.get_line_buffer() + u'\n'
|
||||
self.console.write('\r\n')
|
||||
log('returning(%s)' % self.get_line_buffer())
|
||||
return self.get_line_buffer() + '\n'
|
||||
|
||||
def handle_ctrl_c(self):
|
||||
from pyreadline.keysyms.common import KeyPress
|
||||
from pyreadline.console.event import Event
|
||||
log(u"KBDIRQ")
|
||||
log("KBDIRQ")
|
||||
event = Event(0,0)
|
||||
event.char = u"c"
|
||||
event.keyinfo = KeyPress(u"c", shift=False, control=True,
|
||||
event.char = "c"
|
||||
event.keyinfo = KeyPress("c", shift=False, control=True,
|
||||
meta=False, keyname=None)
|
||||
if self.allow_ctrl_c:
|
||||
now = time.time()
|
||||
if (now - self.ctrl_c_timeout) < self.ctrl_c_tap_time_interval:
|
||||
log(u"Raise KeyboardInterrupt")
|
||||
log("Raise KeyboardInterrupt")
|
||||
raise KeyboardInterrupt
|
||||
else:
|
||||
self.ctrl_c_timeout = now
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
+12
-11
@@ -5,6 +5,7 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
from pyreadline.modes.emacs import *
|
||||
from pyreadline import keysyms
|
||||
from pyreadline.lineeditor import lineobj
|
||||
@@ -13,7 +14,7 @@ from pyreadline.keysyms.common import make_KeyPress_from_keydescr
|
||||
import unittest
|
||||
class MockReadline:
|
||||
def __init__ (self):
|
||||
self.l_buffer=lineobj.ReadLineTextBuffer(u"")
|
||||
self.l_buffer=lineobj.ReadLineTextBuffer("")
|
||||
self._history=history.LineHistory()
|
||||
|
||||
def add_history (self, line):
|
||||
@@ -26,7 +27,7 @@ class MockReadline:
|
||||
pass
|
||||
|
||||
def insert_text(self, string):
|
||||
u'''Insert text into the command line.'''
|
||||
'''Insert text into the command line.'''
|
||||
self.l_buffer.insert_text(string)
|
||||
|
||||
|
||||
@@ -52,20 +53,20 @@ class MockConsole:
|
||||
|
||||
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' '
|
||||
if char=="escape":
|
||||
self.char='\x1b'
|
||||
elif char=="backspace":
|
||||
self.char='\x08'
|
||||
elif char=="tab":
|
||||
self.char='\t'
|
||||
elif char=="space":
|
||||
self.char=' '
|
||||
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'"':
|
||||
if len(keytext) == 3 and keytext[0] == '"' and keytext[2] == '"':
|
||||
event = Event (keytext[1])
|
||||
else:
|
||||
event = Event (keyinfo.tuple() [3])
|
||||
|
||||
+185
-186
@@ -6,10 +6,11 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import sys, unittest
|
||||
import pdb
|
||||
sys.path.insert(0, u'../..')
|
||||
sys.path.insert(0, '../..')
|
||||
from pyreadline.modes.emacs import *
|
||||
from pyreadline import keysyms
|
||||
from pyreadline.lineeditor import lineobj
|
||||
@@ -18,7 +19,7 @@ from pyreadline.test.common import *
|
||||
from pyreadline.logger import log
|
||||
import pyreadline.logger as logger
|
||||
logger.sock_silent=True
|
||||
logger.show_event=[u"debug"]
|
||||
logger.show_event=["debug"]
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
@@ -31,7 +32,7 @@ class EmacsModeTest (EmacsMode):
|
||||
self.init_editing_mode (None)
|
||||
self.lst_completions = []
|
||||
self.completer = self.mock_completer
|
||||
self.completer_delims = u' u'
|
||||
self.completer_delims = ' '
|
||||
self.tabstop = 4
|
||||
self.mark_directories=False
|
||||
self.show_all_if_ambiguous=False
|
||||
@@ -52,15 +53,15 @@ class EmacsModeTest (EmacsMode):
|
||||
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]]
|
||||
if keytext[0:1] == '"' and keytext[-1:] == '"':
|
||||
lst_key = ['"%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__))
|
||||
log("keydisp: %s %s"%( key,dispatch_func.__name__))
|
||||
dispatch_func (event)
|
||||
self.previous_func=dispatch_func
|
||||
|
||||
@@ -78,141 +79,141 @@ class EmacsModeTest (EmacsMode):
|
||||
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)
|
||||
keyinfo, event = keytext_to_keyinfo_and_event ('"d"')
|
||||
self.assertEqual ('d', event.char)
|
||||
keyinfo, event = keytext_to_keyinfo_and_event ('"D"')
|
||||
self.assertEqual ('D', event.char)
|
||||
keyinfo, event = keytext_to_keyinfo_and_event ('"$"')
|
||||
self.assertEqual ('$', event.char)
|
||||
keyinfo, event = keytext_to_keyinfo_and_event ('Escape')
|
||||
self.assertEqual ('\x1b', event.char)
|
||||
|
||||
|
||||
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, '')
|
||||
r.input('"First Second Third"')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Control-a')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Control-a')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
r.input(u'Control-e')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Control-e')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Home')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Home')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
r.input(u'Right')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Right')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 1)
|
||||
r.input(u'Ctrl-f')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-f')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Ctrl-Right')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Right')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 5)
|
||||
r.input(u'Ctrl-Right')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Right')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 12)
|
||||
r.input(u'Ctrl-Right')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Right')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Ctrl-Right')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Right')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Ctrl-Left')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Left')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 13)
|
||||
r.input(u'Ctrl-Left')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Left')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 6)
|
||||
r.input(u'Ctrl-Left')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Left')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
r.input(u'Ctrl-Left')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Ctrl-Left')
|
||||
self.assertEqual (r.line, '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, '')
|
||||
r.input('"First Second Third"')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Delete')
|
||||
self.assertEqual (r.line, u'First Second Third')
|
||||
r.input('Delete')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Left')
|
||||
r.input('Left')
|
||||
r.input('Delete')
|
||||
self.assertEqual (r.line, 'First Second Thid')
|
||||
self.assertEqual (r.line_cursor, 16)
|
||||
r.input(u'Delete')
|
||||
self.assertEqual (r.line, u'First Second Thi')
|
||||
r.input('Delete')
|
||||
self.assertEqual (r.line, 'First Second Thi')
|
||||
self.assertEqual (r.line_cursor, 16)
|
||||
r.input(u'Backspace')
|
||||
self.assertEqual (r.line, u'First Second Th')
|
||||
r.input('Backspace')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Home')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
self.assertEqual (r.line, 'First Second Th')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Backspace')
|
||||
self.assertEqual (r.line, u'Frst Second Th')
|
||||
r.input('Backspace')
|
||||
self.assertEqual (r.line, 'Frst Second Th')
|
||||
self.assertEqual (r.line_cursor, 1)
|
||||
r.input(u'Backspace')
|
||||
self.assertEqual (r.line, u'rst Second Th')
|
||||
r.input('Backspace')
|
||||
self.assertEqual (r.line, 'rst Second Th')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
r.input(u'Backspace')
|
||||
self.assertEqual (r.line, u'rst Second Th')
|
||||
r.input('Backspace')
|
||||
self.assertEqual (r.line, 'rst Second Th')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
r.input(u'Escape')
|
||||
self.assertEqual (r.line, u'')
|
||||
r.input('Escape')
|
||||
self.assertEqual (r.line, '')
|
||||
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, '')
|
||||
r.input('"First Second Third"')
|
||||
self.assertEqual (r.line, 'First Second Third')
|
||||
self.assertEqual (r.line_cursor, 18)
|
||||
r.input(u'Control-Backspace')
|
||||
self.assertEqual (r.line, u'First Second ')
|
||||
r.input('Control-Backspace')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Backspace')
|
||||
r.input('Left')
|
||||
r.input('Left')
|
||||
self.assertEqual (r.line, 'First Second')
|
||||
self.assertEqual (r.line_cursor, 10)
|
||||
r.input(u'Control-Backspace')
|
||||
self.assertEqual (r.line, u'First nd')
|
||||
r.input('Control-Backspace')
|
||||
self.assertEqual (r.line, 'First nd')
|
||||
self.assertEqual (r.line_cursor, 6)
|
||||
r.input(u'Escape')
|
||||
self.assertEqual (r.line, u'')
|
||||
r.input('Escape')
|
||||
self.assertEqual (r.line, '')
|
||||
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')
|
||||
r.input('"First Second Third"')
|
||||
r.input('Home')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
r.input('Control-Delete')
|
||||
self.assertEqual (r.line, 'FiSecond Third')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Control-Delete')
|
||||
self.assertEqual (r.line, u'FiThird')
|
||||
r.input('Control-Delete')
|
||||
self.assertEqual (r.line, 'FiThird')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Control-Delete')
|
||||
self.assertEqual (r.line, u'Fi')
|
||||
r.input('Control-Delete')
|
||||
self.assertEqual (r.line, 'Fi')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Control-Delete')
|
||||
self.assertEqual (r.line, u'Fi')
|
||||
r.input('Control-Delete')
|
||||
self.assertEqual (r.line, 'Fi')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input(u'Escape')
|
||||
self.assertEqual (r.line, u'')
|
||||
r.input('Escape')
|
||||
self.assertEqual (r.line, '')
|
||||
self.assertEqual (r.line_cursor, 0)
|
||||
|
||||
|
||||
@@ -220,30 +221,30 @@ class TestsDelete (unittest.TestCase):
|
||||
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, '')
|
||||
r.input('"First Second Third"')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Home')
|
||||
r.input('Shift-Right')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Shift-Control-Right')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('"a"')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Shift-End')
|
||||
self.assertEqual (r.line, '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')
|
||||
r.input('Delete')
|
||||
self.assertEqual (r.line, 'a')
|
||||
self.assertEqual (r.line_cursor, 1)
|
||||
self.assertEqual (r.l_buffer.selection_mark, -1)
|
||||
|
||||
@@ -252,94 +253,94 @@ class TestsSelectionMovement (unittest.TestCase):
|
||||
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')
|
||||
r.add_history ('aa')
|
||||
r.add_history ('bbb')
|
||||
self.assertEqual (r.line, '')
|
||||
r.input ('Up')
|
||||
self.assertEqual (r.line, 'bbb')
|
||||
self.assertEqual (r.line_cursor, 3)
|
||||
r.input (u'Up')
|
||||
self.assertEqual (r.line, u'aa')
|
||||
r.input ('Up')
|
||||
self.assertEqual (r.line, 'aa')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input (u'Up')
|
||||
self.assertEqual (r.line, u'aa')
|
||||
r.input ('Up')
|
||||
self.assertEqual (r.line, 'aa')
|
||||
self.assertEqual (r.line_cursor, 2)
|
||||
r.input (u'Down')
|
||||
self.assertEqual (r.line, u'bbb')
|
||||
r.input ('Down')
|
||||
self.assertEqual (r.line, 'bbb')
|
||||
self.assertEqual (r.line_cursor, 3)
|
||||
r.input (u'Down')
|
||||
self.assertEqual (r.line, u'')
|
||||
r.input ('Down')
|
||||
self.assertEqual (r.line, '')
|
||||
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')
|
||||
r.add_history ('aaaa')
|
||||
r.add_history ('aaba')
|
||||
r.add_history ('aaca')
|
||||
r.add_history ('akca')
|
||||
r.add_history ('bbb')
|
||||
r.add_history ('ako')
|
||||
self.assert_line(r,'',0)
|
||||
r.input (u'"a"')
|
||||
r.input (u'Up')
|
||||
r.input ('"a"')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'ako',1)
|
||||
r.input (u'Up')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'akca',1)
|
||||
r.input (u'Up')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'aaca',1)
|
||||
r.input (u'Up')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'aaba',1)
|
||||
r.input (u'Up')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'aaaa',1)
|
||||
r.input (u'Right')
|
||||
r.input ('Right')
|
||||
self.assert_line(r,'aaaa',2)
|
||||
r.input (u'Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'aaba',2)
|
||||
r.input (u'Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'aaca',2)
|
||||
r.input (u'Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'aaca',2)
|
||||
r.input (u'Left')
|
||||
r.input (u'Left')
|
||||
r.input (u'Down')
|
||||
r.input (u'Down')
|
||||
r.input ('Left')
|
||||
r.input ('Left')
|
||||
r.input ('Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'bbb',3)
|
||||
r.input (u'Left')
|
||||
r.input ('Left')
|
||||
self.assert_line(r,'bbb',2)
|
||||
r.input (u'Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'bbb',2)
|
||||
r.input (u'Up')
|
||||
r.input ('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')
|
||||
r.add_history ('aaaa')
|
||||
r.add_history ('aaba')
|
||||
r.add_history ('aaca')
|
||||
r.add_history ('akca')
|
||||
r.add_history ('bbb')
|
||||
r.add_history ('ako')
|
||||
self.assert_line(r,'',0)
|
||||
r.input (u'')
|
||||
r.input (u'Up')
|
||||
r.input ('')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'ako',3)
|
||||
r.input (u'Down')
|
||||
r.input ('Down')
|
||||
self.assert_line(r,'',0)
|
||||
r.input (u'Up')
|
||||
r.input ('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')
|
||||
r.add_history ('aaaa')
|
||||
r.add_history ('aaba')
|
||||
r.add_history ('aaca')
|
||||
r.add_history ('akca')
|
||||
r.add_history ('bbb')
|
||||
r.add_history ('ako')
|
||||
self.assert_line(r,'',0)
|
||||
r.input (u'k')
|
||||
r.input (u'Up')
|
||||
r.input ('k')
|
||||
r.input ('Up')
|
||||
self.assert_line(r,'k',1)
|
||||
|
||||
def test_complete (self):
|
||||
@@ -354,22 +355,22 @@ class TestsHistory (unittest.TestCase):
|
||||
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('"exi(ksdjksjd)"')
|
||||
r.input('Control-a')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
r.input('Tab')
|
||||
self.assert_line(r, "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)
|
||||
r.input('Escape')
|
||||
r.input('"exi"')
|
||||
r.input('Control-a')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
r.input('Right')
|
||||
r.input('Tab')
|
||||
self.assert_line(r, "exit", 4)
|
||||
|
||||
|
||||
|
||||
@@ -382,19 +383,17 @@ class TestsHistory (unittest.TestCase):
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
Tester()
|
||||
tested=EmacsModeTest.tested_commands.keys()
|
||||
tested.sort()
|
||||
# print " Tested functions ".center(60,"-")
|
||||
# print "\n".join(tested)
|
||||
# print
|
||||
# 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)
|
||||
|
||||
|
||||
print(" Not tested functions ".center(60,"-"))
|
||||
print("\n".join(not_tested))
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: UTF-8 -*-
|
||||
# Copyright (C) 2007 Jörgen Stenarson. <>
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import sys, unittest
|
||||
sys.path.append (u'../..')
|
||||
sys.path.append ('../..')
|
||||
#from pyreadline.modes.vi import *
|
||||
#from pyreadline import keysyms
|
||||
from pyreadline.lineeditor import lineobj
|
||||
@@ -19,110 +20,110 @@ from pyreadline.logger import log
|
||||
RL=lineobj.ReadLineTextBuffer
|
||||
|
||||
class Test_prev_next_history(unittest.TestCase):
|
||||
t = u"test text"
|
||||
t = "test text"
|
||||
|
||||
def setUp(self):
|
||||
self.q = q = LineHistory()
|
||||
for x in [u"aaaa", u"aaba", u"aaca", u"akca", u"bbb", u"ako"]:
|
||||
for x in ["aaaa", "aaba", "aaca", "akca", "bbb", "ako"]:
|
||||
q.add_history(RL(x))
|
||||
|
||||
def test_previous_history (self):
|
||||
hist = self.q
|
||||
assert hist.history_cursor == 6
|
||||
l = RL(u"")
|
||||
l = RL("")
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"ako"
|
||||
assert l.get_line_text() == "ako"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"bbb"
|
||||
assert l.get_line_text() == "bbb"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"akca"
|
||||
assert l.get_line_text() == "akca"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"aaca"
|
||||
assert l.get_line_text() == "aaca"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"aaba"
|
||||
assert l.get_line_text() == "aaba"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"aaaa"
|
||||
assert l.get_line_text() == "aaaa"
|
||||
hist.previous_history(l)
|
||||
assert l.get_line_text() == u"aaaa"
|
||||
assert l.get_line_text() == "aaaa"
|
||||
|
||||
def test_next_history (self):
|
||||
hist=self.q
|
||||
hist.beginning_of_history()
|
||||
assert hist.history_cursor==0
|
||||
l=RL(u"")
|
||||
l=RL("")
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"aaba"
|
||||
assert l.get_line_text()=="aaba"
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"aaca"
|
||||
assert l.get_line_text()=="aaca"
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"akca"
|
||||
assert l.get_line_text()=="akca"
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"bbb"
|
||||
assert l.get_line_text()=="bbb"
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"ako"
|
||||
assert l.get_line_text()=="ako"
|
||||
hist.next_history(l)
|
||||
assert l.get_line_text()==u"ako"
|
||||
assert l.get_line_text()=="ako"
|
||||
|
||||
class Test_prev_next_history(unittest.TestCase):
|
||||
t = u"test text"
|
||||
t = "test text"
|
||||
|
||||
def setUp(self):
|
||||
self.q = q = LineHistory()
|
||||
for x in [u"aaaa",u"aaba",u"aaca",u"akca",u"bbb",u"ako"]:
|
||||
for x in ["aaaa","aaba","aaca","akca","bbb","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"]:
|
||||
for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","ako"]:
|
||||
q.add_history(RL(x))
|
||||
a=RL(u"aa",point=2)
|
||||
for x in [u"aaca",u"aaba",u"aaaa",u"aaaa"]:
|
||||
a=RL("aa",point=2)
|
||||
for x in ["aaca","aaba","aaaa","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"]:
|
||||
for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","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"]:
|
||||
a=RL("aa",point=2)
|
||||
for x in ["aaba","aaca","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"]:
|
||||
for x in ["aaaa","aaba","aaca","akca","bbb","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")
|
||||
self.assertEqual(q.reverse_search_history("b"), "bbb")
|
||||
self.assertEqual(q.reverse_search_history("b"), "aaba")
|
||||
self.assertEqual(q.reverse_search_history("bb"), "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")
|
||||
self.assertEqual(q.reverse_search_history("a"), "ako")
|
||||
self.assertEqual(q.reverse_search_history("aa"), "aaca")
|
||||
self.assertEqual(q.reverse_search_history("a"), "aaca")
|
||||
self.assertEqual(q.reverse_search_history("ab"), "aaba")
|
||||
|
||||
|
||||
def test_forward_1(self):
|
||||
q = self.q
|
||||
self.assertEqual(q.forward_search_history(u"a"), u"ako")
|
||||
self.assertEqual(q.forward_search_history("a"), "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")
|
||||
self.assertEqual(q.forward_search_history("a"), "aaaa")
|
||||
self.assertEqual(q.forward_search_history("a"), "aaba")
|
||||
self.assertEqual(q.forward_search_history("ak"), "akca")
|
||||
self.assertEqual(q.forward_search_history("akl"), "akca")
|
||||
self.assertEqual(q.forward_search_history("ak"), "akca")
|
||||
self.assertEqual(q.forward_search_history("ako"), "ako")
|
||||
|
||||
class Test_empty_history_search_incr_fwd_backwd(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -130,11 +131,11 @@ class Test_empty_history_search_incr_fwd_backwd(unittest.TestCase):
|
||||
|
||||
def test_backward_1(self):
|
||||
q = self.q
|
||||
self.assertEqual(q.reverse_search_history(u"b"), u"")
|
||||
self.assertEqual(q.reverse_search_history("b"), "")
|
||||
|
||||
def test_forward_1(self):
|
||||
q = self.q
|
||||
self.assertEqual(q.forward_search_history(u"a"), u"")
|
||||
self.assertEqual(q.forward_search_history("a"), "")
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
@@ -142,7 +143,7 @@ class Test_empty_history_search_incr_fwd_backwd(unittest.TestCase):
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
l=lineobj.ReadLineTextBuffer(u"First Second Third")
|
||||
l=lineobj.ReadLineTextBuffer("First Second Third")
|
||||
+138
-137
@@ -1,7 +1,8 @@
|
||||
# Copyright (C) 2006 Michael Graz. <mgraz@plan10.com>
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
|
||||
import sys, unittest
|
||||
sys.path.append (u'../..')
|
||||
sys.path.append ('../..')
|
||||
#from pyreadline.modes.vi import *
|
||||
#from pyreadline import keysyms
|
||||
from pyreadline.lineeditor import lineobj
|
||||
@@ -13,14 +14,14 @@ from pyreadline.lineeditor import lineobj
|
||||
|
||||
class Test_copy (unittest.TestCase):
|
||||
def test_copy1 (self):
|
||||
l=lineobj.ReadLineTextBuffer(u"first second")
|
||||
l=lineobj.ReadLineTextBuffer("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)
|
||||
l=lineobj.ReadLineTextBuffer("first second",point=5)
|
||||
q=l.copy()
|
||||
self.assertEqual(q.get_line_text(),l.get_line_text())
|
||||
self.assertEqual(q.point,l.point)
|
||||
@@ -77,19 +78,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_NextChar (self):
|
||||
cmd=lineobj.NextChar
|
||||
tests=[
|
||||
# u"First"
|
||||
# "First"
|
||||
(cmd,
|
||||
u"First",
|
||||
u"# u",
|
||||
u" # u"),
|
||||
"First",
|
||||
"# ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First",
|
||||
u" # u",
|
||||
u" #"),
|
||||
"First",
|
||||
" # ",
|
||||
" #"),
|
||||
(cmd,
|
||||
u"First",
|
||||
u" #",
|
||||
u" #"),
|
||||
"First",
|
||||
" #",
|
||||
" #"),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -99,19 +100,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_PrevChar (self):
|
||||
cmd=lineobj.PrevChar
|
||||
tests=[
|
||||
# u"First"
|
||||
# "First"
|
||||
(cmd,
|
||||
u"First",
|
||||
u" #",
|
||||
u" # u"),
|
||||
"First",
|
||||
" #",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First",
|
||||
u" # u",
|
||||
u"# u"),
|
||||
"First",
|
||||
" # ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First",
|
||||
u"# u",
|
||||
u"# u"),
|
||||
"First",
|
||||
"# ",
|
||||
"# "),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -123,23 +124,23 @@ class Test_movement (unittest.TestCase):
|
||||
def test_PrevWordStart (self):
|
||||
cmd=lineobj.PrevWordStart
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" #",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
"# "),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -149,23 +150,23 @@ class Test_movement (unittest.TestCase):
|
||||
def test_NextWordStart (self):
|
||||
cmd=lineobj.NextWordStart
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" #"),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -175,23 +176,23 @@ class Test_movement (unittest.TestCase):
|
||||
def test_NextWordEnd (self):
|
||||
cmd=lineobj.NextWordEnd
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" #"),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -201,23 +202,23 @@ class Test_movement (unittest.TestCase):
|
||||
def test_PrevWordEnd (self):
|
||||
cmd=lineobj.PrevWordEnd
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" #",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
"# "),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -227,19 +228,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_WordEnd_1 (self):
|
||||
cmd=lineobj.WordEnd
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" #"),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -249,16 +250,16 @@ class Test_movement (unittest.TestCase):
|
||||
def test_WordEnd_2 (self):
|
||||
cmd=lineobj.WordEnd
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" #"),
|
||||
]
|
||||
|
||||
for cmd,text,init_point in tests:
|
||||
@@ -269,19 +270,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_WordStart_1 (self):
|
||||
cmd=lineobj.WordStart
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" # "),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -291,16 +292,16 @@ class Test_movement (unittest.TestCase):
|
||||
def test_WordStart_2 (self):
|
||||
cmd=lineobj.WordStart
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u"),
|
||||
"First Second Third",
|
||||
" # "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" #"),
|
||||
]
|
||||
|
||||
for cmd,text,init_point in tests:
|
||||
@@ -311,19 +312,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_StartOfLine (self):
|
||||
cmd=lineobj.StartOfLine
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
"# "),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #",
|
||||
u"# u"),
|
||||
"First Second Third",
|
||||
" #",
|
||||
"# "),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -333,19 +334,19 @@ class Test_movement (unittest.TestCase):
|
||||
def test_EndOfLine (self):
|
||||
cmd=lineobj.EndOfLine
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u"# u",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
"# ",
|
||||
" #"),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" # u",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" # ",
|
||||
" #"),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
u" #",
|
||||
u" #"),
|
||||
"First Second Third",
|
||||
" #",
|
||||
" #"),
|
||||
]
|
||||
for cmd,text,init_point,expected_point in tests:
|
||||
l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
|
||||
@@ -355,15 +356,15 @@ class Test_movement (unittest.TestCase):
|
||||
def test_Point(self):
|
||||
cmd=lineobj.Point
|
||||
tests=[
|
||||
# u"First Second Third"
|
||||
# "First Second Third"
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
"First Second Third",
|
||||
0),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
"First Second Third",
|
||||
12),
|
||||
(cmd,
|
||||
u"First Second Third",
|
||||
"First Second Third",
|
||||
18),
|
||||
]
|
||||
for cmd,text,p in tests:
|
||||
@@ -375,16 +376,16 @@ class Test_movement (unittest.TestCase):
|
||||
# utility functions
|
||||
|
||||
def get_point_pos(pstr):
|
||||
return pstr.index(u"#")
|
||||
return pstr.index("#")
|
||||
|
||||
def get_mark_pos(mstr):
|
||||
try:
|
||||
return mstr.index(u"#")
|
||||
return mstr.index("#")
|
||||
except ValueError:
|
||||
return -1
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
if __name__ == u'__main__':
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
l=lineobj.ReadLineTextBuffer(u"First Second Third")
|
||||
l=lineobj.ReadLineTextBuffer("First Second Third")
|
||||
|
||||
+1293
-1292
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#*****************************************************************************
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
import sys
|
||||
|
||||
try:
|
||||
@@ -12,10 +13,10 @@ try:
|
||||
except AttributeError:
|
||||
# This error occurs when pdb imports readline and doctest has replaced
|
||||
# stdout with stdout collector. We will assume ascii codepage
|
||||
pyreadline_codepage = u"ascii"
|
||||
pyreadline_codepage = "ascii"
|
||||
|
||||
if pyreadline_codepage is None:
|
||||
pyreadline_codepage = u"ascii"
|
||||
pyreadline_codepage = "ascii"
|
||||
|
||||
if sys.version_info < (2, 6):
|
||||
bytes = str
|
||||
@@ -23,21 +24,21 @@ if sys.version_info < (2, 6):
|
||||
PY3 = (sys.version_info >= (3, 0))
|
||||
|
||||
def ensure_unicode(text):
|
||||
u"""helper to ensure that text passed to WriteConsoleW is unicode"""
|
||||
"""helper to ensure that text passed to WriteConsoleW is unicode"""
|
||||
if isinstance(text, bytes):
|
||||
try:
|
||||
return text.decode(pyreadline_codepage, u"replace")
|
||||
return text.decode(pyreadline_codepage, "replace")
|
||||
except (LookupError, TypeError):
|
||||
return text.decode(u"ascii", u"replace")
|
||||
return text.decode("ascii", "replace")
|
||||
return text
|
||||
|
||||
def ensure_str(text):
|
||||
u"""Convert unicode to str using pyreadline_codepage"""
|
||||
"""Convert unicode to str using pyreadline_codepage"""
|
||||
if isinstance(text, unicode):
|
||||
try:
|
||||
return text.encode(pyreadline_codepage, u"replace")
|
||||
return text.encode(pyreadline_codepage, "replace")
|
||||
except (LookupError, TypeError):
|
||||
return text.encode(u"ascii", u"replace")
|
||||
return text.encode("ascii", "replace")
|
||||
return text
|
||||
|
||||
def biter(text):
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
#this file is needed in site-packages to emulate readline
|
||||
#necessary for rlcompleter since it relies on the existance
|
||||
#of a readline module
|
||||
from __future__ import print_function, unicode_literals, absolute_import
|
||||
from pyreadline.rlmain import Readline
|
||||
|
||||
__all__ = [ 'parse_and_bind',
|
||||
@@ -39,7 +40,7 @@ if rl.disable_readline:
|
||||
globals()[funk] = dummy
|
||||
else:
|
||||
def GetOutputFile():
|
||||
u'''Return the console object used by readline so that it can be used for printing in color.'''
|
||||
'''Return the console object used by readline so that it can be used for printing in color.'''
|
||||
return rl.console
|
||||
__all__.append("GetOutputFile")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user