Уведомления

Группа в Telegram: @pythonsu

#1 Сен. 5, 2013 11:55:12

_alexs_
Зарегистрирован: 2012-04-02
Сообщения: 42
Репутация: +  0  -
Профиль   Отправить e-mail  

QScintilla: добавить подстветку для языка

Потребовалось реализовать подстветку синтаксиса для R в QScintilla. К сожалению документация весьма скудная и без примеров, да и не сталкивался с подобными задачами до этого. Сейчас есть вот такой незаконченный код

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import *
class MyLexer(QsciLexerCustom):
    PRIMARY = ["break", "else", "F", "FALSE", "for", "function", "if", "in", "Inf", "NA", "NaN", "next", "NULL", "repeat", "require", 
               "return", "source", "T", "TRUE", "while"]
    def __init__(self, parent=None):
        QsciLexerCustom.__init__(self, parent)
        self._styles = {0 : "Default",
                        1 : "Keyword",
                        2 : "Comment",
                        3 : "Number",
                        4 : "String"
                       }
        for k, v in self._styles.iteritems():
            setattr(self, v, k)
    def description(self, style):
         return self._styles.get(style, "")
    def defaultColor(self, style):
        if style == self.Default:
            return QColor("#2e3436")
        elif style == self.Keyword:
            return QColor("#204a87")
        elif style == self.Comment:
            return QColor("#c00")
        elif style == self.Number:
            return QColor("#4e9a06")
        elif style == self.String:
            return QColor("#ce5c00")
        return QsciLexerCustom.defaultColor(self, style)
    def styleText(self, start, end):
        editor = self.editor()
        if editor is None:
            return
        source = ""
        if end > editor.length():
           end = editor.length()
        if end > start:
               source = bytearray(end - start)
               editor.SendScintilla(editor.SCI_GETTEXTRANGE, start, end, source)
        if not source:
           return
        # the line index will also be needed to implement folding
        index = editor.SendScintilla(editor.SCI_LINEFROMPOSITION, start)
        if index > 0:
           # the previous state may be needed for multi-line styling
           pos = editor.SendScintilla(editor.SCI_GETLINEENDPOSITION, index - 1)
           state = editor.SendScintilla(editor.SCI_GETSTYLEAT, pos)
        else:
           state = self.Default
        set_style = self.setStyling
        self.startStyling(start, 0x1f)
        for line in source.splitlines(True):
            length = len(line)
            if line.startswith("#"):
                state = self.Comment
            else:
                pass

Не могу придумать как реализовать разбор кода и его раскраску. Может, посоветуете, что можно почитать по теме? Особенно интресует алгоритмическая составляющая: выделение ключевых слов, операторов и других элементов. Если у кого-то есть более-менее полный пример буду очень благодарен.

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version