Esempio n. 1
0
File: code.py Progetto: Asan96/car
    def __init__(self):
        super().__init__()

        self.setEolMode(self.SC_EOL_LF)    # 以\n换行
        self.setWrapMode(self.WrapWord)    # 自动换行。self.WrapWord是父类QsciScintilla的
        self.setAutoCompletionSource(self.AcsAll)  # 自动补全。对于所有Ascii字符
        self.setAutoCompletionCaseSensitivity(False)  # 自动补全大小写敏感
        self.setAutoCompletionThreshold(1)  # 输入多少个字符才弹出补全提示
        self.setFolding(True)  # 代码可折叠
        self.setTabWidth(4)  # 设置缩进长度
        self.setUtf8(True)  # 设置文档的编码格式为 “utf8”
        self.setIndentationGuides(True)  # 设置缩进参考线
        self.setAutoIndent(True)  # 设置自动缩进
        self.setCaretLineVisible(True)
        self.lexer = LexerPython(self)  # 语法高亮显示
        self.setLexer(self.lexer)
        self.setCaretLineVisible(True)  # 是否高亮显示光标所在行
        self.setCaretLineBackgroundColor(QtGui.QColor(250, 244, 217))  # 光标所在行的底色
        self.setIndentationsUseTabs(True)  # 设置使用Tabs缩进
        # self.setFont(QtGui.QFont('Consolas', 20))  # 设置默认字体
        self.setMarginType(0, self.NumberMargin)    # 0~4。第0个左边栏显示行号
        self.setMarginsBackgroundColor(QtGui.QColor(255, 255, 255))  # 边栏背景颜色
        # self.setScrollWidthTracking(True)
        # self.setScrollWidth(500)
        self.setMarginWidth(0, 40)  # 边栏宽度
        self.setAutoIndent(True)  # 换行后自动缩进
        self.__api = QsciAPIs(self.lexer)
        for kw in keyword.kwlist:
            self.__api.add(kw)
        self.__api.prepare()
        self.setText("#!/usr/bin/python \n# coding=utf-8\n# version: Python3\n# please edit your code here:\n")
Esempio n. 2
0
    def lock(self):
        """
        Sets the default properties for the Python lexer.
        """
        # Lexer Initialization
        lexer = QsciLexerPython(self.ui.code_editor)
        lexer.setDefaultFont(self.font)
        self.ui.code_editor.setLexer(lexer)

        # Auto Completion
        api = QsciAPIs(lexer)
        for var in dir(builtins):
            if not (var[0] == "_"):
                api.add(var)
        api.prepare()

        self.ui.code_editor.setAutoCompletionThreshold(1)
        self.ui.code_editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        # Auto Indentation
        self.ui.code_editor.setAutoIndent(True)
        self.ui.code_editor.setIndentationGuides(True)
        self.ui.code_editor.setIndentationsUseTabs(True)
        self.ui.code_editor.setIndentationWidth(4)

        # Font Settings
        font_metrics = QFontMetrics(self.font)
        self.ui.code_editor.setMinimumSize(int(font_metrics.width("0" * 80)),
                                           0)
Esempio n. 3
0
    def __init__(self, language, forPreparation=False, parent=None):
        """
        Constructor
        
        @param language language of the APIs object (string)
        @param forPreparation flag indicating this object is just needed
            for a preparation process (boolean)
        @param parent reference to the parent object (QObject)
        """
        super(APIs, self).__init__(parent)
        self.setObjectName("APIs_{0}".format(language))

        self.__inPreparation = False
        self.__language = language
        self.__forPreparation = forPreparation
        self.__lexer = Lexers.getLexer(self.__language)
        self.__apifiles = Preferences.getEditorAPI(self.__language)
        self.__apifiles.sort()
        if self.__lexer is None:
            self.__apis = None
        else:
            self.__apis = QsciAPIs(self.__lexer)
            self.__apis.apiPreparationFinished.connect(
                self.__apiPreparationFinished)
            self.__apis.apiPreparationCancelled.connect(
                self.__apiPreparationCancelled)
            self.__apis.apiPreparationStarted.connect(
                self.__apiPreparationStarted)
            self.__loadAPIs()
Esempio n. 4
0
    def setPythonAutocomplete(self):

        self.autocomplete = QsciAPIs(self.lexer)
        self.keywords = self.lexer.keywords(1)

        self.keywords = self.keywords.split(' ')

        for word in self.keywords:
            self.autocomplete.add(word)

        self.autocomplete.add('super')
        self.autocomplete.add('self')
        self.autocomplete.add('__name__')
        self.autocomplete.add('__main__')
        self.autocomplete.add('__init__')
        self.autocomplete.add('__str__')
        self.autocomplete.add('__repr__')

        self.autocomplete.prepare()

        ## Set the length of the string before the editor tries to autocomplete
        self.setAutoCompletionThreshold(3)

        ## Tell the editor we are using a QsciAPI for the autocompletion
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.updateAutoComplete()
Esempio n. 5
0
    def set_theme(self, theme=DayTheme):
        """
        Connect the theme to a lexer and return the lexer for the editor to
        apply to the script text.
        """
        theme.apply_to(self.lexer)
        self.lexer.setDefaultPaper(theme.Paper)
        self.setCaretForegroundColor(theme.Caret)
        self.setMarginsBackgroundColor(theme.Margin)
        self.setMarginsForegroundColor(theme.Caret)
        self.setIndicatorForegroundColor(theme.IndicatorError,
                                         self.check_indicators['error']['id'])
        self.setIndicatorForegroundColor(theme.IndicatorStyle,
                                         self.check_indicators['style']['id'])
        for type_ in self.search_indicators:
            self.setIndicatorForegroundColor(
                theme.IndicatorWordMatch, self.search_indicators[type_]['id'])
        self.setMarkerBackgroundColor(theme.IndicatorError, self.MARKER_NUMBER)

        api = QsciAPIs(self.lexer)
        for entry in self.api:
            api.add(entry)
        api.prepare()
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAll)

        self.setLexer(self.lexer)
Esempio n. 6
0
File: editor.py Progetto: zencuke/mu
 def set_api(self, api_definitions):
     """
     Sets the API entries for tooltips, calltips and the like.
     """
     self.api = QsciAPIs(self.lexer)
     for entry in api_definitions:
         self.api.add(entry)
     self.api.prepare()
Esempio n. 7
0
 def __init__(self):
     self.lexer = QsciLexerPython()
     self.apis = QsciAPIs(self.lexer)
     self.lexer.setAPIs(self.apis)
     self.apis.apiPreparationFinished.connect(
         self.slotApiPreparationFinished)
     for fn in API_FILES:
         ok = self.apis.load(PATH + '/api_raw/' + fn)
     self.apis.prepare()
Esempio n. 8
0
 def _init_apis(self):
     """
     加载自定义智能提示文件
     Returns:
     """
     self._apis = QsciAPIs(self._lexer)
     for path in Path(os.path.dirname(__file__)).rglob('*.api'):
         self._apis.load(str(path.absolute()))
     self._apis.prepare()
    def __init__(self, parent=None):
        super(panelCodigo, self).__init__(parent)
        # Definir propiedades graficas
        fuente = QFont()
        fuente.setFamily('Roboto')
        fuente.setFixedPitch(True)
        fuente.setPointSize(8)
        self.setFont(fuente)
        self.setMarginsFont(fuente)
        fuenteEditor = QFontMetrics(fuente)
        self.setMarginsFont(fuente)
        self.setMarginWidth(0, fuenteEditor.width("00000") - 15)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor("#E0E0E0"))
        self.setMarginSensitivity(1, True)
        # Ocultar scrollbar inferior
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        # Dimension del panel donde se edita el codigo
        self.setMinimumSize(600, 360)
        # funcion(señal) para la linea marcada
        self.marginClicked.connect(self.asignarBreak)
        # Icono que se mostrara en la linea marcada
        self.markerDefine(QsciScintilla.Rectangle, self.CONTROL_LINEA_MARCADA)
        self.setMarkerBackgroundColor(QColor("#F90000"),
                                      self.CONTROL_LINEA_MARCADA)
        # Dar valor a los caracteres especiales
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Identificar la linea donde se encuentra la ejecucion
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#00ff22"))

        # Funciones para identar las lineas del editor de codigo
        self.setAutoIndent(True)
        self.setIndentationGuides(True)
        self.setIndentationsUseTabs(True)
        self.setIndentationWidth(4)

        # Resaltado y fuente del lexer
        self.lexer = QsciLexerPascal()
        self.lexer.setDefaultFont(fuente)

        # Autocompletar haciendo uso de la API Qsci
        api = QsciAPIs(self.lexer)
        self.palabrasGramatica(api)  #flta
        api.prepare()
        # Asignar colores a las keywords de la gramatica
        self.asignarColores()  #falta
        self.setLexer(self.lexer)
        self.setAutoCompletionThreshold(1)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        # Lineas marcadas
        self.controlLineasM = []
Esempio n. 10
0
    def _initCodeEdit(self):
        # 初始化编辑器的工作
        self.codeEdit.setUtf8(True)
        self.codeEdit.linesChanged.connect(self.onLinesChanged)  # 行改变
        # 代码高亮
        self.codeEdit.setLexer(QsciLexerJavaScript(self))
        # 自动折叠
        self.codeEdit.setMarginType(3, QsciScintilla.SymbolMargin)
        self.codeEdit.setMarginLineNumbers(3, False)
        self.codeEdit.setMarginWidth(3, 15)
        self.codeEdit.setMarginSensitivity(3, True)
        # 显示行号
        #self.codeEdit.setMarginType(0, QsciScintilla.NumberMargin)
        self.codeEdit.setMarginLineNumbers(0, True)
        self.onLinesChanged()
        # 代码提示
        sciApi = QsciAPIs(self.codeEdit.lexer())
        sciApi.prepare()
        self.codeEdit.setAutoCompletionSource(QsciScintilla.AcsAll)  # 设置源
        self.codeEdit.setAutoCompletionCaseSensitivity(True)  # 设置自动补全大小写敏感
        self.codeEdit.setAutoCompletionThreshold(1)  # 设置每输入一个字符就会出现自动补全的提示
        # 设置字体
        self.codeEdit.setFont(QFont('Consolas', 16))
        self.codeEdit.setMarginsFont(self.codeEdit.font())
        # 设置编码
        self.codeEdit.SendScintilla(QsciScintilla.SCI_SETCODEPAGE,
                                    QsciScintilla.SC_CP_UTF8)

        self.codeEdit.setBraceMatching(QsciScintilla.StrictBraceMatch)

        # 设置当前行高亮
        self.codeEdit.setCaretLineVisible(True)
        self.codeEdit.setCaretLineBackgroundColor(Qt.lightGray)
        self.codeEdit.setCaretForegroundColor(Qt.white)

        # tab
        # table relative
        self.codeEdit.setIndentationsUseTabs(True)
        self.codeEdit.setIndentationWidth(4)
        self.codeEdit.setTabIndents(True)
        self.codeEdit.setAutoIndent(True)
        self.codeEdit.setBackspaceUnindents(True)
        self.codeEdit.setTabWidth(4)

        # indentation guides
        self.codeEdit.setIndentationGuides(True)

        # folding margin
        self.codeEdit.setFolding(QsciScintilla.PlainFoldStyle)
        self.codeEdit.setMarginWidth(2, 12)

        # 自动换行
        self.codeEdit.setWrapMode(QsciScintilla.WrapWord)
Esempio n. 11
0
    def setPythonAutocomplete(self):
        self.autocomplete = QsciAPIs(self.lexer)
        self.keywords = wordList

        for word in self.keywords:
            self.autocomplete.add(word)

        self.setAutoCompletionThreshold(2)

        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.updateAutoComplete(self.parent.fileName)

        self.autocomplete.prepare()
Esempio n. 12
0
    def _init_apis(self) -> None:
        """
        加载自定义智能提示文件

        :return: None
        """
        self._apis = QsciAPIs(self._lexer)
        # for path in Path(os.path.join(os.path.dirname(__file__), 'api')).rglob('*.api'):
        #     logger.info('load %s' % str(path.absolute()))
        #     self._apis.load(str(path.absolute()))
        try:
            # 添加额外关键词
            for word in self._parent.keywords():
                self._apis.add(word)
        except Exception as e:
            logger.warning(str(e))
        self._apis.prepare()
Esempio n. 13
0
 def __init__(self, parent=None):
     QsciScintilla.__init__(self, parent)
     self.complete = AutoComplete()
     self.complete.prepare.connect(self.update_completes)
     self.lexer = text_lexer(self)
     self.setLexer(self.lexer)
     self.api = QsciAPIs(self.lexer)
     self.setAutoIndent(True)
     self.setMarginLineNumbers(0, True)
     self.setEdgeMode(QsciScintilla.EdgeLine)
     self.setEdgeColumn(79)
     self.setEdgeColor(QColor(0, 0, 0))
     """
     self.setIndentationsUseTabs(True)
     self.setIndentationWidth(get_configs()['tab_width'])
     self.setTabWidth(get_configs()['tab_width'])
     self.setTabIndents(get_configs()['indent_with_tabs'])
     self.setBackspaceUnindents(True)
     self.setCaretLineVisible(True)
     self.setIndentationGuides(True)
     self.setCaretForegroundColor(QColor(get_configs()['cursor_color']))
     self.setCaretLineBackgroundColor(QColor(get_configs()['line_background_color']))
     self.setCaretWidth(6)
     self.setWrapMode(QsciScintilla.WrapNone if not get_configs()['text_wrap'] else QsciScintilla.WrapWhitespace)
     self.setEolMode(get_eol_mode(get_configs()['eol_mode']))
     # self.setMarginsForegroundColor(QColor("#ff888888"))
     """
     self.setMarginWidth(0, len(str(len(self.text().split('\n')))) * 20)
     self.setFolding(QsciScintilla.PlainFoldStyle)
     self.setAutoCompletionSource(QsciScintilla.AcsAll)
     self.setAutoCompletionCaseSensitivity(True)
     self.setAutoCompletionReplaceWord(True)
     self.autoCompleteFromAll()
     self.setAutoCompletionThreshold(1)
     self.setAutoCompletionSource(QsciScintilla.AcsAll)
     self.setUtf8(True)
     self.setBraceMatching(QsciScintilla.StrictBraceMatch)
     self.setMatchedBraceForegroundColor(
         QColor(self.lexer.styles[Name.Decorator]))
     self.setMatchedBraceBackgroundColor(RGB(0, 255, 0).to_pyqt_color())
     self.setCallTipsVisible(-1)
Esempio n. 14
0
 def __cCompletion(self):
     r"""
         C自动补全
     :return:
     """
     c_keywords = [
         "char", "double", "enum", "float", "int", "long", "short",
         "signed", "struct", "union", "unsigned", "void", "for", "do",
         "while", "break", "continue", "if", "else", "goto", "switch",
         "case", "default", "return", "auto", "extern", "register",
         "static", "const", "sizeof", "typedef", "volatile"
     ]
     try:
         if isinstance(self.api, QsciAPIs):
             del self.api
     except:
         pass
     self.api = QsciAPIs(self.lxr)
     for kw in c_keywords:
         self.api.add(kw)
     self.api.prepare()
Esempio n. 15
0
 def __pythonCompletion(self):
     r"""
         python 自动补全
     :return:
     """
     python_keywords = [
         "False", "None", "True", "and", "as", "assert", "break", "class",
         "continue", "def", "del", "elif", "else", "except", "finally",
         "for", "from", "global", "if", "import", "in", "is", "isinstance",
         "print", "len", "range", "enumerate", "input", "int", "float",
         "bool", "lambda", "nonlocal", "not", "or", "pass", "raise",
         "return", "try", "while", "with", "yield", "next", "iter"
     ]
     try:
         if isinstance(self.api, QsciAPIs):
             del self.api
     except:
         pass
     self.api = QsciAPIs(self.lxr)
     for kw in python_keywords:
         self.api.add(kw)
     self.api.prepare()
Esempio n. 16
0
    def set_theme(self, theme=DayTheme):
        """
        Connect the theme to a lexer and return the lexer for the editor to
        apply to the script text.
        """
        self.lexer = PythonLexer()
        theme.apply_to(self.lexer)
        self.lexer.setDefaultPaper(theme.Paper)
        self.setCaretForegroundColor(theme.Caret)
        self.setMarginsBackgroundColor(theme.Margin)
        self.setMarginsForegroundColor(theme.Caret)
        self.setIndicatorForegroundColor(theme.Indicator)
        self.setMarkerBackgroundColor(theme.Indicator, self.MARKER_NUMBER)

        api = QsciAPIs(self.lexer)
        for entry in self.api:
            api.add(entry)
        api.prepare()
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAll)

        self.setLexer(self.lexer)
Esempio n. 17
0
    def __init__(self, parent=None, fileName=None, readOnlyFiles=[]):
        '''
        Constructor
        '''
        super(CppEditor, self).__init__(parent)
        self.parent = parent
        self.roFiles = readOnlyFiles

        self.setAcceptDrops(False) # drag&drop is on its parent

        # Set the default font
        font = QtGui.QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        # C/C++ lexer
        self.lexer = QsciLexerCPP(self,  True)
        self.lexer.setDefaultFont(font)
        self.libraryAPIs = QsciAPIs(QsciLexerCPP(self,True))
        self.setLexer(self.lexer)
        #self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')

        # Auto-indent
        self.setTabWidth(4)
        #self.setIndentationsUseTabs(False)
        self.setAutoIndent(True)

        # Current line visible with special background color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QtGui.QColor("#ffe4e4"))

        # Enable brace matching
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Enable folding visual- use boxes
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        # show line numbers
        fontmetrics = QtGui.QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, fontmetrics.width("00000") + 4)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QtGui.QColor("#ccccee"))

        # not too small
        self.setMinimumSize(400, 200)

        # set the length of the string before the editor tries to auto-complete
        self.setAutoCompletionThreshold(3)
        # tell the editor we are using a QsciAPI for the auto-completion
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        # removed remaining right side characters from the current cursor
        self.setAutoCompletionReplaceWord(True)

        # "CTRL+Space" autocomplete
        self.shortcut_ctrl_space = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+Space"), self)
        self.shortcut_ctrl_space.activated.connect(self.autoCompleteFromAll)

        if fileName:
            self.curFile = fileName
            self.loadFile(fileName)
            self.isUntitled = False
        else:
            self.curFile = PROJECT_NONAME + USER_CODE_EXT
            self.setText( __default_content__ )
            self.isUntitled = True

        self.updateApiKeywords()
        self.isModified = False
        self.textChanged.connect(self.onTextChanged )
Esempio n. 18
0
 def __prepare_autoCompletion(self):
     self.api = QsciAPIs(self.lexer)
     self.setAutoCompletionThreshold(5)
     autocompletions = ["variable_one", "variable_two", "function_one(int arg_1)", "function_two(float arg_1)"]
     map(self.api.add, autocompletions)
     self.api.prepare()
 def setQssAutocomplete(self):
     api = QsciAPIs(self)
     widgets = ("QAbstractScrollArea", "QCheckBox", "QColumnView",
                "QComboBox", "QDateEdit", "QDateTimeEdit", "QDialog",
                "QDialogButtonBox", "QDockWidget", "QDoubleSpinBox",
                "QFrame", "QGroupBox", "QHeaderView", "QLabel", "QLineEdit",
                "QListView", "QListWidget", "QMainWindow", "QMenu",
                "QMenuBar", "QMessageBox", "QProgressBar", "QPushButton",
                "QRadioButton", "QScrollBar", "QSizeGrip", "QSlider",
                "QSpinBox", "QSplitter", "QStatusBar", "QTabBar",
                "QTabWidget", "QTableView", "QTableWidget", "QTextEdit",
                "QTimeEdit", "QToolBar", "QToolButton", "QToolBox",
                "QToolTip", "QTreeView", "QTreeWidget", "QWidget")
     properties = (
         "alternate-background-color", "background", "background-color",
         "background-image", "background-repeat", "background-position",
         "background-attachment", "background-clip", "background-origin",
         "border", "border-top", "border-right", "border-bottom",
         "border-left", "border-color", "border-top-color",
         "border-right-color", "border-bottom-color", "border-left-color",
         "border-image", "border-radius", "border-top-left-radius",
         "border-top-right-radius", "border-bottom-right-radius",
         "border-bottom-left-radius", "border-style", "border-top-style",
         "border-right-style", "border-bottom-style", "border-left-style",
         "border-width", "border-top-width", "border-right-width",
         "border-bottom-width", "border-left-width", "bottom",
         "button-layout", "color", "dialogbuttonbox-buttons-have-icons",
         "font", "font-family", "font-size", "font-style", "font-weight",
         "gridline-color", "height", "icon-size", "image", "image-position",
         "left", "lineedit-password-character",
         "lineedit-password-mask-delay", "margin", "margin-top",
         "margin-right", "margin-bottom", "margin-left", "max-height",
         "max-width", "messagebox-text-interaction-flags", "min-height",
         "min-width", "opacity*", "outline", "outline-color",
         "outline-offset", "outline-style", "outline-radius",
         "outline-bottom-left-radius", "outline-bottom-right-radius",
         "outline-top-left-radius", "outline-top-right-radius", "padding",
         "padding-top", "padding-right", "padding-bottom", "padding-left",
         "paint-alternating-row-colors-for-empty-area", "position", "right",
         "selection-background-color", "selection-color",
         "show-decoration-selected", "spacing", "subcontrol-origin",
         "subcontrol-position", "titlebar-show-tooltips-on-buttons",
         "widget-animation-duration", "text-align", "text-decoration",
         "top", "width")
     subcontrols0 = ("::add-line", "::add-page", "::branch", "::chunk",
                     "::close-button", "::corner", "::down-arrow",
                     "::down-button", "::drop-down", "::float-button",
                     "::groove", "::indicator", "::handle", "::icon",
                     "::item", "::left-arrow", "::left-corner",
                     "::menu-arrow", "::menu-button", "::menu-indicator",
                     "::right-arrow", "::pane", "::right-corner",
                     "::scroller", "::section", "::separator", "::sub-line",
                     "::sub-page", "::tab", "::tab-bar", "::tear",
                     "::tearoff", "::text", "::title", "::up-arrow",
                     "::up-button")
     pseudostates0 = (":active", ":adjoins-item", ":alternate", ":bottom",
                      ":checked", ":closable", ":closed", ":default",
                      ":disabled", ":editable", ":edit-focus", ":enabled",
                      ":exclusive", ":first", ":flat", ":floatable",
                      ":focus", ":has-children", ":has-siblings",
                      ":horizontal", ":hover", ":indeterminate", ":last",
                      ":left", ":maximized", ":middle", ":minimized",
                      ":movable", ":no-frame", ":non-exclusive", ":off",
                      ":on", ":only-one", ":open", ":next-selected",
                      ":pressed", ":previous-selected", ":read-only",
                      ":right", ":selected", ":top", ":unchecked",
                      ":vertical", ":window")
     subcontrols = ("add-line", "add-page", "branch", "chunk",
                    "close-button", "corner", "down-arrow", "down-button",
                    "drop-down", "float-button", "groove", "indicator",
                    "handle", "icon", "item", "left-arrow", "left-corner",
                    "menu-arrow", "menu-button", "menu-indicator",
                    "right-arrow", "pane", "right-corner", "scroller",
                    "section", "separator", "sub-line", "sub-page", "tab",
                    "tab-bar", "tear", "tearoff", "text", "title",
                    "up-arrow", "up-button")
     pseudostates = ("active", "adjoins-item", "alternate", "bottom",
                     "checked", "closable", "closed", "default", "disabled",
                     "editable", "edit-focus", "enabled", "exclusive",
                     "first", "flat", "floatable", "focus", "has-children",
                     "has-siblings", "horizontal", "hover", "indeterminate",
                     "last", "left", "maximized", "middle", "minimized",
                     "movable", "no-frame", "non-exclusive", "off", "on",
                     "only-one", "open", "next-selected", "pressed",
                     "previous-selected", "read-only", "right", "selected",
                     "top", "unchecked", "vertical", "window")
     kwset = (widgets, properties, subcontrols, pseudostates)
     for ks in kwset:
         for k in ks:
             api.add(k)
     api.prepare()
Esempio n. 20
0
    def __init__(self, parent=None, lineNumberOn=False):
        super(highlightEditor, self).__init__()

        self.editor = QsciScintilla(parent)
        font = QFont()
        font.setFamily("Consolas")
        font.setPointSize(12)
        font.setFixedPitch(True)
        self.editor.setFont(font)
        self.editor.setObjectName("editor")

        self.editor.setUtf8(True)
        self.editor.setMarginsFont(font)
        if lineNumberOn:
            self.editor.setMarginWidth(
                0,
                len(str(len(self.editor.text().split('\n')))) * 20)
        self.editor.setMarginLineNumbers(0, lineNumberOn)

        self.editor.setBraceMatching(QsciScintilla.StrictBraceMatch)

        self.editor.setIndentationsUseTabs(True)
        self.editor.setIndentationWidth(4)
        self.editor.setTabIndents(True)
        self.editor.setAutoIndent(True)
        self.editor.setBackspaceUnindents(True)
        self.editor.setTabWidth(4)

        self.editor.setCaretLineVisible(True)
        self.editor.setCaretLineBackgroundColor(QColor('#DCDCDC'))

        self.editor.setIndentationGuides(True)

        self.editor.setFolding(QsciScintilla.PlainFoldStyle)
        self.editor.setMarginWidth(2, 12)

        self.editor.markerDefine(QsciScintilla.Minus,
                                 QsciScintilla.SC_MARKNUM_FOLDEROPEN)
        self.editor.markerDefine(QsciScintilla.Plus,
                                 QsciScintilla.SC_MARKNUM_FOLDER)
        self.editor.markerDefine(QsciScintilla.Minus,
                                 QsciScintilla.SC_MARKNUM_FOLDEROPENMID)
        self.editor.markerDefine(QsciScintilla.Plus,
                                 QsciScintilla.SC_MARKNUM_FOLDEREND)

        self.editor.setMarkerBackgroundColor(
            QColor("#FFFFFF"), QsciScintilla.SC_MARKNUM_FOLDEREND)
        self.editor.setMarkerForegroundColor(
            QColor("#272727"), QsciScintilla.SC_MARKNUM_FOLDEREND)
        self.editor.setMarkerBackgroundColor(
            QColor("#FFFFFF"), QsciScintilla.SC_MARKNUM_FOLDEROPENMID)
        self.editor.setMarkerForegroundColor(
            QColor("#272727"), QsciScintilla.SC_MARKNUM_FOLDEROPENMID)
        self.editor.setAutoCompletionSource(QsciScintilla.AcsAll)
        self.editor.setAutoCompletionCaseSensitivity(True)
        self.editor.setAutoCompletionReplaceWord(False)
        self.editor.setAutoCompletionThreshold(1)
        self.editor.setAutoCompletionUseSingle(QsciScintilla.AcusExplicit)
        self.lexer = highlight(self.editor)
        self.editor.setLexer(self.lexer)
        self.__api = QsciAPIs(self.lexer)
        autocompletions = keyword.kwlist + []
        for ac in autocompletions:
            self.__api.add(ac)
        self.__api.prepare()
        self.editor.autoCompleteFromAll()

        self.editor.textChanged.connect(self.changed)
Esempio n. 21
0
 def _setup_editor(self):
     # set default editor settings
     self.editor.setFont(DEFAULT_FONT)
     self.editor.setMarginsFont(LINENO_FONT)
     self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)
     self.editor.setCaretLineVisible(True)
     self.editor.setCaretForegroundColor(QColor('#000000'))
     self.editor.setCaretLineBackgroundColor(QColor('#c4e8fd'))
     self.editor.setAutoIndent(True)
     self.editor.setTabIndents(True)
     # tab width
     self.editor.setTabWidth(4)
     #  line numbers (margin 0)
     self.editor.setMarginLineNumbers(0, True)
     self.editor.setMarginWidth(0, '00000')
     # hide symbol margin
     self.editor.setMarginWidth(1, 0)
     # folding
     self.editor.setFolding(1)
     # indentation guides
     self.editor.setIndentationGuides(True)
     # wrap mode
     wrap_lines = False
     self.editor.setWrapMode(wrap_lines)
     if wrap_lines:
         # remove horizontal scrollBar
         self.editor.SendScintilla(SCI.SCI_SETHSCROLLBAR, 0, 0)
     lexer = QsciLexerPython(self)
     # apply default settings to lexer
     lexer.setDefaultFont(DEFAULT_FONT)
     lexer.setFont(DEFAULT_FONT)
     # margins
     lexer.setPaper(MARGIN_BGCOLOR, SCI.STYLE_LINENUMBER)
     lexer.setColor(MARGIN_COLOR, SCI.STYLE_LINENUMBER)
     lexer.setFont(DEFAULT_FONT, SCI.STYLE_LINENUMBER)
     # assign the lexer
     self.editor.setLexer(lexer)
     self.editor.SendScintilla(SCI.SCI_COLOURISE, 0, -1)
     # margins
     self.editor.setMarginsBackgroundColor(MARGIN_BGCOLOR)
     self.editor.setMarginsForegroundColor(MARGIN_COLOR)
     self.editor.setMarginsFont(LINENO_FONT)
     # folding
     self.editor.setFolding(FOLDING)
     self.editor.SendScintilla(SCI.SCI_SETMARGINWIDTHN, FOLD_MARGIN_NUM,
                               FOLD_MARGIN_WIDTH)
     # set fold margin colors
     self.editor.SendScintilla(SCI.SCI_SETFOLDMARGINCOLOUR, True,
                               Main._color_to_bgr_int(FOLD_MARGIN_COLOR))
     self.editor.SendScintilla(SCI.SCI_SETFOLDMARGINHICOLOUR, True,
                               Main._color_to_bgr_int(FOLD_MARGIN_HICOLOR))
     # create and configure the breakpoint column
     self.editor.setMarginWidth(self.__symbol_margin_num, 17)
     self.editor.markerDefine(BREAKPOINT_SYMBOL,
                              self.__breakpoint_marker_num)
     self.editor.setMarginMarkerMask(self.__symbol_margin_num,
                                     self.__breakpoint_marker_mask)
     self.editor.setMarkerBackgroundColor(BREAKPOINT_COLOR,
                                          self.__breakpoint_marker_num)
     # make breakpoint margin clickable
     self.editor.setMarginSensitivity(self.__symbol_margin_num, True)
     # add new callback for breakpoints
     self.editor.marginClicked.connect(self._slot_margin_clicked)
     # setup active line marker
     self.editor.markerDefine(ACTIVE_LINE_SYMBOL,
                              self.__active_line_marker_num)
     self.editor.setMarkerForegroundColor(ACTIVE_LINE_COLOR,
                                          self.__active_line_marker_num)
     self.editor.setMarkerBackgroundColor(ACTIVE_LINE_COLOR,
                                          self.__active_line_marker_num)
     # connect signals
     self.editor.textChanged.connect(self._slot_text_changed)
     self.editor.modificationChanged.connect(
         self._slot_editor_modification_changed)
     self.editor.SCN_URIDROPPED.connect(self._slot_file_dropped)
     self.editor.copyAvailable.connect(self.actionCut.setEnabled)
     self.editor.copyAvailable.connect(self.actionCopy.setEnabled)
     self.editor.selectionChanged.connect(
         lambda: self.actionDelete.setEnabled(self.editor.hasSelectedText()
                                              ))
     self.editor.selectionChanged.connect(
         lambda: self.actionSelectAll.setEnabled(self.editor.
                                                 hasSelectedText()))
     # autocomplete
     if API_FILE is not None:
         apis = QsciAPIs(self.editor.lexer())
         apis.loadPrepared(API_FILE)
     self.editor.setAutoCompletionThreshold(3)
     # The source is any installed APIs.
     self.editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)
Esempio n. 22
0
    def _load_code_editor_settings(self):
        """
		Load settings on the code editor like, font style, margins, scroll, etc.
		Based on the example from http://eli.thegreenplace.net/2011/04/01/sample-using-qscintilla-with-pyqt/
		"""

        item = self.form.font_size.currentText()
        size = int(item)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(size)
        self._code_editor.setFont(font)
        self._code_editor.setMarginsFont(font)

        # Margin 0 is used for line numbers
        fontmetrics = QFontMetrics(font)
        self._code_editor.setMarginsFont(font)
        self._code_editor.setMarginWidth(0, fontmetrics.width("00000") + 6)
        self._code_editor.setMarginLineNumbers(0, True)
        self._code_editor.setMarginsBackgroundColor(QColor("#cccccc"))

        # Clickable margin 1 for showing markers
        self._code_editor.setMarginSensitivity(1, True)
        self._code_editor.marginClicked.connect(self.on_margin_clicked)
        self._code_editor.markerDefine(QsciScintilla.RightArrow,
                                       self.ARROW_MARKER_NUM)
        self._code_editor.setMarkerBackgroundColor(QColor("#ee1111"),
                                                   self.ARROW_MARKER_NUM)

        # Detect changes to text
        self._code_editor.modificationChanged.connect(
            self.on_modification_changed)

        # Brace matching: enable for a brace immediately before or after the current position
        self._code_editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self._code_editor.setCaretLineVisible(True)
        self._code_editor.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width Courier.
        lexer = self.lexer()
        lexer.setDefaultFont(font)
        self._code_editor.setLexer(lexer)
        self._code_editor.setIndentationWidth(4)
        # self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')
        self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1)

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented here: http://www.scintilla.org/ScintillaDoc.html)
        self._code_editor.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self._lexer_obj = lexer
        self.qsci_api = QsciAPIs(self._lexer_obj)
        ## Add autocompletion strings
        self.qsci_api.add("aLongString")
        self.qsci_api.add("aLongerString")
        self.qsci_api.add("aDifferentString")
        self.qsci_api.add("sOmethingElse")
        ## Compile the api for use in the lexer
        self.qsci_api.prepare()
        self._code_editor.setAutoCompletionThreshold(1)
        self._code_editor.setAutoCompletionSource(QsciScintilla.AcsAll)
Esempio n. 23
0
    def __init__(self, parent=None):
        #CONSTRUCTOR DE LA CLASE HEREDADA
        super(editor, self).__init__(parent)

        #DEFINICION DE LA FUENTE Y SUS PROPIEDADES
        font = QFont()
        #font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        self.lineas_marcadas = []

        #PROFIEDADES AVANZADAS DE LA FUENTE DEL EDITOR
        fontmetrics = QFontMetrics(font)
        self.setMarginsFont(font)
        #SE CAMBIA EL MARGEN ANCHO DE LA FUNETE
        self.setMarginWidth(0, fontmetrics.width("00000") - 15)
        #MARGEN DE LOS NUMEROS DE LINEA
        self.setMarginLineNumbers(0, True)
        #COLOR DE FONDO DE LOS NUMEROS DE LINEA
        self.setMarginsBackgroundColor(QColor("#E0E0E0"))

        self.setMarginSensitivity(1, True)

        #CREAMOS LA SEÑA PARA AGREGAR LINEA MARCADA
        self.marginClicked.connect(self.on_margin_clicked)

        #SE DEFINE EL ICONO A MOSTRAR EN LA LINEA MARCADA
        self.markerDefine(QsciScintilla.Circle, self.ARROW_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor("#FF6C3B"), self.ARROW_MARKER_NUM)

        #RESALTADO DE PARENTECIS,CORCHETES Y OTROS
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        #RESALTADO DE LA LINEA DONDE SE ENCUENTRA EL CURSOR
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#32f24c"))

        #AUTOIDENTACION
        self.setAutoIndent(True)
        self.setIndentationGuides(True)
        self.setIndentationsUseTabs(True)
        self.setIndentationWidth(4)

        #DEFINIMOS EL RESALTADO O LEXER
        self.lexer = QsciLexerPascal()
        self.lexer.setDefaultFont(font)  #FUENTE DEL LEXER

        #API PARA EL AUTOCOMPETADO
        api = QsciAPIs(self.lexer)
        self.palabraAutocompletar(api)
        api.prepare()

        self.cambiarColores()
        self.setLexer(self.lexer)
        self.setAutoCompletionThreshold(1)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        #ESCONDER SCROLLBAR HORIZONTAL
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        #TAMAÑO MINIMO DEL EDITOR
        self.setMinimumSize(600, 360)
Esempio n. 24
0
    def updateAutoComplete(self, text=None):
        self.autocomplete = QsciAPIs(self.lexer)  # clear all

        self.keywords = self.lexer.keywords(1)
        self.keywords = self.keywords.split(' ')

        for word in self.keywords:
            self.autocomplete.add(word)

        self.autocomplete.add('super')
        self.autocomplete.add('self')
        self.autocomplete.add('__name__')
        self.autocomplete.add('__main__')
        self.autocomplete.add('__init__')
        self.autocomplete.add('__str__')
        self.autocomplete.add('__repr__')

        if not text:

            firstList = []  # list to edit
            secondList = []  # collect all items for autocomplete

            text = self.text()

            # parse complete text ....
            firstList = text.splitlines()

            for line in firstList:
                if 'def' in line:
                    item = line.strip()
                    item = item.strip('def')
                    item = item.replace(':', '')
                    if not item in secondList:
                        secondList.append(item)
                elif 'class' in line:
                    item = line.strip()
                    item = item.strip('class')
                    item = item.replace(':', '')
                    if not item in secondList:
                        secondList.append(item)


            text = text.replace('"', " ").replace("'", " ").replace("(", " ").replace\
                                (")", " ").replace("[", " ").replace("]", " ").replace\
                                (':', " ").replace(',', " ").replace("<", " ").replace\
                                (">", " ").replace("/", " ").replace("=", " ").replace\
                                (";", " ")

            firstList = text.split('\n')

            for row in firstList:

                if (row.strip().startswith('#')) or (
                        row.strip().startswith('//')):
                    continue

                else:
                    wordList = row.split()

                    for word in wordList:

                        if re.match("(^[0-9])", word):
                            continue

                        elif '#' in word or '//' in word:
                            continue

                        elif word in self.keywords:
                            continue

                        elif (word == '__init__') or (word == '__main__') or \
                             (word == '__name__') or (word == '__str__') or \
                             (word == '__repr__'):
                            continue

                        elif word in secondList:
                            continue

                        elif len(word) > 15:
                            continue

                        elif not len(word) < 3:
                            w = re.sub("{}<>;,:]", '', word)
                            #print(w)
                            secondList.append(w)

            # delete doubled entries
            x = set(secondList)
            secondList = list(x)

            # debugging ...
            #print(secondList)

            for item in secondList:
                self.autocomplete.add(item)

            self.autocomplete.prepare()