Source

codeaide / codeaide / modes / occurrences.py

Full commit
import re
from codeaide.base import *


is_word = re.compile("^\w+$").match


class Occurrences(ModeBase):


    def init(self, wait_seconds=2):
        self.old_pos = -1
        self.color = QColor(self.textedit.scheme.occurrence_color)
        self.brush = QBrush(QColor(self.textedit.scheme.occurrence_background))
        self.selections = []
        self.textedit.connect(self.textedit, SIGNAL("idle()"), self.on_idle)

        
    def highlight_word_in_block(self, word, block):
        block_pos = block.position()
        text = unicode(block.text())
        length = len(word)
        i = 0
        while True:
            found = text.find(word, i)
            if found == -1:
                break
            col = block_pos + found
            sel = QTextEdit.ExtraSelection()
            sel.cursor = QTextCursor(block)
            sel.cursor.setPosition(col)
            sel.cursor.setPosition(col+length, QTextCursor.KeepAnchor)
            #sel.cursor.select(QTextCursor.WordUnderCursor)
            sel.format.setForeground(self.color)
            sel.format.setBackground(self.brush)
            self.selections.append(sel)
            i += len(word)


    def on_idle(self):
        self.highlight_current_word()

        
    def highlight_word(self, word):
        # This maybe also used by a search function
        self.textedit.remove_extra_selections(self.selections)
        self.selections = []

        block = self.textedit.firstVisibleBlock()
        bounding_rect = self.textedit.blockBoundingRect
        y = 0
        height = self.textedit.height()
        while block and block.isValid() and y < height:
            if not block.isVisible():
                continue
            self.highlight_word_in_block(word, block)
            y += bounding_rect(block).height()
            block = block.next()
        self.textedit.add_extra_selections(self.selections)


    def highlight_current_word(self):
        cursor = self.textedit.textCursor()
        pos = cursor.position()
        if pos == self.old_pos:
            return
        self.old_pos = pos

        cursor.select(QTextCursor.WordUnderCursor)
        word = unicode(cursor.selectedText())
        if not word or not is_word(word):
            return
        self.highlight_word(word)

        
    def on_highlight_current_word(self, event, key, modifiers, text):
        self.highlight_current_word()


    keyboard_hooks = {
        (Qt.Key_O, Qt.ControlModifier): on_highlight_current_word,
        }