def __init__(self, parent=None): """ Constructor """ super().__init__(parent) self.symbol_format = gui.TextCharFormat() self.symbol_format.set_foreground_color("red") self.symbol_format.set_font_weight("bold") self.name_format = gui.TextCharFormat() self.name_format.set_foreground_color("blue") self.name_format.set_font_weight("bold") self.name_format.setFontItalic(True) self.value_format = gui.TextCharFormat() self.value_format.set_foreground_color("darkgreen")
def _get_format_from_style(self, token: str, style: Style) -> gui.TextCharFormat: """Return a QTextCharFormat for token by reading a Pygments style.""" result = gui.TextCharFormat() try: token_style = style.style_for_token(token) except KeyError: return result for key, value in token_style.items(): if value: if key == "color": result.set_foreground_color(self._get_brush(value)) elif key == "bgcolor": result.set_background_color(self._get_brush(value)) elif key == "bold": result.set_font_weight("bold") elif key == "italic": result.setFontItalic(True) elif key == "underline": result.set_underline_style("single") elif key == "sans": result.set_font_style_hint("sans_serif") elif key == "roman": result.set_font_style_hint("serif") elif key == "mono": result.set_font_style_hint("typewriter") return result
class LevelName(Highlighter): placeholder = "%(levelname)s" color = "red" formats = dict( DEBUG=gui.TextCharFormat(text_color="green", bold=True), INFO=gui.TextCharFormat(text_color="blue", bold=True), WARNING=gui.TextCharFormat(text_color="orange", bold=True), CRITICAL=gui.TextCharFormat(text_color="darkorange", bold=True), ERROR=gui.TextCharFormat(text_color="red", bold=True), ) def format_string(self, record: logging.LogRecord) -> str: return record.levelname def get_format(self, value) -> gui.TextCharFormat: return self.formats[value]
class HighlightRule: regex: str | list[str] = "" color: str = "black" italic: bool = False bold: bool = False minimal: bool = False font_size: float | None = None nth: int = 0 compiled = None fmt: gui.TextCharFormat = gui.TextCharFormat() def __init_subclass__(cls): super().__init_subclass__() if isinstance(cls.regex, str): cls.compiled = re.compile(cls.regex) # cls.compiled.setMinimal(True) else: cls.compiled = [re.compile(r) for r in cls.regex] cls.fmt = cls.get_format() @classmethod def get_format(cls) -> gui.TextCharFormat: fmt = gui.TextCharFormat() fmt.setFontItalic(cls.italic) fmt.set_foreground_color(cls.color) if cls.font_size: fmt.setFontPointSize(cls.font_size) if cls.bold: fmt.set_font_weight("bold") return fmt
def test_textcharformat(): fmt = gui.TextCharFormat() fmt.set_font_weight("bold") assert fmt.get_font_weight() == "bold" fmt.set_foreground_color("yellow") with pytest.raises(ValueError): fmt.set_font_weight("test")
def get_format(cls) -> gui.TextCharFormat: fmt = gui.TextCharFormat() fmt.setFontItalic(cls.italic) fmt.set_foreground_color(cls.color) if cls.font_size: fmt.setFontPointSize(cls.font_size) if cls.bold: fmt.set_font_weight("bold") return fmt
def __init__(self, formatter: logging.Formatter): self.formatter = formatter self.format = gui.TextCharFormat(self.color, self.bold, self.italic) text = re.escape(self.placeholder) pat = fr"{text[:-1]}([ +-]?\#?\#?\d*,?(?:\.\d+)?[bcdeEfFgGnosxX%]?)" self.pattern = re.compile(pat) if self.formatter._fmt is None: raise TypeError("Formatter does not contain format string") self.is_included = self.pattern.search(self.formatter._fmt) is not None
def return_format(color, style=""): """ Return a QTextCharFormat with the given attributes. """ fmt = gui.TextCharFormat() fmt.set_foreground_color(color) if "bold" in style: fmt.set_font_weight("bold") if "italic" in style: fmt.setFontItalic(True) return fmt
def test_textcharformat(): fmt = gui.TextCharFormat() fmt.set_font_weight("bold") assert fmt.get_font_weight() == "bold" fmt.set_foreground_color("yellow") fmt.set_background_color("yellow") with pytest.raises(InvalidParamError): fmt.set_font_weight("test") fmt = gui.TextCharFormat(bold=True) assert fmt.get_font_weight() == "bold" fmt.select_full_width() fmt.set_underline_style("dash") with pytest.raises(InvalidParamError): fmt.set_underline_style("test") assert fmt.get_underline_style() == "dash" fmt.set_font_style_hint("serif") with pytest.raises(InvalidParamError): fmt.set_font_style_hint("test") fmt.set_vertical_alignment("baseline") with pytest.raises(InvalidParamError): fmt.set_vertical_alignment("test") assert fmt.get_vertical_alignment() == "baseline" fmt.get_font()
color = "lightgray" class Number(Rule): regex = [ 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", ] color = gui.Color(100, 150, 190) # Multi-line strings (expression, flag, style) # FIXME: The triple-quotes in these two lines will mess up the # syntax highlighting from this point onward fmt = gui.TextCharFormat() fmt.set_foreground_color((30, 120, 110)) TRI_SINGLE = (core.RegularExpression("'''"), 1, fmt) TRI_DOUBLE = (core.RegularExpression('"""'), 2, fmt) class PythonHighlighter(gui.SyntaxHighlighter): """Syntax highlighter for the Python language.""" RULES = Rule.__subclasses__() def highlightBlock(self, text: str): """Apply syntax highlighting to the given block of text.""" # Do other syntax formatting super().highlightBlock(text) self.setCurrentBlockState(0)
def get_format(self, position: int) -> gui.TextBlock: return gui.TextCharFormat(self.format(position))
# see https://github.com/ITVRoC/SeekurJr/blob/master/seekur_12.04/packages/ # multimaster_fkie/node_manager_fkie/src/node_manager_fkie/yaml_highlighter.py from __future__ import annotations from prettyqt import core, gui, syntaxhighlighters COMMENT_START = core.RegularExpression("#") COMMENT_END = core.RegularExpression("\n|\r") # Unused? COMMENT_FORMAT = gui.TextCharFormat() COMMENT_FORMAT.setFontItalic(True) COMMENT_FORMAT.set_foreground_color("darkgray") class Rule(syntaxhighlighters.HighlightRule): minimal = True class Bool(Rule): regex = [r"\btrue\b", r"\bfalse\b"] color = "blue" bold = True class Decimal(Rule): regex = r"\d+" color = "darkMagenta" class Rule2(Rule): regex = r"^\s*[_.\w]*\s*:"
class LineComment(Rule): regex = r"<!--[^\n]*-->" color = "lightgrey" class Text(Rule): regex = r">(.+)(?=</)" class Keyword(Rule): regex = [r"\b?xml\b", "/>", ">", "<", "</"] bold = True color = "red" VALUE_FORMAT = gui.TextCharFormat() VALUE_FORMAT.set_foreground_color("orange") VALUE_START_EXPRESSION = core.RegularExpression(r"\"") VALUE_END_EXPRESSION = core.RegularExpression(r"\"(?=[\s></])") class XmlHighlighter(gui.SyntaxHighlighter): RULES = Rule.__subclasses__() def highlightBlock(self, text: str): super().highlightBlock(text) # HANDLE QUOTATION MARKS NOW.. WE WANT TO START WITH " AND END WITH ".. # A THIRD " SHOULD NOT CAUSE THE WORDS INBETWEEN SECOND AND THIRD # TO BE COLORED self.setCurrentBlockState(0)
from __future__ import annotations from prettyqt import gui FORMAT_1 = gui.TextCharFormat() FORMAT_1.set_background_color("lightgreen") FORMAT_2 = gui.TextCharFormat() FORMAT_2.set_background_color("lightblue") class RegexMatchHighlighter(gui.SyntaxHighlighter): def __init__(self, document=None): super().__init__(document) self.spans: list[tuple[int, int]] | None = [] def set_spans(self, spans: list[tuple[int, int]] | None): self.spans = spans # print(self.spans) self.rehighlight() def _colorize(self, line_pos: int, match_len: int, match_num: int): fmt = FORMAT_1 if match_num % 2 == 0 else FORMAT_2 self.setFormat(line_pos, match_len, fmt) def highlightBlock(self, text: str): block = self.currentBlock() # line_no = block.blockNumber() # if line_no == 0: # self.setCurrentBlockState(-1) start_char = block.position() end_char = start_char + block.length()
def __init__(self, parent=None): super().__init__(parent) self.rules = [] self.commentStart = core.RegExp("#") self.commentEnd = core.RegExp("\n|\r") self.commentFormat = gui.TextCharFormat() self.commentFormat.setFontItalic(True) self.commentFormat.set_foreground_color("darkgray") f = gui.TextCharFormat() r = core.RegExp() r.setMinimal(True) f.setFontWeight(gui.Font.Normal) f.set_foreground_color("blue") tag_list = ["\\btrue\\b", "\\bfalse\\b"] for tag in tag_list: r.setPattern(tag) self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setForeground(gui.Color(127, 64, 127)) r.setPattern(r"\\d+") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkblue") r.setPattern(r"^\s*[_.\w]*\s*:") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkblue") r.setPattern(r":\s*:[_\.\w]*$|:\s*\@[_\.\w]*$") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setFontWeight(gui.Font.Bold) f.set_foreground_color("darkred") r.setPattern(r"^\s*-") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkred") r.setPattern(r"^---$") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("darkgreen") r.setPattern(r"[\[\]\{\}\,]") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setFontWeight(gui.Font.Normal) f.set_foreground_color("magenta") r.setPattern(r"\".*\"|\'.*\'") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.setForeground(gui.Color(127, 64, 127)) r.setPattern(r"\\$\\(.*\\)") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) f.set_foreground_color("lightgray") r.setPattern(r"<!DOCTYPE.*>") self.rules.append((core.RegExp(r), gui.TextCharFormat(f))) r.setPattern(r"<\\?xml.*\\?>") self.rules.append((core.RegExp(r), gui.TextCharFormat(f)))
def test_textcharformat(): fmt = gui.TextCharFormat() fmt.set_font_weight("bold") fmt.set_foreground_color("yellow")
from __future__ import annotations import regex as re from prettyqt import gui BRACKETS = re.compile(r"(\{|\}|\[|\]|\:|\,)") REGEXP1 = re.compile(r"\".*\" *\:") REGEXP2 = re.compile(r"\: *\".*\"") SYMBOL_FORMAT = gui.TextCharFormat() SYMBOL_FORMAT.set_foreground_color("red") SYMBOL_FORMAT.set_font_weight("bold") NAME_FORMAT = gui.TextCharFormat() NAME_FORMAT.set_foreground_color("blue") VALUE_FORMAT = gui.TextCharFormat() VALUE_FORMAT.set_foreground_color("darkgreen") class JsonHighlighter(gui.SyntaxHighlighter): def highlightBlock(self, text: str): """Highlight a block of code using the rules outlined in the Constructor.""" for m in BRACKETS.finditer(text): self.setFormat(m.span()[0], m.span()[1] - m.span()[0], SYMBOL_FORMAT) text.replace('\\"', " ") for m in REGEXP1.finditer(text): self.setFormat(m.span()[0], m.span()[1] - m.span()[0], NAME_FORMAT)