Files
krowlog/highlight_regex.py

66 lines
2.1 KiB
Python

from typing import Optional
from highlight import Highlight
from highlighted_range import HighlightedRange
from line import Line
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from settings import Settings
from typing import List
import re
class HighlightRegex(Highlight):
def __init__(self, query: str, ignore_case: bool, is_regex: bool, hit_background_color: str = "None",
line_background_color: str = "None"):
self.query = query
self.ignore_case = ignore_case
self.is_regex = is_regex
self.regex = self._get_regex()
self.hit_background_color = hit_background_color
self.line_background_color = line_background_color
def _get_regex(self):
flags = re.IGNORECASE if self.ignore_case else 0
if self.is_regex:
return re.compile(self.query, flags=flags)
else:
return re.compile(re.escape(self.query), flags=flags)
def compute_highlight(self, line: Line) -> Optional[List[HighlightedRange]]:
result = []
# print("execute regex: %s in %s" % (self.regex, line.line()))
match_iter = re.finditer(self.regex, line.line())
for match in match_iter:
# print("%s" % match)
start_char = match.start(0)
end_char = match.end(0)
start_column = line.char_to_column(start_char)
end_column = line.char_to_column(end_char)
result.append(HighlightedRange(
start_column,
end_column - start_column,
highlight_full_line=True,
brush=self.brush(self.hit_background_color),
brush_full_line=self.brush(self.line_background_color)
))
return result
def hit_background_brush(self):
return self.brush(self.hit_background_color)
@staticmethod
def brush(color: str) -> QBrush:
if re.match("[0-9a-f]{6}", color, flags=re.IGNORECASE):
red = int(color[0:2], 16)
green = int(color[2:4], 16)
blue = int(color[4:6], 16)
return QBrush(QColor(red, green, blue))
return QBrush()