codis 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/ui/search_bar.py ADDED
@@ -0,0 +1,1274 @@
1
+ """Barra de busca e substituição do editor do Codis.
2
+
3
+ Provê ``SearchBar``, widget que implementa busca por texto ou regex no
4
+ arquivo aberto, substituição simples e em massa, com realce de ocorrências
5
+ e navegação entre resultados.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import logging
12
+ import re
13
+ import tkinter as tk
14
+ from collections.abc import Callable
15
+ from tkinter import messagebox, ttk
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from src.config import ConfigManager
19
+ from src.constants import (
20
+ FONT_MONO,
21
+ FONT_UI,
22
+ )
23
+ from src.i18n import _t
24
+ from src.theme.base import Theme
25
+ from src.theme.manager import ThemeManager
26
+ from src.ui.grab_safe import safe_grab_set
27
+
28
+ logger = logging.getLogger("Codis")
29
+
30
+ if TYPE_CHECKING:
31
+ from src.editor.pane import EditorPane
32
+
33
+
34
+ class _SearchEngine:
35
+ """
36
+ Motor de busca que opera sobre o conteúdo do editor sem tocar no Tk.
37
+
38
+ Estratégias de performance:
39
+ - Índice de linhas precalculado (offset -> (linha, col)) para O(1) lookup
40
+ - Busca incremental: só recomputa se o texto ou padrão mudou
41
+ - Limite configurável com early-exit
42
+ - Suporte a grupos de captura nos spans para replace com backreferences
43
+
44
+ Thread-safety: projetado para ser chamado apenas da thread principal do Tk.
45
+ """
46
+
47
+ MAX_MATCHES = 10_000
48
+
49
+ def __init__(self) -> None:
50
+ self._text_id: int = 0
51
+ self._content: str = ""
52
+ self._line_index: list[int] = []
53
+ self._matches: list[tuple[int, int]] = []
54
+ self._pat: re.Pattern | None = None
55
+ self._pat_id: int = 0
56
+ self._capped: bool = False
57
+
58
+ def ingest(self, content: str) -> None:
59
+ """Fornece novo conteúdo ao motor. Invalida o cache."""
60
+ if content is self._content:
61
+ return
62
+ self._content = content
63
+ self._text_id += 1
64
+
65
+ idx = [0]
66
+ pos = content.find("\n")
67
+ while pos != -1:
68
+ idx.append(pos + 1)
69
+ pos = content.find("\n", pos + 1)
70
+ self._line_index = idx
71
+
72
+ self._matches = []
73
+ self._pat_id = -1
74
+
75
+ def offset_to_line_col(self, offset: int) -> tuple[int, int]:
76
+ """Converte offset de char em (linha 1-based, col 0-based). O(log N)."""
77
+ import bisect
78
+
79
+ li = bisect.bisect_right(self._line_index, offset) - 1
80
+ li = max(0, min(li, len(self._line_index) - 1))
81
+ col = offset - self._line_index[li]
82
+ return li + 1, col
83
+
84
+ def tk_index(self, offset: int) -> str:
85
+ """Retorna índice no formato Tk 'linha.col'."""
86
+ ln, col = self.offset_to_line_col(offset)
87
+ return f"{ln}.{col}"
88
+
89
+ def search(
90
+ self, pat: re.Pattern, sel_start: int = 0, sel_end: int = -1
91
+ ) -> list[tuple[int, int]]:
92
+ """
93
+ Executa a busca no conteúdo ingerido.
94
+ sel_end == -1 -> busca no conteúdo inteiro
95
+ Retorna lista de (start_offset, end_offset).
96
+ """
97
+ if not self._content:
98
+ self._matches = []
99
+ self._capped = False
100
+ return self._matches
101
+
102
+ end = sel_end if sel_end != -1 else len(self._content)
103
+ content_slice = self._content[sel_start:end]
104
+
105
+ matches: list[tuple[int, int]] = []
106
+ capped = False
107
+ for m in pat.finditer(content_slice):
108
+ s = m.start() + sel_start
109
+ e = m.end() + sel_start
110
+ if s == e:
111
+ e = s + 1
112
+ matches.append((s, e))
113
+ if len(matches) >= self.MAX_MATCHES:
114
+ capped = True
115
+ break
116
+
117
+ self._matches = matches
118
+ self._capped = capped
119
+ self._pat = pat
120
+ return matches
121
+
122
+ def replace_all(
123
+ self, pat: re.Pattern, repl_fn: Callable[[str, str], str], repl_template: str
124
+ ) -> tuple[str, int]:
125
+ """
126
+ Substitui todas as ocorrências no conteúdo.
127
+ repl_fn(match_text, template) -> replacement_string
128
+ Retorna (novo_conteúdo, número_de_substituições).
129
+ """
130
+
131
+ def _sub(m: re.Match) -> str:
132
+
133
+ try:
134
+ raw = m.expand(repl_template)
135
+ except re.error:
136
+ raw = repl_template
137
+ return repl_fn(m.group(), raw)
138
+
139
+ new_content, n = pat.subn(_sub, self._content)
140
+ return new_content, n
141
+
142
+ @property
143
+ def matches(self) -> list[tuple[int, int]]:
144
+ """Executa a busca e retorna a lista de (início, fim) de cada ocorrência."""
145
+ return self._matches
146
+
147
+ @property
148
+ def capped(self) -> bool:
149
+ """Indica se o número de resultados foi limitado pelo teto máximo de exibição."""
150
+ return self._capped
151
+
152
+
153
+ def _build_pattern(
154
+ query: str, case_sensitive: bool, whole_word: bool, is_regex: bool
155
+ ) -> re.Pattern | None:
156
+ """Compila o padrão de busca com tratamento de erros. Retorna None se inválido."""
157
+ if not query:
158
+ return None
159
+ flags = 0 if case_sensitive else re.IGNORECASE
160
+ try:
161
+ if is_regex:
162
+ raw = query
163
+ elif whole_word:
164
+ raw = r"\b" + re.escape(query) + r"\b"
165
+ else:
166
+ raw = re.escape(query)
167
+ return re.compile(raw, flags)
168
+ except re.error:
169
+ return None
170
+
171
+
172
+ class SearchBar(tk.Frame):
173
+ """
174
+ Barra de busca e substituição:
175
+
176
+ +-------------------------------------------------------------------+
177
+ | ⠿ 🔍 [campo de busca ....................] 12/347 ↑ ↓ ⇄ 📂 ✕ |
178
+ | [Aa] [\\b] [.*] [≡] [⌂] -- active: regex·case |
179
+ | ⇄ [campo de substituição ...............] [\\1 \\2 vars ok] |
180
+ | [Cc Preserve] [AB] [ab] [Ab] [⧉ Preview] |
181
+ | [▶ Substituir] [▶▶ Substituir Tudo] |
182
+ +-------------------------------------------------------------------+
183
+
184
+ Backend (_SearchEngine):
185
+ - Índice bisect de linhas -> offset_to_line_col em O(log N)
186
+ - Debounce 80ms antes de recalcular (evita lag em arquivos grandes)
187
+ - Limite 10 000 matches com early-exit e indicador "10000+"
188
+ - replace_all atômico via set_content (undo group nativo do Tk)
189
+ - Backreferences \\1 \\2 no campo replace
190
+ - Preview diff unificado antes de aplicar substitution
191
+
192
+ UX/Frontend:
193
+ - Flash breve no match atual (180ms)
194
+ - Indicador ↺ wrap-around no contador
195
+ - Borda vermelha no campo find quando regex inválido
196
+ - Barra de progresso proporcional ao match atual/total
197
+ - Novo toggle: Multiline (^ $ por linha) Alt+M
198
+ - Ctrl+Return insere \\n literal no campo find
199
+ - Esc com texto -> limpa; sem texto -> fecha
200
+ - Botão Preview diff: vê antes de aplicar replace all
201
+ """
202
+
203
+ _HIST_MAX = 100
204
+ _DEBOUNCE_MS = 80
205
+
206
+ def __init__(
207
+ self,
208
+ parent: tk.Widget,
209
+ tmgr: ThemeManager,
210
+ cfg: ConfigManager,
211
+ get_editor: Callable[[], EditorPane | None],
212
+ on_find_in_files: Callable | None = None,
213
+ pack_before: tk.Widget | None = None,
214
+ ) -> None:
215
+ """Inicializa a barra de busca e substituição do editor.
216
+
217
+ Args:
218
+ parent: Widget pai Tkinter.
219
+ editor: Referência ao EditorPane ativo.
220
+ cfg: Instância de ConfigManager.
221
+ pack_before: Widget antes do qual a barra deve ser inserida no
222
+ layout pack (evita ficar atrás de widgets com expand=True).
223
+ """
224
+ t = tmgr.theme
225
+ super().__init__(
226
+ parent,
227
+ bg=t.floating_bg,
228
+ highlightthickness=1,
229
+ highlightbackground=t.floating_border,
230
+ bd=0,
231
+ )
232
+ self._tmgr = tmgr
233
+ self._cfg = cfg
234
+ self._get_editor = get_editor
235
+ self._on_find_files = on_find_in_files
236
+ self._pack_before: tk.Widget | None = pack_before
237
+
238
+ self._engine = _SearchEngine()
239
+ self._matches: list[tuple[int, int]] = []
240
+ self._match_idx = 0
241
+ self._visible = False
242
+ self._replace_open = False
243
+ self._debounce_id: str | None = None
244
+
245
+ self._case_mode = False
246
+ self._word_mode = False
247
+ self._re_mode = False
248
+ self._sel_mode = False
249
+ self._multi_mode = False
250
+
251
+ self._preserve_case = False
252
+ self._case_transform = ""
253
+
254
+ self._find_history: list[str] = []
255
+ self._repl_history: list[str] = []
256
+ self._find_hist_pos = -1
257
+ self._repl_hist_pos = -1
258
+
259
+ self._find_entry: tk.Entry | None = None
260
+ self._repl_entry: tk.Entry | None = None
261
+ self._count_lbl: tk.Label | None = None
262
+ self._prog_canvas: tk.Canvas | None = None
263
+ self._repl_row: tk.Frame | None = None
264
+ self._repl_toggle: tk.Label | None = None
265
+ self._hint_lbl: tk.Label | None = None
266
+ self._opt_btns: dict[str, tk.Label] = {}
267
+ self._ct_btns: dict[str, tk.Label] = {}
268
+ self._find_wrap: tk.Frame | None = None
269
+ self._err_border = False
270
+ self._repl_opts_row: tk.Frame | None = None
271
+
272
+ self._build()
273
+ self.pack_forget()
274
+
275
+ def _build(self) -> None:
276
+ t = self._tmgr.theme
277
+
278
+ def _ekw(width: int = 26) -> dict:
279
+ return {
280
+ "bg": t.input_bg,
281
+ "fg": t.fg,
282
+ "insertbackground": t.cursor,
283
+ "relief": "flat",
284
+ "bd": 0,
285
+ "width": width,
286
+ "font": (FONT_UI, 10),
287
+ "highlightthickness": 0,
288
+ }
289
+
290
+ grip = tk.Label(
291
+ self,
292
+ text="⠿",
293
+ bg=t.floating_bg,
294
+ fg=t.fg_muted,
295
+ font=(FONT_UI, 9),
296
+ cursor="fleur",
297
+ padx=3,
298
+ )
299
+ grip.pack(side="top", anchor="e", padx=2, pady=(2, 0))
300
+
301
+ rowA = tk.Frame(self, bg=t.floating_bg)
302
+ rowA.pack(fill="x", padx=8, pady=(2, 1))
303
+
304
+ tk.Label(
305
+ rowA, text="🔍", bg=t.floating_bg, fg=t.fg_muted, font=(FONT_UI, 10)
306
+ ).pack(side="left", padx=(0, 4))
307
+
308
+ self._find_wrap = tk.Frame(
309
+ rowA, bg=t.border, highlightthickness=0, bd=1, relief="flat"
310
+ )
311
+ self._find_wrap.pack(side="left", padx=(0, 4))
312
+ self._find_var = tk.StringVar()
313
+ self._find_var.trace_add("write", lambda *_: self._schedule_find())
314
+ self._find_entry = tk.Entry(
315
+ self._find_wrap, textvariable=self._find_var, **_ekw(26)
316
+ )
317
+ self._find_entry.pack(padx=1, pady=1)
318
+
319
+ counter_col = tk.Frame(rowA, bg=t.floating_bg)
320
+ counter_col.pack(side="left", padx=(0, 4))
321
+ self._count_lbl = tk.Label(
322
+ counter_col,
323
+ text="",
324
+ bg=t.floating_bg,
325
+ fg=t.fg_muted,
326
+ font=(FONT_MONO, 8),
327
+ width=10,
328
+ anchor="w",
329
+ )
330
+ self._count_lbl.pack()
331
+ self._prog_canvas = tk.Canvas(
332
+ counter_col, height=2, width=72, bg=t.floating_bg, highlightthickness=0
333
+ )
334
+ self._prog_canvas.pack(fill="x")
335
+
336
+ tk.Frame(rowA, bg=t.border, width=1).pack(
337
+ side="left", fill="y", padx=3, pady=2)
338
+
339
+ self._ibtn(rowA, "↑", self.prev_match, "Anterior Shift+F3")
340
+ self._ibtn(rowA, "↓", self.next_match, "Próximo F3")
341
+
342
+ tk.Frame(rowA, bg=t.border, width=1).pack(
343
+ side="left", fill="y", padx=3, pady=2)
344
+
345
+ self._repl_toggle = tk.Label(
346
+ rowA,
347
+ text="⇄",
348
+ bg=t.btn_bg,
349
+ fg=t.fg_muted,
350
+ font=(FONT_UI, 10),
351
+ padx=7,
352
+ pady=1,
353
+ cursor="hand2",
354
+ relief="flat",
355
+ )
356
+ self._repl_toggle.pack(side="left", padx=1)
357
+ self._repl_toggle.bind("<Button-1>", lambda _: self._toggle_replace())
358
+ self._tip(self._repl_toggle, "Abrir/fechar substituição Ctrl+H")
359
+
360
+ if self._on_find_files:
361
+ tk.Frame(rowA, bg=t.border, width=1).pack(
362
+ side="left", fill="y", padx=3, pady=2
363
+ )
364
+ self._ibtn(
365
+ rowA,
366
+ "📂",
367
+ self._trigger_find_files,
368
+ "Buscar em todos os arquivos Ctrl+Shift+F",
369
+ )
370
+
371
+ self._ibtn(rowA, "✕", self.hide, "Fechar Escape")
372
+
373
+ rowB = tk.Frame(self, bg=t.floating_bg)
374
+ rowB.pack(fill="x", padx=8, pady=(2, 2))
375
+
376
+ for text, attr, tip in (
377
+ ("Aa", "_case_mode", "Case sensitive Alt+C"),
378
+ ("\\b", "_word_mode", "Palavra inteira Alt+W"),
379
+ (".*", "_re_mode", "Expressão regular (Python re) Alt+R"),
380
+ ("≡", "_sel_mode", "Apenas na seleção Alt+S"),
381
+ ("⌂", "_multi_mode", "Multiline (^ e $ por linha) Alt+M"),
382
+ ):
383
+ b = self._opt_btn(rowB, text, attr, tip)
384
+ self._opt_btns[attr] = b
385
+
386
+ self._hint_lbl = tk.Label(
387
+ rowB,
388
+ text="",
389
+ bg=t.floating_bg,
390
+ fg=t.fg_muted,
391
+ font=(FONT_UI, 7),
392
+ anchor="w",
393
+ )
394
+ self._hint_lbl.pack(side="left", padx=(10, 0))
395
+
396
+ self._repl_row = tk.Frame(self, bg=t.floating_bg)
397
+
398
+ tk.Label(
399
+ self._repl_row,
400
+ text="⇄",
401
+ bg=t.floating_bg,
402
+ fg=t.fg_muted,
403
+ font=(FONT_UI, 10),
404
+ ).pack(side="left", padx=(0, 4))
405
+
406
+ self._repl_var = tk.StringVar()
407
+ self._repl_entry = tk.Entry(
408
+ self._repl_row, textvariable=self._repl_var, **_ekw(26)
409
+ )
410
+ self._repl_entry.pack(side="left", padx=(0, 4), ipady=2)
411
+ self._tip(
412
+ self._repl_entry,
413
+ "Use \\1, \\2 ... para grupos de captura em modo regex\n"
414
+ "Ex: buscar (\\w+)\\s(\\w+) → substituir \\2 \\1",
415
+ )
416
+
417
+ for lbl, cmd, tip_text in (
418
+ ("▶ Substituir", self._replace_one,
419
+ "Substituir ocorrência atual Enter"),
420
+ ("▶▶ Subst. Tudo", self._replace_all, "Substituir todas Shift+Enter"),
421
+ ):
422
+ b = tk.Label(
423
+ self._repl_row,
424
+ text=lbl,
425
+ bg=t.btn_bg,
426
+ fg=t.fg,
427
+ font=(FONT_UI, 8),
428
+ padx=9,
429
+ pady=2,
430
+ cursor="hand2",
431
+ relief="flat",
432
+ highlightthickness=1,
433
+ highlightbackground=t.border,
434
+ )
435
+ b.pack(side="left", padx=2)
436
+ b.bind("<Button-1>", lambda _, c=cmd: c())
437
+ b.bind("<Enter>", lambda _, x=b: x.config(bg=t.btn_hover))
438
+ b.bind("<Leave>", lambda _, x=b: x.config(bg=t.btn_bg))
439
+ self._tip(b, tip_text)
440
+
441
+ preview_btn = tk.Label(
442
+ self._repl_row,
443
+ text=_t("hc.search_bar.preview"),
444
+ bg=t.btn_bg,
445
+ fg=t.fg_muted,
446
+ font=(FONT_UI, 8),
447
+ padx=7,
448
+ pady=2,
449
+ cursor="hand2",
450
+ relief="flat",
451
+ highlightthickness=1,
452
+ highlightbackground=t.border,
453
+ )
454
+ preview_btn.pack(side="left", padx=2)
455
+ preview_btn.bind("<Button-1>", lambda _: self._show_replace_preview())
456
+ self._tip(preview_btn, "Pré-visualizar substituições antes de aplicar")
457
+
458
+ self._repl_opts_row = tk.Frame(self, bg=t.floating_bg)
459
+
460
+ tk.Label(
461
+ self._repl_opts_row,
462
+ text=_t("hc.search_bar.case"),
463
+ bg=t.floating_bg,
464
+ fg=t.fg_muted,
465
+ font=(FONT_UI, 7),
466
+ ).pack(side="left", padx=(0, 3))
467
+
468
+ self._opt_btn(
469
+ self._repl_opts_row,
470
+ "Cc",
471
+ "_preserve_case",
472
+ "Preservar capitalização original",
473
+ )
474
+ self._opt_btns.pop("_preserve_case", None)
475
+
476
+ tk.Label(
477
+ self._repl_opts_row,
478
+ text=_t("hc.search_bar.transform"),
479
+ bg=t.floating_bg,
480
+ fg=t.fg_muted,
481
+ font=(FONT_UI, 7),
482
+ ).pack(side="left", padx=(6, 2))
483
+
484
+ for label, val, tip_text in (
485
+ ("-", "", "Sem transformação"),
486
+ ("AB", "upper", "MAIÚSCULAS"),
487
+ ("ab", "lower", "minúsculas"),
488
+ ("Ab", "title", "Title Case"),
489
+ ):
490
+ b = tk.Label(
491
+ self._repl_opts_row,
492
+ text=label,
493
+ bg=t.btn_bg,
494
+ fg=t.fg_muted,
495
+ font=(FONT_MONO, 8),
496
+ padx=5,
497
+ pady=1,
498
+ cursor="hand2",
499
+ relief="flat",
500
+ )
501
+ b.pack(side="left", padx=1)
502
+ b.bind("<Button-1>", lambda _, v=val: self._set_case_transform(v))
503
+ self._tip(b, tip_text)
504
+ self._ct_btns[val] = b
505
+ self._update_ct_btns()
506
+
507
+ fe = self._find_entry
508
+ re_ = self._repl_entry
509
+
510
+ fe.bind("<Return>", lambda _: self.next_match())
511
+ fe.bind("<Shift-Return>", lambda _: self.prev_match())
512
+ fe.bind("<Escape>", lambda _: self._esc_find())
513
+ fe.bind("<Tab>", self._focus_replace)
514
+ fe.bind("<Up>", self._hist_find_up)
515
+ fe.bind("<Down>", self._hist_find_down)
516
+ fe.bind("<Control-h>", lambda _: self._toggle_replace())
517
+ fe.bind("<Alt-c>", lambda _: self._toggle_opt("_case_mode"))
518
+ fe.bind("<Alt-w>", lambda _: self._toggle_opt("_word_mode"))
519
+ fe.bind("<Alt-r>", lambda _: self._toggle_opt("_re_mode"))
520
+ fe.bind("<Alt-s>", lambda _: self._toggle_opt("_sel_mode"))
521
+ fe.bind("<Alt-m>", lambda _: self._toggle_opt("_multi_mode"))
522
+ fe.bind("<F3>", lambda _: self.next_match())
523
+ fe.bind("<Shift-F3>", lambda _: self.prev_match())
524
+ fe.bind("<Control-Return>", lambda _: self._insert_newline_in_find())
525
+
526
+ re_.bind("<Return>", lambda _: self._replace_one())
527
+ re_.bind("<Shift-Return>", lambda _: self._replace_all())
528
+ re_.bind("<Escape>", lambda _: self.hide())
529
+ re_.bind("<Tab>", lambda _: fe.focus_set() or "break")
530
+ re_.bind("<Up>", self._hist_repl_up)
531
+ re_.bind("<Down>", self._hist_repl_down)
532
+
533
+ def _ibtn(
534
+ self, parent: tk.Widget, text: str, cmd: Callable, tip: str = ""
535
+ ) -> tk.Label:
536
+ """Cria e retorna um botão ícone.
537
+
538
+ Args:
539
+ parent: Widget pai Tkinter.
540
+ text: Dado textual a processar.
541
+ """
542
+ t = self._tmgr.theme
543
+ b = tk.Label(
544
+ parent,
545
+ text=text,
546
+ bg=t.floating_bg,
547
+ fg=t.fg,
548
+ font=(FONT_UI, 10),
549
+ padx=5,
550
+ cursor="hand2",
551
+ )
552
+ b.pack(side="left", padx=1)
553
+ b.bind("<Button-1>", lambda _: cmd())
554
+ b.bind("<Enter>", lambda _: b.config(bg=t.sel_bg))
555
+ b.bind("<Leave>", lambda _: b.config(bg=t.floating_bg))
556
+ if tip:
557
+ self._tip(b, tip)
558
+ return b
559
+
560
+ def _opt_btn(self, parent: tk.Widget, text: str, attr: str, tip: str) -> tk.Label:
561
+ t = self._tmgr.theme
562
+ active = getattr(self, attr, False)
563
+ b = tk.Label(
564
+ parent,
565
+ text=text,
566
+ bg=t.accent if active else t.btn_bg,
567
+ fg="#ffffff" if active else t.fg_muted,
568
+ font=(FONT_MONO, 9),
569
+ padx=6,
570
+ pady=1,
571
+ cursor="hand2",
572
+ relief="flat",
573
+ highlightthickness=1,
574
+ highlightbackground=t.border,
575
+ )
576
+ b.pack(side="left", padx=2)
577
+
578
+ def _toggle(_e=None):
579
+ val = not getattr(self, attr, False)
580
+ setattr(self, attr, val)
581
+ b.config(
582
+ bg=t.accent if val else t.btn_bg, fg="#ffffff" if val else t.fg_muted
583
+ )
584
+ self._do_find()
585
+ self._update_hint()
586
+
587
+ b.bind("<Button-1>", _toggle)
588
+ self._tip(b, tip)
589
+ return b
590
+
591
+ def _tip(self, widget: tk.Widget, text: str) -> None:
592
+ """Exibe tooltip para o widget indicado.
593
+
594
+ Args:
595
+ text: Dado textual a processar.
596
+ """
597
+ _state: dict = {"win": None, "after_id": None}
598
+
599
+ def _make(x: int, y: int) -> None:
600
+ _destroy()
601
+ t = self._tmgr.theme
602
+ tw = tk.Toplevel(widget)
603
+ tw.wm_overrideredirect(True)
604
+ tw.wm_attributes("-topmost", True)
605
+ fr = tk.Frame(tw, bg=t.floating_border, bd=1)
606
+ fr.pack()
607
+ inner = tk.Frame(fr, bg=t.floating_bg, padx=10, pady=6)
608
+ inner.pack()
609
+ tk.Label(
610
+ inner,
611
+ text=text,
612
+ bg=t.floating_bg,
613
+ fg=t.fg,
614
+ font=(FONT_UI, 9),
615
+ justify="left",
616
+ anchor="w",
617
+ wraplength=340,
618
+ ).pack()
619
+ tw.geometry(f"+{x + 12}+{y + 12}")
620
+ _state["win"] = tw
621
+
622
+ def _destroy(_e=None) -> None:
623
+ if _state.get("after_id"):
624
+ with contextlib.suppress(tk.TclError):
625
+ widget.after_cancel(_state["after_id"])
626
+ _state["after_id"] = None
627
+ if _state.get("win"):
628
+ with contextlib.suppress(tk.TclError):
629
+ _state["win"].destroy()
630
+ _state["win"] = None
631
+
632
+ def _enter(e: tk.Event) -> None:
633
+ _state["after_id"] = widget.after(
634
+ 500, lambda: _make(e.x_root, e.y_root))
635
+
636
+ widget.bind("<Enter>", _enter, add="+")
637
+ widget.bind("<Leave>", _destroy, add="+")
638
+
639
+ def _schedule_find(self) -> None:
640
+ """Agenda a execução da busca com debounce após o usuário parar de digitar."""
641
+ if self._debounce_id:
642
+ with contextlib.suppress(tk.TclError):
643
+ self.after_cancel(self._debounce_id)
644
+ self._debounce_id = self.after(self._DEBOUNCE_MS, self._do_find)
645
+
646
+ def _get_pattern(self) -> re.Pattern | None:
647
+ """Obtém e retorna 'pattern'."""
648
+ query = self._find_var.get()
649
+ pat = _build_pattern(query, self._case_mode,
650
+ self._word_mode, self._re_mode)
651
+ self._set_find_error(query != "" and pat is None)
652
+ return pat
653
+
654
+ def _set_find_error(self, has_error: bool) -> None:
655
+ if has_error == self._err_border:
656
+ return
657
+ self._err_border = has_error
658
+ t = self._tmgr.theme
659
+ color = t.err_fg if has_error else t.border
660
+ if self._find_wrap:
661
+ with contextlib.suppress(tk.TclError):
662
+ self._find_wrap.config(bg=color)
663
+ if self._count_lbl and has_error:
664
+ self._count_lbl.config(
665
+ text=_t("hc.search_bar.regex_inv_lido"), fg=t.err_fg)
666
+
667
+ def _do_find(self) -> None:
668
+ """Executa a busca completa e popula os resultados na barra."""
669
+ editor = self._get_editor()
670
+ if not editor:
671
+ return
672
+ query = self._find_var.get()
673
+ t = self._tmgr.theme
674
+
675
+ if not query:
676
+ editor.hl.clear_search()
677
+ self._matches = []
678
+ self._match_idx = 0
679
+ if self._count_lbl:
680
+ self._count_lbl.config(text="", fg=t.fg_muted)
681
+ self._update_progress(0, 0)
682
+ self._set_find_error(False)
683
+ return
684
+
685
+ pat = self._get_pattern()
686
+ if pat is None:
687
+ editor.hl.clear_search()
688
+ return
689
+
690
+ content = editor.text.get("1.0", "end-1c")
691
+ self._engine.ingest(content)
692
+
693
+ sel_start, sel_end = 0, -1
694
+ if self._sel_mode:
695
+ with contextlib.suppress(tk.TclError):
696
+ s_idx = editor.text.index(tk.SEL_FIRST)
697
+ e_idx = editor.text.index(tk.SEL_LAST)
698
+ sel_start = self._tk_to_offset(content, s_idx)
699
+ sel_end = self._tk_to_offset(content, e_idx)
700
+
701
+ raw_matches = self._engine.search(pat, sel_start, sel_end)
702
+ count = len(raw_matches)
703
+
704
+ if count == 0:
705
+ editor.hl.clear_search()
706
+ self._matches = []
707
+ self._match_idx = 0
708
+ if self._count_lbl:
709
+ self._count_lbl.config(
710
+ text=_t("hc.search_bar.nenhum_resultado"), fg=t.warn_fg
711
+ )
712
+ self._update_progress(0, 0)
713
+ return
714
+
715
+ self._matches = raw_matches
716
+ self._match_idx = 0
717
+
718
+ tk_matches = [
719
+ (self._engine.tk_index(s), self._engine.tk_index(e)) for s, e in raw_matches
720
+ ]
721
+ editor.hl.apply_search(tk_matches, 0)
722
+ with contextlib.suppress(tk.TclError):
723
+ editor.text.see(tk_matches[0][0])
724
+
725
+ suffix = "+" if self._engine.capped else ""
726
+ if self._count_lbl:
727
+ self._count_lbl.config(text=f"1/{count}{suffix}", fg=t.fg_muted)
728
+ self._update_progress(1, count)
729
+
730
+ @staticmethod
731
+ def _tk_to_offset(content: str, tk_idx: str) -> int:
732
+ try:
733
+ parts = tk_idx.split(".")
734
+ ln = int(parts[0]) - 1
735
+ col = int(parts[1])
736
+ lines = content.split("\n")
737
+ return sum(len(lines[i]) + 1 for i in range(min(ln, len(lines)))) + col
738
+ except (ValueError, IndexError):
739
+ return 0
740
+
741
+ def _update_progress(self, current: int, total: int) -> None:
742
+ if not self._prog_canvas:
743
+ return
744
+ with contextlib.suppress(tk.TclError):
745
+ t = self._tmgr.theme
746
+ w = self._prog_canvas.winfo_width() or 72
747
+ self._prog_canvas.delete("all")
748
+ if total > 0:
749
+ ratio = current / total
750
+ self._prog_canvas.create_rectangle(
751
+ 0, 0, int(w * ratio), 2, fill=t.accent, outline=""
752
+ )
753
+
754
+ def _jump_to(self, idx: int) -> None:
755
+ editor = self._get_editor()
756
+ if not editor or not self._matches:
757
+ return
758
+ s_off, e_off = self._matches[idx]
759
+ ts = self._engine.tk_index(s_off)
760
+ te = self._engine.tk_index(e_off)
761
+
762
+ content = editor.text.get("1.0", "end-1c")
763
+ self._engine.ingest(content)
764
+ tk_matches = [
765
+ (self._engine.tk_index(s), self._engine.tk_index(e))
766
+ for s, e in self._matches
767
+ ]
768
+
769
+ editor.hl.apply_search(tk_matches, idx)
770
+ with contextlib.suppress(tk.TclError):
771
+ editor.text.see(ts)
772
+ editor.text.mark_set(tk.INSERT, ts)
773
+
774
+ count = len(self._matches)
775
+ suffix = "+" if self._engine.capped else ""
776
+ if self._count_lbl:
777
+ self._count_lbl.config(
778
+ text=f"{idx + 1}/{count}{suffix}", fg=self._tmgr.theme.fg_muted
779
+ )
780
+ self._update_progress(idx + 1, count)
781
+ self._flash_match(editor, ts, te)
782
+
783
+ def _flash_match(self, editor: Any, ts: str, te: str) -> None:
784
+ t = self._tmgr.theme
785
+ flash_tag = "_search_flash"
786
+ with contextlib.suppress(tk.TclError):
787
+ editor.text.tag_configure(
788
+ flash_tag,
789
+ background=getattr(t, "accent", "#007ACC"),
790
+ foreground="#ffffff",
791
+ )
792
+ editor.text.tag_add(flash_tag, ts, te)
793
+ editor.text.after(
794
+ 180,
795
+ lambda: (
796
+ editor.text.tag_remove(flash_tag, "1.0", "end")
797
+ if editor.text.winfo_exists()
798
+ else None
799
+ ),
800
+ )
801
+
802
+ def next_match(self) -> None:
803
+ """Navega para a próxima ocorrência, com wraparound ao final."""
804
+ if not self._matches:
805
+ self._do_find()
806
+ return
807
+ prev = self._match_idx
808
+ self._match_idx = (self._match_idx + 1) % len(self._matches)
809
+ if self._match_idx < prev:
810
+ self._show_wrap_indicator()
811
+ self._jump_to(self._match_idx)
812
+
813
+ def prev_match(self) -> None:
814
+ """Navega para a ocorrência anterior, com wraparound ao início."""
815
+ if not self._matches:
816
+ return
817
+ prev = self._match_idx
818
+ self._match_idx = (self._match_idx - 1) % len(self._matches)
819
+ if self._match_idx > prev:
820
+ self._show_wrap_indicator()
821
+ self._jump_to(self._match_idx)
822
+
823
+ def _show_wrap_indicator(self) -> None:
824
+ """Exibe brevemente o indicador de volta ao início/fim da busca."""
825
+ if not self._count_lbl:
826
+ return
827
+ t = self._tmgr.theme
828
+ orig_text = self._count_lbl.cget("text")
829
+ self._count_lbl.config(
830
+ text=_t("hc.search_bar.wrap"), fg=getattr(t, "accent", "#007ACC")
831
+ )
832
+ self._count_lbl.after(
833
+ 600,
834
+ lambda: (
835
+ self._count_lbl.config(text=orig_text, fg=t.fg_muted)
836
+ if self._count_lbl.winfo_exists()
837
+ else None
838
+ ),
839
+ )
840
+
841
+ def _smart_replace(self, original: str, repl: str) -> str:
842
+ if self._case_transform:
843
+ if self._case_transform == "upper":
844
+ return repl.upper()
845
+ if self._case_transform == "lower":
846
+ return repl.lower()
847
+ if self._case_transform == "title":
848
+ return repl.title()
849
+ if not self._preserve_case:
850
+ return repl
851
+ if original.isupper():
852
+ return repl.upper()
853
+ if original.islower():
854
+ return repl.lower()
855
+ if original and original[0].isupper():
856
+ return repl.capitalize()
857
+ return repl
858
+
859
+ def _replace_one(self) -> None:
860
+ """Substitui a ocorrência atualmente selecionada."""
861
+ editor = self._get_editor()
862
+ if not editor or not self._matches:
863
+ return
864
+ if not self._replace_open:
865
+ self._toggle_replace()
866
+ return
867
+ pat = self._get_pattern()
868
+ if pat is None:
869
+ return
870
+ s_off, e_off = self._matches[self._match_idx]
871
+ ts = self._engine.tk_index(s_off)
872
+ te = self._engine.tk_index(e_off)
873
+ orig = editor.text.get(ts, te)
874
+ repl_template = self._repl_var.get()
875
+ try:
876
+ m = pat.search(orig)
877
+ raw = m.expand(
878
+ repl_template) if m and self._re_mode else repl_template
879
+ except re.error:
880
+ raw = repl_template
881
+ repl = self._smart_replace(orig, raw)
882
+ try:
883
+ editor.text.delete(ts, te)
884
+ editor.text.insert(ts, repl)
885
+ except tk.TclError:
886
+ return
887
+ self._add_history_repl(repl_template)
888
+ self._do_find()
889
+ if self._matches:
890
+ self._jump_to(min(self._match_idx, len(self._matches) - 1))
891
+
892
+ def _replace_all(self) -> None:
893
+ """Substitui todas as ocorrências no editor."""
894
+ editor = self._get_editor()
895
+ if not editor:
896
+ return
897
+ if not self._replace_open:
898
+ self._toggle_replace()
899
+ return
900
+ query = self._find_var.get()
901
+ if not query:
902
+ return
903
+ pat = self._get_pattern()
904
+ if pat is None:
905
+ return
906
+ content = editor.text.get("1.0", "end-1c")
907
+ self._engine.ingest(content)
908
+ repl_template = self._repl_var.get()
909
+ new_content, n = self._engine.replace_all(
910
+ pat, self._smart_replace, repl_template
911
+ )
912
+ t = self._tmgr.theme
913
+ if n:
914
+ editor.set_content(new_content)
915
+ if self._count_lbl:
916
+ self._count_lbl.config(
917
+ text=f"↺ {n} trocado(s)", fg=getattr(t, "diff_add_fg", "#4CAF50")
918
+ )
919
+ self._add_history_find(query)
920
+ self._add_history_repl(repl_template)
921
+ self._matches = []
922
+ self._match_idx = 0
923
+ self._update_progress(0, 0)
924
+ else:
925
+ if self._count_lbl:
926
+ self._count_lbl.config(
927
+ text=_t("hc.search_bar.0_resultados"), fg=t.warn_fg
928
+ )
929
+
930
+ def _show_replace_preview(self) -> None:
931
+ """Exibe prévia visual das substituições antes de aplicá-las."""
932
+ editor = self._get_editor()
933
+ if not editor:
934
+ return
935
+ pat = self._get_pattern()
936
+ if pat is None:
937
+ return
938
+ content = editor.text.get("1.0", "end-1c")
939
+ self._engine.ingest(content)
940
+ repl_template = self._repl_var.get()
941
+ new_content, n = self._engine.replace_all(
942
+ pat, self._smart_replace, repl_template
943
+ )
944
+ if n == 0:
945
+ messagebox.showinfo(
946
+ _t("hc.search_bar.preview_substitui_o"),
947
+ "Nenhuma substituição seria feita.",
948
+ parent=self,
949
+ )
950
+ return
951
+ t = self._tmgr.theme
952
+ win = tk.Toplevel(self)
953
+ win.title(f"Preview - {n} substituição(ões)")
954
+ win.configure(bg=t.panel_bg)
955
+ win.transient(self)
956
+ safe_grab_set(win)
957
+ tk.Label(
958
+ win,
959
+ text=f" {n} substituição(ões) seriam feitas",
960
+ bg=t.panel_bg,
961
+ fg=t.fg,
962
+ font=(FONT_UI, 10, "bold"),
963
+ ).pack(fill="x", padx=12, pady=(10, 4))
964
+ fr = tk.Frame(win, bg=t.panel_bg)
965
+ fr.pack(fill="both", expand=True, padx=8, pady=4)
966
+ vsb = ttk.Scrollbar(fr, orient="vertical",
967
+ style="Thin.Vertical.TScrollbar")
968
+ vsb.pack(side="right", fill="y")
969
+ txt = tk.Text(
970
+ fr,
971
+ bg=t.panel_bg,
972
+ fg=t.fg,
973
+ font=(FONT_MONO, 9),
974
+ relief="flat",
975
+ bd=0,
976
+ wrap="none",
977
+ highlightthickness=0,
978
+ yscrollcommand=vsb.set,
979
+ width=80,
980
+ height=22,
981
+ )
982
+ txt.pack(side="left", fill="both", expand=True)
983
+ vsb.config(command=txt.yview)
984
+ txt.tag_configure(
985
+ "del",
986
+ background=getattr(t, "diff_del_bg", "#3d1212"),
987
+ foreground=getattr(t, "diff_del_fg", "#ff8080"),
988
+ )
989
+ txt.tag_configure(
990
+ "add",
991
+ background=getattr(t, "diff_add_bg", "#0d2d0d"),
992
+ foreground=getattr(t, "diff_add_fg", "#80ff80"),
993
+ )
994
+ txt.tag_configure("ctx", foreground=t.fg_muted)
995
+ import difflib as _diff
996
+
997
+ for grp in _diff.unified_diff(
998
+ content.split("\n"), new_content.split("\n"), lineterm="", n=2
999
+ ):
1000
+ if grp.startswith("---") or grp.startswith("+++"):
1001
+ continue
1002
+ tag = (
1003
+ "del"
1004
+ if grp.startswith("-")
1005
+ else ("add" if grp.startswith("+") else "ctx")
1006
+ )
1007
+ txt.insert("end", grp + "\n", tag)
1008
+ txt.config(state="disabled")
1009
+ btn_row = tk.Frame(win, bg=t.panel_bg)
1010
+ btn_row.pack(fill="x", padx=8, pady=(4, 10))
1011
+
1012
+ def _apply():
1013
+ win.destroy()
1014
+ self._replace_all()
1015
+
1016
+ tk.Button(
1017
+ btn_row,
1018
+ text=_t("hc.search_bar.aplicar"),
1019
+ bg=getattr(t, "diff_add_bg", "#0d2d0d"),
1020
+ fg=getattr(t, "diff_add_fg", "#80ff80"),
1021
+ relief="flat",
1022
+ padx=12,
1023
+ pady=4,
1024
+ font=(FONT_UI, 9, "bold"),
1025
+ cursor="hand2",
1026
+ command=_apply,
1027
+ ).pack(side="right", padx=4)
1028
+ tk.Button(
1029
+ btn_row,
1030
+ text=_t("hc.search_bar.cancelar"),
1031
+ bg=t.btn_bg,
1032
+ fg=t.fg,
1033
+ relief="flat",
1034
+ padx=12,
1035
+ pady=4,
1036
+ font=(FONT_UI, 9),
1037
+ cursor="hand2",
1038
+ command=win.destroy,
1039
+ ).pack(side="right", padx=2)
1040
+ win.update_idletasks()
1041
+ pw = self.winfo_rootx() + self.winfo_width() // 2
1042
+ ph = self.winfo_rooty() + self.winfo_height() // 2
1043
+ w, h = win.winfo_width(), win.winfo_height()
1044
+ win.geometry(f"+{pw - w // 2}+{ph - h // 2}")
1045
+
1046
+ def _trigger_find_files(self) -> None:
1047
+ """Dispara a busca global em arquivos com a query atual."""
1048
+ if self._on_find_files:
1049
+ self._on_find_files(self._find_var.get())
1050
+
1051
+ def _toggle_opt(self, attr: str) -> None:
1052
+ if attr in self._opt_btns:
1053
+ self._opt_btns[attr].event_generate("<Button-1>")
1054
+ else:
1055
+ setattr(self, attr, not getattr(self, attr, False))
1056
+ self._do_find()
1057
+ self._update_hint()
1058
+
1059
+ def _focus_replace(self, _e: Any = None) -> str:
1060
+ """Move o foco para o campo de substituição."""
1061
+ if self._replace_open and self._repl_entry:
1062
+ self._repl_entry.focus_set()
1063
+ return "break"
1064
+
1065
+ def _set_case_transform(self, val: str) -> None:
1066
+ self._case_transform = val
1067
+ self._update_ct_btns()
1068
+
1069
+ def _update_ct_btns(self) -> None:
1070
+ t = self._tmgr.theme
1071
+ for v, b in self._ct_btns.items():
1072
+ active = v == self._case_transform
1073
+ b.config(
1074
+ bg=t.accent if active else t.btn_bg,
1075
+ fg="#ffffff" if active else t.fg_muted,
1076
+ )
1077
+
1078
+ def _update_hint(self) -> None:
1079
+ if not self._hint_lbl:
1080
+ return
1081
+ parts = []
1082
+ if self._case_mode:
1083
+ parts.append("case")
1084
+ if self._word_mode:
1085
+ parts.append("palavra")
1086
+ if self._re_mode:
1087
+ parts.append("regex")
1088
+ if self._sel_mode:
1089
+ parts.append("seleção")
1090
+ if self._multi_mode:
1091
+ parts.append("multiline")
1092
+ self._hint_lbl.config(text=("- " + " - ".join(parts)) if parts else "")
1093
+
1094
+ def _insert_newline_in_find(self) -> str:
1095
+ """Insere uma quebra de linha literal no campo de busca (para busca multilinha)."""
1096
+ if self._find_entry:
1097
+ self._find_entry.insert(tk.INSERT, "\\n")
1098
+ return "break"
1099
+
1100
+ def _toggle_replace(self) -> None:
1101
+ """Alterna a visibilidade da linha de substituição na barra."""
1102
+ self._replace_open = not self._replace_open
1103
+ self._update_replace_row()
1104
+
1105
+ def _update_replace_row(self) -> None:
1106
+ t = self._tmgr.theme
1107
+ if self._replace_open:
1108
+ self._repl_row.pack(fill="x", padx=8, pady=(1, 1))
1109
+ self._repl_opts_row.pack(fill="x", padx=8, pady=(0, 4))
1110
+ if self._repl_toggle:
1111
+ self._repl_toggle.config(bg=t.accent, fg="#ffffff")
1112
+ if self._repl_entry:
1113
+ self._repl_entry.focus_set()
1114
+ else:
1115
+ self._repl_row.pack_forget()
1116
+ self._repl_opts_row.pack_forget()
1117
+ if self._repl_toggle:
1118
+ self._repl_toggle.config(bg=t.btn_bg, fg=t.fg_muted)
1119
+
1120
+ def _add_history_find(self, q: str) -> None:
1121
+ if not q:
1122
+ return
1123
+ if q in self._find_history:
1124
+ self._find_history.remove(q)
1125
+ self._find_history.append(q)
1126
+ if len(self._find_history) > self._HIST_MAX:
1127
+ self._find_history.pop(0)
1128
+ self._find_hist_pos = -1
1129
+
1130
+ def _add_history_repl(self, q: str) -> None:
1131
+ if not q:
1132
+ return
1133
+ if q in self._repl_history:
1134
+ self._repl_history.remove(q)
1135
+ self._repl_history.append(q)
1136
+ if len(self._repl_history) > self._HIST_MAX:
1137
+ self._repl_history.pop(0)
1138
+ self._repl_hist_pos = -1
1139
+
1140
+ def _hist_find_up(self, _e: Any = None) -> str:
1141
+ if not self._find_history:
1142
+ return "break"
1143
+ self._find_hist_pos = min(
1144
+ len(self._find_history) - 1, self._find_hist_pos + 1)
1145
+ self._find_var.set(self._find_history[-(self._find_hist_pos + 1)])
1146
+ self._find_entry.icursor("end")
1147
+ return "break"
1148
+
1149
+ def _hist_find_down(self, _e: Any = None) -> str:
1150
+ if self._find_hist_pos <= 0:
1151
+ self._find_hist_pos = -1
1152
+ return "break"
1153
+ self._find_hist_pos -= 1
1154
+ self._find_var.set(self._find_history[-(self._find_hist_pos + 1)])
1155
+ self._find_entry.icursor("end")
1156
+ return "break"
1157
+
1158
+ def _hist_repl_up(self, _e: Any = None) -> str:
1159
+ if not self._repl_history:
1160
+ return "break"
1161
+ self._repl_hist_pos = min(
1162
+ len(self._repl_history) - 1, self._repl_hist_pos + 1)
1163
+ self._repl_var.set(self._repl_history[-(self._repl_hist_pos + 1)])
1164
+ self._repl_entry.icursor("end")
1165
+ return "break"
1166
+
1167
+ def _hist_repl_down(self, _e: Any = None) -> str:
1168
+ if self._repl_hist_pos <= 0:
1169
+ self._repl_hist_pos = -1
1170
+ return "break"
1171
+ self._repl_hist_pos -= 1
1172
+ self._repl_var.set(self._repl_history[-(self._repl_hist_pos + 1)])
1173
+ self._repl_entry.icursor("end")
1174
+ return "break"
1175
+
1176
+ def _esc_find(self) -> None:
1177
+ """Fecha a barra de busca ao pressionar Escape."""
1178
+ if self._find_var.get():
1179
+ self._find_var.set("")
1180
+ else:
1181
+ self.hide()
1182
+
1183
+ def show(self, mode: str = "find", initial: str = "") -> None:
1184
+ """Exibe a barra de busca e foca no campo de texto."""
1185
+ self._visible = True
1186
+ if self._pack_before is not None:
1187
+ self.pack(side="top", fill="x", before=self._pack_before)
1188
+ else:
1189
+ self.pack(side="top", fill="x")
1190
+ if mode == "replace" and not self._replace_open:
1191
+ self._replace_open = True
1192
+ self._update_replace_row()
1193
+ if initial:
1194
+ self._find_var.set(initial)
1195
+ if self._find_entry:
1196
+ self._find_entry.select_range(0, "end")
1197
+ if self._find_entry:
1198
+ self._find_entry.focus_set()
1199
+ self._find_hist_pos = -1
1200
+ self._do_find()
1201
+
1202
+ def hide(self) -> None:
1203
+ """Oculta a barra de busca e restaura o foco ao editor."""
1204
+ self._visible = False
1205
+ self._add_history_find(self._find_var.get())
1206
+ self.pack_forget()
1207
+ editor = self._get_editor()
1208
+ if editor:
1209
+ editor.hl.clear_search()
1210
+ with contextlib.suppress(tk.TclError):
1211
+ editor.text.focus_set()
1212
+
1213
+ def toggle(self, mode: str = "find") -> None:
1214
+ """Alterna a visibilidade da barra de busca."""
1215
+ if self._visible and not (mode == "replace" and not self._replace_open):
1216
+ self.hide()
1217
+ else:
1218
+ self.show(mode)
1219
+
1220
+ def is_visible(self) -> bool:
1221
+ """Retorna ``True`` se a barra de busca está atualmente visível."""
1222
+ return self._visible
1223
+
1224
+ def notify_editor_change(self) -> None:
1225
+ """Notifica a barra de busca que o editor ativo mudou."""
1226
+ self._matches = []
1227
+ self._match_idx = 0
1228
+ self._engine = _SearchEngine()
1229
+ if self._count_lbl:
1230
+ self._count_lbl.config(text="")
1231
+ self._update_progress(0, 0)
1232
+ if self._visible:
1233
+ editor = self._get_editor()
1234
+ if editor:
1235
+ editor.hl.clear_search()
1236
+ self._do_find()
1237
+
1238
+ def apply_theme(self, t: Theme) -> None:
1239
+ """Aplica o tema visual à barra de busca."""
1240
+ from src.theme.utils import cfg, cfg_many
1241
+
1242
+ cfg(self, bg=t.floating_bg, highlightbackground=t.floating_border)
1243
+ ekw = {"bg": t.input_bg, "fg": t.fg, "insertbackground": t.cursor}
1244
+ cfg_many(
1245
+ [w for w in (self._find_entry, self._repl_entry) if w],
1246
+ **ekw,
1247
+ )
1248
+ cfg_many(
1249
+ [w for w in (self._count_lbl, self._hint_lbl) if w],
1250
+ bg=t.floating_bg,
1251
+ fg=t.fg_muted,
1252
+ )
1253
+ cfg_many(
1254
+ [w for w in (self._repl_row, self._repl_opts_row) if w],
1255
+ bg=t.floating_bg,
1256
+ )
1257
+ if self._repl_toggle:
1258
+ active = self._replace_open
1259
+ cfg(
1260
+ self._repl_toggle,
1261
+ bg=t.accent if active else t.btn_bg,
1262
+ fg="#ffffff" if active else t.fg_muted,
1263
+ )
1264
+ for attr, b in self._opt_btns.items():
1265
+ active = getattr(self, attr, False)
1266
+ cfg(
1267
+ b,
1268
+ bg=t.accent if active else t.btn_bg,
1269
+ fg="#ffffff" if active else t.fg_muted,
1270
+ )
1271
+ self._update_ct_btns()
1272
+ for frame in self.winfo_children():
1273
+ if isinstance(frame, tk.Frame):
1274
+ cfg(frame, bg=t.floating_bg)