tmcode 0.2.0__py3-none-any.whl → 0.3.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.
- termcode/__init__.py +1 -1
- termcode/app.py +133 -6
- termcode/cli.py +13 -3
- termcode/commands.py +1 -1
- termcode/highlighting.py +126 -0
- termcode/modals.py +40 -0
- termcode/pairs.py +100 -0
- termcode/runner.py +284 -5
- termcode/styles.tcss +8 -0
- termcode/update.py +235 -0
- tmcode-0.3.1.dist-info/METADATA +158 -0
- tmcode-0.3.1.dist-info/RECORD +23 -0
- tmcode-0.2.0.dist-info/METADATA +0 -128
- tmcode-0.2.0.dist-info/RECORD +0 -21
- {tmcode-0.2.0.dist-info → tmcode-0.3.1.dist-info}/WHEEL +0 -0
- {tmcode-0.2.0.dist-info → tmcode-0.3.1.dist-info}/entry_points.txt +0 -0
- {tmcode-0.2.0.dist-info → tmcode-0.3.1.dist-info}/licenses/LICENSE +0 -0
- {tmcode-0.2.0.dist-info → tmcode-0.3.1.dist-info}/top_level.txt +0 -0
termcode/__init__.py
CHANGED
termcode/app.py
CHANGED
|
@@ -16,6 +16,7 @@ from textual.app import App, ComposeResult, SuspendNotSupported
|
|
|
16
16
|
from textual.binding import Binding
|
|
17
17
|
from textual.containers import Horizontal, Vertical
|
|
18
18
|
from textual.css.query import NoMatches
|
|
19
|
+
from textual.widgets.text_area import Selection
|
|
19
20
|
from textual.widgets import Button, DirectoryTree, Input, OptionList, Static, TextArea
|
|
20
21
|
from textual.widgets.option_list import Option
|
|
21
22
|
|
|
@@ -29,7 +30,8 @@ from termcode.completions import (
|
|
|
29
30
|
from termcode import __version__, theme
|
|
30
31
|
from termcode.findbar import FindBar
|
|
31
32
|
from termcode.formatting import format_code
|
|
32
|
-
from termcode.highlighting import register_extra_languages
|
|
33
|
+
from termcode.highlighting import pygments_highlights, pygments_lexer_for, register_extra_languages
|
|
34
|
+
from termcode.pairs import CLOSERS, PAIRS, plan_backspace, plan_enter, plan_typed
|
|
33
35
|
from termcode.modals import (
|
|
34
36
|
CommandPaletteModal,
|
|
35
37
|
ConfirmModal,
|
|
@@ -37,6 +39,14 @@ from termcode.modals import (
|
|
|
37
39
|
FolderPickerModal,
|
|
38
40
|
TextInputModal,
|
|
39
41
|
UnsavedChangesModal,
|
|
42
|
+
UpdateModal,
|
|
43
|
+
)
|
|
44
|
+
from termcode.update import (
|
|
45
|
+
InstallKind,
|
|
46
|
+
check_for_update,
|
|
47
|
+
default_state_path,
|
|
48
|
+
detect_install,
|
|
49
|
+
skip_version,
|
|
40
50
|
)
|
|
41
51
|
from termcode.search import parse_goto
|
|
42
52
|
from termcode.runner import (
|
|
@@ -300,6 +310,27 @@ class CodeTextArea(TextArea):
|
|
|
300
310
|
self.register_theme(theme.OUTPUT_THEME)
|
|
301
311
|
self.theme = theme.OUTPUT_THEME_NAME if self.read_only else theme.EDITOR_THEME_NAME
|
|
302
312
|
|
|
313
|
+
# Pygments lexer used when the file's language has no tree-sitter grammar.
|
|
314
|
+
_fallback_lexer = None
|
|
315
|
+
|
|
316
|
+
def set_fallback_lexer(self, lexer) -> None: # type: ignore[no-untyped-def]
|
|
317
|
+
if lexer is None and self._fallback_lexer is None:
|
|
318
|
+
return
|
|
319
|
+
self._fallback_lexer = lexer
|
|
320
|
+
self._build_highlight_map()
|
|
321
|
+
self.refresh()
|
|
322
|
+
|
|
323
|
+
def _build_highlight_map(self) -> None:
|
|
324
|
+
if self._fallback_lexer is None or self.language is not None:
|
|
325
|
+
super()._build_highlight_map()
|
|
326
|
+
return
|
|
327
|
+
self._line_cache.clear()
|
|
328
|
+
self._highlights.clear()
|
|
329
|
+
try:
|
|
330
|
+
self._highlights.update(pygments_highlights(self.text, self._fallback_lexer))
|
|
331
|
+
except Exception:
|
|
332
|
+
pass # never let coloring break editing
|
|
333
|
+
|
|
303
334
|
def action_copy(self) -> None:
|
|
304
335
|
"""Copy selected text, or the current line when nothing is selected (VS Code behavior)."""
|
|
305
336
|
selected = self.selected_text
|
|
@@ -348,6 +379,11 @@ class CodeTextArea(TextArea):
|
|
|
348
379
|
event.stop()
|
|
349
380
|
return
|
|
350
381
|
|
|
382
|
+
if self._handle_pairs(event):
|
|
383
|
+
event.prevent_default()
|
|
384
|
+
event.stop()
|
|
385
|
+
return
|
|
386
|
+
|
|
351
387
|
if event.key == "enter":
|
|
352
388
|
row, col = self.cursor_location
|
|
353
389
|
line_before = self.document.get_line(row)[:col]
|
|
@@ -369,6 +405,53 @@ class CodeTextArea(TextArea):
|
|
|
369
405
|
|
|
370
406
|
await super()._on_key(event)
|
|
371
407
|
|
|
408
|
+
def _handle_pairs(self, event: events.Key) -> bool:
|
|
409
|
+
"""Auto-close brackets/quotes, step over closers, delete empty pairs. True if handled."""
|
|
410
|
+
char = event.character or ""
|
|
411
|
+
selection = self.selection
|
|
412
|
+
has_selection = selection.start != selection.end
|
|
413
|
+
|
|
414
|
+
if has_selection:
|
|
415
|
+
if char not in PAIRS:
|
|
416
|
+
return False
|
|
417
|
+
# Wrap the selection: select `abc`, type ( → (abc), still selected.
|
|
418
|
+
start, end = sorted((selection.start, selection.end))
|
|
419
|
+
inner = self.selected_text
|
|
420
|
+
self.replace(char + inner + PAIRS[char], start, end)
|
|
421
|
+
end_col = end[1] + 1 if start[0] == end[0] else end[1]
|
|
422
|
+
self.selection = Selection((start[0], start[1] + 1), (end[0], end_col))
|
|
423
|
+
return True
|
|
424
|
+
|
|
425
|
+
row, col = self.cursor_location
|
|
426
|
+
line = self.document.get_line(row)
|
|
427
|
+
|
|
428
|
+
if event.key == "backspace":
|
|
429
|
+
span = plan_backspace(line, col)
|
|
430
|
+
if span is None:
|
|
431
|
+
return False
|
|
432
|
+
self.delete((row, span[0]), (row, span[1]))
|
|
433
|
+
return True
|
|
434
|
+
|
|
435
|
+
if event.key == "enter":
|
|
436
|
+
unit = "\t" if line.startswith("\t") else " "
|
|
437
|
+
planned = plan_enter(line, col, unit)
|
|
438
|
+
if planned is None:
|
|
439
|
+
return False
|
|
440
|
+
text, offset = planned
|
|
441
|
+
self.insert(text)
|
|
442
|
+
self.move_cursor((row + 1, offset - 1))
|
|
443
|
+
return True
|
|
444
|
+
|
|
445
|
+
if char in PAIRS or char in CLOSERS:
|
|
446
|
+
edit = plan_typed(char, line, col, self.language)
|
|
447
|
+
if edit is None:
|
|
448
|
+
return False
|
|
449
|
+
if edit.text:
|
|
450
|
+
self.replace(edit.text, (row, edit.start), (row, edit.end))
|
|
451
|
+
self.move_cursor((row, edit.cursor))
|
|
452
|
+
return True
|
|
453
|
+
return False
|
|
454
|
+
|
|
372
455
|
|
|
373
456
|
class FilteredDirectoryTree(DirectoryTree):
|
|
374
457
|
"""DirectoryTree that hides dotfiles and noisy build/cache folders by default,
|
|
@@ -482,7 +565,7 @@ class TermCodeApp(App[None]):
|
|
|
482
565
|
"""Lightweight VS Code-style terminal editor and runner for all major languages."""
|
|
483
566
|
|
|
484
567
|
CSS_PATH = "styles.tcss"
|
|
485
|
-
TITLE = "
|
|
568
|
+
TITLE = "TmCode"
|
|
486
569
|
ENABLE_COMMAND_PALETTE = False
|
|
487
570
|
|
|
488
571
|
BINDINGS = [
|
|
@@ -543,6 +626,9 @@ class TermCodeApp(App[None]):
|
|
|
543
626
|
self.output_visible: bool = True
|
|
544
627
|
self.format_on_save: bool = True
|
|
545
628
|
self._recent_store: Path | None = recent_store
|
|
629
|
+
# Set when the user picks "Update now"; cli.main runs the update after exit.
|
|
630
|
+
self.update_to: str | None = None
|
|
631
|
+
self.install_kind: InstallKind = detect_install()
|
|
546
632
|
self._recent_folders: list[Path] = []
|
|
547
633
|
self._completion_editor: CodeTextArea | None = None
|
|
548
634
|
self._completion_prefix: str = ""
|
|
@@ -639,7 +725,7 @@ class TermCodeApp(App[None]):
|
|
|
639
725
|
with Vertical(id="welcome-card"):
|
|
640
726
|
yield Static(
|
|
641
727
|
Text.assemble(
|
|
642
|
-
("
|
|
728
|
+
("tmcode", f"bold {theme.TEXT}"),
|
|
643
729
|
(f" {__version__}", theme.FAINT),
|
|
644
730
|
),
|
|
645
731
|
id="welcome-title",
|
|
@@ -666,7 +752,7 @@ class TermCodeApp(App[None]):
|
|
|
666
752
|
markup=False,
|
|
667
753
|
)
|
|
668
754
|
yield Static(
|
|
669
|
-
"Run
|
|
755
|
+
"Run tmcode inside a project folder to skip this screen.",
|
|
670
756
|
id="welcome-tip",
|
|
671
757
|
markup=False,
|
|
672
758
|
)
|
|
@@ -741,6 +827,8 @@ class TermCodeApp(App[None]):
|
|
|
741
827
|
self.query_one("#find-bar").display = False
|
|
742
828
|
self._set_run_state("idle")
|
|
743
829
|
self._refresh_recent_list()
|
|
830
|
+
if not self.is_headless:
|
|
831
|
+
self.run_worker(self._check_for_update, thread=True, group="update-check", exit_on_error=False)
|
|
744
832
|
|
|
745
833
|
if self.workspace_root is not None:
|
|
746
834
|
record_recent_folder(self.workspace_root, store_path=self._recent_store)
|
|
@@ -807,9 +895,13 @@ class TermCodeApp(App[None]):
|
|
|
807
895
|
def _apply_editor_language(self, editor: CodeTextArea, path: Path | None) -> None:
|
|
808
896
|
wanted = editor_language_for_path(path)
|
|
809
897
|
if wanted and wanted in editor.available_languages:
|
|
898
|
+
editor.set_fallback_lexer(None)
|
|
810
899
|
editor.language = wanted
|
|
811
900
|
else:
|
|
812
901
|
editor.language = None
|
|
902
|
+
# No tree-sitter grammar: color it with Pygments (hundreds of languages).
|
|
903
|
+
lexer = pygments_lexer_for(path.name, editor.text) if path is not None else None
|
|
904
|
+
editor.set_fallback_lexer(lexer)
|
|
813
905
|
|
|
814
906
|
def _sync_buffer_from_editor(self, pane_id: str) -> None:
|
|
815
907
|
pane = self._pane_for_id(pane_id)
|
|
@@ -869,6 +961,7 @@ class TermCodeApp(App[None]):
|
|
|
869
961
|
self._suppress_dirty = True
|
|
870
962
|
try:
|
|
871
963
|
if buf is None:
|
|
964
|
+
editor.set_fallback_lexer(None)
|
|
872
965
|
editor.text = ""
|
|
873
966
|
editor.language = None
|
|
874
967
|
else:
|
|
@@ -1657,7 +1750,7 @@ class TermCodeApp(App[None]):
|
|
|
1657
1750
|
return True
|
|
1658
1751
|
|
|
1659
1752
|
def action_open_shell(self) -> None:
|
|
1660
|
-
"""Ctrl+T: open the user's own shell; `exit` comes back to
|
|
1753
|
+
"""Ctrl+T: open the user's own shell; `exit` comes back to TmCode."""
|
|
1661
1754
|
if not self._on_main_screen():
|
|
1662
1755
|
return
|
|
1663
1756
|
if self.runner.is_running:
|
|
@@ -1669,7 +1762,7 @@ class TermCodeApp(App[None]):
|
|
|
1669
1762
|
|
|
1670
1763
|
def _shell() -> None:
|
|
1671
1764
|
self._tty_write(
|
|
1672
|
-
f"\x1b[2J\x1b[H\x1b[
|
|
1765
|
+
f"\x1b[2J\x1b[H\x1b[2mTmCode is paused. You're in {cwd}. "
|
|
1673
1766
|
"Type exit to come back.\x1b[0m\n"
|
|
1674
1767
|
)
|
|
1675
1768
|
try:
|
|
@@ -2220,6 +2313,40 @@ class TermCodeApp(App[None]):
|
|
|
2220
2313
|
self.output_history = ""
|
|
2221
2314
|
self.query_one("#output-log", CodeTextArea).load_text("")
|
|
2222
2315
|
|
|
2316
|
+
# ---------- update check ----------
|
|
2317
|
+
|
|
2318
|
+
def _update_state_path(self) -> Path:
|
|
2319
|
+
if self._recent_store is not None:
|
|
2320
|
+
return self._recent_store.parent / "update.json"
|
|
2321
|
+
return default_state_path()
|
|
2322
|
+
|
|
2323
|
+
def _check_for_update(self) -> None:
|
|
2324
|
+
"""Runs in a thread at startup; network at most once a day, silent on failure."""
|
|
2325
|
+
latest = check_for_update(__version__, self.install_kind, self._update_state_path())
|
|
2326
|
+
if latest:
|
|
2327
|
+
self.call_from_thread(self._prompt_update, latest)
|
|
2328
|
+
|
|
2329
|
+
def _prompt_update(self, latest: str) -> None:
|
|
2330
|
+
how = {
|
|
2331
|
+
InstallKind.BINARY: "Update now downloads it and closes TmCode.",
|
|
2332
|
+
InstallKind.PIPX: "Update now runs pipx upgrade tmcode and closes TmCode.",
|
|
2333
|
+
InstallKind.UV: "Update now runs uv tool upgrade tmcode and closes TmCode.",
|
|
2334
|
+
InstallKind.PIP: "Update now runs pip install --upgrade tmcode and closes TmCode.",
|
|
2335
|
+
}.get(self.install_kind, "")
|
|
2336
|
+
|
|
2337
|
+
def _chosen(choice: str | None) -> None:
|
|
2338
|
+
if choice == "update":
|
|
2339
|
+
def _go() -> None:
|
|
2340
|
+
self.update_to = latest
|
|
2341
|
+
self._shutdown_and_exit()
|
|
2342
|
+
|
|
2343
|
+
self._guard_all_unsaved(_go)
|
|
2344
|
+
elif choice == "skip-version":
|
|
2345
|
+
skip_version(self._update_state_path(), latest)
|
|
2346
|
+
self.notify(f"Skipped {latest}. You'll be asked again when a newer version is out.")
|
|
2347
|
+
|
|
2348
|
+
self.push_screen(UpdateModal(latest, __version__, how), _chosen)
|
|
2349
|
+
|
|
2223
2350
|
def action_request_quit(self) -> None:
|
|
2224
2351
|
if not self._on_main_screen():
|
|
2225
2352
|
return
|
termcode/cli.py
CHANGED
|
@@ -8,6 +8,7 @@ import sys
|
|
|
8
8
|
|
|
9
9
|
from termcode import __version__
|
|
10
10
|
from termcode.app import TermCodeApp
|
|
11
|
+
from termcode.update import detect_install, run_update
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def _is_home(path: Path) -> bool:
|
|
@@ -34,7 +35,7 @@ def parse_cli_target(arg: str | None, cwd: Path | None = None) -> tuple[Path | N
|
|
|
34
35
|
target = base / target
|
|
35
36
|
|
|
36
37
|
if not target.exists():
|
|
37
|
-
raise SystemExit(f"
|
|
38
|
+
raise SystemExit(f"tmcode: path not found: {arg}")
|
|
38
39
|
|
|
39
40
|
resolved = target.resolve()
|
|
40
41
|
if resolved.is_dir():
|
|
@@ -44,8 +45,8 @@ def parse_cli_target(arg: str | None, cwd: Path | None = None) -> tuple[Path | N
|
|
|
44
45
|
|
|
45
46
|
def main(argv: list[str] | None = None) -> int:
|
|
46
47
|
parser = argparse.ArgumentParser(
|
|
47
|
-
prog="
|
|
48
|
-
description="
|
|
48
|
+
prog="tmcode",
|
|
49
|
+
description="TmCode: a lightweight terminal code editor. Edit and run code in any language.",
|
|
49
50
|
)
|
|
50
51
|
parser.add_argument(
|
|
51
52
|
"path",
|
|
@@ -53,15 +54,24 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
53
54
|
default=None,
|
|
54
55
|
help="Optional folder or file to open (from home directory, opens the Home folder selector; from any other folder, opens it directly).",
|
|
55
56
|
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--update",
|
|
59
|
+
action="store_true",
|
|
60
|
+
help="Update TmCode to the latest version and exit.",
|
|
61
|
+
)
|
|
56
62
|
parser.add_argument(
|
|
57
63
|
"--version",
|
|
58
64
|
action="version",
|
|
59
65
|
version=f"%(prog)s {__version__}",
|
|
60
66
|
)
|
|
61
67
|
args = parser.parse_args(argv)
|
|
68
|
+
if args.update:
|
|
69
|
+
return run_update(detect_install())
|
|
62
70
|
workspace_root, initial_file = parse_cli_target(args.path)
|
|
63
71
|
app = TermCodeApp(workspace_root=workspace_root, initial_file=initial_file)
|
|
64
72
|
app.run()
|
|
73
|
+
if app.update_to:
|
|
74
|
+
return run_update(app.install_kind, app.update_to)
|
|
65
75
|
return 0
|
|
66
76
|
|
|
67
77
|
|
termcode/commands.py
CHANGED
termcode/highlighting.py
CHANGED
|
@@ -59,3 +59,129 @@ def register_extra_languages(text_area: TextArea) -> None:
|
|
|
59
59
|
text_area.register_language("cpp", _CPP_LANG, _CPP_QUERY)
|
|
60
60
|
except Exception:
|
|
61
61
|
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---------- Pygments fallback: colors for ~500 more languages ----------
|
|
65
|
+
#
|
|
66
|
+
# Tree-sitter grammars cover the common languages. For everything else
|
|
67
|
+
# (Kotlin, Swift, Haskell, Elixir, Zig, Dockerfile, ...) the editor asks
|
|
68
|
+
# Pygments, which ships with TmCode already, and maps its tokens to the
|
|
69
|
+
# same theme colors.
|
|
70
|
+
|
|
71
|
+
_MAX_FALLBACK_CHARS = 400_000 # very large files stay plain for speed
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# Template languages Pygments knows under another name.
|
|
75
|
+
_LEXER_ALIASES = {
|
|
76
|
+
".ejs": "html+erb", # <% %> tags, same syntax as ERB
|
|
77
|
+
".njk": "html+jinja", # Nunjucks is Jinja-compatible
|
|
78
|
+
".nunjucks": "html+jinja",
|
|
79
|
+
".jinja": "html+jinja",
|
|
80
|
+
".jinja2": "html+jinja",
|
|
81
|
+
".j2": "html+jinja",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def pygments_lexer_for(name: str, text: str = ""): # type: ignore[no-untyped-def]
|
|
86
|
+
"""A Pygments lexer for this filename (or a #! line), or None for plain text."""
|
|
87
|
+
try:
|
|
88
|
+
from pygments.lexers import get_lexer_for_filename, guess_lexer
|
|
89
|
+
from pygments.util import ClassNotFound
|
|
90
|
+
except ImportError:
|
|
91
|
+
return None
|
|
92
|
+
head = text[:2048]
|
|
93
|
+
options = {"stripnl": False, "stripall": False, "ensurenl": False}
|
|
94
|
+
lexer = None
|
|
95
|
+
alias = _LEXER_ALIASES.get("." + name.rsplit(".", 1)[-1].lower()) if "." in name else None
|
|
96
|
+
if alias:
|
|
97
|
+
try:
|
|
98
|
+
from pygments.lexers import get_lexer_by_name
|
|
99
|
+
|
|
100
|
+
return get_lexer_by_name(alias, **options)
|
|
101
|
+
except Exception:
|
|
102
|
+
pass
|
|
103
|
+
try:
|
|
104
|
+
lexer = get_lexer_for_filename(name, head, **options)
|
|
105
|
+
except ClassNotFound:
|
|
106
|
+
if head.startswith("#!"):
|
|
107
|
+
try:
|
|
108
|
+
lexer = guess_lexer(head, **options)
|
|
109
|
+
except ClassNotFound:
|
|
110
|
+
lexer = None
|
|
111
|
+
except Exception:
|
|
112
|
+
lexer = None
|
|
113
|
+
if lexer is None or lexer.name in ("Text only", "Text output"):
|
|
114
|
+
return None
|
|
115
|
+
return lexer
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _token_map(): # type: ignore[no-untyped-def]
|
|
119
|
+
from pygments.token import (
|
|
120
|
+
Comment, Generic, Keyword, Literal, Name, Number, Operator, String,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
return [
|
|
124
|
+
(Comment, "comment"),
|
|
125
|
+
(String.Doc, "string.documentation"),
|
|
126
|
+
(String, "string"),
|
|
127
|
+
(Number, "number"),
|
|
128
|
+
(Keyword.Constant, "constant.builtin"),
|
|
129
|
+
(Keyword.Type, "type.builtin"),
|
|
130
|
+
(Keyword, "keyword"),
|
|
131
|
+
(Operator.Word, "keyword.operator"),
|
|
132
|
+
(Operator, "operator"),
|
|
133
|
+
(Name.Builtin.Pseudo, "constant.builtin"),
|
|
134
|
+
(Name.Builtin, "function.call"),
|
|
135
|
+
(Name.Function, "function"),
|
|
136
|
+
(Name.Decorator, "function"),
|
|
137
|
+
(Name.Class, "class"),
|
|
138
|
+
(Name.Namespace, "type"),
|
|
139
|
+
(Name.Exception, "type"),
|
|
140
|
+
(Name.Constant, "constant.builtin"),
|
|
141
|
+
(Name.Tag, "tag"),
|
|
142
|
+
(Name.Attribute, "css.property"),
|
|
143
|
+
(Name.Label, "json.label"),
|
|
144
|
+
(Generic.Heading, "heading"),
|
|
145
|
+
(Generic.Subheading, "heading"),
|
|
146
|
+
(Generic.Strong, "bold"),
|
|
147
|
+
(Generic.Emph, "italic"),
|
|
148
|
+
(Generic.Inserted, "string"),
|
|
149
|
+
(Generic.Deleted, "number"),
|
|
150
|
+
(Literal, "string"),
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
_NAME_CACHE: dict[object, str | None] = {}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _highlight_name(token_type) -> str | None: # type: ignore[no-untyped-def]
|
|
158
|
+
if token_type in _NAME_CACHE:
|
|
159
|
+
return _NAME_CACHE[token_type]
|
|
160
|
+
name = None
|
|
161
|
+
for parent, highlight in _token_map():
|
|
162
|
+
if token_type in parent:
|
|
163
|
+
name = highlight
|
|
164
|
+
break
|
|
165
|
+
_NAME_CACHE[token_type] = name
|
|
166
|
+
return name
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def pygments_highlights(text: str, lexer) -> dict[int, list[tuple[int, int, str]]]: # type: ignore[no-untyped-def]
|
|
170
|
+
"""Per-line (start_byte, end_byte, highlight_name) ranges, like TextArea's tree-sitter map."""
|
|
171
|
+
result: dict[int, list[tuple[int, int, str]]] = {}
|
|
172
|
+
if len(text) > _MAX_FALLBACK_CHARS:
|
|
173
|
+
return result
|
|
174
|
+
row = 0
|
|
175
|
+
col = 0 # byte column within the current line
|
|
176
|
+
for _index, token_type, value in lexer.get_tokens_unprocessed(text):
|
|
177
|
+
name = _highlight_name(token_type)
|
|
178
|
+
parts = value.split("\n")
|
|
179
|
+
for i, part in enumerate(parts):
|
|
180
|
+
if i:
|
|
181
|
+
row += 1
|
|
182
|
+
col = 0
|
|
183
|
+
size = len(part.encode("utf-8"))
|
|
184
|
+
if name and size:
|
|
185
|
+
result.setdefault(row, []).append((col, col + size, name))
|
|
186
|
+
col += size
|
|
187
|
+
return result
|
termcode/modals.py
CHANGED
|
@@ -266,6 +266,46 @@ class ConfirmModal(ModalScreen[bool]):
|
|
|
266
266
|
self.dismiss(False)
|
|
267
267
|
|
|
268
268
|
|
|
269
|
+
class UpdateModal(ModalScreen[str]):
|
|
270
|
+
"""'A new version is available' prompt: update / skip / skip until next version."""
|
|
271
|
+
|
|
272
|
+
BINDINGS = [
|
|
273
|
+
Binding("escape", "skip", "Skip", show=False),
|
|
274
|
+
]
|
|
275
|
+
|
|
276
|
+
def __init__(self, latest: str, current: str, how: str) -> None:
|
|
277
|
+
super().__init__()
|
|
278
|
+
self._latest = latest
|
|
279
|
+
self._current = current
|
|
280
|
+
self._how = how
|
|
281
|
+
|
|
282
|
+
def compose(self) -> ComposeResult:
|
|
283
|
+
with Vertical(id="update-dialog", classes="modal-box"):
|
|
284
|
+
yield Label(f"TmCode {self._latest} is available", classes="modal-title")
|
|
285
|
+
yield Label(
|
|
286
|
+
f"You have {self._current}. {self._how}",
|
|
287
|
+
classes="modal-subtitle",
|
|
288
|
+
)
|
|
289
|
+
with Horizontal(classes="modal-buttons"):
|
|
290
|
+
yield Button("Update now", variant="primary", id="update-now-btn")
|
|
291
|
+
yield Button("Skip", id="update-skip-btn")
|
|
292
|
+
yield Button("Skip until next version", id="update-skip-version-btn")
|
|
293
|
+
|
|
294
|
+
def on_mount(self) -> None:
|
|
295
|
+
self.query_one("#update-now-btn", Button).focus()
|
|
296
|
+
|
|
297
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
298
|
+
self.dismiss(
|
|
299
|
+
{
|
|
300
|
+
"update-now-btn": "update",
|
|
301
|
+
"update-skip-version-btn": "skip-version",
|
|
302
|
+
}.get(event.button.id or "", "skip")
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def action_skip(self) -> None:
|
|
306
|
+
self.dismiss("skip")
|
|
307
|
+
|
|
308
|
+
|
|
269
309
|
class UnsavedChangesModal(ModalScreen[str]):
|
|
270
310
|
"""Three-way confirmation when leaving a buffer with unsaved changes."""
|
|
271
311
|
|
termcode/pairs.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Auto-closing brackets and quotes, VS Code style (pure helpers, no UI).
|
|
2
|
+
|
|
3
|
+
- Typing ( [ { " ' ` inserts the closing partner and puts the cursor between.
|
|
4
|
+
- Typing a closer when the same closer is next just steps over it.
|
|
5
|
+
- Backspace inside an empty pair deletes both halves.
|
|
6
|
+
- Enter between { } (or ( ) / [ ]) opens an indented block.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
PAIRS = {"(": ")", "[": "]", "{": "}", '"': '"', "'": "'", "`": "`"}
|
|
14
|
+
CLOSERS = {")", "]", "}"}
|
|
15
|
+
QUOTES = {'"', "'", "`"}
|
|
16
|
+
|
|
17
|
+
# Auto-close only when the next character is one of these (or end of line),
|
|
18
|
+
# so `(|value` doesn't turn into `()value`.
|
|
19
|
+
_OK_BEFORE = set(")]};,:.") | {" ", "\t", ""}
|
|
20
|
+
|
|
21
|
+
_PY_STRING_PREFIXES = {"f", "r", "b", "u", "rb", "br", "fr", "rf"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class LineEdit:
|
|
26
|
+
"""Replace line[start:end] with text, then put the cursor at column `cursor`."""
|
|
27
|
+
|
|
28
|
+
start: int
|
|
29
|
+
end: int
|
|
30
|
+
text: str
|
|
31
|
+
cursor: int
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _word_before(line: str, col: int) -> str:
|
|
35
|
+
i = col
|
|
36
|
+
while i > 0 and (line[i - 1].isalnum() or line[i - 1] == "_"):
|
|
37
|
+
i -= 1
|
|
38
|
+
return line[i:col]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _inside_string(line_before: str, quote: str) -> bool:
|
|
42
|
+
"""True if line_before has an unclosed `quote` string (odd count of unescaped quotes)."""
|
|
43
|
+
count = 0
|
|
44
|
+
escaped = False
|
|
45
|
+
for ch in line_before:
|
|
46
|
+
if escaped:
|
|
47
|
+
escaped = False
|
|
48
|
+
elif ch == "\\":
|
|
49
|
+
escaped = True
|
|
50
|
+
elif ch == quote:
|
|
51
|
+
count += 1
|
|
52
|
+
return count % 2 == 1
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def plan_typed(char: str, line: str, col: int, language: str | None) -> LineEdit | None:
|
|
56
|
+
"""What typing `char` at `col` should do, or None for normal typing."""
|
|
57
|
+
nxt = line[col : col + 1]
|
|
58
|
+
|
|
59
|
+
# Step over a closer that is already there.
|
|
60
|
+
if (char in CLOSERS or char in QUOTES) and nxt == char:
|
|
61
|
+
if char in CLOSERS or _inside_string(line[:col], char):
|
|
62
|
+
return LineEdit(col, col, "", col + 1)
|
|
63
|
+
|
|
64
|
+
if char not in PAIRS or nxt not in _OK_BEFORE:
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
if char in QUOTES:
|
|
68
|
+
if char == "'" and language == "rust":
|
|
69
|
+
return None # lifetimes: &'a, <'a>
|
|
70
|
+
if char == "`" and language not in (None, "javascript", "typescript", "markdown", "bash", "go", "sql"):
|
|
71
|
+
return None
|
|
72
|
+
word = _word_before(line, col)
|
|
73
|
+
if word and not (language == "python" and word.lower() in _PY_STRING_PREFIXES):
|
|
74
|
+
return None # don't, it's, abc" ...
|
|
75
|
+
if _inside_string(line[:col], char):
|
|
76
|
+
return None # this quote closes a string being typed
|
|
77
|
+
|
|
78
|
+
return LineEdit(col, col, char + PAIRS[char], col + 1)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def plan_backspace(line: str, col: int) -> tuple[int, int] | None:
|
|
82
|
+
"""Columns (start, end) to delete when Backspace is pressed inside an empty pair."""
|
|
83
|
+
if col <= 0 or col >= len(line):
|
|
84
|
+
return None
|
|
85
|
+
before, after = line[col - 1], line[col]
|
|
86
|
+
if PAIRS.get(before) == after:
|
|
87
|
+
return col - 1, col + 1
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def plan_enter(line: str, col: int, indent_unit: str = " ") -> tuple[str, int] | None:
|
|
92
|
+
"""Text to insert for Enter between an opener and its closer, and the cursor offset in it."""
|
|
93
|
+
if col <= 0 or col >= len(line):
|
|
94
|
+
return None
|
|
95
|
+
before, after = line[col - 1], line[col]
|
|
96
|
+
if before not in "([{" or PAIRS[before] != after:
|
|
97
|
+
return None
|
|
98
|
+
base = line[: len(line) - len(line.lstrip(" \t"))]
|
|
99
|
+
inner = base + indent_unit
|
|
100
|
+
return "\n" + inner + "\n" + base, 1 + len(inner)
|