from __future__ import annotations import os import json import re from pathlib import Path from typing import Callable from PySide6.QtCore import QObject, QRect, QSize, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot from PySide6.QtWebChannel import QWebChannel from PySide6.QtGui import ( QAction, QColor, QFont, QKeySequence, QPainter, QSyntaxHighlighter, QTextCharFormat, QTextCursor, QTextDocument, QTextFormat, ) from PySide6.QtWebEngineCore import QWebEngineSettings from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWidgets import ( QCheckBox, QComboBox, QDialog, QFileDialog, QHBoxLayout, QLabel, QLineEdit, QMenu, QMessageBox, QPlainTextEdit, QPushButton, QSplitter, QTextEdit, QToolBar, QVBoxLayout, QWidget, ) from shiboken6 import isValid from .markdown_renderer import MarkdownRenderer from .markdown_utils import slugify_heading MAX_SYNTAX_HIGHLIGHT_CHARS = 1_000_000 def convert_latex_display_delimiters(source: str) -> tuple[str, int]: """Convert LaTeX display-math delimiters to Markdown ``$$`` delimiters.""" replacement_count = source.count("\\[") + source.count("\\]") return source.replace("\\[", "$$").replace("\\]", "$$"), replacement_count class LineNumberArea(QWidget): def __init__(self, editor: "MarkdownSourceEditor") -> None: super().__init__(editor) self.editor = editor def sizeHint(self) -> QSize: return QSize(self.editor.line_number_area_width(), 0) def paintEvent(self, event: object) -> None: self.editor.line_number_area_paint_event(event) class MarkdownSourceEditor(QPlainTextEdit): def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.image_handler = None self.line_number_background = QColor("#f3f5f8") self.line_number_foreground = QColor("#7a8494") self.current_line_background = QColor("#edf4ff") self.line_number_area = LineNumberArea(self) self.blockCountChanged.connect(self.update_line_number_area_width) self.updateRequest.connect(self.update_line_number_area) self.cursorPositionChanged.connect(self.highlight_current_line) self.update_line_number_area_width(0) self.highlight_current_line() def canInsertFromMimeData(self, source: object) -> bool: from .editor_assets import image_files return bool(source.hasImage() or image_files(source)) or super().canInsertFromMimeData(source) def insertFromMimeData(self, source: object) -> None: if callable(self.image_handler) and self.image_handler(source): return super().insertFromMimeData(source) def apply_theme(self, dark: bool) -> None: if dark: self.line_number_background = QColor("#22272e") self.line_number_foreground = QColor("#8b949e") self.current_line_background = QColor("#273447") self.setStyleSheet( "QPlainTextEdit { background: #1f242b; color: #dbe2ea; " "selection-background-color: #2f6feb; selection-color: #ffffff; }" ) else: self.line_number_background = QColor("#f3f5f8") self.line_number_foreground = QColor("#7a8494") self.current_line_background = QColor("#edf4ff") self.setStyleSheet("") self.line_number_area.update() self.highlight_current_line() def line_number_area_width(self) -> int: digits = max(2, len(str(max(1, self.blockCount())))) return 12 + self.fontMetrics().horizontalAdvance("9") * digits def update_line_number_area_width(self, new_block_count: int) -> None: del new_block_count self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) def update_line_number_area(self, rect: QRect, dy: int) -> None: if dy: self.line_number_area.scroll(0, dy) else: self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) if rect.contains(self.viewport().rect()): self.update_line_number_area_width(0) def resizeEvent(self, event: object) -> None: super().resizeEvent(event) content_rect = self.contentsRect() self.line_number_area.setGeometry( QRect(content_rect.left(), content_rect.top(), self.line_number_area_width(), content_rect.height()) ) def line_number_area_paint_event(self, event: object) -> None: painter = QPainter(self.line_number_area) painter.fillRect(event.rect(), self.line_number_background) block = self.firstVisibleBlock() block_number = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): painter.setPen(self.line_number_foreground) painter.drawText( 0, top, self.line_number_area.width() - 6, self.fontMetrics().height(), Qt.AlignmentFlag.AlignRight, str(block_number + 1), ) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) block_number += 1 def highlight_current_line(self) -> None: selection = QTextEdit.ExtraSelection() selection.format.setBackground(self.current_line_background) selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True) selection.cursor = self.textCursor() selection.cursor.clearSelection() self.setExtraSelections([selection]) class MarkdownSyntaxHighlighter(QSyntaxHighlighter): def __init__(self, document: object, dark: bool = False) -> None: super().__init__(document) self.dark = dark self._rebuild_rules() def apply_theme(self, dark: bool) -> None: self.dark = dark self._rebuild_rules() self.rehighlight() def _rebuild_rules(self) -> None: if self.dark: heading = "#79c0ff" link = "#58a6ff" strong = "#f0f6fc" accent = "#d2a8ff" code = "#ffa657" media = "#7ee787" quote = "#8b949e" fence = "#ffab70" block_code = "#c9d1d9" else: heading = "#1f6feb" link = "#0969da" strong = "#24292f" accent = "#8250df" code = "#bf3989" media = "#1a7f37" quote = "#6e7781" fence = "#953800" block_code = "#57606a" self.rules = [ (re.compile(r"^#{1,6}\s+.+$"), self._format(heading, bold=True)), (re.compile(r"^\s*[-*+]\s+"), self._format(link)), (re.compile(r"^\s*\d+\.\s+"), self._format(link)), (re.compile(r"\*\*[^*]+\*\*"), self._format(strong, bold=True)), (re.compile(r"(?\s?.*$"), self._format(quote, italic=True)), (re.compile(r"^\s{0,3}---+\s*$"), self._format(quote)), ] self.code_format = self._format(block_code) self.fence_format = self._format(fence, bold=True) def _format(self, color: str, bold: bool = False, italic: bool = False, underline: bool = False) -> QTextCharFormat: text_format = QTextCharFormat() text_format.setForeground(QColor(color)) if bold: text_format.setFontWeight(QFont.Weight.Bold) if italic: text_format.setFontItalic(True) if underline: text_format.setFontUnderline(True) return text_format def highlightBlock(self, text: str) -> None: in_fence = self.previousBlockState() == 1 if text.strip().startswith("```"): self.setFormat(0, len(text), self.fence_format) self.setCurrentBlockState(0 if in_fence else 1) return if in_fence: self.setFormat(0, len(text), self.code_format) self.setCurrentBlockState(1) return self.setCurrentBlockState(0) for pattern, text_format in self.rules: for match in pattern.finditer(text): self.setFormat(match.start(), match.end() - match.start(), text_format) class PreviewScrollBridge(QObject): @Slot(float) def sourceLine(self, line: float) -> None: self.parent()._sync_source_to_preview_line(line) class MarkdownEditorDialog(QDialog): save_requested = Signal(object, str, object) close_requested = Signal() title_changed = Signal(str) def __init__( self, path: Path, source: str, renderer: MarkdownRenderer, theme: str, font_scale: float, document_font_family: str, document_font_size: int, document_width_scale: float = 1.0, document_style_css: str = "", math_engine: str = "katex", original_source: str | None = None, file_signature: tuple[int, int] | None = None, draft_callback: Callable[[str], None] | None = None, embedded: bool = False, parent: QWidget | None = None, ) -> None: super().__init__(parent) self.embedded = embedded if embedded: self.setWindowFlag(Qt.WindowType.Widget, True) self.path = path self.save_target_path = path self.renderer = renderer self.theme = theme self.font_scale = font_scale self.document_font_family = document_font_family self.document_font_size = document_font_size self.document_width_scale = document_width_scale self.document_style_css = document_style_css self.math_engine = math_engine self.file_signature = file_signature self.draft_callback = draft_callback self._preview_dirty = True self._preview_scroll_y = 0 self._preview_scroll_ratio = 0.0 self._syncing_scroll = False self._match_positions: list[int] = [] self._current_match_index = -1 self.setWindowTitle(f"编辑 Markdown - {path.name}") self.setMinimumSize(1120, 720) self._original_source = source if original_source is None else original_source layout = QVBoxLayout(self) layout.setContentsMargins(12, 12, 12, 12) layout.setSpacing(8) self.path_label = QLabel(str(path)) self.path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) if not embedded: layout.addWidget(self.path_label) self.insert_toolbar = QToolBar("插入") self.insert_toolbar.setMovable(False) self._build_insert_toolbar() layout.addWidget(self.insert_toolbar) control_layout = QHBoxLayout() control_layout.setContentsMargins(0, 0, 0, 0) control_layout.addWidget(QLabel("视图")) self.view_mode_box = QComboBox() self.view_mode_box.addItem("源码", "source") self.view_mode_box.addItem("预览", "preview") self.view_mode_box.addItem("分屏", "split") self.view_mode_box.setCurrentIndex(2 if embedded else 0) self.view_mode_box.currentIndexChanged.connect(self._apply_view_mode) control_layout.addWidget(self.view_mode_box) self.sync_scroll_checkbox = QCheckBox("同步滚动") self.sync_scroll_checkbox.setChecked(True) control_layout.addWidget(self.sync_scroll_checkbox) self.editor_find_box = QLineEdit() self.editor_find_box.setPlaceholderText("查找源码") self.editor_find_box.returnPressed.connect(self.find_next_in_editor) self.editor_find_box.textChanged.connect(self._rebuild_find_matches) self.editor_replace_box = QLineEdit() self.editor_replace_box.setPlaceholderText("替换为") self.match_case_checkbox = QCheckBox("区分大小写") self.match_case_checkbox.toggled.connect(self._rebuild_find_matches) self.whole_word_checkbox = QCheckBox("全词") self.whole_word_checkbox.toggled.connect(self._rebuild_find_matches) self.editor_find_previous_button = QPushButton("上一个") self.editor_find_previous_button.clicked.connect(self.find_previous_in_editor) self.editor_find_next_button = QPushButton("下一个") self.editor_find_next_button.clicked.connect(self.find_next_in_editor) self.editor_replace_button = QPushButton("替换") self.editor_replace_button.clicked.connect(self.replace_current_in_editor) self.editor_replace_all_button = QPushButton("全部替换") self.editor_replace_all_button.clicked.connect(self.replace_all_in_editor) self.find_status_label = QLabel("0/0") control_layout.addWidget(self.editor_find_box, 2) control_layout.addWidget(self.editor_replace_box, 2) control_layout.addWidget(self.match_case_checkbox) control_layout.addWidget(self.whole_word_checkbox) control_layout.addWidget(self.editor_find_previous_button) control_layout.addWidget(self.editor_find_next_button) control_layout.addWidget(self.editor_replace_button) control_layout.addWidget(self.editor_replace_all_button) control_layout.addWidget(self.find_status_label) layout.addLayout(control_layout) self.preview_refresh_timer = QTimer(self) self.preview_refresh_timer.setSingleShot(True) self.preview_refresh_timer.setInterval(350) self.preview_refresh_timer.timeout.connect(self._refresh_preview_with_scroll_capture) self.draft_save_timer = QTimer(self) self.draft_save_timer.setSingleShot(True) self.draft_save_timer.setInterval(5000) self.draft_save_timer.timeout.connect(self._auto_save_draft) self.splitter = QSplitter(Qt.Orientation.Horizontal) self.editor = MarkdownSourceEditor() self.editor.image_handler = self._insert_image_mime self.editor.setPlainText(source) self.editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth) editor_font = QFont("Consolas") editor_font.setStyleHint(QFont.StyleHint.Monospace) self.editor.setFont(editor_font) self._apply_editor_font() self.highlighter = ( MarkdownSyntaxHighlighter(self.editor.document()) if len(source) <= MAX_SYNTAX_HIGHLIGHT_CHARS else None ) self.editor.textChanged.connect(self._on_editor_text_changed) self.editor.verticalScrollBar().valueChanged.connect(self._sync_preview_to_editor_scroll) self.scroll_sync_timer = QTimer(self) self.scroll_sync_timer.setSingleShot(True) self.scroll_sync_timer.setInterval(40) self.scroll_sync_timer.timeout.connect(self._sync_preview_to_source_line) self.splitter.addWidget(self.editor) self.preview = QWebEngineView() self.preview_channel = QWebChannel(self.preview.page()) self.preview_bridge = PreviewScrollBridge(self) self.preview_channel.registerObject("mdhelperEditor", self.preview_bridge) self.preview.page().setWebChannel(self.preview_channel) self.preview.loadFinished.connect(self._restore_preview_scroll) self._configure_preview_settings(self.preview.settings()) self.splitter.addWidget(self.preview) self.splitter.setSizes([560, 560]) layout.addWidget(self.splitter, 1) button_layout = QHBoxLayout() button_layout.addStretch(1) self.redo_button = QPushButton("前进") self.redo_button.setShortcut(QKeySequence.StandardKey.Redo) self.redo_button.clicked.connect(self._redo_editor) button_layout.addWidget(self.redo_button) self.undo_button = QPushButton("回退") self.undo_button.setShortcut(QKeySequence.StandardKey.Undo) self.undo_button.clicked.connect(self._undo_editor) button_layout.addWidget(self.undo_button) self.save_button = QPushButton("保存") self.save_button.setShortcut("Ctrl+S") if embedded: self.save_button.clicked.connect(self._emit_save_requested) else: self.save_button.clicked.connect(self.accept) button_layout.addWidget(self.save_button) self.save_as_button = QPushButton("另存为") self.save_as_button.clicked.connect(self._choose_save_as_path) button_layout.addWidget(self.save_as_button) self.cancel_button = QPushButton("取消") if embedded: self.cancel_button.clicked.connect(self.close_requested.emit) else: self.cancel_button.clicked.connect(self.reject) button_layout.addWidget(self.cancel_button) layout.addLayout(button_layout) self._install_shortcuts() self.apply_theme(theme == "dark") self._update_undo_redo_actions() self._update_dirty_title() self._rebuild_find_matches() self._apply_view_mode() def source_text(self) -> str: return self.editor.toPlainText() def has_unsaved_changes(self) -> bool: return self.source_text() != self._original_source def apply_theme(self, dark: bool) -> None: self.editor.apply_theme(dark) if self.highlighter is not None: self.highlighter.apply_theme(dark) if dark: self.setStyleSheet( "QDialog { background: #1f242b; color: #dbe2ea; }" "QLabel, QCheckBox, QToolButton { color: #dbe2ea; }" "QTableWidget, QListWidget, QPlainTextEdit { background: #15191f; color: #dbe2ea; gridline-color: #444c56; }" "QHeaderView::section { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; }" "QLineEdit, QComboBox { background: #15191f; color: #dbe2ea; border: 1px solid #3a4553; padding: 4px; }" "QToolBar { background: #22272e; border: 1px solid #3a4553; }" "QPushButton { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; padding: 4px 8px; }" ) else: self.setStyleSheet("") def _apply_editor_font(self) -> None: font = self.editor.font() font.setStyleHint(QFont.StyleHint.Monospace) font.setPointSize(max(8, min(22, round(self.document_font_size * 0.75)))) self.editor.setFont(font) self.editor.update_line_number_area_width(0) def update_rendering_options( self, theme: str, font_scale: float, document_font_family: str, document_font_size: int, document_width_scale: float = 1.0, document_style_css: str = "", math_engine: str = "katex", ) -> None: self.theme = theme self.font_scale = font_scale self.document_font_family = document_font_family self.document_font_size = document_font_size self.document_width_scale = document_width_scale self.document_style_css = document_style_css self.math_engine = math_engine self.apply_theme(theme == "dark") self._apply_editor_font() self._preview_dirty = True if self.preview.isVisible(): self._refresh_preview_with_scroll_capture() def _install_shortcuts(self) -> None: find_action = QAction(self) find_action.setShortcut(QKeySequence.StandardKey.Find) find_action.triggered.connect(self.editor_find_box.setFocus) self.addAction(find_action) replace_action = QAction(self) replace_action.setShortcut(QKeySequence("Ctrl+H")) replace_action.triggered.connect(self.editor_replace_box.setFocus) self.addAction(replace_action) self.editor.undoAvailable.connect(lambda available: self.undo_button.setEnabled(available)) self.editor.redoAvailable.connect(lambda available: self.redo_button.setEnabled(available)) def _build_insert_toolbar(self) -> None: for label, template in ( ("H1", "# {selection}"), ("H2", "## {selection}"), ("B", "**{selection}**"), ("I", "*{selection}*"), ("代码", "```\n{selection}\n```"), ("链接", "[{selection}](target.md)"), ("提示", "> [!NOTE]\n> {selection}"), ("Mermaid", "```mermaid\ngraph TD\n A --> B\n```"), ("公式", "$${selection}$$"), ): action = QAction(label, self) action.setToolTip(label) action.triggered.connect(lambda checked=False, item=template: self.insert_template(item)) self.insert_toolbar.addAction(action) for label, callback in [("表格", self._edit_table), ("图片", self._choose_images), ("历史版本", self.show_history)]: action = QAction(label, self) action.triggered.connect(callback) anchor = next(item for item in self.insert_toolbar.actions() if item.text() == "Mermaid") self.insert_toolbar.insertAction(anchor, action) self.convert_latex_formula_action = QAction("转换latex公式到md", self) self.convert_latex_formula_action.setToolTip("将文档中的 \\[ 和 \\] 转换为 $$") self.convert_latex_formula_action.triggered.connect(self.convert_latex_formulas_to_markdown) self.insert_toolbar.addAction(self.convert_latex_formula_action) def insert_template(self, template: str) -> None: cursor = self.editor.textCursor() selection = cursor.selectedText().replace("\u2029", "\n") replacement = template.format(selection=selection or "内容") cursor.insertText(replacement) self.editor.setTextCursor(cursor) self.editor.setFocus() def convert_latex_formulas_to_markdown(self) -> int: converted_source, replacement_count = convert_latex_display_delimiters(self.source_text()) if replacement_count == 0: self.editor.setFocus() return 0 current_cursor = self.editor.textCursor() anchor = current_cursor.anchor() position = current_cursor.position() document_cursor = QTextCursor(self.editor.document()) document_cursor.beginEditBlock() document_cursor.select(QTextCursor.SelectionType.Document) document_cursor.insertText(converted_source) document_cursor.endEditBlock() restored_cursor = self.editor.textCursor() restored_cursor.setPosition(anchor) restored_cursor.setPosition( position, QTextCursor.MoveMode.KeepAnchor if position != anchor else QTextCursor.MoveMode.MoveAnchor, ) self.editor.setTextCursor(restored_cursor) self.editor.setFocus() return replacement_count def scroll_to_heading(self, slug: str) -> bool: target_line = self._heading_line_for_slug(slug) if target_line is None: return False block = self.editor.document().findBlockByNumber(target_line) if not block.isValid(): return False cursor = QTextCursor(block) self.editor.setTextCursor(cursor) self.editor.centerCursor() self.editor.setFocus() if self.preview.isVisible(): self._scroll_preview_to_heading(slug) return True def _heading_line_for_slug(self, target_slug: str) -> int | None: seen: dict[str, int] = {} in_fenced_block = False for line_number, line in enumerate(self.source_text().splitlines()): stripped = line.strip() if stripped.startswith("```") or stripped.startswith("~~~"): in_fenced_block = not in_fenced_block continue if in_fenced_block: continue match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped) if not match: continue slug = slugify_heading(match.group(2).strip()) if not slug: continue count = seen.get(slug, 0) seen[slug] = count + 1 if count: slug = f"{slug}-{count + 1}" if slug == target_slug: return line_number return None def _scroll_preview_to_heading(self, slug: str) -> None: if not isValid(self) or not isValid(self.preview): return script = ( "(() => {" "const id = " f"{json.dumps(slug)}" ";" "const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';" "const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);" "if (target) {" " target.scrollIntoView({block: 'start', behavior: 'auto'});" " const scroller = document.scrollingElement || document.documentElement || document.body;" " scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);" "}" "})();" ) self.preview.page().runJavaScript(script) def _on_editor_text_changed(self) -> None: self._schedule_preview_refresh() if self.has_unsaved_changes(): self.draft_save_timer.start() self._update_dirty_title() self._rebuild_find_matches() self._update_undo_redo_actions() def _update_undo_redo_actions(self) -> None: self.undo_button.setEnabled(self.editor.document().isUndoAvailable()) self.redo_button.setEnabled(self.editor.document().isRedoAvailable()) def _undo_editor(self) -> None: self.editor.undo() self._update_undo_redo_actions() def _redo_editor(self) -> None: self.editor.redo() self._update_undo_redo_actions() def _update_dirty_title(self) -> None: marker = "*" if self.has_unsaved_changes() else "" title = f"{marker}编辑 Markdown - {self.save_target_path.name}" self.setWindowTitle(title) self.title_changed.emit(title) self.path_label.setText(str(self.save_target_path)) def _auto_save_draft(self) -> None: if self.has_unsaved_changes() and callable(self.draft_callback): self.draft_callback(self.source_text()) def _find_flags(self) -> QTextDocument.FindFlag: flags = QTextDocument.FindFlag(0) if self.match_case_checkbox.isChecked(): flags |= QTextDocument.FindFlag.FindCaseSensitively if self.whole_word_checkbox.isChecked(): flags |= QTextDocument.FindFlag.FindWholeWords return flags def _rebuild_find_matches(self) -> None: query = self.editor_find_box.text() self._match_positions = [] self._current_match_index = -1 if not query: self.find_status_label.setText("0/0") return text = self.source_text() flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE pattern = re.escape(query) if self.whole_word_checkbox.isChecked(): pattern = r"\b" + pattern + r"\b" self._match_positions = [start for start, _ in self._qt_match_spans(text, re.finditer(pattern, text, flags))] cursor_pos = self.editor.textCursor().selectionStart() for index, position in enumerate(self._match_positions): if position >= cursor_pos: self._current_match_index = index - 1 break else: self._current_match_index = len(self._match_positions) - 1 self._update_find_status() def _select_match(self, index: int) -> None: if not self._match_positions: self._update_find_status() return self._current_match_index = index % len(self._match_positions) query = self.editor_find_box.text() cursor = self.editor.textCursor() cursor.setPosition(self._match_positions[self._current_match_index]) cursor.setPosition(cursor.position() + self._qt_position(query, len(query)), QTextCursor.MoveMode.KeepAnchor) self.editor.setTextCursor(cursor) self.editor.ensureCursorVisible() self._update_find_status() def _update_find_status(self) -> None: total = len(self._match_positions) current = self._current_match_index + 1 if total and self._current_match_index >= 0 else 0 self.find_status_label.setText(f"{current}/{total}") def find_next_in_editor(self) -> None: if not self.editor_find_box.text(): return if not self._match_positions: self._rebuild_find_matches() if self._match_positions: self._select_match(self._current_match_index + 1) def find_previous_in_editor(self) -> None: if not self.editor_find_box.text(): return if not self._match_positions: self._rebuild_find_matches() if self._match_positions: self._select_match(self._current_match_index - 1) def replace_current_in_editor(self) -> None: query = self.editor_find_box.text() if not query: return cursor = self.editor.textCursor() selected = cursor.selectedText().replace("\u2029", "\n") matches = selected == query if self.match_case_checkbox.isChecked() else selected.lower() == query.lower() if cursor.hasSelection() and matches: cursor.insertText(self.editor_replace_box.text()) self._rebuild_find_matches() return self.find_next_in_editor() def replace_all_in_editor(self) -> None: query = self.editor_find_box.text() if not query: return replacement = self.editor_replace_box.text() flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE pattern = re.escape(query) if self.whole_word_checkbox.isChecked(): pattern = r"\b" + pattern + r"\b" source = self.source_text() matches = self._qt_match_spans(source, re.finditer(pattern, source, flags=flags)) cursor = self.editor.textCursor() cursor.beginEditBlock() for start, end in reversed(matches): cursor.setPosition(start) cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor) cursor.insertText(replacement) cursor.endEditBlock() self._rebuild_find_matches() @staticmethod def _qt_match_spans(source: str, matches) -> list[tuple[int, int]]: """Convert ordered, non-overlapping matches in one pass over UTF-16 text.""" spans = [] offset = position = 0 for match in matches: position += len(source[offset:match.start()].encode("utf-16-le")) // 2 end = position + len(source[match.start():match.end()].encode("utf-16-le")) // 2 spans.append((position, end)) offset, position = match.end(), end return spans @staticmethod def _qt_position(source: str, offset: int) -> int: return len(source[:offset].encode("utf-16-le")) // 2 def replace_source_undoable(self, source: str) -> None: cursor = self.editor.textCursor() cursor.beginEditBlock() cursor.select(QTextCursor.SelectionType.Document) cursor.insertText(source) cursor.endEditBlock() def show_history(self) -> None: from .file_versions import show_version_history source = show_version_history(self, self.save_target_path, self.source_text()) if source is not None: self.replace_source_undoable(source) def _insert_image_mime(self, mime: object) -> bool: from .editor_assets import image_markdown try: text = image_markdown(mime, self.save_target_path) if text is None: return False self.editor.textCursor().insertText(text) except (OSError, ValueError) as exc: QMessageBox.warning(self, "图片插入失败", str(exc)) return True def _choose_images(self) -> None: from PySide6.QtCore import QMimeData paths, _ = QFileDialog.getOpenFileNames(self, "插入图片", str(self.save_target_path.parent), "图片 (*.png *.jpg *.jpeg *.gif *.webp *.bmp *.svg *.tif *.tiff)") if paths: mime = QMimeData() mime.setUrls([QUrl.fromLocalFile(path) for path in paths]) self._insert_image_mime(mime) def _edit_table(self) -> None: from .table_editor import edit_table, table_at_line source = self.source_text() selected = table_at_line(source, self.editor.textCursor().blockNumber()) table = edit_table(self, selected.rows if selected else None, selected.alignments if selected else None) if table is None: return cursor = self.editor.textCursor() cursor.beginEditBlock() if selected: cursor.setPosition(self._qt_position(source, selected.start)) cursor.setPosition(self._qt_position(source, selected.end), QTextCursor.MoveMode.KeepAnchor) cursor.insertText(table + "\n") else: cursor.insertText("\n\n" + table + "\n\n") cursor.endEditBlock() self.editor.setTextCursor(cursor) def _configure_preview_settings(self, settings: QWebEngineSettings) -> None: attributes = QWebEngineSettings.WebAttribute settings.setAttribute(attributes.LocalContentCanAccessFileUrls, True) settings.setAttribute(attributes.LocalContentCanAccessRemoteUrls, True) settings.setAttribute(attributes.PlaybackRequiresUserGesture, False) settings.setAttribute(attributes.FullScreenSupportEnabled, True) settings.setAttribute(attributes.JavascriptEnabled, True) def _apply_view_mode(self) -> None: mode = str(self.view_mode_box.currentData() or "source") self.editor.setVisible(mode in {"source", "split"}) self.preview.setVisible(mode in {"preview", "split"}) if mode in {"preview", "split"} and self._preview_dirty: self._refresh_preview_now() if mode == "split" and self.sync_scroll_checkbox.isChecked(): QTimer.singleShot(0, lambda: self._sync_preview_to_editor_scroll(self.editor.verticalScrollBar().value())) def _schedule_preview_refresh(self) -> None: self._preview_dirty = True mode = str(self.view_mode_box.currentData() or "source") if mode in {"preview", "split"}: self.preview_refresh_timer.start() def _refresh_preview_with_scroll_capture(self) -> None: mode = str(self.view_mode_box.currentData() or "source") if mode == "split" and self.sync_scroll_checkbox.isChecked(): self._preview_scroll_ratio = self._editor_scroll_ratio() self._refresh_preview_now() return self.preview.page().runJavaScript("Math.max(0, window.scrollY || 0)", self._store_scroll_and_refresh_preview) def _store_scroll_and_refresh_preview(self, scroll_y: object) -> None: if not isValid(self) or not isValid(self.preview): return try: self._preview_scroll_y = max(0, int(float(scroll_y or 0))) except (TypeError, ValueError): self._preview_scroll_y = 0 self._refresh_preview_now() def _refresh_preview_now(self) -> None: if not isValid(self) or not isValid(self.preview): return html_content = self.renderer.render_source( self.source_text(), self.save_target_path, theme=self.theme, font_scale=self.font_scale, document_font_family=self.document_font_family, document_font_size=self.document_font_size, document_width_scale=self.document_width_scale, document_style_css=self.document_style_css, math_engine=self.math_engine, source_map=True, ) base_path = str(self.save_target_path.parent.resolve()) + os.sep self.preview.setHtml(html_content, QUrl.fromLocalFile(base_path)) self._preview_dirty = False def _restore_preview_scroll(self, ok: bool) -> None: if not ok: return if str(self.view_mode_box.currentData() or "source") == "split" and self.sync_scroll_checkbox.isChecked(): self._sync_preview_to_source_line() return if self._preview_scroll_y > 0: script = f"(() => {{ window.scrollTo({{top: {self._preview_scroll_y}, behavior: 'instant'}}); }})();" self.preview.page().runJavaScript(script) def _editor_scroll_ratio(self) -> float: maximum = max(1, self.editor.verticalScrollBar().maximum()) return max(0.0, min(1.0, self.editor.verticalScrollBar().value() / maximum)) def _sync_preview_to_editor_scroll(self, value: int) -> None: del value if self._syncing_scroll or not self.sync_scroll_checkbox.isChecked() or str(self.view_mode_box.currentData() or "source") != "split": return self._preview_scroll_ratio = self._editor_scroll_ratio() self.scroll_sync_timer.start() def _sync_preview_to_source_line(self) -> None: if not isValid(self) or not self.sync_scroll_checkbox.isChecked() or self.view_mode_box.currentData() != "split": return block = self.editor.firstVisibleBlock() line = block.blockNumber() height = max(1.0, self.editor.blockBoundingRect(block).height()) offset = -self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top() / height script = """(() => { window.mdhelperProgrammaticScrollUntil = performance.now() + 200; const line = %s; const blocks = [...document.querySelectorAll('[data-source-line]')] .filter(e => e.getBoundingClientRect().height > 0); let target = null; for (const e of blocks) { const start = Number(e.dataset.sourceLine), end = Number(e.dataset.sourceEnd); if (start <= line && (!target || start >= Number(target.dataset.sourceLine))) target = e; } if (!target) return; const start = Number(target.dataset.sourceLine), end = Number(target.dataset.sourceEnd); const fraction = Math.max(0, Math.min(1, (line - start) / Math.max(1, end - start))); const rect = target.getBoundingClientRect(); window.scrollTo({top: window.scrollY + rect.top + rect.height * fraction - 12, behavior: 'instant'}); })();""" % json.dumps(line + max(0, offset)) self.preview.page().runJavaScript(script) def _sync_source_to_preview_line(self, line: float) -> None: if not self.sync_scroll_checkbox.isChecked() or self.view_mode_box.currentData() != "split": return block = self.editor.document().findBlockByNumber(max(0, min(int(line), self.editor.blockCount() - 1))) if not block.isValid(): return document = self.editor.document() key = (document.revision(), self.editor.viewport().width(), self.editor.font().toString()) if getattr(self, "_visual_line_key", None) != key: offsets = [0] current = document.firstBlock() layout = document.documentLayout() while current.isValid(): layout.ensureBlockLayout(current) offsets.append(offsets[-1] + max(1, current.layout().lineCount())) current = current.next() self._visual_line_offsets = offsets self._visual_line_key = key offsets = self._visual_line_offsets index = block.blockNumber() position = offsets[index] + int((line - int(line)) * (offsets[index + 1] - offsets[index])) bar = self.editor.verticalScrollBar() self._syncing_scroll = True try: bar.setValue(position) finally: self._syncing_scroll = False def _scroll_preview_to_ratio(self, ratio: float) -> None: if not isValid(self) or not isValid(self.preview): return script = ( "(() => {" "const ratio = %0.6f;" "const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);" "window.scrollTo({top: Math.round(maxY * ratio), behavior: 'instant'});" "})();" % ratio ) self._syncing_scroll = True self.preview.page().runJavaScript(script, lambda result=None: self._clear_scroll_sync()) def _clear_scroll_sync(self) -> None: self._syncing_scroll = False def _choose_save_as_path(self) -> None: file_name, _ = QFileDialog.getSaveFileName( self, "另存为 Markdown", str(self.save_target_path), "Markdown Files (*.md *.markdown);;All Files (*)", ) if not file_name: return target = Path(file_name) if target.suffix.lower() not in {".md", ".markdown"}: target = target.with_suffix(".md") if self.embedded: self.save_requested.emit(target.resolve(), self.source_text(), self.file_signature) else: self.save_target_path = target.resolve() self._update_dirty_title() self.accept() def accept(self) -> None: super().accept() def _emit_save_requested(self) -> None: self.save_requested.emit(self.save_target_path, self.source_text(), self.file_signature) def mark_saved(self, path: Path, source: str, file_signature: tuple[int, int] | None) -> None: self.path = path self.save_target_path = path self.file_signature = file_signature if source != self.source_text(): self.replace_source_undoable(source) self._original_source = source self.draft_save_timer.stop() self._preview_dirty = True self._update_dirty_title() def confirm_close(self) -> bool: if not self.has_unsaved_changes(): return True choice = QMessageBox.question( self, "关闭编辑标签?", "当前编辑内容尚未保存,确定要关闭此编辑标签吗?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No, ) return choice == QMessageBox.StandardButton.Yes def reject(self) -> None: if not self.confirm_close(): return super().reject()