tmcode 0.2.0__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 +3 -0
- termcode/app.py +2236 -0
- termcode/buffers.py +168 -0
- termcode/cli.py +69 -0
- termcode/commands.py +234 -0
- termcode/completions.py +205 -0
- termcode/findbar.py +258 -0
- termcode/formatting.py +365 -0
- termcode/highlighting.py +61 -0
- termcode/modals.py +431 -0
- termcode/runner.py +725 -0
- termcode/search.py +105 -0
- termcode/styles.tcss +796 -0
- termcode/theme.py +99 -0
- termcode/workspace.py +271 -0
- tmcode-0.2.0.dist-info/METADATA +128 -0
- tmcode-0.2.0.dist-info/RECORD +21 -0
- tmcode-0.2.0.dist-info/WHEEL +5 -0
- tmcode-0.2.0.dist-info/entry_points.txt +3 -0
- tmcode-0.2.0.dist-info/licenses/LICENSE +21 -0
- tmcode-0.2.0.dist-info/top_level.txt +1 -0
termcode/findbar.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Inline find / replace bar that works on whichever editor is active."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from rich.text import Text
|
|
8
|
+
from textual.app import ComposeResult
|
|
9
|
+
from textual.binding import Binding
|
|
10
|
+
from textual.containers import Horizontal, Vertical
|
|
11
|
+
from textual.widgets import Button, Input, Static, TextArea
|
|
12
|
+
from textual.widgets.text_area import Selection
|
|
13
|
+
|
|
14
|
+
from termcode import theme
|
|
15
|
+
from termcode.search import (
|
|
16
|
+
Match,
|
|
17
|
+
SearchError,
|
|
18
|
+
find_matches,
|
|
19
|
+
next_match_index,
|
|
20
|
+
replace_all,
|
|
21
|
+
replace_one,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FindBar(Vertical):
|
|
26
|
+
"""Find (Ctrl+F) and replace (Ctrl+R) for the active editor.
|
|
27
|
+
|
|
28
|
+
Enter / Down = next match, Up = previous, Esc = close.
|
|
29
|
+
In the replace field, Enter replaces the current match and moves on.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
BINDINGS = [
|
|
33
|
+
Binding("escape", "close", "Close", show=False),
|
|
34
|
+
Binding("down", "next", "Next", show=False),
|
|
35
|
+
Binding("up", "prev", "Previous", show=False),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
def __init__(self, get_editor: Callable[[], TextArea], *, id: str | None = None) -> None:
|
|
39
|
+
super().__init__(id=id)
|
|
40
|
+
self._get_editor = get_editor
|
|
41
|
+
self.case_sensitive = False
|
|
42
|
+
self.regex = False
|
|
43
|
+
self._matches: list[Match] = []
|
|
44
|
+
self._current: int | None = None
|
|
45
|
+
|
|
46
|
+
def compose(self) -> ComposeResult:
|
|
47
|
+
with Horizontal(id="find-row"):
|
|
48
|
+
yield Input(placeholder="Find", id="find-input")
|
|
49
|
+
yield Static("", id="find-count")
|
|
50
|
+
case_btn = Button("Aa", id="find-case", classes="find-btn")
|
|
51
|
+
case_btn.tooltip = "Match case"
|
|
52
|
+
yield case_btn
|
|
53
|
+
regex_btn = Button(".*", id="find-regex", classes="find-btn")
|
|
54
|
+
regex_btn.tooltip = "Use regular expression"
|
|
55
|
+
yield regex_btn
|
|
56
|
+
prev_btn = Button("↑", id="find-prev", classes="find-btn")
|
|
57
|
+
prev_btn.tooltip = "Previous match (Up)"
|
|
58
|
+
yield prev_btn
|
|
59
|
+
next_btn = Button("↓", id="find-next", classes="find-btn")
|
|
60
|
+
next_btn.tooltip = "Next match (Enter / Down)"
|
|
61
|
+
yield next_btn
|
|
62
|
+
close_btn = Button("×", id="find-close", classes="find-btn")
|
|
63
|
+
close_btn.tooltip = "Close (Esc)"
|
|
64
|
+
yield close_btn
|
|
65
|
+
with Horizontal(id="replace-row"):
|
|
66
|
+
yield Input(placeholder="Replace with", id="replace-input")
|
|
67
|
+
yield Button("Replace", id="replace-one", classes="find-btn")
|
|
68
|
+
yield Button("All", id="replace-all", classes="find-btn")
|
|
69
|
+
|
|
70
|
+
# ---- public API ----
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def is_open(self) -> bool:
|
|
74
|
+
return bool(self.display)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def query_text(self) -> str:
|
|
78
|
+
return self.query_one("#find-input", Input).value
|
|
79
|
+
|
|
80
|
+
def open(self, *, replace: bool) -> None:
|
|
81
|
+
editor = self._get_editor()
|
|
82
|
+
self.display = True
|
|
83
|
+
self.query_one("#replace-row").display = replace
|
|
84
|
+
find_input = self.query_one("#find-input", Input)
|
|
85
|
+
selected = editor.selected_text
|
|
86
|
+
if selected and "\n" not in selected:
|
|
87
|
+
find_input.value = selected
|
|
88
|
+
find_input.focus()
|
|
89
|
+
find_input.select_all()
|
|
90
|
+
self._search(from_cursor=True)
|
|
91
|
+
|
|
92
|
+
def action_close(self) -> None:
|
|
93
|
+
self.display = False
|
|
94
|
+
self._matches = []
|
|
95
|
+
self._current = None
|
|
96
|
+
self._get_editor().focus()
|
|
97
|
+
|
|
98
|
+
def action_next(self) -> None:
|
|
99
|
+
self._step(backwards=False)
|
|
100
|
+
|
|
101
|
+
def action_prev(self) -> None:
|
|
102
|
+
self._step(backwards=True)
|
|
103
|
+
|
|
104
|
+
# ---- events ----
|
|
105
|
+
|
|
106
|
+
def on_input_changed(self, event: Input.Changed) -> None:
|
|
107
|
+
if event.input.id == "find-input":
|
|
108
|
+
event.stop()
|
|
109
|
+
self._search(from_cursor=True)
|
|
110
|
+
|
|
111
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
112
|
+
event.stop()
|
|
113
|
+
if event.input.id == "find-input":
|
|
114
|
+
self._step(backwards=False)
|
|
115
|
+
elif event.input.id == "replace-input":
|
|
116
|
+
self.replace_current()
|
|
117
|
+
|
|
118
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
119
|
+
event.stop()
|
|
120
|
+
bid = event.button.id
|
|
121
|
+
if bid == "find-case":
|
|
122
|
+
self.case_sensitive = not self.case_sensitive
|
|
123
|
+
event.button.set_class(self.case_sensitive, "-on")
|
|
124
|
+
self._search(from_cursor=True)
|
|
125
|
+
elif bid == "find-regex":
|
|
126
|
+
self.regex = not self.regex
|
|
127
|
+
event.button.set_class(self.regex, "-on")
|
|
128
|
+
self._search(from_cursor=True)
|
|
129
|
+
elif bid == "find-prev":
|
|
130
|
+
self._step(backwards=True)
|
|
131
|
+
elif bid == "find-next":
|
|
132
|
+
self._step(backwards=False)
|
|
133
|
+
elif bid == "find-close":
|
|
134
|
+
self.action_close()
|
|
135
|
+
elif bid == "replace-one":
|
|
136
|
+
self.replace_current()
|
|
137
|
+
elif bid == "replace-all":
|
|
138
|
+
self.replace_everything()
|
|
139
|
+
|
|
140
|
+
# ---- search core ----
|
|
141
|
+
|
|
142
|
+
def _selection_offsets(self, editor: TextArea) -> tuple[int, int]:
|
|
143
|
+
doc = editor.document
|
|
144
|
+
start, end = sorted((editor.selection.start, editor.selection.end))
|
|
145
|
+
return doc.get_index_from_location(start), doc.get_index_from_location(end)
|
|
146
|
+
|
|
147
|
+
def _recompute(self) -> bool:
|
|
148
|
+
editor = self._get_editor()
|
|
149
|
+
try:
|
|
150
|
+
self._matches = find_matches(
|
|
151
|
+
editor.text,
|
|
152
|
+
self.query_text,
|
|
153
|
+
case_sensitive=self.case_sensitive,
|
|
154
|
+
regex=self.regex,
|
|
155
|
+
)
|
|
156
|
+
except SearchError:
|
|
157
|
+
self._matches = []
|
|
158
|
+
self._current = None
|
|
159
|
+
self._show_count(error="Invalid regex")
|
|
160
|
+
return False
|
|
161
|
+
return True
|
|
162
|
+
|
|
163
|
+
def _search(self, *, from_cursor: bool) -> None:
|
|
164
|
+
if not self._recompute():
|
|
165
|
+
return
|
|
166
|
+
editor = self._get_editor()
|
|
167
|
+
start, _ = self._selection_offsets(editor)
|
|
168
|
+
self._current = next_match_index(self._matches, start) if from_cursor else None
|
|
169
|
+
self._select_current()
|
|
170
|
+
|
|
171
|
+
def _step(self, *, backwards: bool) -> None:
|
|
172
|
+
if not self._recompute():
|
|
173
|
+
return
|
|
174
|
+
editor = self._get_editor()
|
|
175
|
+
start, end = self._selection_offsets(editor)
|
|
176
|
+
cursor = start if backwards else end
|
|
177
|
+
self._current = next_match_index(self._matches, cursor, backwards=backwards)
|
|
178
|
+
self._select_current()
|
|
179
|
+
|
|
180
|
+
def _select_current(self) -> None:
|
|
181
|
+
if self._current is None or not self._matches:
|
|
182
|
+
self._show_count()
|
|
183
|
+
return
|
|
184
|
+
editor = self._get_editor()
|
|
185
|
+
doc = editor.document
|
|
186
|
+
s, e = self._matches[self._current]
|
|
187
|
+
editor.selection = Selection(doc.get_location_from_index(s), doc.get_location_from_index(e))
|
|
188
|
+
editor.scroll_cursor_visible(center=True)
|
|
189
|
+
self._show_count()
|
|
190
|
+
|
|
191
|
+
def _show_count(self, *, error: str | None = None) -> None:
|
|
192
|
+
label = self.query_one("#find-count", Static)
|
|
193
|
+
if error:
|
|
194
|
+
label.update(Text(error, style=theme.FAIL))
|
|
195
|
+
elif not self.query_text:
|
|
196
|
+
label.update("")
|
|
197
|
+
elif not self._matches:
|
|
198
|
+
label.update(Text("No results", style=theme.FAIL))
|
|
199
|
+
else:
|
|
200
|
+
pos = (self._current or 0) + 1
|
|
201
|
+
label.update(Text(f"{pos} of {len(self._matches)}", style=theme.MUTED))
|
|
202
|
+
|
|
203
|
+
# ---- replace ----
|
|
204
|
+
|
|
205
|
+
def replace_current(self) -> None:
|
|
206
|
+
if not self._recompute() or not self._matches:
|
|
207
|
+
self._show_count()
|
|
208
|
+
return
|
|
209
|
+
editor = self._get_editor()
|
|
210
|
+
start, end = self._selection_offsets(editor)
|
|
211
|
+
if (start, end) not in self._matches:
|
|
212
|
+
# Nothing selected yet: first jump to a match, replace on the next press.
|
|
213
|
+
self._step(backwards=False)
|
|
214
|
+
return
|
|
215
|
+
doc = editor.document
|
|
216
|
+
matched = editor.text[start:end]
|
|
217
|
+
try:
|
|
218
|
+
new = replace_one(
|
|
219
|
+
matched,
|
|
220
|
+
self.query_text,
|
|
221
|
+
self.query_one("#replace-input", Input).value,
|
|
222
|
+
case_sensitive=self.case_sensitive,
|
|
223
|
+
regex=self.regex,
|
|
224
|
+
)
|
|
225
|
+
except SearchError as exc:
|
|
226
|
+
self._show_count(error=str(exc))
|
|
227
|
+
return
|
|
228
|
+
editor.replace(new, doc.get_location_from_index(start), doc.get_location_from_index(end))
|
|
229
|
+
after = start + len(new)
|
|
230
|
+
editor.selection = Selection.cursor(editor.document.get_location_from_index(after))
|
|
231
|
+
self._step(backwards=False)
|
|
232
|
+
|
|
233
|
+
def replace_everything(self) -> None:
|
|
234
|
+
editor = self._get_editor()
|
|
235
|
+
try:
|
|
236
|
+
new_text, count = replace_all(
|
|
237
|
+
editor.text,
|
|
238
|
+
self.query_text,
|
|
239
|
+
self.query_one("#replace-input", Input).value,
|
|
240
|
+
case_sensitive=self.case_sensitive,
|
|
241
|
+
regex=self.regex,
|
|
242
|
+
)
|
|
243
|
+
except SearchError as exc:
|
|
244
|
+
self._show_count(error=str(exc))
|
|
245
|
+
return
|
|
246
|
+
if count == 0:
|
|
247
|
+
self._show_count()
|
|
248
|
+
return
|
|
249
|
+
cursor = editor.cursor_location
|
|
250
|
+
# One edit over the whole document, so a single Ctrl+Z undoes it.
|
|
251
|
+
editor.replace(new_text, (0, 0), editor.document.end)
|
|
252
|
+
row = min(cursor[0], editor.document.line_count - 1)
|
|
253
|
+
col = min(cursor[1], len(editor.document.get_line(row)))
|
|
254
|
+
editor.selection = Selection.cursor((row, col))
|
|
255
|
+
self._recompute()
|
|
256
|
+
self._current = None
|
|
257
|
+
self.app.notify(f"Replaced {count} occurrence{'s' if count != 1 else ''}")
|
|
258
|
+
self._show_count()
|
termcode/formatting.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Format-on-save: fix indentation before a file is saved (and so before it runs).
|
|
2
|
+
|
|
3
|
+
If a real formatter is installed (black/ruff, clang-format, prettier, gofmt,
|
|
4
|
+
rustfmt) it is used. Otherwise a built-in, dependency-free indenter runs:
|
|
5
|
+
|
|
6
|
+
* Python - rebuilds indentation as 4 spaces per block using the tokenizer,
|
|
7
|
+
so meaning never changes (levels map 1:1).
|
|
8
|
+
* braces - C, C++, Java, JS/TS, Go, Rust, CSS: indent by bracket depth,
|
|
9
|
+
ignoring brackets inside strings and comments.
|
|
10
|
+
* JSON - pretty-printed with 4 spaces.
|
|
11
|
+
* other - trailing whitespace removed, final newline added.
|
|
12
|
+
|
|
13
|
+
Built-in results are only applied if they change nothing but whitespace.
|
|
14
|
+
Code that can't be parsed (syntax error, unbalanced braces) is left as is and
|
|
15
|
+
the reason is reported, so saving is never blocked.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
import io
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import tokenize
|
|
28
|
+
|
|
29
|
+
INDENT = " "
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class FormatResult:
|
|
34
|
+
text: str
|
|
35
|
+
changed: bool
|
|
36
|
+
tool: str | None = None
|
|
37
|
+
error: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class FormatError(ValueError):
|
|
41
|
+
"""The code couldn't be understood well enough to re-indent safely."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ---------------------------------------------------------------- external tools
|
|
45
|
+
|
|
46
|
+
_EXTERNAL: dict[str, list[tuple[str, Callable[[str], list[str]]]]] = {
|
|
47
|
+
"python": [
|
|
48
|
+
("ruff", lambda fn: ["format", "--stdin-filename", fn, "-"]),
|
|
49
|
+
("black", lambda fn: ["-q", "--stdin-filename", fn, "-"]),
|
|
50
|
+
],
|
|
51
|
+
"c": [("clang-format", lambda fn: [f"--assume-filename={fn}"])],
|
|
52
|
+
"cpp": [("clang-format", lambda fn: [f"--assume-filename={fn}"])],
|
|
53
|
+
"java": [("clang-format", lambda fn: [f"--assume-filename={fn}"])],
|
|
54
|
+
"javascript": [("prettier", lambda fn: ["--stdin-filepath", fn])],
|
|
55
|
+
"typescript": [("prettier", lambda fn: ["--stdin-filepath", fn])],
|
|
56
|
+
"css": [("prettier", lambda fn: ["--stdin-filepath", fn])],
|
|
57
|
+
"go": [("gofmt", lambda fn: [])],
|
|
58
|
+
"rust": [("rustfmt", lambda fn: ["--emit", "stdout", "--edition", "2021"])],
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run_external(
|
|
63
|
+
text: str,
|
|
64
|
+
language: str,
|
|
65
|
+
filename: str,
|
|
66
|
+
which: Callable[[str], str | None],
|
|
67
|
+
run: Callable[..., object],
|
|
68
|
+
) -> FormatResult | None:
|
|
69
|
+
for name, args in _EXTERNAL.get(language, []):
|
|
70
|
+
exe = which(name)
|
|
71
|
+
if not exe:
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
proc = run(
|
|
75
|
+
[exe, *args(filename)],
|
|
76
|
+
input=text.encode("utf-8"),
|
|
77
|
+
capture_output=True,
|
|
78
|
+
timeout=10,
|
|
79
|
+
)
|
|
80
|
+
except (OSError, subprocess.SubprocessError):
|
|
81
|
+
continue # broken install: fall through to the next option
|
|
82
|
+
rc = getattr(proc, "returncode", 1)
|
|
83
|
+
if rc != 0:
|
|
84
|
+
err = (getattr(proc, "stderr", b"") or b"").decode("utf-8", "replace").strip()
|
|
85
|
+
first = err.splitlines()[0] if err else f"{name} exited {rc}"
|
|
86
|
+
return FormatResult(text, False, name, f"{name}: {first}")
|
|
87
|
+
out = (getattr(proc, "stdout", b"") or b"").decode("utf-8", "replace")
|
|
88
|
+
return FormatResult(out, out != text, name, None)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------------------------------------------------------------- python
|
|
93
|
+
|
|
94
|
+
def _expand_leading_tabs(text: str) -> str:
|
|
95
|
+
"""Expand tabs in indentation the way Python measures them (next multiple of 8)."""
|
|
96
|
+
out = []
|
|
97
|
+
for line in text.splitlines(keepends=True):
|
|
98
|
+
stripped = line.lstrip(" \t")
|
|
99
|
+
out.append(line[: len(line) - len(stripped)].expandtabs(8) + stripped)
|
|
100
|
+
return "".join(out)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def reindent_python(text: str) -> str:
|
|
104
|
+
"""Re-indent Python to 4 spaces per block without changing its meaning."""
|
|
105
|
+
try:
|
|
106
|
+
tokens = list(tokenize.generate_tokens(io.StringIO(text).readline))
|
|
107
|
+
except TabError:
|
|
108
|
+
# Tabs mixed with spaces: measure tabs as Python does, then re-indent.
|
|
109
|
+
expanded = _expand_leading_tabs(text)
|
|
110
|
+
if expanded == text:
|
|
111
|
+
raise FormatError("inconsistent use of tabs and spaces") from None
|
|
112
|
+
return reindent_python(expanded)
|
|
113
|
+
except (tokenize.TokenError, IndentationError, SyntaxError) as exc:
|
|
114
|
+
lineno = getattr(exc, "lineno", None) or (exc.args[1][0] if len(exc.args) > 1 else "?")
|
|
115
|
+
msg = exc.msg if isinstance(exc, SyntaxError) else exc.args[0]
|
|
116
|
+
raise FormatError(f"line {lineno}: {msg}") from exc
|
|
117
|
+
|
|
118
|
+
depth = 0
|
|
119
|
+
starts: dict[int, int] = {} # row -> block depth, for first rows of statements
|
|
120
|
+
cont_owner: dict[int, int] = {} # continuation row -> its statement's first row
|
|
121
|
+
frozen: set[int] = set() # rows inside multi-line strings: leave untouched
|
|
122
|
+
keep_trailing: set[int] = set() # rows where a multi-line string begins
|
|
123
|
+
pending_comments: list[int] = []
|
|
124
|
+
at_line_start = True
|
|
125
|
+
current: int | None = None
|
|
126
|
+
|
|
127
|
+
for tok in tokens:
|
|
128
|
+
ttype = tok.type
|
|
129
|
+
if ttype == tokenize.INDENT:
|
|
130
|
+
depth += 1
|
|
131
|
+
continue
|
|
132
|
+
if ttype == tokenize.DEDENT:
|
|
133
|
+
depth -= 1
|
|
134
|
+
continue
|
|
135
|
+
if ttype in (tokenize.NEWLINE, tokenize.ENDMARKER):
|
|
136
|
+
at_line_start, current = True, None
|
|
137
|
+
if ttype == tokenize.ENDMARKER:
|
|
138
|
+
for row in pending_comments:
|
|
139
|
+
starts[row] = depth
|
|
140
|
+
continue
|
|
141
|
+
if ttype == tokenize.NL:
|
|
142
|
+
continue
|
|
143
|
+
if ttype == tokenize.COMMENT and at_line_start:
|
|
144
|
+
pending_comments.append(tok.start[0])
|
|
145
|
+
continue
|
|
146
|
+
if at_line_start:
|
|
147
|
+
at_line_start = False
|
|
148
|
+
current = tok.start[0]
|
|
149
|
+
starts[current] = depth
|
|
150
|
+
for row in pending_comments: # comments line up with the next statement
|
|
151
|
+
starts[row] = depth
|
|
152
|
+
pending_comments = []
|
|
153
|
+
if tok.start[0] != tok.end[0]:
|
|
154
|
+
keep_trailing.add(tok.start[0])
|
|
155
|
+
frozen.update(range(tok.start[0] + 1, tok.end[0] + 1))
|
|
156
|
+
for row in range(tok.start[0], tok.end[0] + 1):
|
|
157
|
+
if current is not None and row != current and row not in starts:
|
|
158
|
+
cont_owner.setdefault(row, current)
|
|
159
|
+
|
|
160
|
+
shift: dict[int, int] = {}
|
|
161
|
+
out: list[str] = []
|
|
162
|
+
for row, line in enumerate(text.splitlines(keepends=True), start=1):
|
|
163
|
+
body = line.rstrip("\r\n")
|
|
164
|
+
nl = line[len(body):]
|
|
165
|
+
if row in frozen:
|
|
166
|
+
out.append(line)
|
|
167
|
+
continue
|
|
168
|
+
stripped = body.lstrip(" \t")
|
|
169
|
+
old_indent = body[: len(body) - len(stripped)]
|
|
170
|
+
if row not in keep_trailing:
|
|
171
|
+
stripped = stripped.rstrip()
|
|
172
|
+
if not stripped:
|
|
173
|
+
out.append(nl)
|
|
174
|
+
continue
|
|
175
|
+
old_width = len(old_indent.expandtabs(8))
|
|
176
|
+
if row in starts:
|
|
177
|
+
new_indent = INDENT * starts[row]
|
|
178
|
+
shift[row] = len(new_indent) - old_width
|
|
179
|
+
elif row in cont_owner:
|
|
180
|
+
new_indent = " " * max(0, old_width + shift.get(cont_owner[row], 0))
|
|
181
|
+
else:
|
|
182
|
+
new_indent = old_indent
|
|
183
|
+
out.append(new_indent + stripped + nl)
|
|
184
|
+
return "".join(out)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---------------------------------------------------------------- brace languages
|
|
188
|
+
|
|
189
|
+
BRACE_LANGUAGES = frozenset({"c", "cpp", "java", "javascript", "typescript", "go", "rust", "css"})
|
|
190
|
+
_CASE_LANGUAGES = frozenset({"c", "cpp", "java", "javascript", "typescript", "go"})
|
|
191
|
+
_CASE_RE = re.compile(r"^(case\b.*|default\s*):")
|
|
192
|
+
_RUST_CHAR_RE = re.compile(r"'(\\.[^']*|[^'\\])'")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _scan(s: str, language: str, in_block: bool, in_raw: bool) -> tuple[int, int, bool, bool]:
|
|
196
|
+
"""Scan one line: (bracket delta, leading closers, in_block_comment, in_raw_string)."""
|
|
197
|
+
i, n = 0, len(s)
|
|
198
|
+
delta = leading = 0
|
|
199
|
+
seen_code = False
|
|
200
|
+
while i < n:
|
|
201
|
+
if in_block:
|
|
202
|
+
end = s.find("*/", i)
|
|
203
|
+
if end < 0:
|
|
204
|
+
return delta, leading, True, in_raw
|
|
205
|
+
i, in_block = end + 2, False
|
|
206
|
+
continue
|
|
207
|
+
if in_raw: # JS template literal / Go raw string spanning lines
|
|
208
|
+
end = s.find("`", i)
|
|
209
|
+
if end < 0:
|
|
210
|
+
return delta, leading, in_block, True
|
|
211
|
+
i, in_raw = end + 1, False
|
|
212
|
+
continue
|
|
213
|
+
c = s[i]
|
|
214
|
+
if c in " \t":
|
|
215
|
+
i += 1
|
|
216
|
+
continue
|
|
217
|
+
if s.startswith("//", i):
|
|
218
|
+
break
|
|
219
|
+
if s.startswith("/*", i):
|
|
220
|
+
in_block, i = True, i + 2
|
|
221
|
+
continue
|
|
222
|
+
if c == "'" and language == "rust" and not _RUST_CHAR_RE.match(s, i):
|
|
223
|
+
i += 1 # lifetime like 'a, not a char literal
|
|
224
|
+
seen_code = True
|
|
225
|
+
continue
|
|
226
|
+
if c in "\"'":
|
|
227
|
+
j = i + 1
|
|
228
|
+
while j < n and s[j] != c:
|
|
229
|
+
j += 2 if s[j] == "\\" else 1
|
|
230
|
+
i, seen_code = j + 1, True
|
|
231
|
+
continue
|
|
232
|
+
if c == "`" and language in ("javascript", "typescript", "go"):
|
|
233
|
+
end = s.find("`", i + 1)
|
|
234
|
+
if end < 0:
|
|
235
|
+
return delta, leading, in_block, True
|
|
236
|
+
i, seen_code = end + 1, True
|
|
237
|
+
continue
|
|
238
|
+
if c in "{([":
|
|
239
|
+
delta += 1
|
|
240
|
+
seen_code = True
|
|
241
|
+
elif c in "})]":
|
|
242
|
+
delta -= 1
|
|
243
|
+
if not seen_code:
|
|
244
|
+
leading += 1
|
|
245
|
+
else:
|
|
246
|
+
seen_code = True
|
|
247
|
+
i += 1
|
|
248
|
+
return delta, leading, in_block, in_raw
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def reindent_braces(text: str, language: str) -> str:
|
|
252
|
+
"""Re-indent a C-family file by bracket depth (4 spaces per level)."""
|
|
253
|
+
depth = 0
|
|
254
|
+
in_block = in_raw = False
|
|
255
|
+
case_levels: list[int] = [] # depths of switch bodies that have case labels
|
|
256
|
+
out: list[str] = []
|
|
257
|
+
for row, line in enumerate(text.splitlines(keepends=True), start=1):
|
|
258
|
+
body = line.rstrip("\r\n")
|
|
259
|
+
nl = line[len(body):]
|
|
260
|
+
stripped = body.strip()
|
|
261
|
+
if in_raw: # inside a multi-line string: copy verbatim
|
|
262
|
+
_, _, in_block, in_raw = _scan(body, language, in_block, in_raw)
|
|
263
|
+
out.append(line)
|
|
264
|
+
continue
|
|
265
|
+
if not stripped:
|
|
266
|
+
out.append(nl)
|
|
267
|
+
continue
|
|
268
|
+
if language in ("c", "cpp") and stripped.startswith("#") and not in_block:
|
|
269
|
+
out.append(stripped + nl) # preprocessor stays at column 0
|
|
270
|
+
continue
|
|
271
|
+
started_in_comment = in_block
|
|
272
|
+
delta, leading, in_block, in_raw = _scan(stripped, language, in_block, in_raw)
|
|
273
|
+
line_depth = max(depth - leading, 0)
|
|
274
|
+
|
|
275
|
+
is_case = (
|
|
276
|
+
language in _CASE_LANGUAGES and not started_in_comment and bool(_CASE_RE.match(stripped))
|
|
277
|
+
)
|
|
278
|
+
while case_levels and case_levels[-1] > line_depth:
|
|
279
|
+
case_levels.pop()
|
|
280
|
+
extra = sum(1 for lvl in case_levels if lvl < line_depth or (lvl == line_depth and not is_case))
|
|
281
|
+
if is_case and (not case_levels or case_levels[-1] != line_depth):
|
|
282
|
+
case_levels.append(line_depth)
|
|
283
|
+
|
|
284
|
+
indent = INDENT * (line_depth + extra)
|
|
285
|
+
if started_in_comment:
|
|
286
|
+
out.append(indent + (" " + stripped if stripped.startswith("*") else stripped) + nl)
|
|
287
|
+
else:
|
|
288
|
+
out.append(indent + stripped + nl)
|
|
289
|
+
depth += delta
|
|
290
|
+
if depth < 0:
|
|
291
|
+
raise FormatError(f"line {row}: closing bracket without an opening one")
|
|
292
|
+
if depth > 0:
|
|
293
|
+
raise FormatError(f"{depth} bracket(s) never closed")
|
|
294
|
+
if in_block:
|
|
295
|
+
raise FormatError("a /* comment is never closed")
|
|
296
|
+
return "".join(out)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# ---------------------------------------------------------------- entry point
|
|
300
|
+
|
|
301
|
+
def _strip_trailing(text: str) -> str:
|
|
302
|
+
return "".join(
|
|
303
|
+
line.rstrip("\r\n").rstrip() + line[len(line.rstrip("\r\n")):]
|
|
304
|
+
for line in text.splitlines(keepends=True)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _final_newline(text: str) -> str:
|
|
309
|
+
return text if not text or text.endswith("\n") else text + "\n"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _only_whitespace_changed(a: str, b: str) -> bool:
|
|
313
|
+
return re.sub(r"\s+", "", a) == re.sub(r"\s+", "", b)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def format_code(
|
|
317
|
+
text: str,
|
|
318
|
+
language: str | None,
|
|
319
|
+
*,
|
|
320
|
+
filename: str = "untitled",
|
|
321
|
+
which: Callable[[str], str | None] = shutil.which,
|
|
322
|
+
run: Callable[..., object] = subprocess.run,
|
|
323
|
+
) -> FormatResult:
|
|
324
|
+
"""Format text for language. Never raises; on failure returns the original text."""
|
|
325
|
+
lang = language or ""
|
|
326
|
+
external = _run_external(text, lang, filename, which, run)
|
|
327
|
+
if external is not None:
|
|
328
|
+
return external
|
|
329
|
+
|
|
330
|
+
try:
|
|
331
|
+
if lang == "json":
|
|
332
|
+
if not text.strip():
|
|
333
|
+
return FormatResult(text, False, "built-in")
|
|
334
|
+
try:
|
|
335
|
+
data = json.loads(text)
|
|
336
|
+
except json.JSONDecodeError as exc:
|
|
337
|
+
raise FormatError(f"line {exc.lineno}: {exc.msg}") from exc
|
|
338
|
+
new = json.dumps(data, indent=4, ensure_ascii=False) + "\n"
|
|
339
|
+
return FormatResult(new, new != text, "built-in")
|
|
340
|
+
if lang == "python":
|
|
341
|
+
new = reindent_python(text)
|
|
342
|
+
elif lang in BRACE_LANGUAGES:
|
|
343
|
+
new = reindent_braces(text, lang)
|
|
344
|
+
elif lang == "markdown":
|
|
345
|
+
new = text # trailing double spaces are line breaks in Markdown
|
|
346
|
+
else:
|
|
347
|
+
new = _strip_trailing(text)
|
|
348
|
+
new = _final_newline(new)
|
|
349
|
+
except FormatError as exc:
|
|
350
|
+
return FormatResult(text, False, "built-in", str(exc))
|
|
351
|
+
|
|
352
|
+
if not _only_whitespace_changed(text, new):
|
|
353
|
+
return FormatResult(text, False, "built-in", "formatting would change code; skipped")
|
|
354
|
+
if lang == "python":
|
|
355
|
+
try:
|
|
356
|
+
compile(text, filename, "exec")
|
|
357
|
+
except TabError:
|
|
358
|
+
pass # tabs mixed with spaces: exactly what re-indenting fixes
|
|
359
|
+
except SyntaxError as exc:
|
|
360
|
+
return FormatResult(text, False, "built-in", f"line {exc.lineno}: {exc.msg}")
|
|
361
|
+
try:
|
|
362
|
+
compile(new, filename, "exec")
|
|
363
|
+
except SyntaxError:
|
|
364
|
+
return FormatResult(text, False, "built-in", "formatting would break the code; skipped")
|
|
365
|
+
return FormatResult(new, new != text, "built-in")
|
termcode/highlighting.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Optional tree-sitter syntax highlighting registration (C and C++)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from textual.widgets import TextArea
|
|
6
|
+
|
|
7
|
+
_C_LANG = None
|
|
8
|
+
_C_QUERY: str | None = None
|
|
9
|
+
_CPP_LANG = None
|
|
10
|
+
_CPP_QUERY: str | None = None
|
|
11
|
+
_LOADED = False
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load_extra_grammars() -> None:
|
|
15
|
+
global _C_LANG, _C_QUERY, _CPP_LANG, _CPP_QUERY, _LOADED
|
|
16
|
+
if _LOADED:
|
|
17
|
+
return
|
|
18
|
+
_LOADED = True
|
|
19
|
+
try:
|
|
20
|
+
from tree_sitter import Language
|
|
21
|
+
except ImportError:
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
import tree_sitter_c
|
|
26
|
+
|
|
27
|
+
_C_LANG = Language(tree_sitter_c.language())
|
|
28
|
+
_C_QUERY = str(tree_sitter_c.HIGHLIGHTS_QUERY)
|
|
29
|
+
except Exception:
|
|
30
|
+
_C_LANG = None
|
|
31
|
+
_C_QUERY = None
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
import tree_sitter_cpp
|
|
35
|
+
|
|
36
|
+
_CPP_LANG = Language(tree_sitter_cpp.language())
|
|
37
|
+
cpp_q = str(tree_sitter_cpp.HIGHLIGHTS_QUERY)
|
|
38
|
+
# tree-sitter-cpp builds on C's node types; combining C + C++ queries
|
|
39
|
+
# ensures full coverage for strings, comments, #include, types, and functions.
|
|
40
|
+
_CPP_QUERY = f"{_C_QUERY}\n{cpp_q}" if _C_QUERY else cpp_q
|
|
41
|
+
except Exception:
|
|
42
|
+
_CPP_LANG = None
|
|
43
|
+
_CPP_QUERY = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def register_extra_languages(text_area: TextArea) -> None:
|
|
47
|
+
"""Register C and C++ tree-sitter languages on a TextArea when installed."""
|
|
48
|
+
_load_extra_grammars()
|
|
49
|
+
available = text_area.available_languages
|
|
50
|
+
|
|
51
|
+
if _C_LANG is not None and _C_QUERY and "c" not in available:
|
|
52
|
+
try:
|
|
53
|
+
text_area.register_language("c", _C_LANG, _C_QUERY)
|
|
54
|
+
except Exception:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
if _CPP_LANG is not None and _CPP_QUERY and "cpp" not in available:
|
|
58
|
+
try:
|
|
59
|
+
text_area.register_language("cpp", _CPP_LANG, _CPP_QUERY)
|
|
60
|
+
except Exception:
|
|
61
|
+
pass
|