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 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._current_match_index = -1
|
|
|
|
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.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_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.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
|
|
|
|
|