#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    1
    Rep Power
    0

    Syntax Highlighting


    I've recently picked up on learning Python (because i have since been too lazy to continue my ventures in C/C++). As an exercise, i decided to create a small Notepad - like program using the Tkinter module (once i get Fedora set up on my new hard drive i'll probably try out some stuff with GTK). Well, then i figured i'd go the extra mile and add a syntax highlighter (you know, just to see if i could). Well, that's about where i've been for the past hour or two. I was wondering if any of you had any ideas on how to do syntax highlighting. As i said before, i'm using the Tkinter module. I'm guessing that i have to use tags (like text.tag_config("n", background="yellow", foreground="red")) but i'm not sure how to nsert the tags at the given place automatically. Any help is appreciated.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    84
    Rep Power
    11
    I saw your post yesterday, but didn't have time to give you an answer then. seeing as you still haven't received help, I hacked up this little example of a syntax highlighting Text widget. You are correct in assuming you need to use tags. My code binds any key press to a function that analyses the current line of code and highlights python keywords and integers. You could expand on it to do class/function names and strings. It also needs to be fixed up so that if you were to load a script in an editor environment (this is just a text window without any other features) it would highlight the whole thing. Just a few ideas to play with

    Code:
    from Tkinter import *
    import keyword
    from string import ascii_letters, digits, punctuation, join
    
    class SyntaxHighlightingText(Text):
    
        tags = {'kw': 'orange',
                'int': 'red'}
    
        def __init__(self, root):
            Text.__init__(self, root)
            self.config_tags()
            self.characters = ascii_letters + digits + punctuation
    
            self.bind('<Key>', self.key_press)
    
        def config_tags(self):
            for tag, val in self.tags.items():
                self.tag_config(tag, foreground=val)
    
        def remove_tags(self, start, end):
            for tag in self.tags.keys():
                self.tag_remove(tag, start, end)
    
        def key_press(self, key):
            cline = self.index(INSERT).split('.')[0]
            lastcol = 0
            char = self.get('%s.%d'%(cline, lastcol))
            while char != '\n':
                lastcol += 1
                char = self.get('%s.%d'%(cline, lastcol))
    
            buffer = self.get('%s.%d'%(cline,0),'%s.%d'%(cline,lastcol))
            tokenized = buffer.split(' ')
    
            self.remove_tags('%s.%d'%(cline, 0), '%s.%d'%(cline, lastcol))
    
            start, end = 0, 0
            for token in tokenized:
                end = start + len(token)
                if token in keyword.kwlist:
                    self.tag_add('kw', '%s.%d'%(cline, start), '%s.%d'%(cline, end))
                else:
                    for index in range(len(token)):
                        try:
                            int(token[index])
                        except ValueError:
                            pass
                        else:
                            self.tag_add('int', '%s.%d'%(cline, start+index))
    
                start += len(token)+1
    
    if __name__ == '__main__':
        root = Tk()
        sht = SyntaxHighlightingText(root)
        sht.pack()
        root.mainloop()

IMN logo majestic logo threadwatch logo seochat tools logo