def getPlainSequence(self, inOmitSymbols=False): """ Returns a plain text QString (without HTML stylization) of the current sequence. All characters are preserved (unless specified explicitly), including valid base letters, punctuation symbols, whitespace and invalid letters. @param inOmitSymbols: Omits characters listed in self.validSymbols. @type inOmitSymbols: bool @return: The current DNA sequence in the PM. @rtype: QString """ outSequence = self.sequenceTextEdit.toPlainText() if inOmitSymbols: # This may look like a sloppy piece of code, but Qt's QRegExp # class makes it pretty tricky to remove all punctuation. theString = '[<>' \ + str( QRegExp.escape(self.validSymbols) ) \ + ']|-' outSequence.remove(QRegExp(theString)) return outSequence
def getPlainSequence( self, inOmitSymbols = False ): """ Returns a plain text QString (without HTML stylization) of the current sequence. All characters are preserved (unless specified explicitly), including valid base letters, punctuation symbols, whitespace and invalid letters. @param inOmitSymbols: Omits characters listed in self.validSymbols. @type inOmitSymbols: bool @return: The current DNA sequence in the PM. @rtype: QString """ outSequence = self.sequenceTextEdit.toPlainText() if inOmitSymbols: # This may look like a sloppy piece of code, but Qt's QRegExp # class makes it pretty tricky to remove all punctuation. theString = '[<>' \ + str( QRegExp.escape(self.validSymbols) ) \ + ']|-' outSequence.remove(QRegExp( theString )) return outSequence
def __init__(self, *args): QLineEdit.__init__(self, *args) self.setValidator(QRegExpValidator(QRegExp(r'\d+\.\d+'), self)) self.setToolTip(textwrap.fill('<p>'+_( 'Go to a reference. To get reference numbers, use the <i>reference ' 'mode</i>, by clicking the reference mode button in the toolbar.'))) if hasattr(self, 'setPlaceholderText'): self.setPlaceholderText(_('Go to...')) self.editingFinished.connect(self.editing_finished)
def __init__(self, parent=None): super(TemplateHighlighter, self).__init__(parent) self.initializeFormats() TemplateHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS])), "keyword")) TemplateHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % builtin for builtin in formatter_functions().get_builtins()])), "builtin")) TemplateHighlighter.Rules.append((QRegExp( r"\b[+-]?[0-9]+[lL]?\b" r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), "number")) stringRe = QRegExp(r"""(?:[^:]'[^']*'|"[^"]*")""") stringRe.setMinimal(True) TemplateHighlighter.Rules.append((stringRe, "string")) lparenRe = QRegExp(r'\(') lparenRe.setMinimal(True) TemplateHighlighter.Rules.append((lparenRe, "lparen")) rparenRe = QRegExp(r'\)') rparenRe.setMinimal(True) TemplateHighlighter.Rules.append((rparenRe, "rparen")) self.regenerate_paren_positions() self.highlighted_paren = False
def __init__(self, *args): QLineEdit.__init__(self, *args) self.setValidator( QRegExpValidator(QRegExp(r'(^\d*\.[\d]{1,2}$)|(^[1-9]\d*[\.]$)'), self))
def __init__(self, parent=None): super(PythonHighlighter, self).__init__(parent) if not self.Config: self.loadConfig() self.initializeFormats() PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS])), "keyword")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % builtin for builtin in self.BUILTINS])), "builtin")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % constant for constant in self.CONSTANTS])), "constant")) PythonHighlighter.Rules.append((QRegExp( r"\b[+-]?[0-9]+[lL]?\b" r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), "number")) PythonHighlighter.Rules.append((QRegExp( r"\bPyQt4\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt")) PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator")) stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""") stringRe.setMinimal(True) PythonHighlighter.Rules.append((stringRe, "string")) self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""") self.stringRe.setMinimal(True) PythonHighlighter.Rules.append((self.stringRe, "string")) self.tripleSingleRe = QRegExp(r"""'''(?!")""") self.tripleDoubleRe = QRegExp(r'''"""(?!')''')
class PythonHighlighter(QSyntaxHighlighter): # {{{ Rules = [] Formats = {} Config = {} KEYWORDS = ["and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield"] BUILTINS = ["abs", "all", "any", "basestring", "bool", "callable", "chr", "classmethod", "cmp", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "execfile", "exit", "file", "filter", "float", "frozenset", "getattr", "globals", "hasattr", "hex", "id", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "long", "map", "max", "min", "object", "oct", "open", "ord", "pow", "property", "range", "reduce", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "unichr", "unicode", "vars", "xrange", "zip"] CONSTANTS = ["False", "True", "None", "NotImplemented", "Ellipsis"] def __init__(self, parent=None): super(PythonHighlighter, self).__init__(parent) if not self.Config: self.loadConfig() self.initializeFormats() PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS])), "keyword")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % builtin for builtin in self.BUILTINS])), "builtin")) PythonHighlighter.Rules.append((QRegExp( "|".join([r"\b%s\b" % constant for constant in self.CONSTANTS])), "constant")) PythonHighlighter.Rules.append((QRegExp( r"\b[+-]?[0-9]+[lL]?\b" r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), "number")) PythonHighlighter.Rules.append((QRegExp( r"\bPyQt4\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt")) PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator")) stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""") stringRe.setMinimal(True) PythonHighlighter.Rules.append((stringRe, "string")) self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""") self.stringRe.setMinimal(True) PythonHighlighter.Rules.append((self.stringRe, "string")) self.tripleSingleRe = QRegExp(r"""'''(?!")""") self.tripleDoubleRe = QRegExp(r'''"""(?!')''') @classmethod def loadConfig(cls): Config = cls.Config for name in ("window", "shell"): Config["%swidth" % name] = QVariant(QApplication.desktop().availableGeometry().width() / 2).toInt()[0] Config["%sheight" % name] = QVariant(QApplication.desktop().availableGeometry().height() / 2).toInt()[0] Config["%sy" % name] = QVariant(0).toInt()[0] Config["toolbars"] = QByteArray(b'') Config["splitter"] = QByteArray(b'') Config["shellx"] = QVariant(0).toInt()[0] Config["windowx"] = QVariant(QApplication.desktop().availableGeometry().width() / 2).toInt()[0] Config["remembergeometry"] = QVariant(True).toBool() Config["startwithshell"] = QVariant(True).toBool() Config["showwindowinfo"] = QVariant(True).toBool() Config["backupsuffix"] = QVariant(".bak").toString() Config["cwd"] = QVariant(".").toString() Config["tooltipsize"] = QVariant(150).toInt()[0] Config["maxlinestoscan"] = QVariant(5000).toInt()[0] Config["pythondocpath"] = QVariant("http://docs.python.org").toString() Config["autohidefinddialog"] = QVariant(True).toBool() Config["findcasesensitive"] = QVariant(False).toBool() Config["findwholewords"] = QVariant(False).toBool() Config["tabwidth"] = QVariant(4).toInt()[0] Config["fontfamily"] = QVariant("monospace").toString() Config["fontsize"] = QVariant(10).toInt()[0] for name, color, bold, italic in ( ("normal", "#000000", False, False), ("keyword", "#000080", True, False), ("builtin", "#0000A0", False, False), ("constant", "#0000C0", False, False), ("decorator", "#0000E0", False, False), ("comment", "#007F00", False, True), ("string", "#808000", False, False), ("number", "#924900", False, False), ("error", "#FF0000", False, False), ("pyqt", "#50621A", False, False)): Config["%sfontcolor" % name] = QVariant(color).toString() Config["%sfontbold" % name] = QVariant(bold).toBool() Config["%sfontitalic" % name] = QVariant(italic).toBool() @classmethod def initializeFormats(cls): Config = cls.Config baseFormat = QTextCharFormat() baseFormat.setFontFamily(Config["fontfamily"]) baseFormat.setFontPointSize(Config["fontsize"]) for name in ("normal", "keyword", "builtin", "constant", "decorator", "comment", "string", "number", "error", "pyqt"): format = QTextCharFormat(baseFormat) format.setForeground(QColor(Config["%sfontcolor" % name])) if Config["%sfontbold" % name]: format.setFontWeight(QFont.Bold) format.setFontItalic(Config["%sfontitalic" % name]) PythonHighlighter.Formats[name] = format def highlightBlock(self, text): NORMAL, TRIPLESINGLE, TRIPLEDOUBLE, ERROR = range(4) textLength = text.length() prevState = self.previousBlockState() self.setFormat(0, textLength, PythonHighlighter.Formats["normal"]) if text.startsWith("Traceback") or text.startsWith("Error: "): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return if prevState == ERROR and \ not (text.startsWith('>>>') or text.startsWith("#")): self.setCurrentBlockState(ERROR) self.setFormat(0, textLength, PythonHighlighter.Formats["error"]) return for regex, format in PythonHighlighter.Rules: i = regex.indexIn(text) while i >= 0: length = regex.matchedLength() self.setFormat(i, length, PythonHighlighter.Formats[format]) i = regex.indexIn(text, i + length) # Slow but good quality highlighting for comments. For more # speed, comment this out and add the following to __init__: # PythonHighlighter.Rules.append((QRegExp(r"#.*"), "comment")) if text.isEmpty(): pass elif text[0] == "#": self.setFormat(0, text.length(), PythonHighlighter.Formats["comment"]) else: stack = [] for i, c in enumerate(text): if c in ('"', "'"): if stack and stack[-1] == c: stack.pop() else: stack.append(c) elif c == "#" and len(stack) == 0: self.setFormat(i, text.length(), PythonHighlighter.Formats["comment"]) break self.setCurrentBlockState(NORMAL) if self.stringRe.indexIn(text) != -1: return # This is fooled by triple quotes inside single quoted strings for i, state in ((self.tripleSingleRe.indexIn(text), TRIPLESINGLE), (self.tripleDoubleRe.indexIn(text), TRIPLEDOUBLE)): if self.previousBlockState() == state: if i == -1: i = text.length() self.setCurrentBlockState(state) self.setFormat(0, i + 3, PythonHighlighter.Formats["string"]) elif i > -1: self.setCurrentBlockState(state) self.setFormat(i, text.length(), PythonHighlighter.Formats["string"]) def rehighlight(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor()