# A GUI real time spell checker.
# for removing special characters
import re
# for GUI
from tkinter import scrolledtext
import tkinter as tk
from customtkinter import *
# for matching words
import nltk
from nltk.corpus import words

nltk.download("words")
class SpellingChecker(CTk):
    def __init__(self):
        super().__init__()
        self.title("Spelling Checker")
        self.geometry("600x500")

        # Creating a widget to let user type
        self.text_area = scrolledtext.ScrolledText(self,
                                      wrap = tk.WORD, 
                                      width = 70, 
                                      height = 27, 
                                      font = ("Times New Roman",
                                              15))
        # To check the spellings whenever any key is released.
        self.text_area.bind("<KeyRelease>", self.check)
        self.text_area.grid(column = 0, pady = 10, padx = 10)
        # keeping track of spaces.
        self.old_spaces = 0
    
    def check(self, event):
        # getting whole content typed by user
        content = self.text_area.get("1.0", tk.END)
        # counting spaces
        space_count = content.count(" ")

        # checks spelling only if the space key was pressed.
        if space_count != self.old_spaces: #checking if there are anymore spaces.
            self.old_spaces = space_count #updating the new no. of spaces.

            # removing any red highlights if there
            for tag in self.text_area.tag_names():
                self.text_area.tag_delete(tag)

            # getting all the words
            for word in content.split(" "):
                # removinga any special characters if there
                if re.sub(r"[^\w]", '', word.lower()) not in words.words():
                    # getting the starting position of incorrect word
                    position = content.find(word)
                    # marking wrong spelling red
                    self.text_area.tag_add(word, f"1.{position}", f"1.{position + len( word)}")
                    self.text_area.tag_config(word, foreground="red")


if __name__ == "__main__":
    si = SpellingChecker()
    si.mainloop()