misc/python/requery.py
2018-08-05 18:53:07 +02:00

124 lines
2.9 KiB
Python
Executable File

#!/usr/bin/env nix-script
#!>python3
## Regex tester
import tkinter
import tkinter.messagebox
import traceback
class Text(tkinter.Text):
"""
Tkinter Text Widget
Override that allows to highlight words with regex.
"""
def __init__(self, *args, **kwargs):
tkinter.Text.__init__(self, *args, **kwargs)
def highlight(self, pattern, tag, start="1.0", stop="end", regex=True):
"""
Highlight text matched by "pattern" and apply it the tag "tag"
Specify "start" and "stop" in order to restrict the search and
regex=False if pattern is not a regex.
"""
start = self.index(start)
stop = self.index(stop)
self.mark_set("matchStart", start)
self.mark_set("matchEnd", start)
self.mark_set("searchLimit", stop)
occurrences = tkinter.IntVar()
while True:
index = self.search(
pattern,
"matchEnd",
"searchLimit",
count=occurrences,
regexp=regex
)
if index == "":
break
self.mark_set("matchStart", index)
self.mark_set("matchEnd", "%s+%sc" % (index, occurrences.get()))
self.tag_add(tag, "matchStart", "matchEnd")
class Application(tkinter.Frame):
"""
Application
Initialize it with a window created by Tk().
"""
def __init__(self, window):
tkinter.Frame.__init__(self, window)
self.options = {
"font": ("Monaco", 13),
"borderwidth": 2,
"highlightthickness": 0,
"relief": "sunken",
"insertbackground": "#fff"
}
self.last = ""
#Window settings
window.columnconfigure(1, weight=1)
window.rowconfigure(0, weight=1)
window.geometry("800x500+540+300")
window.title("reQuery")
#Inizialize
self.grid()
self.widgets()
#Main loop
self.loop()
def widgets(self):
"""Create and draw the widgets of the window."""
self.search = Text(
window, width=100, height=30, **self.options)
self.expression = tkinter.Entry(window, **self.options)
#Layout
self.search.grid(
column=1, row=0, sticky="nswe", pady=(6, 3), padx=6)
self.expression.grid(
column=1, row=1, sticky="nswe", pady=(3, 6), padx=6)
def test(self):
"""
Highlight in the text output generated by the search
If this is not valid is colored in red.
If it is valid is colored in green as well as the text
to which it corresponds.
"""
expression = self.expression.get()
if expression == "" or expression == self.last:
return
try:
self.search.tag_configure("result", foreground="#648f00")
self.search.highlight(expression, "result")
except tkinter.TclError:
self.expression.config(fg="#92182b")
tkinter.messagebox.showerror(
"reQuery", "Syntax error",
detail=traceback.format_exc(0).split(":")[3])
self.display_error = False
else:
self.expression.config(fg="#648f00")
self.last = expression
def loop(self):
"""
Main loop
Executed every 200 ms.
Updates regex search.
"""
self.test()
self.after(200, self.loop)
window = tkinter.Tk()
app = Application(window)
app.mainloop()