Autocomplete disappearing after triggering - sublimetext

I'm trying to trigger autocomplete to show itself after certain words are entered and finalized with a space which does work but only after double tapping space. It does momentarily show the autocomplete when you press space once but then disappears. Only after tapping space again does it show autocomplete and stays. Putting in print() statements to check if it's triggering on the first space does show it works fine but why it closes straight away, I don't know.
Current code:
class ScriptListener(sublime_plugin.EventListener):
commands = [
'&Command1',
'&Command2'
]
Command1_completions = [
'param1=',
'param2='
]
Command2_completions = [
'param1=',
'param2='
]
last_word = ""
current_row = ""
def on_query_completions(self, view, prefix, locations):
if not view.match_selector(locations[0], "source.script"):
return None
if self.last_word == self.commands[0] or self.commands[0] in self.current_row:
return self._remove_known_arguments(self.Command1_completions)
elif self.last_word == self.commands[1] or self.commands[1] in self.current_row:
return self._remove_known_arguments(self.Command2_completions)
else:
return None
def on_modified(self, view):
for region in view.sel():
if (' ' in view.substr(view.word(region))):
self.current_row = view.substr(view.line(view.sel()[0]))
if any(command in self.current_row for command in self.commands):
view.run_command("auto_complete")
else:
self.last_word = view.substr(view.word(region))
def on_selection_modified(self, view):
#Get current row
self.current_row = view.substr(view.line(view.sel()[0]))
def _remove_known_arguments(self, comp_list):
for arg in comp_list:
if (arg in self.current_row):
comp_list.remove(arg)
return comp_list

Related

tk.Entry validate command doesn't restore previous value when False returned

I have carefully reviewed answers to Interactively validating Entry widget content in tkinter, but my script fails to restore previous value if the validate command returns False. I captured %P and %s and print them out...They both show the same value.
import tkinter as tk
class Controller :
def __init__(self) :
i=10
j=20
# list comprehension
self.entry_widgets = [[None for col in range(j)] for row in range(i)]
#print(self.entry_widgets)
self.values = [["string"+str(row) + str(col) for col in range(10)] for row in range(20)]
#print(self.values)
class EnterBox(tk.Entry):
def __init__(self,*args,**kwargs):
#print (args)
self._modified = False
self._save = 0
self._raise = 1
self._lower = 2
frame, i,j, *newargs = args
self._content = tk.StringVar()
# tk.Entry.__init__(self,frame,*newargs,
# validate = 'focusout',
# validatecommand = vcmd,
# **kwargs)
tk.Entry.__init__(self,frame,*newargs,**kwargs)
vcmd = (self.register(self._revert), '%P', '%s')
ct.entry_widgets[i][j] = self
self.config(textvariable=self._content)
self.config(validate = "focusout")
self.config(validatecommand = vcmd )
x=(ct.values[i][j])
self.insert(0,x)
#self._content.set(x)
self.bind("<Return>",lambda event, x=self._save : self._action(event,x) )
self.bind("<Button-2>",lambda event, x=self._save : self._action(event,x) )
self.bind("<FocusIn>", lambda event, x=self._raise : self._action(event,x))
self.bind("<FocusOut>", lambda event, x=self._lower : self._action(event,x))
self.bind('<Button-3>', lambda event, x=self._lower : self._action(event,x))
self.grid(column=i+1,row=j+2)
def _revert(self,P,s):
print ("Hi There")
print(P)
print(s)
return False
def _action(self,event,action):
print(str(action)+' ' + str(event))
if action == self._save :
ct.values[i][j] = self._content.get()
self.config(bg='lightskyblue2')
self._modified = True
elif action == self._raise :
self.config(bg = 'light pink')
elif action == self._lower :
self.config(bg = 'gray80')
self._modified = False
else :
print('action value is bad action =>' + str(action))
if "__main__" == __name__ :
root = tk.Tk()
frame = tk.Frame()
i=j=0
ct = Controller()
root.grid()
frame.grid()
check = EnterBox(frame,i,j,width = 24)
check2 = EnterBox(frame,i+1,j,width = 24)
root.mainloop()
I have tried removing all other bindings, to no avail.
Interestingly, but a separate issue, If I use StringVar. set instead of self.insert, (see commented out line) the validate command runs once, and never again despite several focus changes. Using Python 3.8
The validation isn't designed to restore anything if the validation happens on focusout. The validation can only prevent characters from being added at the time they are added. You will have to add code to restore the previous value.

Entry validation fails when replacing spaces with empty strings

I am not sure why validation stops working after I end up replacing spaces in a string.
The validation works fine for most things I need. It allows for only numbers and up to 10 of them while also allowing for back spaces and highlighting all and back spacing. It also works once when pasting in values that contain spaces.
For example if I try to paste 12 34 into the entry field it will correctly change the value to 1234 but after that validation just stops working.
Update:
It appears that validation stops working after entry.delete() though I still am not sure how to correct this. I have tried to redefine the validation but that did not work.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.vcmd = (self.register(self.validate), '%d', '%P', '%s')
self.entry = tk.Entry(self, validate='key', validatecommand=self.vcmd)
self.entry.pack()
def validate(self, *a):
b = a[1].replace(' ', '')
if b.isdigit() and len(b) <= 10 or ((b == '' or b < a[2]) and a[0] == '0'):
if ' ' in a[1]:
x = a[1]
x = x.replace(' ', '')
self.entry.delete(0, 'end')
self.entry.insert(0, x)
return True
else:
return False
App().mainloop()
Update:
I managed to get it working by deleting the entry field and redefining it and its validation after inserting the new string. But this seams like the wrong way to do this.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.vcmd = (self.register(self.validate), '%d', '%P', '%s')
self.entry = tk.Entry(self, validate='key', validatecommand=self.vcmd)
self.entry.pack()
def validate(self, *a):
b = a[1].replace(' ', '')
if b.isdigit() and len(b) <= 10 or ((b == '' or b < a[2]) and a[0] == '0'):
if ' ' in a[1]:
x = a[1]
x = x.replace(' ', '')
self.entry.destroy()
self.entry = tk.Entry(self)
self.entry.insert(0, x)
self.entry.config(validate='key', validatecommand=self.vcmd)
self.entry.pack()
return True
else:
return False
App().mainloop()
I am not sure why validation stops working after I end up replacing spaces in a string. The validation works fine for most things I need.
It stops working because that's how it is designed to work. If you try to modify the data from within the validation function, the validate option is automatically reset to "none".
This is what the official tcl/tk documentation says:
The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand.
You will need to reset the validate option in the case where you modify the widget from within the validation function.

Tool/Algorithm for text comparision after every key hit

I am struggling to find a text comparison tool or algorithm that can compare an expected text against the current state of the text being typed.
I will have an experimentee typewrite a text that he has in front of his eyes. My idea is to compare the current state of the text against the expected text whenever something is typed. That way I want to find out when and what the subject does wrong (I also want to find errors that are not in the resulting text but were in the intermediate text for some time).
Can someone point me in a direction?
Update #1
I have access to the typing data in a csv format:
This is example output data of me typing "foOBar". Every line has the form (timestamp, Key, Press/Release)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
In Python
Given your input csv file (I called it keyboard_records.csv)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
The following code does the following:
Read its content and store it in a list named steps
For each step in steps recognizes what happened and
If it was a shift press or release sets a flag (shift_on) accordingly
If it was an arrow pressed moves the cursor (index of current where we insert characters) – if it the cursor is at the start or at the end of the string it shouldn't move, that's why those min() and max()
If it was a letter/number/symbol it adds it in curret at cursor position and increments cursor
Here you have it
import csv
steps = [] # list of all actions performed by user
expected = "Hello"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
current = [] # text written by the user
shift_on = False # is shift pressed
cursor = 0 # where is the cursor in the current text
for step in steps:
time, key, action = step
if key == 'LeftShift':
if action == 'P':
shift_on = True
else:
shift_on = False
continue
if key == 'LeftArrow' and action == 'P':
cursor = max(0, cursor-1)
continue
if key == 'RightArrow' and action == 'P':
cursor = min(len(current), cursor+1)
continue
if action == 'P':
if shift_on is True:
current.insert(cursor, key.upper())
else:
current.insert(cursor, key.lower())
cursor += 1
# Now you can join current into a string
# and compare current with expected
print(''.join(current)) # printing current (just to see what's happening)
else:
# What to do when a key is released?
# Depends on your needs...
continue
To compare current and expected have a look here.
Note: by playing around with the code above and a few more flags you can make it recognize also symbols. This will depend on your keyboard. In mine Shift + 6 = &, AltGr + E = € and Ctrl + Shift + AltGr + è = {. I think this is a good point to start.
Update
Comparing 2 texts isn't a difficult task and you can find tons of pages on the web about it.
Anyway I wanted to present you an object oriented approach to the problem, so I added the compare part that I previously omitted in the first solution.
This is still a rough code, without primary controls over the input. But, as you asked, this is pointing you in a direction.
class UserText:
# Initialize UserText:
# - empty text
# - cursor at beginning
# - shift off
def __init__(self, expected):
self.expected = expected
self.letters = []
self.cursor = 0
self.shift = False
# compares a and b and returns a
# list containing the indices of
# mismatches between a and b
def compare(a, b):
err = []
for i in range(min(len(a), len(b))):
if a[i] != b[i]:
err.append(i)
return err
# Parse a command given in the
# form (time, key, action)
def parse(self, command):
time, key, action = command
output = ""
if action == 'P':
if key == 'LeftShift':
self.shift = True
elif key == 'LeftArrow':
self.cursor = max(0, self.cursor - 1)
elif key == 'RightArrow':
self.cursor = min(len(self.letters), self.cursor + 1)
else:
# Else, a letter/number was pressed. Let's
# add it to self.letters in cursor position
if self.shift is True:
self.letters.insert(self.cursor, key.upper())
else:
self.letters.insert(self.cursor, key.lower())
self.cursor += 1
########## COMPARE WITH EXPECTED ##########
output += "Expected: \t" + self.expected + "\n"
output += "Current: \t" + str(self) + "\n"
errors = UserText.compare(str(self), self.expected[:len(str(self))])
output += "\t\t"
i = 0
for e in errors:
while i != e:
output += " "
i += 1
output += "^"
i += 1
output += "\n[{} errors at time {}]".format(len(errors), time)
return output
else:
if key == 'LeftShift':
self.shift = False
return output
def __str__(self):
return "".join(self.letters)
import csv
steps = [] # list of all actions performed by user
expected = "foobar"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
ut = UserText(expected)
for step in steps:
print(ut.parse(step))
The output for the csv file above was:
Expected: foobar
Current: f
[0 errors at time 17293398.576653]
Expected: foobar
Current: fo
[0 errors at time 17293401.313254]
Expected: foobar
Current: foO
^
[1 errors at time 17293402.073046]
Expected: foobar
Current: foOB
^^
[2 errors at time 17293403.178612]
Expected: foobar
Current: foOBa
^^
[2 errors at time 17293404.966193]
Expected: foobar
Current: foOBar
^^
[2 errors at time 17293405.725405]
I found the solution to my own question around a year ago. Now i have time to share it with you:
In their 2003 paper 'Metrics for text entry research: An evaluation of MSD and KSPC, and a new unified error metric', R. William Soukoreff and I. Scott MacKenzie propose three major new metrics: 'total error rate', 'corrected error rate' and 'not corrected error rate'. These metrics have become well established since the publication of this paper. These are exaclty the metrics i was looking for.
If you are trying to do something similiar to what i did, e.g. compare the writing performance on different input devices this is the way to go.

wxpython grid: multiple cell edit (ala Excel)

I'm looking for a way for a user to edit data in bulk in a wxPython grid, a little like in Excel when you select a range, type data and press shift-Enter. This is a simplified version of my grid:
class MyGrid(gridlib.Grid):
def __init__(self, panel):
gridlib.Grid.__init__(self, panel)
self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.onEditCell)
self.Bind(gridlib.EVT_GRID_RANGE_SELECT, self.onSelection)
def onSelection(self, event):
if self.GetSelectionBlockTopLeft() == []:
self.selected_row_number = 0
self.selected_col_number = 0
else:
self.selected_row_number = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
self.selected_col_number = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
print self.selected_row_number, self.selected_col_number
def onEditCell(self,event):
print self.selected_row_number, self.selected_col_number
The issue seems to be that the onEditCell event overwrites the previous selection. So I can select e.g. a four by four block in the grid, and onSelection will print 4 4. But when I start typing and press Enter, onEditCell will print 0,0 as if only the cell I'm editing was selected. How can I keep a "memory" of how many cells are selected? Thank you,
Answering my own question: I can get it to work with an ugly hack that doesn't seem like the right way to do things:
def onSelection(self, event):
self.previous_selected_row_number = self.selected_row_number
self.previous_selected_col_number = self.selected_col_number
if self.GetSelectionBlockTopLeft() == []:
self.selected_row_number = 0
self.selected_col_number = 0
else:
self.selected_row_number = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
self.selected_col_number = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
print self.selected_row_number, self.selected_col_number
print self.previous_selected_row_number, self.previous_selected_col_number
def onEditCell(self,event):
print self.previous_selected_row_number, self.previous_selected_col_number
If anyone can think of a better way...

How to override the key search in a treectrl?

i wanna know how to override the default keysearch in a treectrl.
When i bind a method to the EVT_TREE_KEY_DOWN event and call the selectItem method of the treectrl, it doesn't have any effect.
This is my Tree:
Test <--root
-Aero orea(EI)
-Blub(BL)
-Test(AX)
-123(45)
-Blib (LOL)
My intention:
With the keydown event i am concatenating a searchstring. when iterating over the treeitems, i split the names to get the content of the brackets(e.g.:"EI", "BL"...).
Then i check if the content of the brackets starts with my searchstring. if it is true the selectItem(TreeItemId) is called. But this won't work. It seems that the default search ist still working and is causing problems in my keysearch.
class MeinTreeCtrl(wx.TreeCtrl):
def __init__(self, parent):
wx.TreeCtrl.__init__(self, parent, -1)
root = self.AddRoot("test")
self.AppendItem(root, "Aero orea(EI)")
self.AppendItem(root, "Blub(BL)")
self.AppendItem(root, "Test(AX)")
self.AppendItem(root, "123(45)")
self.AppendItem(root, "Blib(LOL)")
self.searchString = ""
self.lastKeyDown = time.time()
parent.Bind(wx.EVT_TREE_KEY_DOWN, self.OnTreeKeySearch, self)
def GetItem(self, match, root):
item = self.GetFirstChild(root)
while item.IsOk():
tmp = self.GetItemText(item)
tmp = tmp.split(")")
tmp = tmp[len(tmp) - 2]
tmp = tmp.split("(")
tmp = tmp[len(tmp) - 1]
if tmp.startswith(match):
self.SelectItem(item)
break
item = self.GetNextChild(root, item)
return False
def OnTreeKeySearch(self, event):
now = time.time()
if self.searchString == "":
self.searchString = chr(event.GetKeyCode())
if (now - self.lastKeyDown) < 3:
self.searchString += str(chr(event.GetKeyCode()))
else:
self.searchString = str(chr(event.GetKeyCode()))
self.lastKeyDown = now
self.GetItem(self.searchString, self.GetRootItem())
Do you have any clue?
Thank you and best regards
Thomas
After a few days of search i found my mistake.
This line was the problem:
parent.Bind(wx.EVT_TREE_KEY_DOWN, self.OnTreeKeySearch, self)
First I need just the EVT_KEY_DOWN not the tree event for key down.
Second I binded the method to my parent not to self (That is because i did copy & paste :( )
This statement was really useful to me:
A typical example of an event not propagated is the wx.EVT_KEY_DOWN.
It is send only to the control having the focus, and will not
propagate to its parent.
-- EventPropagation

Resources