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,836 @@
|
|
|
1
|
+
"""Codis - CodeFolding.
|
|
2
|
+
|
|
3
|
+
DETECÇÃO
|
|
4
|
+
--------
|
|
5
|
+
- Python/indent: bloco composto (try+except+finally, if+elif+else) é uma
|
|
6
|
+
ÚNICA região. A seta fica na primeira linha (try, if) e recolhe tudo.
|
|
7
|
+
- A detecção processa linha a linha com um stack tipado. A ordem é:
|
|
8
|
+
1. Verifica se a linha FECHA algum bloco aberto no stack.
|
|
9
|
+
2. Verifica se a linha ABRE um novo bloco.
|
|
10
|
+
Assim a seta fica sempre na linha de abertura do bloco.
|
|
11
|
+
|
|
12
|
+
FOLD/UNFOLD
|
|
13
|
+
-----------
|
|
14
|
+
- Salva de start_line.end -> end_line.end (inclui o \\n inicial), garantindo
|
|
15
|
+
restauração exata sem acumular conteúdo na linha de abertura.
|
|
16
|
+
|
|
17
|
+
SUPORTE A LINGUAGENS
|
|
18
|
+
--------------------
|
|
19
|
+
indent : Python, YAML, CoffeeScript, Haskell, Elixir, Elm
|
|
20
|
+
brace : JS, TS, Java, C, C++, C#, Rust, Go, PHP, Kotlin, Swift,
|
|
21
|
+
Scala, Groovy, CSS, SCSS, JSON
|
|
22
|
+
doend : Ruby, Lua, Elixir (do/end), Crystal
|
|
23
|
+
markup : HTML, XML, Markdown
|
|
24
|
+
sql : SQL, PL/pgSQL
|
|
25
|
+
fallback: tenta brace depois indent
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import contextlib
|
|
31
|
+
import logging
|
|
32
|
+
import re
|
|
33
|
+
import tkinter as tk
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from typing import TYPE_CHECKING
|
|
36
|
+
|
|
37
|
+
from src.constants import FONT_MONO, FONT_SIZE
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from src.theme.base import Theme
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger("Codis")
|
|
43
|
+
|
|
44
|
+
_FOLD_PLACEHOLDER = " ... "
|
|
45
|
+
_TAG_FOLD = "codis_fold_placeholder"
|
|
46
|
+
|
|
47
|
+
INDENT_LANGS = frozenset(
|
|
48
|
+
{
|
|
49
|
+
"python",
|
|
50
|
+
"yaml",
|
|
51
|
+
"coffee",
|
|
52
|
+
"coffeescript",
|
|
53
|
+
"haskell",
|
|
54
|
+
"elm",
|
|
55
|
+
"pug",
|
|
56
|
+
"haml",
|
|
57
|
+
"stylus",
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
BRACE_LANGS = frozenset(
|
|
61
|
+
{
|
|
62
|
+
"javascript",
|
|
63
|
+
"typescript",
|
|
64
|
+
"java",
|
|
65
|
+
"c",
|
|
66
|
+
"cpp",
|
|
67
|
+
"csharp",
|
|
68
|
+
"rust",
|
|
69
|
+
"go",
|
|
70
|
+
"kotlin",
|
|
71
|
+
"swift",
|
|
72
|
+
"scala",
|
|
73
|
+
"groovy",
|
|
74
|
+
"php",
|
|
75
|
+
"dart",
|
|
76
|
+
"fsharp",
|
|
77
|
+
"css",
|
|
78
|
+
"scss",
|
|
79
|
+
"less",
|
|
80
|
+
"json",
|
|
81
|
+
"jsonc",
|
|
82
|
+
"objectivec",
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
DOEND_LANGS = frozenset(
|
|
86
|
+
{
|
|
87
|
+
"ruby",
|
|
88
|
+
"lua",
|
|
89
|
+
"elixir",
|
|
90
|
+
"erlang",
|
|
91
|
+
"crystal",
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
MARKUP_LANGS = frozenset(
|
|
95
|
+
{
|
|
96
|
+
"html",
|
|
97
|
+
"xml",
|
|
98
|
+
"svg",
|
|
99
|
+
"markdown",
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
SQL_LANGS = frozenset(
|
|
103
|
+
{
|
|
104
|
+
"sql",
|
|
105
|
+
"plpgsql",
|
|
106
|
+
"tsql",
|
|
107
|
+
"mysql",
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
_PY_OPEN = re.compile(
|
|
112
|
+
r"^(\s*)(async\s+def|def|class|if|for|while|with|try|match)\b[^#]*:\s*(?:#.*)?$"
|
|
113
|
+
)
|
|
114
|
+
_PY_CONT = re.compile(r"^(\s*)(elif|else|except|finally)\b")
|
|
115
|
+
|
|
116
|
+
_PY_DOCSTR = re.compile(r'"""')
|
|
117
|
+
|
|
118
|
+
_REGION_OPEN = re.compile(r"^\s*(?://|#)\s*region\b", re.IGNORECASE)
|
|
119
|
+
_REGION_CLOSE = re.compile(r"^\s*(?://|#)\s*endregion\b", re.IGNORECASE)
|
|
120
|
+
|
|
121
|
+
_BRACE_OPEN = re.compile(r"\{\s*(?://[^\n]*)?\s*$")
|
|
122
|
+
_BRACE_CLOSE = re.compile(r"^\s*\}")
|
|
123
|
+
|
|
124
|
+
_BLOCK_CMT_OPEN = re.compile(r"/\*")
|
|
125
|
+
_BLOCK_CMT_CLOSE = re.compile(r"\*/")
|
|
126
|
+
|
|
127
|
+
_DOEND_OPEN = re.compile(
|
|
128
|
+
r"^\s*(def|class|module|if|unless|while|until|for|case|begin|do|function|then)\b",
|
|
129
|
+
re.IGNORECASE,
|
|
130
|
+
)
|
|
131
|
+
_DOEND_CLOSE = re.compile(r"^\s*end\b", re.IGNORECASE)
|
|
132
|
+
|
|
133
|
+
_HTML_BLOCK = (
|
|
134
|
+
"div|section|article|header|footer|nav|main|aside|form|ul|ol|"
|
|
135
|
+
"table|template|component|script|style|html|body|head|svg|figure|"
|
|
136
|
+
"details|summary|dialog|menu|fieldset|select"
|
|
137
|
+
)
|
|
138
|
+
_HTML_OPEN = re.compile(rf"<({_HTML_BLOCK})(\s[^>]*)?>", re.IGNORECASE)
|
|
139
|
+
_HTML_CLOSE = re.compile(rf"</({_HTML_BLOCK})>", re.IGNORECASE)
|
|
140
|
+
_HTML_SELF = re.compile(r"/>\s*$")
|
|
141
|
+
|
|
142
|
+
_MD_HEADING = re.compile(r"^(#{1,6})\s")
|
|
143
|
+
|
|
144
|
+
_SQL_OPEN = re.compile(r"\bBEGIN\b", re.IGNORECASE)
|
|
145
|
+
_SQL_CLOSE = re.compile(r"\bEND\b", re.IGNORECASE)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class FoldRegion:
|
|
150
|
+
start_line: int
|
|
151
|
+
end_line: int
|
|
152
|
+
folded: bool = False
|
|
153
|
+
hidden_text: str = ""
|
|
154
|
+
kind: str = "block"
|
|
155
|
+
folded_children: list = field(default_factory=list, repr=False)
|
|
156
|
+
_tag: str = field(default="", repr=False)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def tag(self) -> str:
|
|
160
|
+
"""Nome único da tag Tkinter para esta região, derivado do intervalo de linhas."""
|
|
161
|
+
if not self._tag:
|
|
162
|
+
self._tag = f"fold_{self.start_line}_{self.end_line}"
|
|
163
|
+
return self._tag
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _detect_indent(lines: list[str]) -> list[FoldRegion]:
|
|
167
|
+
"""Detecta regiões de fold em linguagens baseadas em indentação (Python, YAML, ...).
|
|
168
|
+
|
|
169
|
+
Palavras-chave de abertura (``def``, ``class``, ``if``, etc.) empilham um bloco.
|
|
170
|
+
Palavras de continuação (``elif``, ``else``, ``except``, ``finally``) estendem o
|
|
171
|
+
bloco corrente sem fechá-lo. Uma linha não-vazia com indentação ≤ à de abertura
|
|
172
|
+
fecha o bloco. Docstrings com aspas triplas são detectadas como região separada
|
|
173
|
+
do tipo ``"docstring"``.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
lines: Linhas do arquivo-fonte (sem ``\\n`` terminal necessário).
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
Lista não filtrada de objetos ``FoldRegion``; pode conter spans de linha única.
|
|
180
|
+
"""
|
|
181
|
+
regions: list[FoldRegion] = []
|
|
182
|
+
n = len(lines)
|
|
183
|
+
|
|
184
|
+
stack: list[list] = []
|
|
185
|
+
|
|
186
|
+
i = 0
|
|
187
|
+
while i < n:
|
|
188
|
+
raw = lines[i]
|
|
189
|
+
stripped = raw.lstrip()
|
|
190
|
+
indent = len(raw) - len(stripped)
|
|
191
|
+
lnum = i + 1
|
|
192
|
+
|
|
193
|
+
if not stripped:
|
|
194
|
+
i += 1
|
|
195
|
+
continue
|
|
196
|
+
|
|
197
|
+
if '"""' in raw:
|
|
198
|
+
count = raw.count('"""')
|
|
199
|
+
if count == 1:
|
|
200
|
+
j = i + 1
|
|
201
|
+
while j < n:
|
|
202
|
+
if '"""' in lines[j]:
|
|
203
|
+
if j > i + 1:
|
|
204
|
+
regions.append(FoldRegion(
|
|
205
|
+
lnum, j + 1, kind="docstring"))
|
|
206
|
+
i = j
|
|
207
|
+
break
|
|
208
|
+
j += 1
|
|
209
|
+
|
|
210
|
+
if _REGION_OPEN.match(raw):
|
|
211
|
+
j = i + 1
|
|
212
|
+
while j < n:
|
|
213
|
+
if _REGION_CLOSE.match(lines[j]):
|
|
214
|
+
regions.append(FoldRegion(lnum, j + 1, kind="region"))
|
|
215
|
+
i = j
|
|
216
|
+
break
|
|
217
|
+
j += 1
|
|
218
|
+
|
|
219
|
+
if _PY_CONT.match(raw):
|
|
220
|
+
for entry in reversed(stack):
|
|
221
|
+
if entry[1] == indent:
|
|
222
|
+
entry[3] = lnum
|
|
223
|
+
break
|
|
224
|
+
i += 1
|
|
225
|
+
continue
|
|
226
|
+
|
|
227
|
+
new_stack = []
|
|
228
|
+
for entry in stack:
|
|
229
|
+
s_line, s_indent, s_kind, cur_end = entry
|
|
230
|
+
if s_kind == "block" and lnum > s_line and indent <= s_indent:
|
|
231
|
+
if cur_end >= lnum:
|
|
232
|
+
new_stack.append(entry)
|
|
233
|
+
continue
|
|
234
|
+
end = max(cur_end, s_line + 1)
|
|
235
|
+
regions.append(FoldRegion(s_line, end, kind=s_kind))
|
|
236
|
+
else:
|
|
237
|
+
new_stack.append(entry)
|
|
238
|
+
stack = new_stack
|
|
239
|
+
|
|
240
|
+
if _PY_OPEN.match(raw):
|
|
241
|
+
stack.append([lnum, indent, "block", lnum])
|
|
242
|
+
|
|
243
|
+
i += 1
|
|
244
|
+
|
|
245
|
+
for entry in stack:
|
|
246
|
+
s_line, _, s_kind, cur_end = entry
|
|
247
|
+
end = max(cur_end, n) if n > s_line else cur_end
|
|
248
|
+
if end > s_line:
|
|
249
|
+
regions.append(FoldRegion(s_line, end, kind=s_kind))
|
|
250
|
+
|
|
251
|
+
return regions
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _detect_brace(lines: list[str]) -> list[FoldRegion]:
|
|
255
|
+
"""Detecta regiões de fold em linguagens com blocos ``{ }`` (JS, TS, Java, C, ...).
|
|
256
|
+
|
|
257
|
+
Rastreia pares ``{`` / ``}`` em uma pilha; cada par casado vira uma região
|
|
258
|
+
``"brace"``. Comentários de bloco (``/* ... */``) imediatamente seguidos de uma
|
|
259
|
+
declaração com ``{`` são ignorados para evitar colocar a seta no comentário.
|
|
260
|
+
Marcadores ``# region`` / ``# endregion`` são detectados independentemente.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
lines: Linhas do arquivo-fonte.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Lista não filtrada de objetos ``FoldRegion``.
|
|
267
|
+
"""
|
|
268
|
+
regions: list[FoldRegion] = []
|
|
269
|
+
stack: list[int] = []
|
|
270
|
+
n = len(lines)
|
|
271
|
+
i = 0
|
|
272
|
+
while i < n:
|
|
273
|
+
raw = lines[i]
|
|
274
|
+
lnum = i + 1
|
|
275
|
+
|
|
276
|
+
if _REGION_OPEN.match(raw):
|
|
277
|
+
j = i + 1
|
|
278
|
+
while j < n:
|
|
279
|
+
if _REGION_CLOSE.match(lines[j]):
|
|
280
|
+
regions.append(FoldRegion(lnum, j + 1, kind="region"))
|
|
281
|
+
break
|
|
282
|
+
j += 1
|
|
283
|
+
|
|
284
|
+
if _BLOCK_CMT_OPEN.search(raw) and not _BLOCK_CMT_CLOSE.search(raw):
|
|
285
|
+
j = i + 1
|
|
286
|
+
while j < n:
|
|
287
|
+
if _BLOCK_CMT_CLOSE.search(lines[j]):
|
|
288
|
+
next_code = j + 1
|
|
289
|
+
if next_code < n and _BRACE_OPEN.search(lines[next_code]):
|
|
290
|
+
pass
|
|
291
|
+
elif j > i + 1:
|
|
292
|
+
regions.append(FoldRegion(lnum, j + 1, kind="comment"))
|
|
293
|
+
break
|
|
294
|
+
j += 1
|
|
295
|
+
|
|
296
|
+
if _BRACE_OPEN.search(raw):
|
|
297
|
+
stack.append(lnum)
|
|
298
|
+
|
|
299
|
+
if _BRACE_CLOSE.match(raw) and stack:
|
|
300
|
+
start = stack.pop()
|
|
301
|
+
if lnum > start:
|
|
302
|
+
regions.append(FoldRegion(start, lnum, kind="brace"))
|
|
303
|
+
|
|
304
|
+
i += 1
|
|
305
|
+
return regions
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _detect_doend(lines: list[str]) -> list[FoldRegion]:
|
|
309
|
+
"""Detecta regiões de fold em linguagens do/end (Ruby, Lua, Elixir, Crystal).
|
|
310
|
+
|
|
311
|
+
Palavras-chave de abertura empilham o número da linha; ``end`` desempilha a
|
|
312
|
+
entrada mais recente e cria uma região ``"block"``. Marcadores
|
|
313
|
+
``# region`` / ``# endregion`` também são tratados.
|
|
314
|
+
|
|
315
|
+
Args:
|
|
316
|
+
lines: Linhas do arquivo-fonte.
|
|
317
|
+
|
|
318
|
+
Returns:
|
|
319
|
+
Lista não filtrada de objetos ``FoldRegion``.
|
|
320
|
+
"""
|
|
321
|
+
regions: list[FoldRegion] = []
|
|
322
|
+
stack: list[int] = []
|
|
323
|
+
for i, raw in enumerate(lines):
|
|
324
|
+
lnum = i + 1
|
|
325
|
+
if not raw.strip():
|
|
326
|
+
continue
|
|
327
|
+
if _REGION_OPEN.match(raw):
|
|
328
|
+
j = i + 1
|
|
329
|
+
while j < len(lines):
|
|
330
|
+
if _REGION_CLOSE.match(lines[j]):
|
|
331
|
+
regions.append(FoldRegion(lnum, j + 1, kind="region"))
|
|
332
|
+
break
|
|
333
|
+
j += 1
|
|
334
|
+
if _DOEND_OPEN.match(raw):
|
|
335
|
+
stack.append(lnum)
|
|
336
|
+
if _DOEND_CLOSE.match(raw) and stack:
|
|
337
|
+
start = stack.pop()
|
|
338
|
+
if lnum > start + 1:
|
|
339
|
+
regions.append(FoldRegion(start, lnum, kind="block"))
|
|
340
|
+
return regions
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _detect_markup(lines: list[str], lang: str) -> list[FoldRegion]:
|
|
344
|
+
"""Detecta regiões de fold em linguagens de marcação (HTML, XML, Markdown).
|
|
345
|
+
|
|
346
|
+
Para Markdown, os níveis de cabeçalho conduzem uma pilha: um cabeçalho fecha
|
|
347
|
+
todos os cabeçalhos abertos de nível igual ou mais profundo e abre uma nova
|
|
348
|
+
região ``"section"``. Para HTML/XML, um conjunto de tags de bloco é casado por
|
|
349
|
+
pares abrir/fechar; tags auto-fechantes (sufixo ``/>``) são ignoradas.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
lines: Linhas do arquivo-fonte.
|
|
353
|
+
lang: Identificador de linguagem - ``"markdown"`` usa a estratégia de
|
|
354
|
+
cabeçalhos; qualquer outro valor usa casamento de tags HTML/XML.
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
Lista não filtrada de objetos ``FoldRegion``.
|
|
358
|
+
"""
|
|
359
|
+
regions: list[FoldRegion] = []
|
|
360
|
+
|
|
361
|
+
if lang == "markdown":
|
|
362
|
+
heading_stack: list[tuple[int, int]] = []
|
|
363
|
+
for i, raw in enumerate(lines):
|
|
364
|
+
m = _MD_HEADING.match(raw)
|
|
365
|
+
if not m:
|
|
366
|
+
continue
|
|
367
|
+
level = len(m.group(1))
|
|
368
|
+
lnum = i + 1
|
|
369
|
+
new_hs = []
|
|
370
|
+
for h_line, h_level in heading_stack:
|
|
371
|
+
if h_level >= level:
|
|
372
|
+
if lnum > h_line + 1:
|
|
373
|
+
regions.append(FoldRegion(
|
|
374
|
+
h_line, lnum - 1, kind="section"))
|
|
375
|
+
else:
|
|
376
|
+
new_hs.append((h_line, h_level))
|
|
377
|
+
heading_stack = new_hs
|
|
378
|
+
heading_stack.append((lnum, level))
|
|
379
|
+
total = len(lines)
|
|
380
|
+
for h_line, _ in heading_stack:
|
|
381
|
+
if total > h_line:
|
|
382
|
+
regions.append(FoldRegion(h_line, total, kind="section"))
|
|
383
|
+
return regions
|
|
384
|
+
|
|
385
|
+
stack: list[tuple[int, str]] = []
|
|
386
|
+
for i, raw in enumerate(lines):
|
|
387
|
+
lnum = i + 1
|
|
388
|
+
if _HTML_SELF.search(raw):
|
|
389
|
+
continue
|
|
390
|
+
m_open = _HTML_OPEN.search(raw)
|
|
391
|
+
m_close = _HTML_CLOSE.search(raw)
|
|
392
|
+
if m_open and not m_close:
|
|
393
|
+
stack.append((lnum, m_open.group(1).lower()))
|
|
394
|
+
if m_close and stack:
|
|
395
|
+
tag = m_close.group(1).lower()
|
|
396
|
+
for j in range(len(stack) - 1, -1, -1):
|
|
397
|
+
if stack[j][1] == tag:
|
|
398
|
+
start = stack.pop(j)[0]
|
|
399
|
+
if lnum > start + 1:
|
|
400
|
+
regions.append(FoldRegion(start, lnum, kind="html"))
|
|
401
|
+
break
|
|
402
|
+
return regions
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _detect_sql(lines: list[str]) -> list[FoldRegion]:
|
|
406
|
+
"""Detecta regiões de fold em arquivos SQL/PL-SQL usando pares BEGIN/END.
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
lines: Linhas do arquivo-fonte.
|
|
410
|
+
|
|
411
|
+
Returns:
|
|
412
|
+
Lista não filtrada de objetos ``FoldRegion``.
|
|
413
|
+
"""
|
|
414
|
+
regions: list[FoldRegion] = []
|
|
415
|
+
stack: list[int] = []
|
|
416
|
+
for i, raw in enumerate(lines):
|
|
417
|
+
lnum = i + 1
|
|
418
|
+
if _SQL_OPEN.search(raw):
|
|
419
|
+
stack.append(lnum)
|
|
420
|
+
if _SQL_CLOSE.search(raw) and stack:
|
|
421
|
+
start = stack.pop()
|
|
422
|
+
if lnum > start + 1:
|
|
423
|
+
regions.append(FoldRegion(start, lnum, kind="block"))
|
|
424
|
+
return regions
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def detect_regions(lines: list[str], lang: str) -> list[FoldRegion]:
|
|
428
|
+
"""Escolhe a estratégia correta para ``lang`` e retorna regiões válidas.
|
|
429
|
+
|
|
430
|
+
Despacha para ``_detect_indent``, ``_detect_brace``, ``_detect_doend``,
|
|
431
|
+
``_detect_markup`` ou ``_detect_sql`` conforme a família da linguagem.
|
|
432
|
+
Linguagens desconhecidas recorrem ao detector brace e depois ao indent.
|
|
433
|
+
Spans de linha única (``start_line == end_line``) são descartados.
|
|
434
|
+
|
|
435
|
+
Args:
|
|
436
|
+
lines: Linhas do arquivo-fonte.
|
|
437
|
+
lang: Identificador de linguagem em minúsculas (ex.: ``"python"``, ``"typescript"``).
|
|
438
|
+
|
|
439
|
+
Returns:
|
|
440
|
+
Lista de objetos ``FoldRegion`` ordenada por ``start_line``, cada um
|
|
441
|
+
cobrindo ao menos duas linhas (``end_line - start_line >= 1``).
|
|
442
|
+
"""
|
|
443
|
+
if lang in INDENT_LANGS:
|
|
444
|
+
raw = _detect_indent(lines)
|
|
445
|
+
elif lang in BRACE_LANGS:
|
|
446
|
+
raw = _detect_brace(lines)
|
|
447
|
+
elif lang in DOEND_LANGS:
|
|
448
|
+
raw = _detect_doend(lines)
|
|
449
|
+
elif lang in MARKUP_LANGS:
|
|
450
|
+
raw = _detect_markup(lines, lang)
|
|
451
|
+
elif lang in SQL_LANGS:
|
|
452
|
+
raw = _detect_sql(lines)
|
|
453
|
+
else:
|
|
454
|
+
raw = _detect_brace(lines)
|
|
455
|
+
if not raw:
|
|
456
|
+
raw = _detect_indent(lines)
|
|
457
|
+
|
|
458
|
+
result = [r for r in raw if r.end_line - r.start_line >= 1]
|
|
459
|
+
result.sort(key=lambda r: r.start_line)
|
|
460
|
+
return result
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
class CodeFolding:
|
|
464
|
+
"""Motor de code folding para um widget ``tk.Text``.
|
|
465
|
+
|
|
466
|
+
Detecta regiões foldáveis para a linguagem ativa, renderiza placeholders
|
|
467
|
+
de fold inline e notifica o gutter das posições das linhas dobradas.
|
|
468
|
+
Folds aninhados (filhos dentro de um fold pai) são preservados entre
|
|
469
|
+
ciclos de fold/unfold via ``FoldRegion.folded_children``.
|
|
470
|
+
"""
|
|
471
|
+
|
|
472
|
+
def __init__(
|
|
473
|
+
self,
|
|
474
|
+
txt: tk.Text,
|
|
475
|
+
theme: Theme,
|
|
476
|
+
on_gutter_update: callable | None = None,
|
|
477
|
+
lang: str = "text",
|
|
478
|
+
) -> None:
|
|
479
|
+
"""Inicializa o motor de folding e o vincula ao widget ``txt``.
|
|
480
|
+
|
|
481
|
+
Args:
|
|
482
|
+
txt: Widget ``tk.Text`` a ser gerenciado.
|
|
483
|
+
theme: Tema ativo, usado para as cores das tags.
|
|
484
|
+
on_gutter_update: Callback que recebe ``{linha: dobrado}`` sempre que
|
|
485
|
+
o mapa de fold muda.
|
|
486
|
+
lang: Identificador de linguagem inicial para detecção de regiões.
|
|
487
|
+
"""
|
|
488
|
+
self._txt = txt
|
|
489
|
+
self._theme = theme
|
|
490
|
+
self._on_gutter_update = on_gutter_update
|
|
491
|
+
self._lang = lang
|
|
492
|
+
self._regions: list[FoldRegion] = []
|
|
493
|
+
self._after_id: str | None = None
|
|
494
|
+
self._suspended = False
|
|
495
|
+
self._configure_tags()
|
|
496
|
+
self._bind_events()
|
|
497
|
+
|
|
498
|
+
def _configure_tags(self) -> None:
|
|
499
|
+
"""Configura o estilo da tag ``codis_fold_placeholder`` com as cores do tema ativo."""
|
|
500
|
+
t = self._theme
|
|
501
|
+
with contextlib.suppress(tk.TclError):
|
|
502
|
+
self._txt.tag_configure(
|
|
503
|
+
_TAG_FOLD,
|
|
504
|
+
background=t.sel_bg,
|
|
505
|
+
foreground=t.fg_muted,
|
|
506
|
+
font=(FONT_MONO, FONT_SIZE - 1),
|
|
507
|
+
relief="flat",
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
def _bind_events(self) -> None:
|
|
511
|
+
"""Vincula ``<<Modified>>`` e ``<FocusIn>`` ao scan com debounce."""
|
|
512
|
+
self._txt.bind("<<Modified>>", self._schedule_scan, add=True)
|
|
513
|
+
self._txt.bind("<FocusIn>", self._schedule_scan, add=True)
|
|
514
|
+
|
|
515
|
+
def suspend(self, flag: bool) -> None:
|
|
516
|
+
"""Pausa (ou retoma) a detecção de regiões.
|
|
517
|
+
|
|
518
|
+
Em arquivos grandes o scan lê o documento inteiro a cada pausa na digitação, então o
|
|
519
|
+
editor o suspende enquanto o modo de arquivo grande estiver ativo.
|
|
520
|
+
"""
|
|
521
|
+
self._suspended = flag
|
|
522
|
+
if not flag:
|
|
523
|
+
return
|
|
524
|
+
if self._after_id:
|
|
525
|
+
with contextlib.suppress(tk.TclError):
|
|
526
|
+
self._txt.after_cancel(self._after_id)
|
|
527
|
+
self._after_id = None
|
|
528
|
+
if self._regions:
|
|
529
|
+
self._regions = []
|
|
530
|
+
self._notify_gutter()
|
|
531
|
+
|
|
532
|
+
def set_lang(self, lang: str) -> None:
|
|
533
|
+
"""Define a linguagem ativa e dispara um novo scan de regiões.
|
|
534
|
+
|
|
535
|
+
Args:
|
|
536
|
+
lang: Identificador de linguagem em minúsculas (ex.: ``"python"``, ``"go"``).
|
|
537
|
+
"""
|
|
538
|
+
if lang != self._lang:
|
|
539
|
+
self._lang = lang
|
|
540
|
+
self._schedule_scan()
|
|
541
|
+
|
|
542
|
+
def _schedule_scan(self, _e=None, delay: int = 400) -> None:
|
|
543
|
+
"""Aplica debounce na chamada a ``_scan_regions``.
|
|
544
|
+
|
|
545
|
+
Args:
|
|
546
|
+
delay: Milissegundos de espera antes do scan. Use ``400`` para eventos
|
|
547
|
+
de digitação e ``80`` após fold/unfold para que os ícones do
|
|
548
|
+
gutter atualizem antes do próximo pressionamento de tecla.
|
|
549
|
+
"""
|
|
550
|
+
if self._suspended:
|
|
551
|
+
return
|
|
552
|
+
if self._after_id:
|
|
553
|
+
with contextlib.suppress(tk.TclError):
|
|
554
|
+
self._txt.after_cancel(self._after_id)
|
|
555
|
+
self._after_id = self._txt.after(delay, self._scan_regions)
|
|
556
|
+
|
|
557
|
+
def _scan_regions(self) -> None:
|
|
558
|
+
"""Detecta regiões de fold no conteúdo atual do widget e mescla o estado dobrado.
|
|
559
|
+
|
|
560
|
+
Executa após o delay do debounce. Para cada região detectada, verifica se
|
|
561
|
+
uma região previamente dobrada tem sua tag ainda presente na mesma linha do
|
|
562
|
+
widget e transfere os campos ``folded``, ``hidden_text``, ``_tag`` e
|
|
563
|
+
``folded_children``. Regiões cujo placeholder ainda existe no widget mas
|
|
564
|
+
cuja linha de início não coincide com nenhuma região detectada são mantidas
|
|
565
|
+
como ``surviving_folded`` para que seus ícones no gutter permaneçam visíveis.
|
|
566
|
+
"""
|
|
567
|
+
self._after_id = None
|
|
568
|
+
if self._suspended or not self._txt.winfo_exists():
|
|
569
|
+
return
|
|
570
|
+
try:
|
|
571
|
+
content = self._txt.get("1.0", "end-1c")
|
|
572
|
+
except tk.TclError:
|
|
573
|
+
return
|
|
574
|
+
|
|
575
|
+
lines = content.splitlines()
|
|
576
|
+
new_regions = detect_regions(lines, self._lang)
|
|
577
|
+
|
|
578
|
+
old_by_tag: dict[str, FoldRegion] = {
|
|
579
|
+
r.tag: r for r in self._regions if r.folded and r.tag
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
tag_to_current_line: dict[str, int] = {}
|
|
583
|
+
for tag, _r in old_by_tag.items():
|
|
584
|
+
with contextlib.suppress(tk.TclError):
|
|
585
|
+
ranges = self._txt.tag_ranges(tag)
|
|
586
|
+
if ranges:
|
|
587
|
+
idx = str(ranges[0])
|
|
588
|
+
tag_to_current_line[tag] = int(idx.split(".")[0])
|
|
589
|
+
|
|
590
|
+
line_to_old: dict[int, FoldRegion] = {
|
|
591
|
+
ln: old_by_tag[tag] for tag, ln in tag_to_current_line.items()
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
for reg in new_regions:
|
|
595
|
+
old_r = line_to_old.get(reg.start_line)
|
|
596
|
+
if old_r is not None:
|
|
597
|
+
reg.folded = True
|
|
598
|
+
reg.hidden_text = old_r.hidden_text
|
|
599
|
+
reg._tag = old_r._tag
|
|
600
|
+
reg.folded_children = old_r.folded_children
|
|
601
|
+
|
|
602
|
+
self._regions = new_regions
|
|
603
|
+
|
|
604
|
+
surviving_folded = []
|
|
605
|
+
matched_tags = {r._tag for r in new_regions if r.folded}
|
|
606
|
+
for old_r in old_by_tag.values():
|
|
607
|
+
if old_r.tag in matched_tags:
|
|
608
|
+
continue
|
|
609
|
+
with contextlib.suppress(tk.TclError):
|
|
610
|
+
ranges = self._txt.tag_ranges(old_r.tag)
|
|
611
|
+
if ranges:
|
|
612
|
+
current_line = int(str(ranges[0]).split(".")[0])
|
|
613
|
+
old_r.start_line = current_line
|
|
614
|
+
surviving_folded.append(old_r)
|
|
615
|
+
self._regions = new_regions + surviving_folded
|
|
616
|
+
|
|
617
|
+
self._notify_gutter()
|
|
618
|
+
|
|
619
|
+
def toggle_fold(self, line_number: int) -> bool | None:
|
|
620
|
+
"""Alterna o estado de fold da região que começa em ``line_number``.
|
|
621
|
+
|
|
622
|
+
Args:
|
|
623
|
+
line_number: Número de linha base 1 da linha de abertura da região.
|
|
624
|
+
|
|
625
|
+
Returns:
|
|
626
|
+
``True`` se a região foi dobrada agora, ``False`` se desdobrada,
|
|
627
|
+
``None`` se nenhuma região começa nessa linha.
|
|
628
|
+
"""
|
|
629
|
+
reg = self._find_region_at(line_number)
|
|
630
|
+
if reg is None:
|
|
631
|
+
return None
|
|
632
|
+
if reg.folded:
|
|
633
|
+
self.unfold(reg)
|
|
634
|
+
return False
|
|
635
|
+
self.fold(reg)
|
|
636
|
+
return True
|
|
637
|
+
|
|
638
|
+
def fold(self, region: FoldRegion) -> None:
|
|
639
|
+
"""Recolhe a região, ocultando o texto de start.end até end.end.
|
|
640
|
+
|
|
641
|
+
Antes de recolher, captura todos os descendentes atualmente dobrados para
|
|
642
|
+
que seu estado sobreviva ao scan posterior ao fold (que não consegue ver as
|
|
643
|
+
tags que sumiram com o texto). Os filhos capturados são armazenados em
|
|
644
|
+
``region.folded_children`` e restaurados em ``unfold``.
|
|
645
|
+
"""
|
|
646
|
+
if region.folded:
|
|
647
|
+
return
|
|
648
|
+
try:
|
|
649
|
+
region.folded_children = [
|
|
650
|
+
r
|
|
651
|
+
for r in self._regions
|
|
652
|
+
if r.folded
|
|
653
|
+
and r is not region
|
|
654
|
+
and region.start_line < r.start_line <= region.end_line
|
|
655
|
+
]
|
|
656
|
+
|
|
657
|
+
start = f"{region.start_line}.end"
|
|
658
|
+
end = f"{region.end_line}.end"
|
|
659
|
+
region.hidden_text = self._txt.get(start, end)
|
|
660
|
+
self._txt.delete(start, end)
|
|
661
|
+
self._txt.insert(start, _FOLD_PLACEHOLDER, (region.tag, _TAG_FOLD))
|
|
662
|
+
region.folded = True
|
|
663
|
+
self._schedule_scan(delay=80)
|
|
664
|
+
except tk.TclError as e:
|
|
665
|
+
logger.debug("fold error: %s", e)
|
|
666
|
+
|
|
667
|
+
def unfold(self, region: FoldRegion) -> None:
|
|
668
|
+
"""Expande uma região recolhida e restaura todos os descendentes dobrados.
|
|
669
|
+
|
|
670
|
+
Quando o pai foi dobrado, seu texto oculto já continha os placeholders dos
|
|
671
|
+
filhos como texto puro (as tags Tkinter foram removidas). ``fold()`` salvou
|
|
672
|
+
referências a esses filhos em ``region.folded_children`` antes das tags
|
|
673
|
+
desaparecerem do widget. Aqui reinserimos o texto e chamamos
|
|
674
|
+
``_restore_child_folds`` para recriar as tags dos filhos, de modo que o
|
|
675
|
+
gutter mostre ▸ e o unfold dos próprios filhos continue funcionando.
|
|
676
|
+
"""
|
|
677
|
+
if not region.folded:
|
|
678
|
+
return
|
|
679
|
+
try:
|
|
680
|
+
ranges = self._txt.tag_ranges(region.tag)
|
|
681
|
+
if not ranges:
|
|
682
|
+
return
|
|
683
|
+
|
|
684
|
+
insert_pos = str(ranges[0])
|
|
685
|
+
insert_line = int(insert_pos.split(".")[0])
|
|
686
|
+
|
|
687
|
+
folded_children: list[FoldRegion] = list(region.folded_children)
|
|
688
|
+
|
|
689
|
+
self._txt.delete(ranges[0], ranges[1])
|
|
690
|
+
self._txt.insert(insert_pos, region.hidden_text)
|
|
691
|
+
region.folded = False
|
|
692
|
+
region.hidden_text = ""
|
|
693
|
+
region.folded_children = []
|
|
694
|
+
|
|
695
|
+
if folded_children:
|
|
696
|
+
self._restore_child_folds(folded_children, insert_line)
|
|
697
|
+
existing_tags = {r._tag for r in self._regions}
|
|
698
|
+
for child in folded_children:
|
|
699
|
+
if child._tag not in existing_tags:
|
|
700
|
+
self._regions.append(child)
|
|
701
|
+
|
|
702
|
+
self._notify_gutter()
|
|
703
|
+
|
|
704
|
+
self._schedule_scan(delay=80)
|
|
705
|
+
except tk.TclError as e:
|
|
706
|
+
logger.debug("unfold error: %s", e)
|
|
707
|
+
|
|
708
|
+
def _restore_child_folds(
|
|
709
|
+
self, children: list[FoldRegion], parent_insert_line: int
|
|
710
|
+
) -> None:
|
|
711
|
+
"""Recria as tags Tkinter dos filhos dobrados após o unfold do pai.
|
|
712
|
+
|
|
713
|
+
Quando o pai foi dobrado, os placeholders dos filhos foram salvos como
|
|
714
|
+
texto puro dentro de ``hidden_text``. Ao reinserir esse texto, os
|
|
715
|
+
placeholders voltam mas sem suas tags. Este método varre as linhas
|
|
716
|
+
restauradas em busca de cada placeholder e recria a tag correspondente
|
|
717
|
+
do filho, para que o gutter mostre ▸ e o ``unfold`` continue funcionando
|
|
718
|
+
nos filhos.
|
|
719
|
+
|
|
720
|
+
Args:
|
|
721
|
+
children: Descendentes dobrados capturados no momento do fold.
|
|
722
|
+
parent_insert_line: Número de linha no widget onde o placeholder do pai
|
|
723
|
+
estava (e onde o texto restaurado começa).
|
|
724
|
+
"""
|
|
725
|
+
ph_stripped = _FOLD_PLACEHOLDER.strip()
|
|
726
|
+
|
|
727
|
+
if not children:
|
|
728
|
+
return
|
|
729
|
+
max_child_end = max(c.end_line for c in children)
|
|
730
|
+
scan_end = (
|
|
731
|
+
parent_insert_line
|
|
732
|
+
+ (max_child_end - min(c.start_line for c in children))
|
|
733
|
+
+ 5
|
|
734
|
+
)
|
|
735
|
+
|
|
736
|
+
remaining = sorted(children, key=lambda c: c.start_line)
|
|
737
|
+
|
|
738
|
+
for child in remaining:
|
|
739
|
+
try:
|
|
740
|
+
estimated_line = child.start_line
|
|
741
|
+
found_line: int | None = None
|
|
742
|
+
|
|
743
|
+
search_range = list(
|
|
744
|
+
range(
|
|
745
|
+
max(1, estimated_line - 3),
|
|
746
|
+
estimated_line + 4,
|
|
747
|
+
)
|
|
748
|
+
)
|
|
749
|
+
search_range += list(
|
|
750
|
+
range(
|
|
751
|
+
max(1, parent_insert_line),
|
|
752
|
+
min(scan_end, parent_insert_line + 200),
|
|
753
|
+
)
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
seen: set[int] = set()
|
|
757
|
+
for ln in search_range:
|
|
758
|
+
if ln in seen:
|
|
759
|
+
continue
|
|
760
|
+
seen.add(ln)
|
|
761
|
+
try:
|
|
762
|
+
lt = self._txt.get(f"{ln}.0", f"{ln}.end")
|
|
763
|
+
if ph_stripped in lt:
|
|
764
|
+
found_line = ln
|
|
765
|
+
break
|
|
766
|
+
except tk.TclError:
|
|
767
|
+
break
|
|
768
|
+
|
|
769
|
+
if found_line is None:
|
|
770
|
+
continue
|
|
771
|
+
|
|
772
|
+
line_content = self._txt.get(
|
|
773
|
+
f"{found_line}.0", f"{found_line}.end")
|
|
774
|
+
col = line_content.find(ph_stripped)
|
|
775
|
+
if col == -1:
|
|
776
|
+
col = 0
|
|
777
|
+
|
|
778
|
+
start_idx = f"{found_line}.{col}"
|
|
779
|
+
end_idx = f"{found_line}.{col + len(_FOLD_PLACEHOLDER)}"
|
|
780
|
+
|
|
781
|
+
self._txt.tag_add(child.tag, start_idx, end_idx)
|
|
782
|
+
self._txt.tag_add(_TAG_FOLD, start_idx, end_idx)
|
|
783
|
+
self._txt.tag_config(child.tag, elide=False)
|
|
784
|
+
self._txt.tag_config(
|
|
785
|
+
_TAG_FOLD, foreground=self._theme.fg_muted)
|
|
786
|
+
|
|
787
|
+
child.start_line = found_line
|
|
788
|
+
|
|
789
|
+
except (tk.TclError, ValueError) as e:
|
|
790
|
+
logger.debug(
|
|
791
|
+
"_restore_child_folds error for child %s: %s", child, e)
|
|
792
|
+
|
|
793
|
+
def fold_all(self) -> None:
|
|
794
|
+
"""Dobra todas as regiões foldáveis de nível superior do documento."""
|
|
795
|
+
for r in [r for r in self._regions if not r.folded and self._is_top(r)]:
|
|
796
|
+
self.fold(r)
|
|
797
|
+
|
|
798
|
+
def unfold_all(self) -> None:
|
|
799
|
+
"""Desdobra todas as regiões dobradas do documento."""
|
|
800
|
+
for r in list(self._regions):
|
|
801
|
+
if r.folded:
|
|
802
|
+
self.unfold(r)
|
|
803
|
+
|
|
804
|
+
def _find_region_at(self, line: int) -> FoldRegion | None:
|
|
805
|
+
"""Retorna o ``FoldRegion`` cujo ``start_line`` é igual a ``line``, ou ``None``."""
|
|
806
|
+
for r in self._regions:
|
|
807
|
+
if r.start_line == line:
|
|
808
|
+
return r
|
|
809
|
+
return None
|
|
810
|
+
|
|
811
|
+
def _is_top(self, region: FoldRegion) -> bool:
|
|
812
|
+
"""Retorna ``True`` se ``region`` está no nível de indentação zero (topo)."""
|
|
813
|
+
try:
|
|
814
|
+
content = self._txt.get("1.0", f"{region.start_line}.0")
|
|
815
|
+
line = content.splitlines()[-1] if content.splitlines() else ""
|
|
816
|
+
return not line.strip() or len(line) - len(line.lstrip()) == 0
|
|
817
|
+
except tk.TclError:
|
|
818
|
+
return True
|
|
819
|
+
|
|
820
|
+
def _notify_gutter(self) -> None:
|
|
821
|
+
"""Dispara ``on_gutter_update`` com o mapa ``{linha: dobrado}`` atual."""
|
|
822
|
+
if self._on_gutter_update:
|
|
823
|
+
fold_map = {r.start_line: r.folded for r in self._regions}
|
|
824
|
+
with contextlib.suppress(tk.TclError, AttributeError):
|
|
825
|
+
self._on_gutter_update(fold_map)
|
|
826
|
+
|
|
827
|
+
def apply_theme(self, theme: Theme) -> None:
|
|
828
|
+
"""Aplica as cores de ``theme`` à tag de placeholder de fold."""
|
|
829
|
+
self._theme = theme
|
|
830
|
+
self._configure_tags()
|
|
831
|
+
|
|
832
|
+
def destroy(self) -> None:
|
|
833
|
+
"""Cancela qualquer scan pendente e libera as referências ao widget."""
|
|
834
|
+
if self._after_id:
|
|
835
|
+
with contextlib.suppress(tk.TclError):
|
|
836
|
+
self._txt.after_cancel(self._after_id)
|