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/buffers.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Open buffer and multi-tab pane state model for TermCode."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _is_within(child: Path, parent: Path) -> bool:
|
|
10
|
+
try:
|
|
11
|
+
child.resolve().relative_to(parent.resolve())
|
|
12
|
+
return True
|
|
13
|
+
except ValueError:
|
|
14
|
+
return False
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class OpenBuffer:
|
|
19
|
+
"""State of a single open editor tab."""
|
|
20
|
+
|
|
21
|
+
path: Path | None = None
|
|
22
|
+
content: str = ""
|
|
23
|
+
saved_content: str = ""
|
|
24
|
+
cursor: tuple[int, int] = (0, 0)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def is_dirty(self) -> bool:
|
|
28
|
+
return self.content != self.saved_content
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def title(self) -> str:
|
|
32
|
+
return self.path.name if self.path is not None else "Untitled"
|
|
33
|
+
|
|
34
|
+
def mark_saved(self, path: Path | None = None) -> None:
|
|
35
|
+
if path is not None:
|
|
36
|
+
self.path = path.resolve()
|
|
37
|
+
self.saved_content = self.content
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class EditorPaneState:
|
|
42
|
+
"""Manages the list of open tabs and active tab index for one editor pane."""
|
|
43
|
+
|
|
44
|
+
tabs: list[OpenBuffer] = field(default_factory=list)
|
|
45
|
+
active_index: int = -1
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def active_buffer(self) -> OpenBuffer | None:
|
|
49
|
+
if 0 <= self.active_index < len(self.tabs):
|
|
50
|
+
return self.tabs[self.active_index]
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
def find_by_path(self, path: Path) -> OpenBuffer | None:
|
|
54
|
+
resolved = path.resolve()
|
|
55
|
+
for buf in self.tabs:
|
|
56
|
+
if buf.path is not None and buf.path.resolve() == resolved:
|
|
57
|
+
return buf
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
def index_of_path(self, path: Path) -> int | None:
|
|
61
|
+
resolved = path.resolve()
|
|
62
|
+
for idx, buf in enumerate(self.tabs):
|
|
63
|
+
if buf.path is not None and buf.path.resolve() == resolved:
|
|
64
|
+
return idx
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
def ensure_untitled(self) -> OpenBuffer:
|
|
68
|
+
if not self.tabs:
|
|
69
|
+
buf = OpenBuffer()
|
|
70
|
+
self.tabs.append(buf)
|
|
71
|
+
self.active_index = 0
|
|
72
|
+
return buf
|
|
73
|
+
assert self.active_buffer is not None
|
|
74
|
+
return self.active_buffer
|
|
75
|
+
|
|
76
|
+
def open_file(self, path: Path, content: str) -> OpenBuffer:
|
|
77
|
+
resolved = path.resolve()
|
|
78
|
+
existing_idx = self.index_of_path(resolved)
|
|
79
|
+
if existing_idx is not None:
|
|
80
|
+
self.active_index = existing_idx
|
|
81
|
+
return self.tabs[existing_idx]
|
|
82
|
+
|
|
83
|
+
# Replace a pristine empty untitled buffer if it's the only tab
|
|
84
|
+
if (
|
|
85
|
+
len(self.tabs) == 1
|
|
86
|
+
and self.tabs[0].path is None
|
|
87
|
+
and not self.tabs[0].content
|
|
88
|
+
and not self.tabs[0].is_dirty
|
|
89
|
+
):
|
|
90
|
+
buf = OpenBuffer(path=resolved, content=content, saved_content=content)
|
|
91
|
+
self.tabs[0] = buf
|
|
92
|
+
self.active_index = 0
|
|
93
|
+
return buf
|
|
94
|
+
|
|
95
|
+
buf = OpenBuffer(path=resolved, content=content, saved_content=content)
|
|
96
|
+
self.tabs.append(buf)
|
|
97
|
+
self.active_index = len(self.tabs) - 1
|
|
98
|
+
return buf
|
|
99
|
+
|
|
100
|
+
def select_tab(self, index: int) -> OpenBuffer | None:
|
|
101
|
+
if 0 <= index < len(self.tabs):
|
|
102
|
+
self.active_index = index
|
|
103
|
+
return self.tabs[index]
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
def next_tab(self) -> OpenBuffer | None:
|
|
107
|
+
if not self.tabs:
|
|
108
|
+
return None
|
|
109
|
+
self.active_index = (self.active_index + 1) % len(self.tabs)
|
|
110
|
+
return self.tabs[self.active_index]
|
|
111
|
+
|
|
112
|
+
def close_tab(self, index: int) -> OpenBuffer | None:
|
|
113
|
+
if not (0 <= index < len(self.tabs)):
|
|
114
|
+
return None
|
|
115
|
+
removed = self.tabs.pop(index)
|
|
116
|
+
if not self.tabs:
|
|
117
|
+
self.active_index = -1
|
|
118
|
+
elif self.active_index >= len(self.tabs):
|
|
119
|
+
self.active_index = len(self.tabs) - 1
|
|
120
|
+
elif index < self.active_index:
|
|
121
|
+
self.active_index -= 1
|
|
122
|
+
return removed
|
|
123
|
+
|
|
124
|
+
def handle_rename(self, old_path: Path, new_path: Path) -> None:
|
|
125
|
+
old_res = old_path.resolve()
|
|
126
|
+
new_res = new_path.resolve()
|
|
127
|
+
for buf in self.tabs:
|
|
128
|
+
if buf.path is None:
|
|
129
|
+
continue
|
|
130
|
+
buf_res = buf.path.resolve()
|
|
131
|
+
if buf_res == old_res:
|
|
132
|
+
buf.path = new_res
|
|
133
|
+
elif _is_within(buf_res, old_res):
|
|
134
|
+
buf.path = new_res / buf_res.relative_to(old_res)
|
|
135
|
+
|
|
136
|
+
def handle_delete(self, deleted_path: Path) -> None:
|
|
137
|
+
del_res = deleted_path.resolve()
|
|
138
|
+
for buf in self.tabs:
|
|
139
|
+
if buf.path is None:
|
|
140
|
+
continue
|
|
141
|
+
buf_res = buf.path.resolve()
|
|
142
|
+
if buf_res == del_res or _is_within(buf_res, del_res):
|
|
143
|
+
buf.path = None
|
|
144
|
+
buf.saved_content = ""
|
|
145
|
+
|
|
146
|
+
def merge_from(self, other: EditorPaneState) -> None:
|
|
147
|
+
"""Merge tabs from another pane without duplicating paths or dropping unsaved edits."""
|
|
148
|
+
for buf in other.tabs:
|
|
149
|
+
if buf.path is not None:
|
|
150
|
+
existing = self.find_by_path(buf.path)
|
|
151
|
+
if existing is not None:
|
|
152
|
+
if buf.is_dirty and not existing.is_dirty:
|
|
153
|
+
existing.content = buf.content
|
|
154
|
+
continue
|
|
155
|
+
elif not buf.content and not buf.is_dirty and self.tabs:
|
|
156
|
+
continue
|
|
157
|
+
self.tabs.append(buf)
|
|
158
|
+
if self.tabs and self.active_index < 0:
|
|
159
|
+
self.active_index = 0
|
|
160
|
+
other.tabs.clear()
|
|
161
|
+
other.active_index = -1
|
|
162
|
+
|
|
163
|
+
def has_dirty_tabs(self) -> bool:
|
|
164
|
+
return any(buf.is_dirty for buf in self.tabs)
|
|
165
|
+
|
|
166
|
+
def clear(self) -> None:
|
|
167
|
+
self.tabs.clear()
|
|
168
|
+
self.active_index = -1
|
termcode/cli.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""CLI entrypoint for TermCode (`termcode [path]`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from termcode import __version__
|
|
10
|
+
from termcode.app import TermCodeApp
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _is_home(path: Path) -> bool:
|
|
14
|
+
try:
|
|
15
|
+
return path == Path.home().resolve()
|
|
16
|
+
except RuntimeError: # no resolvable home directory
|
|
17
|
+
return False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_cli_target(arg: str | None, cwd: Path | None = None) -> tuple[Path | None, Path | None]:
|
|
21
|
+
"""Resolve optional CLI path into (workspace_root, initial_file).
|
|
22
|
+
|
|
23
|
+
The home directory is never opened as a workspace: nobody keeps a project
|
|
24
|
+
directly in ~, and scanning all of it would be slow. Whether you run
|
|
25
|
+
`termcode`, `termcode .` or `termcode ~` there, you get the start page
|
|
26
|
+
asking which folder to open. Any other directory opens directly.
|
|
27
|
+
"""
|
|
28
|
+
base = (cwd or Path.cwd()).resolve()
|
|
29
|
+
if arg is None:
|
|
30
|
+
return (None, None) if _is_home(base) else (base, None)
|
|
31
|
+
|
|
32
|
+
target = Path(arg).expanduser()
|
|
33
|
+
if not target.is_absolute():
|
|
34
|
+
target = base / target
|
|
35
|
+
|
|
36
|
+
if not target.exists():
|
|
37
|
+
raise SystemExit(f"termcode: path not found: {arg}")
|
|
38
|
+
|
|
39
|
+
resolved = target.resolve()
|
|
40
|
+
if resolved.is_dir():
|
|
41
|
+
return (None, None) if _is_home(resolved) else (resolved, None)
|
|
42
|
+
return resolved.parent, resolved
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv: list[str] | None = None) -> int:
|
|
46
|
+
parser = argparse.ArgumentParser(
|
|
47
|
+
prog="termcode",
|
|
48
|
+
description="Lightweight VS Code-style terminal editor and runner for Python, C, and C++.",
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"path",
|
|
52
|
+
nargs="?",
|
|
53
|
+
default=None,
|
|
54
|
+
help="Optional folder or file to open (from home directory, opens the Home folder selector; from any other folder, opens it directly).",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--version",
|
|
58
|
+
action="version",
|
|
59
|
+
version=f"%(prog)s {__version__}",
|
|
60
|
+
)
|
|
61
|
+
args = parser.parse_args(argv)
|
|
62
|
+
workspace_root, initial_file = parse_cli_target(args.path)
|
|
63
|
+
app = TermCodeApp(workspace_root=workspace_root, initial_file=initial_file)
|
|
64
|
+
app.run()
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
raise SystemExit(main(sys.argv[1:]))
|
termcode/commands.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Slash command registry and filtering for TermCode."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class CommandSpec:
|
|
10
|
+
command: str
|
|
11
|
+
action: str
|
|
12
|
+
shortcut: str
|
|
13
|
+
binding: str
|
|
14
|
+
description: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
COMMANDS: tuple[CommandSpec, ...] = (
|
|
18
|
+
CommandSpec(
|
|
19
|
+
command="/run",
|
|
20
|
+
action="run_file",
|
|
21
|
+
shortcut="F5",
|
|
22
|
+
binding="f5",
|
|
23
|
+
description="Save and run active file in Output panel",
|
|
24
|
+
),
|
|
25
|
+
CommandSpec(
|
|
26
|
+
command="/run-in-terminal",
|
|
27
|
+
action="run_in_terminal",
|
|
28
|
+
shortcut="Shift+F5",
|
|
29
|
+
binding="shift+f5",
|
|
30
|
+
description="Run with the full terminal (colors, curses, key input)",
|
|
31
|
+
),
|
|
32
|
+
CommandSpec(
|
|
33
|
+
command="/shell",
|
|
34
|
+
action="open_shell",
|
|
35
|
+
shortcut="Ctrl+T",
|
|
36
|
+
binding="ctrl+t",
|
|
37
|
+
description="Open your shell here; type exit to come back",
|
|
38
|
+
),
|
|
39
|
+
CommandSpec(
|
|
40
|
+
command="/stop",
|
|
41
|
+
action="stop_run",
|
|
42
|
+
shortcut="F7",
|
|
43
|
+
binding="f7",
|
|
44
|
+
description="Stop currently running program",
|
|
45
|
+
),
|
|
46
|
+
CommandSpec(
|
|
47
|
+
command="/save",
|
|
48
|
+
action="save_file",
|
|
49
|
+
shortcut="Ctrl+S",
|
|
50
|
+
binding="ctrl+s",
|
|
51
|
+
description="Save active file",
|
|
52
|
+
),
|
|
53
|
+
CommandSpec(
|
|
54
|
+
command="/save-as",
|
|
55
|
+
action="save_file_as",
|
|
56
|
+
shortcut="F8",
|
|
57
|
+
binding="f8",
|
|
58
|
+
description="Save current buffer under a new name",
|
|
59
|
+
),
|
|
60
|
+
CommandSpec(
|
|
61
|
+
command="/new-file",
|
|
62
|
+
action="new_file",
|
|
63
|
+
shortcut="Ctrl+N",
|
|
64
|
+
binding="ctrl+n",
|
|
65
|
+
description="Create a new file in the selected folder",
|
|
66
|
+
),
|
|
67
|
+
CommandSpec(
|
|
68
|
+
command="/new-folder",
|
|
69
|
+
action="new_folder",
|
|
70
|
+
shortcut="F3",
|
|
71
|
+
binding="f3",
|
|
72
|
+
description="Create a new folder in the selected folder",
|
|
73
|
+
),
|
|
74
|
+
CommandSpec(
|
|
75
|
+
command="/open-file",
|
|
76
|
+
action="open_file",
|
|
77
|
+
shortcut="Ctrl+P",
|
|
78
|
+
binding="ctrl+p",
|
|
79
|
+
description="Quick-select and open a file in this folder",
|
|
80
|
+
),
|
|
81
|
+
CommandSpec(
|
|
82
|
+
command="/open-folder",
|
|
83
|
+
action="open_folder",
|
|
84
|
+
shortcut="Ctrl+O",
|
|
85
|
+
binding="ctrl+o",
|
|
86
|
+
description="Switch to another folder as workspace root",
|
|
87
|
+
),
|
|
88
|
+
CommandSpec(
|
|
89
|
+
command="/rename",
|
|
90
|
+
action="rename_item",
|
|
91
|
+
shortcut="F2",
|
|
92
|
+
binding="f2",
|
|
93
|
+
description="Rename the selected file or folder",
|
|
94
|
+
),
|
|
95
|
+
CommandSpec(
|
|
96
|
+
command="/delete",
|
|
97
|
+
action="delete_item",
|
|
98
|
+
shortcut="F4",
|
|
99
|
+
binding="f4",
|
|
100
|
+
description="Delete the selected file or folder",
|
|
101
|
+
),
|
|
102
|
+
CommandSpec(
|
|
103
|
+
command="/toggle-sidebar",
|
|
104
|
+
action="toggle_sidebar",
|
|
105
|
+
shortcut="Ctrl+B",
|
|
106
|
+
binding="ctrl+b",
|
|
107
|
+
description="Show or hide the Explorer sidebar",
|
|
108
|
+
),
|
|
109
|
+
CommandSpec(
|
|
110
|
+
command="/toggle-terminal",
|
|
111
|
+
action="toggle_terminal",
|
|
112
|
+
shortcut="Ctrl+J",
|
|
113
|
+
binding="ctrl+j",
|
|
114
|
+
description="Show or hide the bottom Output panel",
|
|
115
|
+
),
|
|
116
|
+
CommandSpec(
|
|
117
|
+
command="/toggle-hidden",
|
|
118
|
+
action="toggle_hidden",
|
|
119
|
+
shortcut="F9",
|
|
120
|
+
binding="f9",
|
|
121
|
+
description="Show or hide hidden dotfiles in Explorer",
|
|
122
|
+
),
|
|
123
|
+
CommandSpec(
|
|
124
|
+
command="/terminal-grow",
|
|
125
|
+
action="terminal_grow",
|
|
126
|
+
shortcut="Ctrl+Up",
|
|
127
|
+
binding="ctrl+up",
|
|
128
|
+
description="Increase Output panel height",
|
|
129
|
+
),
|
|
130
|
+
CommandSpec(
|
|
131
|
+
command="/terminal-shrink",
|
|
132
|
+
action="terminal_shrink",
|
|
133
|
+
shortcut="Ctrl+Down",
|
|
134
|
+
binding="ctrl+down",
|
|
135
|
+
description="Decrease Output panel height",
|
|
136
|
+
),
|
|
137
|
+
CommandSpec(
|
|
138
|
+
command="/copy-output",
|
|
139
|
+
action="copy_output",
|
|
140
|
+
shortcut="F10",
|
|
141
|
+
binding="f10",
|
|
142
|
+
description="Copy selected or full Output panel text",
|
|
143
|
+
),
|
|
144
|
+
CommandSpec(
|
|
145
|
+
command="/clear-output",
|
|
146
|
+
action="clear_output",
|
|
147
|
+
shortcut="Ctrl+L",
|
|
148
|
+
binding="ctrl+l",
|
|
149
|
+
description="Clear the Output panel text",
|
|
150
|
+
),
|
|
151
|
+
CommandSpec(
|
|
152
|
+
command="/next-tab",
|
|
153
|
+
action="next_tab",
|
|
154
|
+
shortcut="F11",
|
|
155
|
+
binding="f11",
|
|
156
|
+
description="Switch to the next open file tab",
|
|
157
|
+
),
|
|
158
|
+
CommandSpec(
|
|
159
|
+
command="/close-tab",
|
|
160
|
+
action="close_tab",
|
|
161
|
+
shortcut="Ctrl+W",
|
|
162
|
+
binding="ctrl+w",
|
|
163
|
+
description="Close the current file tab",
|
|
164
|
+
),
|
|
165
|
+
CommandSpec(
|
|
166
|
+
command="/split-editor",
|
|
167
|
+
action="toggle_split",
|
|
168
|
+
shortcut="F12",
|
|
169
|
+
binding="f12",
|
|
170
|
+
description="Toggle side-by-side split editor",
|
|
171
|
+
),
|
|
172
|
+
CommandSpec(
|
|
173
|
+
command="/find",
|
|
174
|
+
action="find",
|
|
175
|
+
shortcut="Ctrl+F",
|
|
176
|
+
binding="ctrl+f",
|
|
177
|
+
description="Find in the current file",
|
|
178
|
+
),
|
|
179
|
+
CommandSpec(
|
|
180
|
+
command="/replace",
|
|
181
|
+
action="replace",
|
|
182
|
+
shortcut="Ctrl+R",
|
|
183
|
+
binding="ctrl+r",
|
|
184
|
+
description="Find and replace in the current file",
|
|
185
|
+
),
|
|
186
|
+
CommandSpec(
|
|
187
|
+
command="/goto-line",
|
|
188
|
+
action="goto_line",
|
|
189
|
+
shortcut="Ctrl+G",
|
|
190
|
+
binding="ctrl+g",
|
|
191
|
+
description="Jump to a line (and column)",
|
|
192
|
+
),
|
|
193
|
+
CommandSpec(
|
|
194
|
+
command="/format-file",
|
|
195
|
+
action="format_file",
|
|
196
|
+
shortcut="F6",
|
|
197
|
+
binding="f6",
|
|
198
|
+
description="Fix indentation in the current file now",
|
|
199
|
+
),
|
|
200
|
+
CommandSpec(
|
|
201
|
+
command="/format-on-save",
|
|
202
|
+
action="toggle_format_on_save",
|
|
203
|
+
shortcut="",
|
|
204
|
+
binding="",
|
|
205
|
+
description="Turn formatting on save (and run) on or off",
|
|
206
|
+
),
|
|
207
|
+
CommandSpec(
|
|
208
|
+
command="/quit",
|
|
209
|
+
action="request_quit",
|
|
210
|
+
shortcut="Ctrl+Q",
|
|
211
|
+
binding="ctrl+q",
|
|
212
|
+
description="Exit TermCode",
|
|
213
|
+
),
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def filter_commands(query: str) -> list[CommandSpec]:
|
|
218
|
+
"""Filter commands by leading-slash-optional substring match on command or description."""
|
|
219
|
+
cleaned = query.strip().lower()
|
|
220
|
+
if cleaned.startswith("/"):
|
|
221
|
+
cleaned = cleaned[1:]
|
|
222
|
+
if not cleaned:
|
|
223
|
+
return list(COMMANDS)
|
|
224
|
+
|
|
225
|
+
prefix_matches: list[CommandSpec] = []
|
|
226
|
+
other_matches: list[CommandSpec] = []
|
|
227
|
+
for spec in COMMANDS:
|
|
228
|
+
cmd_body = spec.command[1:].lower()
|
|
229
|
+
haystack = f"{cmd_body} {spec.description.lower()} {spec.shortcut.lower()}"
|
|
230
|
+
if cmd_body.startswith(cleaned):
|
|
231
|
+
prefix_matches.append(spec)
|
|
232
|
+
elif cleaned in haystack:
|
|
233
|
+
other_matches.append(spec)
|
|
234
|
+
return prefix_matches + other_matches
|
termcode/completions.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Lightweight offline code completion and auto-indentation helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
_PREFIX_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_:\.\-]*$")
|
|
8
|
+
_WORD_RE = re.compile(r"\b[A-Za-z_][A-Za-z0-9_]{1,}\b")
|
|
9
|
+
|
|
10
|
+
LANGUAGE_COMPLETIONS: dict[str, tuple[str, ...]] = {
|
|
11
|
+
"python": (
|
|
12
|
+
"print", "input", "range", "len", "enumerate", "isinstance", "type",
|
|
13
|
+
"def", "class", "return", "import", "from", "as", "if", "elif", "else",
|
|
14
|
+
"for", "while", "break", "continue", "pass", "try", "except", "finally",
|
|
15
|
+
"raise", "with", "yield", "lambda", "async", "await", "True", "False",
|
|
16
|
+
"None", "and", "or", "not", "in", "is", "list", "dict", "set", "tuple",
|
|
17
|
+
"str", "int", "float", "bool", "open", "sorted", "reversed", "zip",
|
|
18
|
+
"map", "filter", "sum", "min", "max", "abs", "any", "all", "super",
|
|
19
|
+
"__init__", "__name__", "__main__", "self", "dataclass", "Path",
|
|
20
|
+
),
|
|
21
|
+
"c": (
|
|
22
|
+
"printf", "scanf", "fprintf", "fscanf", "sprintf", "snprintf", "puts",
|
|
23
|
+
"fgets", "getchar", "putchar", "include", "define", "ifdef", "ifndef",
|
|
24
|
+
"endif", "int", "long", "short", "char", "float", "double", "void",
|
|
25
|
+
"unsigned", "signed", "const", "static", "extern", "struct", "union",
|
|
26
|
+
"enum", "typedef", "sizeof", "return", "if", "else", "for", "while",
|
|
27
|
+
"do", "switch", "case", "default", "break", "continue", "NULL",
|
|
28
|
+
"malloc", "calloc", "realloc", "free", "memcpy", "memset", "strlen",
|
|
29
|
+
"strcpy", "strcmp", "strcat", "stdio.h", "stdlib.h", "string.h",
|
|
30
|
+
"math.h", "stdbool.h", "stdint.h", "main", "size_t", "FILE",
|
|
31
|
+
),
|
|
32
|
+
"cpp": (
|
|
33
|
+
"printf", "scanf", "std::cout", "std::cin", "std::cerr", "std::endl",
|
|
34
|
+
"std::string", "std::vector", "std::map", "std::unordered_map",
|
|
35
|
+
"std::set", "std::unordered_set", "std::pair", "std::sort",
|
|
36
|
+
"std::max", "std::min", "std::getline", "std::unique_ptr",
|
|
37
|
+
"std::shared_ptr", "std::make_unique", "std::make_shared",
|
|
38
|
+
"include", "iostream", "vector", "string", "algorithm", "cmath",
|
|
39
|
+
"namespace", "using", "class", "struct", "public", "private",
|
|
40
|
+
"protected", "virtual", "override", "template", "typename", "auto",
|
|
41
|
+
"constexpr", "const", "static", "nullptr", "true", "false", "new",
|
|
42
|
+
"delete", "return", "if", "else", "for", "while", "switch", "case",
|
|
43
|
+
"break", "continue", "try", "catch", "throw", "int", "long", "double",
|
|
44
|
+
"float", "char", "bool", "void", "size_t", "main", "push_back",
|
|
45
|
+
"emplace_back", "begin", "end", "size", "empty",
|
|
46
|
+
),
|
|
47
|
+
"javascript": (
|
|
48
|
+
"console.log", "console.error", "console.warn", "const", "let", "var",
|
|
49
|
+
"function", "return", "async", "await", "import", "export", "default",
|
|
50
|
+
"from", "class", "extends", "constructor", "this", "super", "new",
|
|
51
|
+
"if", "else", "for", "while", "switch", "case", "break", "continue",
|
|
52
|
+
"try", "catch", "finally", "throw", "true", "false", "null",
|
|
53
|
+
"undefined", "typeof", "instanceof", "Promise", "Array", "Object",
|
|
54
|
+
"JSON.stringify", "JSON.parse", "fetch", "setTimeout", "setInterval",
|
|
55
|
+
"document.querySelector", "addEventListener", "forEach", "map",
|
|
56
|
+
"filter", "reduce", "length", "push", "includes",
|
|
57
|
+
),
|
|
58
|
+
"html": (
|
|
59
|
+
"<!DOCTYPE html>", "<html>", "<head>", "<body>", "<div>", "<span>",
|
|
60
|
+
"<section>", "<main>", "<header>", "<footer>", "<nav>", "<h1>", "<h2>",
|
|
61
|
+
"<p>", "<a href=\"\">", "<img src=\"\" alt=\"\">", "<ul>", "<ol>",
|
|
62
|
+
"<li>", "<button>", "<input>", "<form>", "<label>", "<script>",
|
|
63
|
+
"<style>", "<link>", "<meta>", "<table>", "<thead>", "<tbody>",
|
|
64
|
+
"<tr>", "<td>", "<th>", "class=", "id=", "href=", "src=",
|
|
65
|
+
),
|
|
66
|
+
"css": (
|
|
67
|
+
"display", "flex", "grid", "position", "relative", "absolute", "fixed",
|
|
68
|
+
"margin", "padding", "width", "height", "max-width", "min-height",
|
|
69
|
+
"background", "background-color", "color", "font-size", "font-weight",
|
|
70
|
+
"font-family", "border", "border-radius", "box-shadow", "gap",
|
|
71
|
+
"align-items", "justify-content", "flex-direction", "transition",
|
|
72
|
+
"transform", "opacity", "cursor", "pointer", "overflow", "z-index",
|
|
73
|
+
),
|
|
74
|
+
"java": (
|
|
75
|
+
"System.out.println", "System.out.print", "public", "private",
|
|
76
|
+
"protected", "class", "interface", "extends", "implements", "static",
|
|
77
|
+
"final", "void", "int", "long", "double", "boolean", "String",
|
|
78
|
+
"return", "new", "this", "super", "import", "package", "if", "else",
|
|
79
|
+
"for", "while", "switch", "case", "try", "catch", "finally", "throw",
|
|
80
|
+
"throws", "ArrayList", "HashMap", "List", "Map", "Scanner", "main",
|
|
81
|
+
),
|
|
82
|
+
"go": (
|
|
83
|
+
"fmt.Println", "fmt.Printf", "fmt.Sprintf", "package", "import",
|
|
84
|
+
"func", "return", "var", "const", "type", "struct", "interface",
|
|
85
|
+
"map", "chan", "go", "defer", "select", "if", "else", "for", "range",
|
|
86
|
+
"switch", "case", "default", "break", "continue", "make", "len",
|
|
87
|
+
"cap", "append", "copy", "delete", "error", "nil", "true", "false",
|
|
88
|
+
"string", "int", "int64", "float64", "bool", "byte", "main",
|
|
89
|
+
),
|
|
90
|
+
"rust": (
|
|
91
|
+
"println!", "print!", "eprintln!", "format!", "vec!", "fn", "let",
|
|
92
|
+
"mut", "const", "pub", "struct", "enum", "impl", "trait", "for",
|
|
93
|
+
"while", "loop", "if", "else", "match", "return", "use", "mod",
|
|
94
|
+
"crate", "self", "Self", "Some", "None", "Ok", "Err", "Option",
|
|
95
|
+
"Result", "String", "Vec", "HashMap", "usize", "i32", "i64", "f64",
|
|
96
|
+
"bool", "str", "async", "await", "unwrap", "expect", "clone", "main",
|
|
97
|
+
),
|
|
98
|
+
"bash": (
|
|
99
|
+
"echo", "printf", "read", "export", "local", "function", "if", "then",
|
|
100
|
+
"elif", "else", "fi", "for", "while", "do", "done", "case", "esac",
|
|
101
|
+
"in", "return", "exit", "set -euo pipefail", "mkdir", "grep", "awk",
|
|
102
|
+
"sed", "find", "chmod", "source",
|
|
103
|
+
),
|
|
104
|
+
"sql": (
|
|
105
|
+
"SELECT", "FROM", "WHERE", "INSERT INTO", "VALUES", "UPDATE", "SET",
|
|
106
|
+
"DELETE FROM", "CREATE TABLE", "ALTER TABLE", "DROP TABLE", "JOIN",
|
|
107
|
+
"LEFT JOIN", "INNER JOIN", "ON", "GROUP BY", "ORDER BY", "HAVING",
|
|
108
|
+
"LIMIT", "OFFSET", "DISTINCT", "COUNT", "SUM", "AVG", "MIN", "MAX",
|
|
109
|
+
"AS", "AND", "OR", "NOT", "NULL", "PRIMARY KEY", "FOREIGN KEY",
|
|
110
|
+
),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
_BRACE_LANGUAGES = frozenset({"c", "cpp", "javascript", "java", "go", "rust", "css", "json"})
|
|
114
|
+
_TAG_OPEN_RE = re.compile(r"<([A-Za-z][A-Za-z0-9\-]*)(?:\s[^>]*)?>$")
|
|
115
|
+
_VOID_HTML_TAGS = frozenset(
|
|
116
|
+
{"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "wbr"}
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def extract_prefix(line: str, col: int) -> str:
|
|
121
|
+
"""Extract the word/symbol prefix immediately before cursor column col."""
|
|
122
|
+
segment = line[: max(0, col)]
|
|
123
|
+
match = _PREFIX_RE.search(segment)
|
|
124
|
+
return match.group(0) if match else ""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def extract_buffer_words(buffer_text: str) -> list[str]:
|
|
128
|
+
"""Return unique identifier-like words from the current file buffer."""
|
|
129
|
+
seen: set[str] = set()
|
|
130
|
+
words: list[str] = []
|
|
131
|
+
for match in _WORD_RE.finditer(buffer_text):
|
|
132
|
+
word = match.group(0)
|
|
133
|
+
if word not in seen:
|
|
134
|
+
seen.add(word)
|
|
135
|
+
words.append(word)
|
|
136
|
+
return words
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_completions(
|
|
140
|
+
prefix: str,
|
|
141
|
+
language: str | None,
|
|
142
|
+
buffer_text: str,
|
|
143
|
+
*,
|
|
144
|
+
limit: int = 8,
|
|
145
|
+
) -> list[str]:
|
|
146
|
+
"""Return ranked completion candidates matching prefix for language + buffer words."""
|
|
147
|
+
if len(prefix) < 2:
|
|
148
|
+
return []
|
|
149
|
+
|
|
150
|
+
needle = prefix.lower()
|
|
151
|
+
lang_words = LANGUAGE_COMPLETIONS.get(language or "", ())
|
|
152
|
+
buf_words = extract_buffer_words(buffer_text)
|
|
153
|
+
|
|
154
|
+
seen: set[str] = set()
|
|
155
|
+
prefix_hits: list[str] = []
|
|
156
|
+
substring_hits: list[str] = []
|
|
157
|
+
|
|
158
|
+
for word in (*lang_words, *buf_words):
|
|
159
|
+
if word in seen or word == prefix:
|
|
160
|
+
continue
|
|
161
|
+
seen.add(word)
|
|
162
|
+
low = word.lower()
|
|
163
|
+
if low.startswith(needle):
|
|
164
|
+
prefix_hits.append(word)
|
|
165
|
+
elif needle in low:
|
|
166
|
+
substring_hits.append(word)
|
|
167
|
+
|
|
168
|
+
return (prefix_hits + substring_hits)[:limit]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def compute_enter_indent(line_before_cursor: str, language: str | None) -> str:
|
|
172
|
+
"""Compute indentation string for a newly inserted line after pressing Enter."""
|
|
173
|
+
leading_len = len(line_before_cursor) - len(line_before_cursor.lstrip(" \t"))
|
|
174
|
+
base_indent = line_before_cursor[:leading_len]
|
|
175
|
+
stripped = line_before_cursor.rstrip()
|
|
176
|
+
|
|
177
|
+
if language == "python":
|
|
178
|
+
if stripped.endswith(":"):
|
|
179
|
+
return base_indent + " "
|
|
180
|
+
return base_indent
|
|
181
|
+
|
|
182
|
+
if language in _BRACE_LANGUAGES:
|
|
183
|
+
if stripped.endswith("{") or stripped.endswith("[") or stripped.endswith("("):
|
|
184
|
+
return base_indent + " "
|
|
185
|
+
return base_indent
|
|
186
|
+
|
|
187
|
+
if language in ("html", "xml"):
|
|
188
|
+
m = _TAG_OPEN_RE.search(stripped)
|
|
189
|
+
if m and m.group(1).lower() not in _VOID_HTML_TAGS:
|
|
190
|
+
return base_indent + " "
|
|
191
|
+
return base_indent
|
|
192
|
+
|
|
193
|
+
return base_indent
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def compute_closing_brace_dedent(line_before_cursor: str) -> int:
|
|
197
|
+
"""Return number of spaces to remove before inserting '}' on a whitespace-only line."""
|
|
198
|
+
if not line_before_cursor or line_before_cursor.strip():
|
|
199
|
+
return 0
|
|
200
|
+
if line_before_cursor.endswith(" "):
|
|
201
|
+
return 4
|
|
202
|
+
if line_before_cursor.endswith("\t"):
|
|
203
|
+
return 1
|
|
204
|
+
spaces = len(line_before_cursor) - len(line_before_cursor.rstrip(" "))
|
|
205
|
+
return min(spaces, 4)
|