jjzjj

python - 如何向 QsciLexerCustom 子类添加折叠?

coder 2023-08-14 原文

考虑这个片段:

import sys
import textwrap
import re

from PyQt5.Qt import *  # noqa

from PyQt5.Qsci import QsciScintilla
from PyQt5.Qsci import QsciLexerCustom

from lark import Lark, inline_args, Transformer


class LexerJson(QsciLexerCustom):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.create_grammar()
        self.create_styles()

    def create_styles(self):
        deeppink = QColor(249, 38, 114)
        khaki = QColor(230, 219, 116)
        mediumpurple = QColor(174, 129, 255)
        mediumturquoise = QColor(81, 217, 205)
        yellowgreen = QColor(166, 226, 46)
        lightcyan = QColor(213, 248, 232)
        darkslategrey = QColor(39, 40, 34)

        styles = {
            0: mediumturquoise,
            1: mediumpurple,
            2: yellowgreen,
            3: deeppink,
            4: khaki,
            5: lightcyan
        }

        for style, color in styles.items():
            self.setColor(color, style)
            self.setPaper(darkslategrey, style)
            self.setFont(self.parent().font(), style)

        self.token_styles = {
            "__COLON": 5,
            "__COMMA": 5,
            "__FALSE1": 0,
            "__LBRACE": 5,
            "__LSQB": 5,
            "__NULL2": 0,
            "__RBRACE": 5,
            "__RSQB": 5,
            "__TRUE0": 0,
            "ESCAPED_STRING": 4,
            "SIGNED_NUMBER": 1,
        }

    def create_grammar(self):
        grammar = '''
            ?start: value
            ?value: object
                  | array
                  | string
                  | SIGNED_NUMBER      -> number
                  | "true"             -> true
                  | "false"            -> false
                  | "null"             -> null
            array  : "[" [value ("," value)*] "]"
            object : "{" [pair ("," pair)*] "}"
            pair   : string ":" value
            string : ESCAPED_STRING
            %import common.ESCAPED_STRING
            %import common.SIGNED_NUMBER
            %import common.WS
            %ignore WS
        '''

        class TreeToJson(Transformer):
            @inline_args
            def string(self, s):
                return s[1:-1].replace('\\"', '"')

            array = list
            pair = tuple
            object = dict
            number = inline_args(float)

            def null(self, _): return None

            def true(self, _): return True

            def false(self, _): return False

        self.lark = Lark(grammar, parser='lalr', transformer=TreeToJson())
        # All tokens: print([t.name for t in self.lark.parser.lexer.tokens])

    def defaultPaper(self, style):
        return QColor(39, 40, 34)

    def language(self):
        return "Json"

    def description(self, style):
        return {v: k for k, v in self.token_styles.items()}.get(style, "")

    def styleText(self, start, end):
        self.startStyling(start)
        text = self.parent().text()[start:end]
        last_pos = 0

        try:
            for token in self.lark.lex(text):
                ws_len = token.pos_in_stream - last_pos
                if ws_len:
                    self.setStyling(ws_len, 0)    # whitespace

                token_len = len(bytearray(token, "utf-8"))
                self.setStyling(
                    token_len, self.token_styles.get(token.type, 0))

                last_pos = token.pos_in_stream + token_len
        except Exception as e:
            print(e)


class EditorAll(QsciScintilla):

    def __init__(self, parent=None):
        super().__init__(parent)

        # Set font defaults
        font = QFont()
        font.setFamily('Consolas')
        font.setFixedPitch(True)
        font.setPointSize(8)
        font.setBold(True)
        self.setFont(font)

        # Set margin defaults
        fontmetrics = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, fontmetrics.width("000") + 6)
        self.setMarginLineNumbers(0, True)
        self.setMarginsForegroundColor(QColor(128, 128, 128))
        self.setMarginsBackgroundColor(QColor(39, 40, 34))
        self.setMarginType(1, self.SymbolMargin)
        self.setMarginWidth(1, 12)

        # Set indentation defaults
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setBackspaceUnindents(True)
        self.setIndentationGuides(True)

        # Set folding defaults (http://www.scintilla.org/ScintillaDoc.html#Folding)
        self.setFolding(QsciScintilla.CircledFoldStyle)

        # Set caret defaults
        self.setCaretForegroundColor(QColor(247, 247, 241))
        self.setCaretWidth(2)

        # Set selection color defaults
        self.setSelectionBackgroundColor(QColor(61, 61, 52))
        self.resetSelectionForegroundColor()

        # Set multiselection defaults
        self.SendScintilla(QsciScintilla.SCI_SETMULTIPLESELECTION, True)
        self.SendScintilla(QsciScintilla.SCI_SETMULTIPASTE, 1)
        self.SendScintilla(
            QsciScintilla.SCI_SETADDITIONALSELECTIONTYPING, True)

        lexer = LexerJson(self)
        self.setLexer(lexer)


def main():
    app = QApplication(sys.argv)
    ex = EditorAll()
    ex.setWindowTitle(__file__)
    ex.setText(textwrap.dedent("""\
        {
            "_id": "5b05ffcbcf8e597939b3f5ca",
            "about": "Excepteur consequat commodo esse voluptate aute aliquip ad sint deserunt commodo eiusmod irure. Sint aliquip sit magna duis eu est culpa aliqua excepteur ut tempor nulla. Aliqua ex pariatur id labore sit. Quis sit ex aliqua veniam exercitation laboris anim adipisicing. Lorem nisi reprehenderit ullamco labore qui sit ut aliqua tempor consequat pariatur proident.",
            "address": "665 Malbone Street, Thornport, Louisiana, 243",
            "age": 23,
            "balance": "$3,216.91",
            "company": "BULLJUICE",
            "email": "elisekelley@bulljuice.com",
            "eyeColor": "brown",
            "gender": "female",
            "guid": "d3a6d865-0f64-4042-8a78-4f53de9b0707",
            "index": 0,
            "isActive": false,
            "isActive2": true,
            "latitude": -18.660714,
            "longitude": -85.378048,
            "name": "Elise Kelley",
            "phone": "+1 (808) 543-3966",
            "picture": "http://placehold.it/32x32",
            "registered": "2017-09-30T03:47:40 -02:00",
            "tags": [
                "et",
                "nostrud",
                "in",
                "fugiat",
                "incididunt",
                "labore",
                "nostrud"
            ]
        }\
    """))
    ex.resize(800, 600)
    ex.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

要运行上面的 mcve,你只需要运行 pip install lark-parser PyQt5 QScintilla

我正在尝试弄清楚如何修改 LexerJson,以便符号 [ ] { } 将支持折叠。使用现有类时,例如 qscilexercpp.cpp折叠行为是免费提供给您的,例如,您只需执行以下操作:

# http://www.scintilla.org/ScintillaDoc.html#Folding
self.setFolding(QsciScintilla.BoxedTreeFoldStyle)

lexer = QsciLexerCPP()
lexer.setFoldAtElse(True)
lexer.setFoldComments(True)
lexer.setFoldCompact(False)
lexer.setFoldPreprocessor(True)
self.setLexer(lexer)

并且折叠将免费工作...但是当使用自定义词法分析器时,就像我在发布的 mcve 中所做的那样,我猜你必须自己实现该行为,不幸的是我不知道该怎么做。

那么,这基本上就是一个问题,您如何在 QsciLexerCustom 子类上实现折叠?

最佳答案

我无法修复你的词法分析器代码,但我可以给你一个相同的工作示例

import sys
from PyQt5.Qt import *
from PyQt5.Qsci import QsciScintilla, QsciLexerCPP
from PyQt5.Qsci import QsciLexerCustom

if sys.hexversion < 0x020600F0:
     print('python 2.6 or greater is required by this program')
     sys.exit(1)

_sample = """
# Sample config file

this is a junk line

[FirstItem]
Width=100
Height=200
Colour=orange
Info=this is some
     multiline
     text

[SecondItem]
Width=200
Height=300
Colour=green
Info=
     this is some
     multiline
     text
"""


class MainWindow(QMainWindow):
     def __init__(self):
         QMainWindow.__init__(self)
         self.setWindowTitle('Custom Lexer For Config Files')
         self.setGeometry(50, 200, 400, 400)
         self.editor = QsciScintilla(self)
         self.editor.setUtf8(True)
         self.editor.setMarginWidth(2, 15)
         self.editor.setFolding(True)
         self.setCentralWidget(self.editor)
         self.lexer = ConfigLexer(self.editor)
         self.editor.setLexer(self.lexer)
         self.editor.setText(_sample)


class ConfigLexer(QsciLexerCustom):
     def __init__(self, parent):
         QsciLexerCustom.__init__(self, parent)
         self._styles = {
             0: 'Default',
             1: 'Comment',
             2: 'Section',
             3: 'Key',
             4: 'Assignment',
             5: 'Value',
             }
         for key,value in self._styles.items():
             setattr(self, value, key)
         self._foldcompact = True

     def foldCompact(self):
         return self._foldcompact

     def setFoldCompact(self, enable):
         self._foldcompact = bool(enable)

     def language(self):
         return 'Config Files'

     def description(self, style):
         return self._styles.get(style, '')

     def defaultColor(self, style):
         if style == self.Default:
             return QColor('#000000')
         elif style == self.Comment:
             return QColor('#A0A0A0')
         elif style == self.Section:
             return QColor('#CC6600')
         elif style == self.Key:
             return QColor('#0000CC')
         elif style == self.Assignment:
             return QColor('#CC0000')
         elif style == self.Value:
             return QColor('#00CC00')
         return QsciLexerCustom.defaultColor(self, style)

     def defaultPaper(self, style):
         if style == self.Section:
             return QColor('#FFEECC')
         return QsciLexerCustom.defaultPaper(self, style)

     def defaultEolFill(self, style):
         if style == self.Section:
             return True
         return QsciLexerCustom.defaultEolFill(self, style)

     def defaultFont(self, style):
         if style == self.Comment:
             if sys.platform in ('win32', 'cygwin'):
                 return QFont('Comic Sans MS', 9)
             return QFont('Bitstream Vera Serif', 9)
         return QsciLexerCustom.defaultFont(self, style)

     def styleText(self, start, end):
         editor = self.editor()
         if editor is None:
             return

         SCI = editor.SendScintilla
         GETFOLDLEVEL = QsciScintilla.SCI_GETFOLDLEVEL
         SETFOLDLEVEL = QsciScintilla.SCI_SETFOLDLEVEL
         HEADERFLAG = QsciScintilla.SC_FOLDLEVELHEADERFLAG
         LEVELBASE = QsciScintilla.SC_FOLDLEVELBASE
         NUMBERMASK = QsciScintilla.SC_FOLDLEVELNUMBERMASK
         WHITEFLAG = QsciScintilla.SC_FOLDLEVELWHITEFLAG
         set_style = self.setStyling

         source = ''
         if end > editor.length():
             end = editor.length()
         if end > start:
             source = bytearray(end - start)
             SCI(QsciScintilla.SCI_GETTEXTRANGE, start, end, source)
         if not source:
             return

         compact = self.foldCompact()

         index = SCI(QsciScintilla.SCI_LINEFROMPOSITION, start)
         if index > 0:
             pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index - 1)
             state = SCI(QsciScintilla.SCI_GETSTYLEAT, pos)
         else:
             state = self.Default

         self.startStyling(start, 0x1f)

         for line in source.splitlines(True):
             length = len(line)
             if length == 1:
                 whitespace = compact
                 state = self.Default
             else:
                 whitespace = False
                 firstchar = chr(line[0])
                 if firstchar in '#;':
                     state = self.Comment
                 elif firstchar == '[':
                     state = self.Section
                 elif firstchar in ' \t':
                     if state == self.Value or state == self.Assignment:
                         state = self.Value
                     else:
                         whitespace = compact and line.isspace()
                         state = self.Default
                 else:
                     pos = line.find(b'=')
                     if pos < 0:
                         pos = line.find(b':')
                     else:
                         tmp = line.find(b':', 0, pos)
                         if tmp >= 0:
                             pos = tmp
                     if pos > 0:
                         set_style(pos, self.Key)
                         set_style(1, self.Assignment)
                         length = length - pos - 1
                         state = self.Value
                     else:
                         state = self.Default
             set_style(length, state)

             if state == self.Section:
                 level = LEVELBASE | HEADERFLAG
             elif index > 0:
                 lastlevel = SCI(GETFOLDLEVEL, index - 1)
                 if lastlevel & HEADERFLAG:
                     level = LEVELBASE + 1
                 else:
                     level = lastlevel & NUMBERMASK
             else:
                 level = LEVELBASE

             if whitespace:
                 level |= WHITEFLAG
             if level != SCI(GETFOLDLEVEL, index):
                 SCI(SETFOLDLEVEL, index, level)

             index += 1

         if index > 0:
             lastlevel = SCI(GETFOLDLEVEL, index - 1)
             if lastlevel & HEADERFLAG:
                 level = LEVELBASE + 1
             else:
                 level = lastlevel & NUMBERMASK
         else:
             level = LEVELBASE

         lastlevel = SCI(GETFOLDLEVEL, index)
         SCI(SETFOLDLEVEL, index, level | lastlevel & ~NUMBERMASK)


if __name__ == "__main__":
     app = QApplication(sys.argv)
     win = MainWindow()
     win.show()
     sys.exit(app.exec_())

关键的事情发生在这里

             if state == self.Section:
                 level = LEVELBASE | HEADERFLAG
             elif index > 0:
                 lastlevel = SCI(GETFOLDLEVEL, index - 1)
                 if lastlevel & HEADERFLAG:
                     level = LEVELBASE + 1
                 else:
                     level = lastlevel & NUMBERMASK
             else:
                 level = LEVELBASE

             if whitespace:
                 level |= WHITEFLAG
             if level != SCI(GETFOLDLEVEL, index):
                 SCI(SETFOLDLEVEL, index, level)

             index += 1

         if index > 0:
             lastlevel = SCI(GETFOLDLEVEL, index - 1)
             if lastlevel & HEADERFLAG:
                 level = LEVELBASE + 1
             else:
                 level = lastlevel & NUMBERMASK
         else:
             level = LEVELBASE

         lastlevel = SCI(GETFOLDLEVEL, index)
         SCI(SETFOLDLEVEL, index, level | lastlevel & ~NUMBERMASK)

PS:感谢 https://github.com/pingf/toys/blob/f808e7c4ed1a76db4800c8e1ee6d163242df52cc/src/201403/customLexer2.py

关于python - 如何向 QsciLexerCustom 子类添加折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50459326/

有关python - 如何向 QsciLexerCustom 子类添加折叠?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

随机推荐