欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

x01.editor: 语法高亮编辑器

程序员文章站 2022-08-26 15:55:36
学习《Tkinter GUI Programming By Example》时,发现了语法高亮编辑器和聊天程序还不错。语法高亮编辑器如下,聊天程序可在下载中获取。 1. 效果图 2. 代码 import os, sys CurrDir = os.path.dirname(__file__) sys. ......

学习《tkinter gui programming by example》时,发现了语法高亮编辑器和聊天程序还不错。语法高亮编辑器如下,聊天程序可在下载中获取。

1. 效果图

x01.editor: 语法高亮编辑器

2. 代码

import os, sys
currdir = os.path.dirname(__file__)
sys.path.append(currdir)

import tkinter as tk 
import tkinter.ttk as ttk 
import tkinter.messagebox as msgbox 
import itertools 

from tkinter import filedialog

from editor.core import textarea, linenumbers, findwindow, highlighter, r 

class mainwindow(tk.tk):
    def __init__(self):
        super().__init__()
        self.title("x01.editor")

        self.text_area = textarea(self, bg="white", fg="black", undo=true)

        self.scrollbar = ttk.scrollbar(orient="vertical", command=self.scroll_text)
        self.text_area.configure(yscrollcommand=self.scrollbar.set)

        self.line_numbers = linenumbers(self, self.text_area,width=1, bg="grey", fg="white")
        self.highlighter = highlighter(self.text_area, os.path.join(currdir,'languages/python.yaml'))

        self.scrollbar.pack(side=tk.right, fill=tk.y)
        self.line_numbers.pack(side=tk.left, fill=tk.y)
        self.text_area.pack(side=tk.left, fill=tk.both, expand=1)

        self.bind_events()

        self.background = 'lightgrey'
        self.foreground = 'black'
        self.menu = tk.menu(self, bg=self.background, fg=self.foreground)
        self.generate_menus(['file', 'help']) #'edit','tools','help'])
        self.configure(menu=self.menu)

        self.open_file = ''

        self.yaml_config()
        r.win_center(self)

    def yaml_config(self):
        config = r.load_config(os.path.join(currdir, 'config.yaml'))
        self.text_area.configure(font=(config['font_family'], config['font_size']))
        self.line_numbers.configure(font=(config['font_family'], config['font_size']))

    def bind_events(self):
        self.text_area.bind("<mousewheel>", self.scroll_text)
        self.text_area.bind("<button-4>", self.scroll_text)
        self.text_area.bind("<button-5>", self.scroll_text)

        self.line_numbers.bind("<mousewheel>", lambda e: "break")
        self.line_numbers.bind("<button-4>", lambda e: "break")
        self.line_numbers.bind("<button-5>", lambda e: "break")

        self.bind('<control-f>', self.show_find_window)
        self.bind("<control-n>", self.file_new)
        self.bind('<control-o>', self.file_open)
        self.bind('<control-s>', self.file_save)
        self.bind('<alt-s>', self.file_saveas)
        self.bind('<control-h>', self.help_about)

    def scroll_text(self, *args):
        if len(args) > 1:
            self.text_area.yview_moveto(args[1])
            self.line_numbers.yview_moveto(args[1])
        else:
            event = args[0]
            if event.delta:
                move = -1 * (event.delta / 120)
            else:
                if event.num == 5:
                    move = 1
                else:
                    move = -1

            self.text_area.yview_scroll(int(move), "units")
            self.line_numbers.yview_scroll(int(move) * 3, "units")

    def show_find_window(self, event=none):
        findwindow(self.text_area)

    def generate_menus(self, items):
        win_methods = [method_name for method_name in dir(self) if callable(getattr(self, method_name))]
        tk_methods = [method_name for method_name in dir(tk.tk) if callable(getattr(tk.tk, method_name))]
        methods = [m for m in set(win_methods) - set(tk_methods)]
        methods = sorted(methods)
        for item in items:
            sub_menu = tk.menu(self.menu, tearoff=0, bg=self.background, fg=self.foreground)
            match_methods = []
            for m in methods:
                if m.startswith(item):
                    match_methods.append(m)
            for m in match_methods:
                actual_method = getattr(self, m)
                shortcut = actual_method.__doc__.strip()
                name = ' '.join(m.split('_')[1:])
                sub_menu.add_command(label=name.title(), command=actual_method, accelerator=shortcut)
            self.menu.add_cascade(label=item.title(), menu=sub_menu)

    def file_new(self, event=none):
        '''
        ctrl+n
        '''
        self.text_area.delete(1.0, tk.end)
        self.open_file = none 
        self.line_numbers.force_update()

    def file_open(self, event=none):
        '''
        ctrl+o
        '''
        types = (('python files', '*.py'), ('all files', '*.*'))
        filename = filedialog.askopenfilename(title='x01.editor', filetypes=types)
        if filename:
            self.open_file = filename
            self.text_area.display_file_contents(filename)
            self.highlighter.highlight()
            self.line_numbers.force_update()

    def file_save(self, event=none):
        '''
        ctrl+s
        '''
        f = self.open_file if self.open_file else none
        if f is none:
            types = (('python files', '*.py'), ('all files', '*.*'))
            f = filedialog.asksaveasfilename(title='x01.editor', filetypes=types)
        if f:
            contents = self.text_area.get(1.0, tk.end)
            with open(f, 'w') as file:
                file.write(contents)

    def file_saveas(self, event=none):
        '''
        alt+s
        '''
        types = (('python files', '*.py'), ('all files', '*.*'))
        f = filedialog.asksaveasfilename(title='x01.editor', filetypes=types)
        if f:
            contents = self.text_area.get(1.0,tk.end)
            with open(f, 'w') as file:
                file.write(contents)

    def help_about(self, event=none):
        '''
        ctrl+h
        '''
        msgbox.showinfo("about", "x01.editor 语法高亮编辑器")
        pass

if __name__ == '__main__':
    mw = mainwindow()
    mw.mainloop()
import tkinter as tk 
import tkinter.ttk as ttk 
import yaml 
import os, sys 

class textarea(tk.text):
    def __init__(self, master, **kwargs):
        super().__init__(**kwargs)

        self.master = master

        self.config(wrap=tk.word)  # char none

        self.tag_configure('find_match', background="yellow")
        self.find_match_index = none
        self.find_search_starting_index = 1.0

        self.bind_events()

    def display_file_contents(self, path):
        with open(path, 'r') as f:
            self.delete(1.0, tk.end)
            self.insert(1.0, f.read())
            
    def bind_events(self):
        self.bind('<control-a>', self.select_all)
        self.bind('<control-c>', self.copy)
        self.bind('<control-v>', self.paste)
        self.bind('<control-x>', self.cut)
        self.bind('<control-y>', self.redo)
        self.bind('<control-z>', self.undo)

    def cut(self, event=none):
        self.event_generate("<<cut>>")

    def copy(self, event=none):
        self.event_generate("<<copy>>")

    def paste(self, event=none):
        self.event_generate("<<paste>>")

    def undo(self, event=none):
        self.event_generate("<<undo>>")

        return "break"

    def redo(self, event=none):
        self.event_generate("<<redo>>")

        return "break"

    def select_all(self, event=none):
        self.tag_add("sel", 1.0, tk.end)

        return "break"

    def find(self, text_to_find):
        length = tk.intvar()
        idx = self.search(text_to_find, self.find_search_starting_index, stopindex=tk.end, count=length)

        if idx:
            self.tag_remove('find_match', 1.0, tk.end)

            end = f'{idx}+{length.get()}c'
            self.tag_add('find_match', idx, end)
            self.see(idx)

            self.find_search_starting_index = end
            self.find_match_index = idx
        else:
            if self.find_match_index != 1.0:
                if msg.askyesno("no more results", "no further matches. repeat from the beginning?"):
                    self.find_search_starting_index = 1.0
                    self.find_match_index = none
                    return self.find(text_to_find)
            else:
                msg.showinfo("no matches", "no matching text found")

    def replace_text(self, target, replacement):
        if self.find_match_index:

            end = f"{self.find_match_index}+{len(target)}c"
            self.replace(self.find_match_index, end, replacement)

            self.find_search_starting_index = f"{self.find_match_index} linestart"
            self.find_match_index = none

    def cancel_find(self):
        self.find_search_starting_index = 1.0
        self.find_match_index = none
        self.tag_remove('find_match', 1.0, tk.end)

class linenumbers(tk.text):
    def __init__(self, master, text_widget, **kwargs):
        super().__init__(master, **kwargs)

        self.text_widget = text_widget
        self.text_widget.bind('<keypress>', self.on_key_press)

        self.insert(1.0, '1')
        self.configure(state='disabled')

    def on_key_press(self, event=none):
        final_index = str(self.text_widget.index(tk.end))
        num_of_lines = final_index.split('.')[0]
        line_numbers_string = "\n".join(str(no + 1) for no in range(int(num_of_lines)))
        width = len(str(num_of_lines))

        self.configure(state='normal', width=width)
        self.delete(1.0, tk.end)
        self.insert(1.0, line_numbers_string)
        self.configure(state='disabled')

    def force_update(self):
        self.on_key_press()

class r:
    currentdir = os.path.dirname(__file__)

    @classmethod
    def load_config(cls, path):
        with open(path, 'r') as f:
            try:
                config = yaml.load(f)
            except yaml.yamlerror as e:
                print(e)
                return
        return config 

    @classmethod
    def win_center(cls, win, w=800,h=600):
        x = (win.winfo_screenwidth() - w) // 2
        y = (win.winfo_screenheight() - h) // 2
        win.geometry('{}x{}+{}+{}'.format(w,h,x,y))

class findwindow(tk.toplevel):
    def __init__(self, master, **kwargs):
        super().__init__(**kwargs)

        self.master = master

        self.geometry('350x100')
        self.title('find and replace')
        self.transient(self.master)

        self.text_to_find = tk.stringvar()
        self.text_to_replace_with = tk.stringvar()

        top_frame = tk.frame(self)
        middle_frame = tk.frame(self)
        bottom_frame = tk.frame(self)

        find_entry_label = tk.label(top_frame, text="find: ")
        self.find_entry = ttk.entry(top_frame, textvar=self.text_to_find)

        replace_entry_label = tk.label(middle_frame, text="replace: ")
        self.replace_entry = ttk.entry(middle_frame, textvar=self.text_to_replace_with)

        self.find_button = ttk.button(bottom_frame, text="find", command=self.on_find)
        self.replace_button = ttk.button(bottom_frame, text="replace", command=self.on_replace)
        self.cancel_button = ttk.button(bottom_frame, text="cancel", command=self.on_cancel)

        find_entry_label.pack(side=tk.left, padx=(20, 0))
        self.find_entry.pack(side=tk.left, fill=tk.x, expand=1)

        replace_entry_label.pack(side=tk.left)
        self.replace_entry.pack(side=tk.left, fill=tk.x, expand=1)

        self.find_button.pack(side=tk.left, padx=(85, 0))
        self.replace_button.pack(side=tk.left, padx=(20, 20))
        self.cancel_button.pack(side=tk.right, padx=(0, 30))

        top_frame.pack(side=tk.top, expand=1, fill=tk.x, padx=30)
        middle_frame.pack(side=tk.top, expand=1, fill=tk.x, padx=30)
        bottom_frame.pack(side=tk.top, expand=1, fill=tk.x)

        self.find_entry.focus_force()

        self.protocol("wm_delete_window", self.on_cancel)

    def on_find(self):
        self.master.find(self.text_to_find.get())

    def on_replace(self):
        self.master.replace_text(self.text_to_find.get(), self.text_to_replace_with.get())

    def on_cancel(self):
        self.master.cancel_find()
        self.destroy()

class highlighter:
    def __init__(self, text_widget, syntax_file):
        self.text_widget = text_widget
        self.syntax_file = syntax_file
        self.categories = none
        self.numbers_color = "blue"

        self.disallowed_previous_chars = ["_", "-", "."]

        self.parse_syntax_file()

        self.text_widget.bind('<keyrelease>', self.on_key_release)

    def on_key_release(self, event=none):
        self.highlight()

    def parse_syntax_file(self):
        with open(self.syntax_file, 'r') as stream:
            try:
                config = yaml.load(stream)
            except yaml.yamlerror as error:
                print(error)
                return

        self.categories = config['categories']
        self.numbers_color = config['numbers']['color']
        self.strings_color = config['strings']['color']

        self.configure_tags()

    def configure_tags(self):
        for category in self.categories.keys():
            color = self.categories[category]['color']
            self.text_widget.tag_configure(category, foreground=color)

        self.text_widget.tag_configure("number", foreground=self.numbers_color)
        self.text_widget.tag_configure("string", foreground=self.strings_color)

    def highlight(self, event=none):
        length = tk.intvar()
        for category in self.categories:
            matches = self.categories[category]['matches']
            for keyword in matches:
                start = 1.0
                keyword = keyword + "[^a-za-z_-]"
                idx = self.text_widget.search(keyword, start, stopindex=tk.end, count=length, regexp=1)
                while idx:
                    char_match_found = int(str(idx).split('.')[1])
                    line_match_found = int(str(idx).split('.')[0])
                    if char_match_found > 0:
                        previous_char_index = str(line_match_found) + '.' + str(char_match_found - 1)
                        previous_char = self.text_widget.get(previous_char_index, previous_char_index + "+1c")

                        if previous_char.isalnum() or previous_char in self.disallowed_previous_chars:
                            end = f"{idx}+{length.get() - 1}c"
                            start = end
                            idx = self.text_widget.search(keyword, start, stopindex=tk.end, regexp=1)
                        else:
                            end = f"{idx}+{length.get() - 1}c"
                            self.text_widget.tag_add(category, idx, end)

                            start = end
                            idx = self.text_widget.search(keyword, start, stopindex=tk.end, regexp=1)
                    else:
                        end = f"{idx}+{length.get() - 1}c"
                        self.text_widget.tag_add(category, idx, end)

                        start = end
                        idx = self.text_widget.search(keyword, start, stopindex=tk.end, regexp=1)

        self.highlight_regex(r"(\d)+[.]?(\d)*", "number")
        self.highlight_regex(r"[\'][^\']*[\']", "string")
        self.highlight_regex(r"[\"][^\"]*[\"]", "string")

    def highlight_regex(self, regex, tag):
        length = tk.intvar()
        start = 1.0
        idx = self.text_widget.search(regex, start, stopindex=tk.end, regexp=1, count=length)
        while idx:
            end = f"{idx}+{length.get()}c"
            self.text_widget.tag_add(tag, idx, end)

            start = end
            idx = self.text_widget.search(regex, start, stopindex=tk.end, regexp=1, count=length)
    
if __name__ == "__main__":
    w = tk.tk()
    h = highlighter(tk.text(w), os.path.join(currdir,'languages/python.yaml'))
    w.mainloop()

3. 下载