45 lines
2.1 KiB
Python
45 lines
2.1 KiB
Python
from PyQt6.QtGui import QTextCharFormat, QFont, QTextCursor
|
|
from PyQt6.QtCore import QRegularExpression
|
|
|
|
class HeaderFormatter:
|
|
def __init__(self):
|
|
self.regex_h1 = QRegularExpression(r'^#\s(.+)$')
|
|
self.regex_h2 = QRegularExpression(r'^##\s(.+)$')
|
|
self.regex_h3 = QRegularExpression(r'^###\s(.+)$')
|
|
self.regex_h4 = QRegularExpression(r'^####\s(.+)$')
|
|
self.regex_h5 = QRegularExpression(r'^#####\s(.+)$')
|
|
self.regex_h6 = QRegularExpression(r'^######\s(.+)$')
|
|
|
|
def apply_header_format(self, block, font_size, font_weight):
|
|
cursor = QTextCursor(block)
|
|
char_format = QTextCharFormat()
|
|
char_format.setFontWeight(font_weight)
|
|
char_format.setFontPointSize(font_size * 16)
|
|
cursor.select(QTextCursor.SelectionType.BlockUnderCursor)
|
|
cursor.setCharFormat(char_format)
|
|
|
|
def clear_header_format(self, block):
|
|
cursor = QTextCursor(block)
|
|
char_format = QTextCharFormat()
|
|
cursor.select(QTextCursor.SelectionType.BlockUnderCursor)
|
|
cursor.setCharFormat(char_format)
|
|
|
|
def process_headers(self, text_edit):
|
|
block = text_edit.document().firstBlock()
|
|
while block.isValid():
|
|
text = block.text()
|
|
if self.regex_h1.match(text).hasMatch():
|
|
self.apply_header_format(block, 2.0, QFont.Weight.Bold)
|
|
elif self.regex_h2.match(text).hasMatch():
|
|
self.apply_header_format(block, 1.5, QFont.Weight.Bold)
|
|
elif self.regex_h3.match(text).hasMatch():
|
|
self.apply_header_format(block, 1.25, QFont.Weight.Bold)
|
|
elif self.regex_h4.match(text).hasMatch():
|
|
self.apply_header_format(block, 1.0, QFont.Weight.Bold)
|
|
elif self.regex_h5.match(text).hasMatch():
|
|
self.apply_header_format(block, 0.875, QFont.Weight.Bold)
|
|
elif self.regex_h6.match(text).hasMatch():
|
|
self.apply_header_format(block, 0.85, QFont.Weight.Bold)
|
|
else:
|
|
self.clear_header_format(block)
|
|
block = block.next() |