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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""Motor de autocompletar do editor do Codis.
|
|
2
|
+
|
|
3
|
+
Provê ``AutocompletePopup`` para sugestões baseadas em LSP e palavras
|
|
4
|
+
do buffer, e ``IgnoreRules`` para filtrar itens indesejados com base
|
|
5
|
+
em regras de glob similares às do ``.gitignore``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import fnmatch
|
|
12
|
+
import logging
|
|
13
|
+
import re
|
|
14
|
+
import tkinter as tk
|
|
15
|
+
import tkinter.font as tkfont
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from src.constants import (
|
|
20
|
+
AUTOCOMPLETE_DELAY,
|
|
21
|
+
AUTOCOMPLETE_MAX_ITEMS,
|
|
22
|
+
AUTOCOMPLETE_MIN_CHARS,
|
|
23
|
+
FONT_MONO,
|
|
24
|
+
FONT_SIZE,
|
|
25
|
+
LANG_KEYWORDS,
|
|
26
|
+
)
|
|
27
|
+
from src.editor.snippets import SnippetEngine
|
|
28
|
+
from src.editor.suggest import SuggestionEngine, analyze
|
|
29
|
+
from src.theme.manager import ThemeManager
|
|
30
|
+
from src.ui.tkbind import bind_add, unbind_one
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger("Codis")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class IgnoreRules:
|
|
36
|
+
"""
|
|
37
|
+
Gerencia regras de exclusão (ignore) a partir de arquivos como .gitignore e .eslintignore.
|
|
38
|
+
|
|
39
|
+
Implementa o comportamento semelhante ao gitignore:
|
|
40
|
+
- Padrões com `*` e `?` (usando fnmatch).
|
|
41
|
+
- Negação com `!` no início.
|
|
42
|
+
- `**` para qualquer número de subdiretórios.
|
|
43
|
+
- Padrões sem `/` são testados contra cada componente do caminho \
|
|
44
|
+
(correspondência por nome base).
|
|
45
|
+
- Padrões com `/` são testados contra o caminho relativo completo.
|
|
46
|
+
|
|
47
|
+
Attributes:
|
|
48
|
+
root: Diretório raiz a partir do qual os caminhos relativos são calculados.
|
|
49
|
+
patterns: Lista de tuplas (pattern, is_negation, is_dir_only) \
|
|
50
|
+
representando as regras carregadas.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, root: Path) -> None:
|
|
54
|
+
self.root = root
|
|
55
|
+
self.patterns: list[tuple[str, bool, bool]] = []
|
|
56
|
+
|
|
57
|
+
def load(self) -> None:
|
|
58
|
+
"""Carrega padrões dos arquivos .gitignore e .eslintignore presentes na raiz."""
|
|
59
|
+
self.patterns.clear()
|
|
60
|
+
for ignore_file in (".gitignore", ".eslintignore"):
|
|
61
|
+
p = self.root / ignore_file
|
|
62
|
+
if p.exists():
|
|
63
|
+
try:
|
|
64
|
+
with open(p, encoding="utf-8") as f:
|
|
65
|
+
for line in f:
|
|
66
|
+
line = line.strip()
|
|
67
|
+
if not line or line.startswith("#"):
|
|
68
|
+
continue
|
|
69
|
+
self._add_pattern(line)
|
|
70
|
+
except (OSError, UnicodeDecodeError):
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
def _add_pattern(self, line: str) -> None:
|
|
74
|
+
"""Interpreta uma linha de regra e adiciona à lista de padrões."""
|
|
75
|
+
is_negation = line.startswith("!")
|
|
76
|
+
if is_negation:
|
|
77
|
+
line = line[1:].lstrip()
|
|
78
|
+
is_dir_only = line.endswith("/")
|
|
79
|
+
if is_dir_only:
|
|
80
|
+
line = line[:-1]
|
|
81
|
+
self.patterns.append((line, is_negation, is_dir_only))
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _matches(pattern: str, rel_path: str) -> bool:
|
|
85
|
+
"""
|
|
86
|
+
Verifica se um caminho relativo corresponde a um padrão específico.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
pattern: Padrão da regra (já tratado, sem `!` ou `/` final).
|
|
90
|
+
rel_path: Caminho relativo no formato POSIX (separador '/').
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
True se houver correspondência, False caso contrário.
|
|
94
|
+
"""
|
|
95
|
+
parts = rel_path.split("/")
|
|
96
|
+
|
|
97
|
+
if "**" in pattern:
|
|
98
|
+
regex = re.escape(pattern).replace(r"\*\*", ".*")
|
|
99
|
+
regex = regex.replace(r"\*", "[^/]*").replace(r"\?", "[^/]")
|
|
100
|
+
return bool(re.match(f"^{regex}$", rel_path))
|
|
101
|
+
|
|
102
|
+
if "/" in pattern:
|
|
103
|
+
pat = pattern.lstrip("/")
|
|
104
|
+
return fnmatch.fnmatch(rel_path, pat) or rel_path.startswith(pat + "/")
|
|
105
|
+
|
|
106
|
+
return any(fnmatch.fnmatch(part, pattern) for part in parts)
|
|
107
|
+
|
|
108
|
+
def is_ignored(self, path: Path) -> bool:
|
|
109
|
+
"""
|
|
110
|
+
Determina se um caminho deve ser ignorado com base nas regras carregadas.
|
|
111
|
+
|
|
112
|
+
A avaliação segue a ordem das regras: a última regra que corresponder
|
|
113
|
+
(considerando negação) prevalece.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
path: Caminho absoluto a ser verificado.
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
True se o caminho for ignorado, False caso contrário.
|
|
120
|
+
"""
|
|
121
|
+
try:
|
|
122
|
+
rel = str(path.relative_to(self.root).as_posix())
|
|
123
|
+
except ValueError:
|
|
124
|
+
return False
|
|
125
|
+
|
|
126
|
+
ignored = False
|
|
127
|
+
for pattern, is_negation, _ in self.patterns:
|
|
128
|
+
if self._matches(pattern, rel):
|
|
129
|
+
if is_negation:
|
|
130
|
+
ignored = False
|
|
131
|
+
else:
|
|
132
|
+
ignored = True
|
|
133
|
+
return ignored
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class AutocompletePopup:
|
|
137
|
+
"""
|
|
138
|
+
Popup flutuante de autocomplete com estilo semelhante ao VS Code.
|
|
139
|
+
|
|
140
|
+
Exibe sugestões contextuais:
|
|
141
|
+
- Palavras-chave da linguagem.
|
|
142
|
+
- Snippets registrados.
|
|
143
|
+
- Símbolos do documento (funções, classes, variáveis).
|
|
144
|
+
- Palavras do próprio buffer.
|
|
145
|
+
- (Opcional) Sugestões do LSP, quando conectado.
|
|
146
|
+
|
|
147
|
+
Atalhos de teclado:
|
|
148
|
+
- ↑ / ↓ : navegar na lista.
|
|
149
|
+
- Tab / Enter : aceitar a sugestão atual.
|
|
150
|
+
- Esc : fechar o popup.
|
|
151
|
+
- Qualquer tecla de caractere : refiltrar as sugestões (após um pequeno atraso).
|
|
152
|
+
|
|
153
|
+
Ícones são usados para identificar visualmente o tipo de cada item.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
ICONS = {
|
|
157
|
+
"keyword": "🔑",
|
|
158
|
+
"snippet": "✂️ ",
|
|
159
|
+
"function": "ƒ ",
|
|
160
|
+
"class": "◆ ",
|
|
161
|
+
"variable": "𝑥 ",
|
|
162
|
+
"property": " ",
|
|
163
|
+
"module": "📦",
|
|
164
|
+
"constant": "π ",
|
|
165
|
+
"param": "->",
|
|
166
|
+
"method": "⚙ ",
|
|
167
|
+
"field": "▪ ",
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
def __init__(
|
|
171
|
+
self, parent: tk.Widget, text_widget: tk.Text, tmgr: ThemeManager
|
|
172
|
+
) -> None:
|
|
173
|
+
"""
|
|
174
|
+
Inicializa o popup associado a um widget de texto.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
parent: Widget pai (normalmente a janela principal).
|
|
178
|
+
text_widget: Widget Text onde o autocomplete será inserido.
|
|
179
|
+
tmgr: Gerenciador de temas para cores e estilos.
|
|
180
|
+
"""
|
|
181
|
+
self._parent = parent
|
|
182
|
+
self._txt = text_widget
|
|
183
|
+
self._tmgr = tmgr
|
|
184
|
+
self._popup: tk.Toplevel | None = None
|
|
185
|
+
self._listbox: tk.Listbox | None = None
|
|
186
|
+
self._items: list[tuple[str, str, str]] = []
|
|
187
|
+
self._job: str | None = None
|
|
188
|
+
self._lang = "text"
|
|
189
|
+
self._snippets: SnippetEngine | None = None
|
|
190
|
+
self._doc_symbols: list[str] = []
|
|
191
|
+
self._hover_win: tk.Toplevel | None = None
|
|
192
|
+
self._lsp_mgr = None
|
|
193
|
+
self._lsp_path = None
|
|
194
|
+
self._engine = SuggestionEngine(AUTOCOMPLETE_MAX_ITEMS)
|
|
195
|
+
self._details: list[str] = []
|
|
196
|
+
self._query_pos: str | None = None
|
|
197
|
+
|
|
198
|
+
self._root_win = self._get_root_window()
|
|
199
|
+
self._unmap_bind: str | None = None
|
|
200
|
+
if self._root_win is not None:
|
|
201
|
+
self._unmap_bind = bind_add(
|
|
202
|
+
self._root_win, "<Unmap>", lambda _: self._on_root_unmap())
|
|
203
|
+
|
|
204
|
+
def _get_root_window(self) -> tk.Tk | None:
|
|
205
|
+
"""Retorna a janela raiz Tk a partir do widget pai."""
|
|
206
|
+
try:
|
|
207
|
+
w = self._parent
|
|
208
|
+
while w is not None:
|
|
209
|
+
if isinstance(w, tk.Tk):
|
|
210
|
+
return w
|
|
211
|
+
w = w.master
|
|
212
|
+
except Exception:
|
|
213
|
+
logger.debug("Falha ao localizar janela raiz Tk.", exc_info=True)
|
|
214
|
+
return None
|
|
215
|
+
|
|
216
|
+
def _on_root_unmap(self) -> None:
|
|
217
|
+
"""Esconde todos os popups flutuantes quando a janela principal é minimizada."""
|
|
218
|
+
|
|
219
|
+
if self._popup and self._popup.winfo_exists():
|
|
220
|
+
with contextlib.suppress(Exception):
|
|
221
|
+
self._popup.withdraw()
|
|
222
|
+
if self._hover_win and self._hover_win.winfo_exists():
|
|
223
|
+
with contextlib.suppress(Exception):
|
|
224
|
+
self._hover_win.withdraw()
|
|
225
|
+
|
|
226
|
+
def destroy(self) -> None:
|
|
227
|
+
"""Remove o binding da janela raiz e destrói as janelas flutuantes.
|
|
228
|
+
|
|
229
|
+
Sem isso, cada aba aberta deixava um handler na raiz (e o painel inteiro
|
|
230
|
+
preso a ele) e o Toplevel da lista, que pertence à janela principal.
|
|
231
|
+
"""
|
|
232
|
+
if self._root_win is not None:
|
|
233
|
+
unbind_one(self._root_win, "<Unmap>", self._unmap_bind)
|
|
234
|
+
self._unmap_bind = None
|
|
235
|
+
self._hide_hover()
|
|
236
|
+
popup, self._popup = self._popup, None
|
|
237
|
+
self._listbox = None
|
|
238
|
+
if popup is not None:
|
|
239
|
+
with contextlib.suppress(tk.TclError):
|
|
240
|
+
popup.destroy()
|
|
241
|
+
self._root_win = None
|
|
242
|
+
|
|
243
|
+
def set_lang(self, lang: str) -> None:
|
|
244
|
+
"""Define a linguagem atual para filtrar palavras-chave e snippets."""
|
|
245
|
+
self._lang = lang
|
|
246
|
+
|
|
247
|
+
def set_snippets(self, engine: SnippetEngine) -> None:
|
|
248
|
+
"""Fornece o motor de snippets para inclusão de sugestões de snippets."""
|
|
249
|
+
self._snippets = engine
|
|
250
|
+
|
|
251
|
+
def set_lsp_manager(self, lsp_mgr, path) -> None:
|
|
252
|
+
"""
|
|
253
|
+
Conecta um gerenciador LSP para obter sugestões adicionais.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
path: Caminho do arquivo atual (para consulta LSP).
|
|
257
|
+
"""
|
|
258
|
+
self._lsp_mgr = lsp_mgr
|
|
259
|
+
self._lsp_path = path
|
|
260
|
+
|
|
261
|
+
def trigger(self, delay: int = AUTOCOMPLETE_DELAY) -> None:
|
|
262
|
+
"""
|
|
263
|
+
Agenda a exibição do popup após um atraso (debounce).
|
|
264
|
+
|
|
265
|
+
Se já houver um job agendado, ele é cancelado antes.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
delay: Milissegundos de espera antes de computar as sugestões.
|
|
269
|
+
"""
|
|
270
|
+
if self._job:
|
|
271
|
+
with contextlib.suppress(tk.TclError):
|
|
272
|
+
self._txt.after_cancel(self._job)
|
|
273
|
+
self._job = self._txt.after(delay, self._compute)
|
|
274
|
+
|
|
275
|
+
_BIG_FILE_LINES = 4000
|
|
276
|
+
_INDEX_WINDOW = 1500 # linhas para cada lado do cursor no índice de palavras de arquivos grandes
|
|
277
|
+
|
|
278
|
+
def _icons(self) -> dict[str, str]:
|
|
279
|
+
return dict(self.ICONS)
|
|
280
|
+
|
|
281
|
+
def _rank(self, ctx: Any, line_no: int, lsp_items: Any = ()) -> list[tuple[str, str, str]]:
|
|
282
|
+
"""Pede ao motor as sugestões ordenadas e converte para ``(label, insert, kind)``."""
|
|
283
|
+
snippets: list[tuple[str, str]] = []
|
|
284
|
+
if self._snippets:
|
|
285
|
+
snippets = [(sn.prefix, sn.description or "") for sn in self._snippets.get_for_lang(self._lang)]
|
|
286
|
+
cands = self._engine.suggest(
|
|
287
|
+
ctx, self._lang, cursor_line=line_no, keywords=LANG_KEYWORDS.get(self._lang, []),
|
|
288
|
+
snippets=snippets, lsp_items=lsp_items, icons=self._icons(),
|
|
289
|
+
)
|
|
290
|
+
self._details = [c.detail for c in cands]
|
|
291
|
+
return [(c.label, c.insert, c.kind) for c in cands]
|
|
292
|
+
|
|
293
|
+
def _compute(self) -> None:
|
|
294
|
+
"""Calcula e exibe as sugestões para a posição do cursor.
|
|
295
|
+
|
|
296
|
+
O contexto léxico (comentário/string/``def |``) pode suprimir o popup; após
|
|
297
|
+
``.`` sugere membros; o ranking combina casamento, fonte, frequência,
|
|
298
|
+
proximidade e o que o usuário costuma aceitar. O LSP, quando responde,
|
|
299
|
+
entra no mesmo ranking (não apenas no fim da lista).
|
|
300
|
+
"""
|
|
301
|
+
try:
|
|
302
|
+
pos = self._txt.index(tk.INSERT)
|
|
303
|
+
line_no, col_no = (int(x) for x in pos.split("."))
|
|
304
|
+
start = "1.0" if line_no <= self._BIG_FILE_LINES else f"{line_no - self._BIG_FILE_LINES}.0"
|
|
305
|
+
before = self._txt.get(start, pos)
|
|
306
|
+
# Em arquivos grandes o índice de palavras usa só o trecho em volta do cursor: ler o
|
|
307
|
+
# documento inteiro a cada sugestão custa mais do que a própria sugestão.
|
|
308
|
+
total = int(self._txt.index("end-1c").split(".")[0])
|
|
309
|
+
first = 1
|
|
310
|
+
if total > 2 * self._INDEX_WINDOW:
|
|
311
|
+
first = max(1, line_no - self._INDEX_WINDOW)
|
|
312
|
+
full = self._txt.get(f"{first}.0", f"{line_no + self._INDEX_WINDOW}.end")
|
|
313
|
+
else:
|
|
314
|
+
full = self._txt.get("1.0", "end-1c")
|
|
315
|
+
except (tk.TclError, ValueError):
|
|
316
|
+
return
|
|
317
|
+
|
|
318
|
+
ctx = analyze(before, self._lang)
|
|
319
|
+
if ctx.suppress or (not ctx.member and len(ctx.prefix) < AUTOCOMPLETE_MIN_CHARS):
|
|
320
|
+
self.hide()
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
self._engine.update_document(full, self._lang, line_no - first + 1)
|
|
324
|
+
self._query_pos = pos
|
|
325
|
+
items = self._rank(ctx, line_no - first + 1)
|
|
326
|
+
lsp_ready = bool(self._lsp_mgr and self._lsp_path)
|
|
327
|
+
if not items and not lsp_ready:
|
|
328
|
+
self.hide()
|
|
329
|
+
return
|
|
330
|
+
if items:
|
|
331
|
+
self._items = items
|
|
332
|
+
self._show(pos)
|
|
333
|
+
elif self.is_visible():
|
|
334
|
+
self.hide()
|
|
335
|
+
|
|
336
|
+
if lsp_ready:
|
|
337
|
+
with contextlib.suppress(OSError, AttributeError, RuntimeError):
|
|
338
|
+
|
|
339
|
+
def _lsp_cb(lsp_items: Any) -> None:
|
|
340
|
+
"""Reordena com os itens do LSP no mesmo ranking."""
|
|
341
|
+
if not lsp_items or not self._txt.winfo_exists():
|
|
342
|
+
return
|
|
343
|
+
try:
|
|
344
|
+
if self._txt.index(tk.INSERT) != self._query_pos:
|
|
345
|
+
return
|
|
346
|
+
except tk.TclError:
|
|
347
|
+
return
|
|
348
|
+
conv = []
|
|
349
|
+
for ci in lsp_items:
|
|
350
|
+
ins = (ci.insert_text or ci.label).strip()
|
|
351
|
+
plain = re.sub(r"\$\{?\d+(?::[^}]*)?\}?", "", ins).strip() or ci.label
|
|
352
|
+
conv.append((ci.label, plain, str(ci.kind_name).lower(), ci.icon))
|
|
353
|
+
merged = self._rank(ctx, line_no, conv)
|
|
354
|
+
if merged:
|
|
355
|
+
self._items = merged
|
|
356
|
+
self._show(self._query_pos)
|
|
357
|
+
|
|
358
|
+
self._lsp_mgr.completion(self._lsp_path, self._lang, line_no - 1, col_no, None, _lsp_cb)
|
|
359
|
+
|
|
360
|
+
def _show(self, cursor_pos: str) -> None:
|
|
361
|
+
"""
|
|
362
|
+
Exibe o popup na posição do cursor, ajustando para não sair da tela.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
cursor_pos: Índice Tkinter no formato "linha.coluna" (ex: "10.5").
|
|
366
|
+
"""
|
|
367
|
+
t = self._tmgr.theme
|
|
368
|
+
try:
|
|
369
|
+
bbox = self._txt.bbox(cursor_pos)
|
|
370
|
+
if bbox:
|
|
371
|
+
x, y, _, h = bbox
|
|
372
|
+
else:
|
|
373
|
+
line, col = map(int, cursor_pos.split("."))
|
|
374
|
+
dline = self._txt.dlineinfo(f"{line}.0")
|
|
375
|
+
if not dline:
|
|
376
|
+
return
|
|
377
|
+
x_line, y, _, h, _ = dline
|
|
378
|
+
|
|
379
|
+
font = tkfont.Font(font=self._txt.cget("font"))
|
|
380
|
+
char_width = font.measure("0")
|
|
381
|
+
x = x_line + col * char_width
|
|
382
|
+
except tk.TclError:
|
|
383
|
+
return
|
|
384
|
+
|
|
385
|
+
wx = self._txt.winfo_rootx() + x
|
|
386
|
+
wy = self._txt.winfo_rooty() + y + h + 2
|
|
387
|
+
|
|
388
|
+
if not self._popup or not self._popup.winfo_exists():
|
|
389
|
+
self._popup = tk.Toplevel(self._parent)
|
|
390
|
+
self._popup.wm_overrideredirect(True)
|
|
391
|
+
self._popup.wm_attributes("-topmost", True)
|
|
392
|
+
self._popup.withdraw()
|
|
393
|
+
|
|
394
|
+
outer = tk.Frame(self._popup, bg=t.floating_border, padx=1, pady=1)
|
|
395
|
+
outer.pack(fill="both", expand=True)
|
|
396
|
+
inner = tk.Frame(outer, bg=t.floating_bg)
|
|
397
|
+
inner.pack(fill="both", expand=True)
|
|
398
|
+
|
|
399
|
+
self._listbox = tk.Listbox(
|
|
400
|
+
inner,
|
|
401
|
+
bg=t.floating_bg,
|
|
402
|
+
fg=t.fg,
|
|
403
|
+
selectbackground=t.sel_bg,
|
|
404
|
+
selectforeground=t.sel_fg,
|
|
405
|
+
relief="flat",
|
|
406
|
+
bd=0,
|
|
407
|
+
font=(FONT_MONO, self._get_font_size()),
|
|
408
|
+
activestyle="none",
|
|
409
|
+
highlightthickness=0,
|
|
410
|
+
exportselection=False,
|
|
411
|
+
)
|
|
412
|
+
self._listbox.pack(fill="both", expand=True, padx=2, pady=2)
|
|
413
|
+
self._listbox.bind("<Double-Button-1>", lambda _: self._accept())
|
|
414
|
+
self._listbox.bind("<Motion>", self._on_hover)
|
|
415
|
+
else:
|
|
416
|
+
assert self._listbox is not None
|
|
417
|
+
self._listbox.delete(0, "end")
|
|
418
|
+
|
|
419
|
+
assert self._listbox is not None
|
|
420
|
+
|
|
421
|
+
self._listbox.config(
|
|
422
|
+
bg=t.floating_bg,
|
|
423
|
+
fg=t.fg,
|
|
424
|
+
selectbackground=t.sel_bg,
|
|
425
|
+
selectforeground=t.sel_fg,
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
for i, (label, _, _kind) in enumerate(self._items):
|
|
429
|
+
det = self._details[i] if i < len(self._details) and self._details[i] else ""
|
|
430
|
+
self._listbox.insert("end", f" {label}" + (f" · {det}" if det else ""))
|
|
431
|
+
|
|
432
|
+
for i, (_, _, kind) in enumerate(self._items):
|
|
433
|
+
color = {
|
|
434
|
+
"keyword": t.t_keyword,
|
|
435
|
+
"snippet": t.t_func,
|
|
436
|
+
"symbol": t.t_class,
|
|
437
|
+
"variable": t.t_variable,
|
|
438
|
+
"function": t.t_func,
|
|
439
|
+
"method": t.t_func,
|
|
440
|
+
"class": t.t_class,
|
|
441
|
+
"module": t.t_class,
|
|
442
|
+
"constant": t.t_variable,
|
|
443
|
+
"property": t.t_variable,
|
|
444
|
+
}.get(kind, t.fg)
|
|
445
|
+
self._listbox.itemconfig(i, foreground=color)
|
|
446
|
+
|
|
447
|
+
count = min(len(self._items), 12)
|
|
448
|
+
lh = self._get_font_size() + 6
|
|
449
|
+
height = count * lh + 8
|
|
450
|
+
width = 380
|
|
451
|
+
|
|
452
|
+
screen_w = self._popup.winfo_screenwidth()
|
|
453
|
+
screen_h = self._popup.winfo_screenheight()
|
|
454
|
+
if wx + width > screen_w:
|
|
455
|
+
wx = screen_w - width - 4
|
|
456
|
+
if wy + height > screen_h:
|
|
457
|
+
wy = wy - h - height - 4
|
|
458
|
+
|
|
459
|
+
self._popup.geometry(f"{width}x{height}+{wx}+{wy}")
|
|
460
|
+
self._popup.deiconify()
|
|
461
|
+
self._popup.lift()
|
|
462
|
+
self._popup.update_idletasks()
|
|
463
|
+
self._listbox.selection_set(0)
|
|
464
|
+
self._listbox.see(0)
|
|
465
|
+
|
|
466
|
+
def _get_font_size(self) -> int:
|
|
467
|
+
"""Obtém o tamanho da fonte do widget de texto ou usa o padrão."""
|
|
468
|
+
with contextlib.suppress(tk.TclError):
|
|
469
|
+
spec = str(self._txt.cget("font"))
|
|
470
|
+
for p in reversed(spec.split()):
|
|
471
|
+
if p.isdigit():
|
|
472
|
+
return int(p)
|
|
473
|
+
return FONT_SIZE
|
|
474
|
+
|
|
475
|
+
@staticmethod
|
|
476
|
+
def _on_hover(e: Any) -> None:
|
|
477
|
+
"""Callback para exibição futura de documentação ao pairar sobre um item."""
|
|
478
|
+
|
|
479
|
+
def is_visible(self) -> bool:
|
|
480
|
+
"""Retorna ``True`` se o popup de autocompletar está visível."""
|
|
481
|
+
return bool(
|
|
482
|
+
self._popup and self._popup.winfo_exists() and self._popup.winfo_viewable()
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
def hide(self) -> None:
|
|
486
|
+
"""Esconde o popup e qualquer janela de hover associada."""
|
|
487
|
+
self._hide_hover()
|
|
488
|
+
if self._popup and self._popup.winfo_exists():
|
|
489
|
+
with contextlib.suppress(tk.TclError):
|
|
490
|
+
self._popup.withdraw()
|
|
491
|
+
|
|
492
|
+
def _hide_hover(self) -> None:
|
|
493
|
+
"""Destrói a janela de hover, se existir."""
|
|
494
|
+
if self._hover_win and self._hover_win.winfo_exists():
|
|
495
|
+
with contextlib.suppress(tk.TclError):
|
|
496
|
+
self._hover_win.destroy()
|
|
497
|
+
self._hover_win = None
|
|
498
|
+
|
|
499
|
+
def navigate(self, direction: int) -> bool:
|
|
500
|
+
"""
|
|
501
|
+
Navega para cima (direction = -1) ou para baixo (direction = 1) na lista.
|
|
502
|
+
|
|
503
|
+
Args:
|
|
504
|
+
direction: -1 para subir, 1 para descer.
|
|
505
|
+
|
|
506
|
+
Returns:
|
|
507
|
+
True se a navegação foi realizada (popup visível), False caso contrário.
|
|
508
|
+
"""
|
|
509
|
+
if not self.is_visible() or self._listbox is None:
|
|
510
|
+
return False
|
|
511
|
+
cur = self._listbox.curselection()
|
|
512
|
+
idx = cur[0] if cur else -1
|
|
513
|
+
new = max(0, min(len(self._items) - 1, idx + direction))
|
|
514
|
+
self._listbox.selection_clear(0, "end")
|
|
515
|
+
self._listbox.selection_set(new)
|
|
516
|
+
self._listbox.see(new)
|
|
517
|
+
return True
|
|
518
|
+
|
|
519
|
+
def accept(self) -> bool:
|
|
520
|
+
"""
|
|
521
|
+
Aceita a sugestão atualmente selecionada, inserindo o texto no editor.
|
|
522
|
+
|
|
523
|
+
Returns:
|
|
524
|
+
True se alguma sugestão foi aceita, False caso contrário.
|
|
525
|
+
"""
|
|
526
|
+
if not self.is_visible() or self._listbox is None:
|
|
527
|
+
return False
|
|
528
|
+
cur = self._listbox.curselection()
|
|
529
|
+
if not cur:
|
|
530
|
+
return False
|
|
531
|
+
idx = cur[0]
|
|
532
|
+
_, insert_text, kind = self._items[idx]
|
|
533
|
+
self._do_insert(insert_text, kind)
|
|
534
|
+
self.hide()
|
|
535
|
+
return True
|
|
536
|
+
|
|
537
|
+
def _accept(self) -> None:
|
|
538
|
+
"""Versão sem argumentos para binding de eventos."""
|
|
539
|
+
self.accept()
|
|
540
|
+
|
|
541
|
+
def _do_insert(self, word: str, kind: str) -> None:
|
|
542
|
+
"""
|
|
543
|
+
Insere a palavra selecionada no editor, substituindo o prefixo atual.
|
|
544
|
+
|
|
545
|
+
Se for um snippet e houver um motor de snippets, expande-o.
|
|
546
|
+
|
|
547
|
+
Args:
|
|
548
|
+
word: Texto a ser inserido (ou prefixo do snippet).
|
|
549
|
+
kind: Tipo do item ('snippet', 'keyword', etc.).
|
|
550
|
+
"""
|
|
551
|
+
with contextlib.suppress(tk.TclError):
|
|
552
|
+
pos = self._txt.index(tk.INSERT)
|
|
553
|
+
line_start = f"{pos} linestart"
|
|
554
|
+
text_before = self._txt.get(line_start, pos)
|
|
555
|
+
m = re.search(r"[\w$]+$", text_before)
|
|
556
|
+
if m:
|
|
557
|
+
start_col = len(text_before) - len(m.group())
|
|
558
|
+
line_num = pos.split(".")[0]
|
|
559
|
+
start_idx = f"{line_num}.{start_col}"
|
|
560
|
+
self._txt.delete(start_idx, pos)
|
|
561
|
+
|
|
562
|
+
SuggestionEngine.record_accept(word)
|
|
563
|
+
if kind == "snippet" and self._snippets:
|
|
564
|
+
snip = self._snippets.find_prefix(self._lang, word)
|
|
565
|
+
if snip:
|
|
566
|
+
self._snippets.expand(snip, self._txt)
|
|
567
|
+
return
|
|
568
|
+
|
|
569
|
+
self._txt.insert(tk.INSERT, word)
|
|
570
|
+
|
|
571
|
+
def update_doc_symbols(self, content: str, lang: str) -> None:
|
|
572
|
+
"""
|
|
573
|
+
Extrai símbolos (funções, classes, variáveis) do conteúdo do documento.
|
|
574
|
+
|
|
575
|
+
Esses símbolos são adicionados às sugestões de autocomplete.
|
|
576
|
+
|
|
577
|
+
Args:
|
|
578
|
+
content: Texto completo do documento.
|
|
579
|
+
lang: Linguagem do documento (para aplicar padrões específicos).
|
|
580
|
+
"""
|
|
581
|
+
syms: list[str] = []
|
|
582
|
+
patterns = {
|
|
583
|
+
"python": [
|
|
584
|
+
r"^\s*def\s+(\w+)",
|
|
585
|
+
r"^\s*class\s+(\w+)",
|
|
586
|
+
r"^\s*(\w+)\s*=",
|
|
587
|
+
],
|
|
588
|
+
"javascript": [
|
|
589
|
+
r"function\s+(\w+)",
|
|
590
|
+
r"class\s+(\w+)",
|
|
591
|
+
r"(?:const|let|var)\s+(\w+)",
|
|
592
|
+
r"(\w+)\s*[:=]\s*(?:function|\(.*\)\s*=>)",
|
|
593
|
+
],
|
|
594
|
+
"typescript": [
|
|
595
|
+
r"function\s+(\w+)",
|
|
596
|
+
r"class\s+(\w+)",
|
|
597
|
+
r"interface\s+(\w+)",
|
|
598
|
+
r"type\s+(\w+)",
|
|
599
|
+
r"(?:const|let|var)\s+(\w+)",
|
|
600
|
+
],
|
|
601
|
+
}
|
|
602
|
+
for pattern in patterns.get(lang, []):
|
|
603
|
+
for m in re.finditer(pattern, content, re.MULTILINE):
|
|
604
|
+
name = m.group(1)
|
|
605
|
+
if len(name) > 1 and name not in syms:
|
|
606
|
+
syms.append(name)
|
|
607
|
+
self._doc_symbols = syms[:200]
|