135 lines
5.2 KiB
Python
135 lines
5.2 KiB
Python
"""Find/replace state and UTF-16 cursor positions, independent of the dialog."""
|
|
from __future__ import annotations
|
|
import re
|
|
from bisect import bisect_left
|
|
from PySide6.QtGui import QTextCursor
|
|
from PySide6.QtWidgets import QPlainTextEdit, QLineEdit, QCheckBox, QLabel
|
|
|
|
|
|
class EditorFindController:
|
|
def __init__(self, editor: QPlainTextEdit, query: QLineEdit, replacement: QLineEdit,
|
|
match_case: QCheckBox, whole_word: QCheckBox, status: QLabel):
|
|
self.editor = editor
|
|
self.editor_find_box, self.editor_replace_box = query, replacement
|
|
self.match_case_checkbox, self.whole_word_checkbox = match_case, whole_word
|
|
self.find_status_label = status
|
|
self._match_positions: list[int] = []
|
|
self._match_spans: list[tuple[int, int]] = []
|
|
self._current_match_index = -1
|
|
|
|
def _rebuild_find_matches(self) -> None:
|
|
query = self.editor_find_box.text()
|
|
self._match_positions = []
|
|
self._match_spans = []
|
|
self._current_match_index = -1
|
|
if not query:
|
|
self.find_status_label.setText("0/0")
|
|
return
|
|
|
|
text = self.editor.toPlainText()
|
|
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_spans = self._qt_match_spans(text, re.finditer(pattern, text, flags))
|
|
self._match_positions = [start for start, _ in self._match_spans]
|
|
cursor = self.editor.textCursor()
|
|
selection = (cursor.selectionStart(), cursor.selectionEnd())
|
|
if cursor.hasSelection() and selection in self._match_spans:
|
|
self._current_match_index = self._match_spans.index(selection)
|
|
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)
|
|
cursor = self.editor.textCursor()
|
|
start, end = self._match_spans[self._current_match_index]
|
|
cursor.setPosition(start)
|
|
cursor.setPosition(end, 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(bisect_left(self._match_positions, self.editor.textCursor().selectionEnd()))
|
|
|
|
|
|
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(bisect_left(self._match_positions, self.editor.textCursor().selectionStart()) - 1)
|
|
|
|
|
|
def replace_current_in_editor(self) -> None:
|
|
query = self.editor_find_box.text()
|
|
if not query:
|
|
return
|
|
|
|
cursor = self.editor.textCursor()
|
|
self._rebuild_find_matches()
|
|
if cursor.hasSelection() and (cursor.selectionStart(), cursor.selectionEnd()) in self._match_spans:
|
|
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.editor.toPlainText()
|
|
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
|
|
|
|
|