nctab 0.1.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.
- nctab/__init__.py +3 -0
- nctab/app.py +604 -0
- nctab/check/__init__.py +13 -0
- nctab/check/model.py +65 -0
- nctab/check/rules.py +360 -0
- nctab/cli.py +1046 -0
- nctab/config.py +227 -0
- nctab/core/__init__.py +0 -0
- nctab/core/format.py +112 -0
- nctab/core/io.py +75 -0
- nctab/core/model.py +166 -0
- nctab/core/parse.py +293 -0
- nctab/core/state.py +218 -0
- nctab/diff/__init__.py +26 -0
- nctab/diff/compare.py +177 -0
- nctab/diff/normalize.py +91 -0
- nctab/dnc/__init__.py +0 -0
- nctab/errors.py +38 -0
- nctab/geom/__init__.py +0 -0
- nctab/geom/arc.py +100 -0
- nctab/geom/transform.py +87 -0
- nctab/nctab.tcss +157 -0
- nctab/ops/__init__.py +0 -0
- nctab/ops/addr_math.py +81 -0
- nctab/ops/base.py +167 -0
- nctab/ops/case.py +46 -0
- nctab/ops/feeds.py +89 -0
- nctab/ops/find.py +362 -0
- nctab/ops/mirror.py +170 -0
- nctab/ops/path.py +130 -0
- nctab/ops/renumber.py +112 -0
- nctab/ops/rotate.py +180 -0
- nctab/ops/scale.py +131 -0
- nctab/ops/shift.py +110 -0
- nctab/ops/stats.py +157 -0
- nctab/ops/strip.py +116 -0
- nctab/ops/tools.py +97 -0
- nctab/profiles/__init__.py +0 -0
- nctab/profiles/fanuc-mill.toml +99 -0
- nctab/profiles/fanuc-turn.toml +83 -0
- nctab/profiles/generic-iso.toml +59 -0
- nctab/profiles/haas-mill.toml +120 -0
- nctab/profiles/loader.py +119 -0
- nctab/profiles/siemens-iso.toml +83 -0
- nctab/snippets/__init__.py +17 -0
- nctab/snippets/common/program-footer.toml +11 -0
- nctab/snippets/common/program-header.toml +32 -0
- nctab/snippets/common/safe-retract.toml +14 -0
- nctab/snippets/common/tool-change.toml +29 -0
- nctab/snippets/fanuc-mill/drill-cycle.toml +27 -0
- nctab/snippets/fanuc-mill/peck-drill.toml +34 -0
- nctab/snippets/fanuc-turn/turn-header.toml +33 -0
- nctab/snippets/loader.py +212 -0
- nctab/tui/__init__.py +0 -0
- nctab/tui/dialogs.py +222 -0
- nctab/tui/editor.py +299 -0
- nctab/tui/explorer.py +85 -0
- nctab/tui/highlight.py +113 -0
- nctab/tui/inspector.py +134 -0
- nctab/tui/outline.py +116 -0
- nctab/tui/palette.py +74 -0
- nctab/tui/panels.py +129 -0
- nctab/tui/search.py +101 -0
- nctab/tui/search_dialog.py +407 -0
- nctab-0.1.0.dist-info/METADATA +239 -0
- nctab-0.1.0.dist-info/RECORD +69 -0
- nctab-0.1.0.dist-info/WHEEL +4 -0
- nctab-0.1.0.dist-info/entry_points.txt +3 -0
- nctab-0.1.0.dist-info/licenses/LICENSE +21 -0
nctab/__init__.py
ADDED
nctab/app.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
"""The Textual application (goal.md §5.2).
|
|
2
|
+
|
|
3
|
+
Layout::
|
|
4
|
+
|
|
5
|
+
┌ nctab OP20.nc fanuc-mill LN 412 G90 G17 G41 T12 *modified ┐
|
|
6
|
+
├──────────────┬─────────────────────────────────┬───────────────┤
|
|
7
|
+
│ Outline/Files│ Editor │ Inspector │
|
|
8
|
+
├──────────────┴─────────────────────────────────┴───────────────┤
|
|
9
|
+
│ status / diagnostics │
|
|
10
|
+
└────────────────────────────────────────────────────────────────┘
|
|
11
|
+
|
|
12
|
+
The app owns no transform logic: dialogs return specs and these handlers call
|
|
13
|
+
``ops.*``, the same functions the CLI uses (goal.md §10).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from decimal import Decimal
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from textual import on, work
|
|
22
|
+
from textual.app import App, ComposeResult
|
|
23
|
+
from textual.binding import Binding
|
|
24
|
+
from textual.containers import Horizontal, Vertical
|
|
25
|
+
from textual.reactive import reactive
|
|
26
|
+
from textual.widgets import Footer, Header, Static, TabbedContent, TabPane
|
|
27
|
+
|
|
28
|
+
from nctab.check import CheckReport, check_program
|
|
29
|
+
from nctab.config import Config, load_config
|
|
30
|
+
from nctab.core.io import read_program, write_program
|
|
31
|
+
from nctab.core.parse import parse_text
|
|
32
|
+
from nctab.core.state import ModalState, apply_line
|
|
33
|
+
from nctab.errors import NctabError
|
|
34
|
+
from nctab.ops.base import OpResult, Range
|
|
35
|
+
from nctab.ops.find import ReplaceSpec, replace
|
|
36
|
+
from nctab.ops.mirror import MirrorSpec, mirror
|
|
37
|
+
from nctab.ops.renumber import RenumberSpec, renumber
|
|
38
|
+
from nctab.ops.rotate import RotateSpec, rotate
|
|
39
|
+
from nctab.ops.scale import ScaleSpec, scale
|
|
40
|
+
from nctab.ops.shift import ShiftSpec, shift
|
|
41
|
+
from nctab.profiles.loader import Profile, load_profile
|
|
42
|
+
from nctab.snippets import load_snippets
|
|
43
|
+
from nctab.tui.dialogs import (
|
|
44
|
+
GotoDialog,
|
|
45
|
+
RenumberDialog,
|
|
46
|
+
TransformDialog,
|
|
47
|
+
TransformRequest,
|
|
48
|
+
)
|
|
49
|
+
from nctab.tui.editor import NcEditor
|
|
50
|
+
from nctab.tui.explorer import Explorer
|
|
51
|
+
from nctab.tui.inspector import Inspector
|
|
52
|
+
from nctab.tui.outline import Outline
|
|
53
|
+
from nctab.tui.palette import NctabCommands
|
|
54
|
+
from nctab.tui.panels import SnippetDialog, SnippetRequest
|
|
55
|
+
from nctab.tui.search_dialog import SearchDialog, SearchRequest
|
|
56
|
+
|
|
57
|
+
CSS_PATH = Path(__file__).with_name("nctab.tcss")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class StatusBar(Static):
|
|
61
|
+
"""Bottom line: the last message, plus the search counter."""
|
|
62
|
+
|
|
63
|
+
message = reactive("")
|
|
64
|
+
search = reactive("")
|
|
65
|
+
|
|
66
|
+
def render(self) -> str:
|
|
67
|
+
return f"{self.message} {self.search}".strip()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class NctabApp(App[None]):
|
|
71
|
+
"""The nctab editor."""
|
|
72
|
+
|
|
73
|
+
CSS_PATH = CSS_PATH
|
|
74
|
+
TITLE = "nctab"
|
|
75
|
+
|
|
76
|
+
# The editor is always in insert mode, so every binding here must be a key
|
|
77
|
+
# that cannot be part of a program. No bare letters, no brackets.
|
|
78
|
+
BINDINGS = [
|
|
79
|
+
Binding("ctrl+s", "save", "Save"),
|
|
80
|
+
Binding("ctrl+q", "quit", "Quit"),
|
|
81
|
+
Binding("ctrl+f", "find", "Find"),
|
|
82
|
+
Binding("f3", "find_next", "Next match"),
|
|
83
|
+
Binding("shift+f3", "find_prev", "Prev match", show=False),
|
|
84
|
+
Binding("ctrl+h", "replace", "Replace"),
|
|
85
|
+
Binding("ctrl+g", "goto", "Go to"),
|
|
86
|
+
Binding("f4", "next_tool", "Next tool"),
|
|
87
|
+
Binding("shift+f4", "prev_tool", "Prev tool", show=False),
|
|
88
|
+
Binding("f5", "next_mode", "Next G", show=False),
|
|
89
|
+
Binding("shift+f5", "prev_mode", "Prev G", show=False),
|
|
90
|
+
Binding("ctrl+b", "set_bookmark", "Mark", show=False),
|
|
91
|
+
Binding("ctrl+j", "goto_bookmark", "Jump", show=False),
|
|
92
|
+
Binding("ctrl+n", "renumber", "Renumber"),
|
|
93
|
+
Binding("ctrl+t", "transform", "Transform"),
|
|
94
|
+
Binding("f2", "snippet", "Snippet"),
|
|
95
|
+
Binding("ctrl+o", "focus_side", "Side panel", show=False),
|
|
96
|
+
Binding("f9", "toggle_side", "Outline/Files"),
|
|
97
|
+
Binding("ctrl+r", "discard_and_open", "Discard and open", show=False),
|
|
98
|
+
Binding("f1", "help", "Help"),
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
COMMANDS = App.COMMANDS | {NctabCommands}
|
|
102
|
+
|
|
103
|
+
modified = reactive(False)
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
path: Path | None = None,
|
|
108
|
+
profile: Profile | None = None,
|
|
109
|
+
config: Config | None = None,
|
|
110
|
+
) -> None:
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.config = config or load_config()
|
|
113
|
+
self.profile = profile or load_profile(self.config.defaults.profile)
|
|
114
|
+
self.path = path
|
|
115
|
+
self._saved_text = ""
|
|
116
|
+
self._pending_open: Path | None = None
|
|
117
|
+
self.snippets = load_snippets(self.profile.id)
|
|
118
|
+
|
|
119
|
+
# -- composition --------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
def compose(self) -> ComposeResult:
|
|
122
|
+
yield Header(show_clock=False)
|
|
123
|
+
with Horizontal(id="main"):
|
|
124
|
+
with TabbedContent(id="side", initial=self._initial_tab()):
|
|
125
|
+
with TabPane("Outline", id="tab-outline"):
|
|
126
|
+
yield Outline(id="outline")
|
|
127
|
+
with TabPane("Files", id="tab-files"):
|
|
128
|
+
yield Explorer(self.config.defaults.gcode_dir, id="explorer")
|
|
129
|
+
with Vertical(id="editor-pane"):
|
|
130
|
+
yield NcEditor(self.profile, id="editor")
|
|
131
|
+
yield Inspector(id="inspector")
|
|
132
|
+
yield StatusBar(id="status")
|
|
133
|
+
yield Footer()
|
|
134
|
+
|
|
135
|
+
def on_mount(self) -> None:
|
|
136
|
+
editor = self.editor
|
|
137
|
+
if self.path is not None:
|
|
138
|
+
self.open_path(self.path)
|
|
139
|
+
else:
|
|
140
|
+
editor.load_program("")
|
|
141
|
+
editor.focus()
|
|
142
|
+
self.refresh_outline()
|
|
143
|
+
self.update_title()
|
|
144
|
+
|
|
145
|
+
# -- accessors ----------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def editor(self) -> NcEditor:
|
|
149
|
+
return self.query_one("#editor", NcEditor)
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def outline(self) -> Outline:
|
|
153
|
+
return self.query_one("#outline", Outline)
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def explorer(self) -> Explorer:
|
|
157
|
+
return self.query_one("#explorer", Explorer)
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def side(self) -> TabbedContent:
|
|
161
|
+
return self.query_one("#side", TabbedContent)
|
|
162
|
+
|
|
163
|
+
def _initial_tab(self) -> str:
|
|
164
|
+
"""Start on the file list when there is nothing open to outline."""
|
|
165
|
+
return "tab-outline" if self.path is not None else "tab-files"
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def inspector(self) -> Inspector:
|
|
169
|
+
return self.query_one("#inspector", Inspector)
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def status(self) -> StatusBar:
|
|
173
|
+
return self.query_one("#status", StatusBar)
|
|
174
|
+
|
|
175
|
+
# -- files --------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def open_path(self, path: Path) -> None:
|
|
178
|
+
try:
|
|
179
|
+
program = read_program(path, self.profile)
|
|
180
|
+
except NctabError as e:
|
|
181
|
+
self.notify(str(e), severity="error")
|
|
182
|
+
return
|
|
183
|
+
self.path = path
|
|
184
|
+
self.editor.load_program(program.text)
|
|
185
|
+
self._saved_text = program.text
|
|
186
|
+
self.modified = False
|
|
187
|
+
self.refresh_outline()
|
|
188
|
+
self.update_title()
|
|
189
|
+
self._pending_open = None
|
|
190
|
+
self.say(f"Opened {path}")
|
|
191
|
+
|
|
192
|
+
def action_save(self) -> None:
|
|
193
|
+
if self.path is None:
|
|
194
|
+
self.notify("No file name; use the CLI to write this buffer", severity="warning")
|
|
195
|
+
return
|
|
196
|
+
text = self.editor.text
|
|
197
|
+
program = parse_text(text, self.profile)
|
|
198
|
+
try:
|
|
199
|
+
write_program(program, self.path, backup=self.config.editor.backup)
|
|
200
|
+
except NctabError as e:
|
|
201
|
+
self.notify(str(e), severity="error")
|
|
202
|
+
return
|
|
203
|
+
self._saved_text = text
|
|
204
|
+
self.modified = False
|
|
205
|
+
self.update_title()
|
|
206
|
+
self.say(f"Saved {self.path}")
|
|
207
|
+
|
|
208
|
+
# -- status -------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
def say(self, message: str) -> None:
|
|
211
|
+
self.status.message = message
|
|
212
|
+
|
|
213
|
+
def mark_modified(self) -> None:
|
|
214
|
+
"""Recompute the dirty flag from the buffer, not from an edit event."""
|
|
215
|
+
self.modified = self.editor.text != self._saved_text
|
|
216
|
+
self.update_title()
|
|
217
|
+
|
|
218
|
+
def update_title(self) -> None:
|
|
219
|
+
name = self.path.name if self.path else "(no file)"
|
|
220
|
+
row = self.editor.cursor_location[0] + 1
|
|
221
|
+
state = self.current_state()
|
|
222
|
+
bits = [name, self.profile.id, f"LN {row}"]
|
|
223
|
+
if state is not None:
|
|
224
|
+
modal = []
|
|
225
|
+
if state.motion is not None:
|
|
226
|
+
modal.append(f"G{state.motion:02d}")
|
|
227
|
+
modal.append(self.profile.absolute if state.absolute else self.profile.incremental)
|
|
228
|
+
modal.append(f"G{state.plane_code}")
|
|
229
|
+
if state.comp != 40:
|
|
230
|
+
modal.append(f"G{state.comp}")
|
|
231
|
+
if state.tool is not None:
|
|
232
|
+
modal.append(f"T{state.tool}")
|
|
233
|
+
bits.append(" ".join(modal))
|
|
234
|
+
if self.modified:
|
|
235
|
+
bits.append("*" + "modified")
|
|
236
|
+
self.sub_title = " ".join(bits)
|
|
237
|
+
|
|
238
|
+
def current_state(self) -> ModalState | None:
|
|
239
|
+
"""Modal state in effect on the cursor's line."""
|
|
240
|
+
editor = self.editor
|
|
241
|
+
row = editor.cursor_location[0]
|
|
242
|
+
program = editor.program
|
|
243
|
+
if row >= len(program.lines):
|
|
244
|
+
return None
|
|
245
|
+
state = ModalState(
|
|
246
|
+
position=dict.fromkeys(self.profile.axes),
|
|
247
|
+
start=dict.fromkeys(self.profile.axes),
|
|
248
|
+
)
|
|
249
|
+
for line in program.lines[: row + 1]:
|
|
250
|
+
state = apply_line(state, line, self.profile)
|
|
251
|
+
return state
|
|
252
|
+
|
|
253
|
+
def refresh_inspector(self) -> None:
|
|
254
|
+
from nctab.core.state import LineState
|
|
255
|
+
|
|
256
|
+
editor = self.editor
|
|
257
|
+
row, col = editor.cursor_location
|
|
258
|
+
program = editor.program
|
|
259
|
+
state = self.current_state()
|
|
260
|
+
if state is None or row >= len(program.lines):
|
|
261
|
+
self.inspector.update(self.profile, None, col)
|
|
262
|
+
return
|
|
263
|
+
self.inspector.update(self.profile, LineState(program.lines[row], state), col)
|
|
264
|
+
|
|
265
|
+
def refresh_outline(self) -> None:
|
|
266
|
+
self.outline.rebuild(self.editor.program, self.profile)
|
|
267
|
+
|
|
268
|
+
# -- events -------------------------------------------------------------
|
|
269
|
+
|
|
270
|
+
@on(NcEditor.Changed)
|
|
271
|
+
def text_changed(self) -> None:
|
|
272
|
+
editor = self.editor
|
|
273
|
+
editor.invalidate_program()
|
|
274
|
+
self.modified = editor.text != self._saved_text
|
|
275
|
+
if editor.search.query is not None:
|
|
276
|
+
editor.search.refresh(editor.program, self.profile)
|
|
277
|
+
self.status.search = f"match {editor.search.position}"
|
|
278
|
+
self.update_title()
|
|
279
|
+
|
|
280
|
+
@on(NcEditor.SelectionChanged)
|
|
281
|
+
def selection_changed(self) -> None:
|
|
282
|
+
self.update_title()
|
|
283
|
+
self.refresh_inspector()
|
|
284
|
+
|
|
285
|
+
@on(NcEditor.SearchMoved)
|
|
286
|
+
def search_moved(self, event: NcEditor.SearchMoved) -> None:
|
|
287
|
+
self.status.search = f"match {event.state.position}"
|
|
288
|
+
|
|
289
|
+
@on(Outline.Selected)
|
|
290
|
+
def outline_selected(self, event: Outline.Selected) -> None:
|
|
291
|
+
self.editor.goto_line(event.line, one_based=False)
|
|
292
|
+
self.editor.focus()
|
|
293
|
+
|
|
294
|
+
@on(Explorer.Open)
|
|
295
|
+
def explorer_open(self, event: Explorer.Open) -> None:
|
|
296
|
+
"""Open a file from the list, unless that would throw away edits."""
|
|
297
|
+
if self.modified:
|
|
298
|
+
self.notify(
|
|
299
|
+
f"{self.path.name if self.path else 'the buffer'} has unsaved changes; "
|
|
300
|
+
"save with Ctrl+S or press Ctrl+R to discard and open",
|
|
301
|
+
severity="warning",
|
|
302
|
+
)
|
|
303
|
+
self._pending_open = event.path
|
|
304
|
+
return
|
|
305
|
+
self.open_path(event.path)
|
|
306
|
+
self.side.active = "tab-outline"
|
|
307
|
+
self.editor.focus()
|
|
308
|
+
|
|
309
|
+
def action_discard_and_open(self) -> None:
|
|
310
|
+
"""Open the file the explorer offered, dropping unsaved changes."""
|
|
311
|
+
pending, self._pending_open = self._pending_open, None
|
|
312
|
+
if pending is None:
|
|
313
|
+
self.say("nothing waiting to open")
|
|
314
|
+
return
|
|
315
|
+
self.open_path(pending)
|
|
316
|
+
self.side.active = "tab-outline"
|
|
317
|
+
self.editor.focus()
|
|
318
|
+
|
|
319
|
+
# -- bookmarks ----------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
@on(NcEditor.PromptKey)
|
|
322
|
+
def prompt_key(self, event: NcEditor.PromptKey) -> None:
|
|
323
|
+
"""A bookmark prompt received its letter."""
|
|
324
|
+
editor = self.editor
|
|
325
|
+
letter = event.character
|
|
326
|
+
if event.purpose == "mark":
|
|
327
|
+
ok = editor.set_bookmark(letter)
|
|
328
|
+
self.say(f"bookmark {letter} set" if ok else "letters a-z only")
|
|
329
|
+
else:
|
|
330
|
+
ok = editor.goto_bookmark(letter)
|
|
331
|
+
self.say(f"bookmark {letter}" if ok else f"no bookmark {letter}")
|
|
332
|
+
|
|
333
|
+
def action_set_bookmark(self) -> None:
|
|
334
|
+
self.editor.await_key("mark")
|
|
335
|
+
self.say("set bookmark: press a letter")
|
|
336
|
+
|
|
337
|
+
def action_goto_bookmark(self) -> None:
|
|
338
|
+
marks = " ".join(sorted(self.editor.bookmarks)) or "none set"
|
|
339
|
+
self.editor.await_key("jump")
|
|
340
|
+
self.say(f"jump to bookmark ({marks}): press a letter")
|
|
341
|
+
|
|
342
|
+
# -- structural navigation ----------------------------------------------
|
|
343
|
+
|
|
344
|
+
def action_next_tool(self) -> None:
|
|
345
|
+
self.say("next tool" if self.editor.next_tool() else "no tool changes")
|
|
346
|
+
|
|
347
|
+
def action_prev_tool(self) -> None:
|
|
348
|
+
self.say("previous tool" if self.editor.prev_tool() else "no tool changes")
|
|
349
|
+
|
|
350
|
+
def action_next_mode(self) -> None:
|
|
351
|
+
self.say("next motion block" if self.editor.next_mode() else "no motion blocks")
|
|
352
|
+
|
|
353
|
+
def action_prev_mode(self) -> None:
|
|
354
|
+
self.say("previous motion block" if self.editor.prev_mode() else "no motion blocks")
|
|
355
|
+
|
|
356
|
+
# -- actions ------------------------------------------------------------
|
|
357
|
+
|
|
358
|
+
def action_focus_side(self) -> None:
|
|
359
|
+
"""Focus whichever of the two left-hand tabs is showing."""
|
|
360
|
+
if self.side.active == "tab-files":
|
|
361
|
+
self.explorer.focus()
|
|
362
|
+
else:
|
|
363
|
+
self.outline.focus()
|
|
364
|
+
|
|
365
|
+
def action_toggle_side(self) -> None:
|
|
366
|
+
self.side.active = "tab-files" if self.side.active == "tab-outline" else "tab-outline"
|
|
367
|
+
self.action_focus_side()
|
|
368
|
+
|
|
369
|
+
def action_find_next(self) -> None:
|
|
370
|
+
if self.editor.find_next() is None:
|
|
371
|
+
self.say("no matches")
|
|
372
|
+
|
|
373
|
+
def action_find_prev(self) -> None:
|
|
374
|
+
if self.editor.find_prev() is None:
|
|
375
|
+
self.say("no matches")
|
|
376
|
+
|
|
377
|
+
def action_help(self) -> None:
|
|
378
|
+
self.say(
|
|
379
|
+
"^F find F3/shift+F3 next,prev ^G goto F4/shift+F4 tool "
|
|
380
|
+
"F5/shift+F5 motion ^B mark ^J jump ^H replace ^N renumber "
|
|
381
|
+
"^T transform F2 snippet F9 outline/files ^O side ^P commands ^S save ^Q quit"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
@work
|
|
385
|
+
async def action_goto(self) -> None:
|
|
386
|
+
target = await self.push_screen_wait(GotoDialog())
|
|
387
|
+
if not target:
|
|
388
|
+
return
|
|
389
|
+
editor = self.editor
|
|
390
|
+
text = str(target).strip()
|
|
391
|
+
if text[:1].upper() == "N":
|
|
392
|
+
number = text[1:].strip()
|
|
393
|
+
ok = number.isdigit() and editor.goto_block(int(number))
|
|
394
|
+
self.say(f"block N{number}" if ok else f"no block N{number}")
|
|
395
|
+
return
|
|
396
|
+
if text.isdigit():
|
|
397
|
+
editor.goto_line(int(text))
|
|
398
|
+
self.say(f"line {text}")
|
|
399
|
+
else:
|
|
400
|
+
self.say(f"cannot parse {text!r}")
|
|
401
|
+
|
|
402
|
+
@work
|
|
403
|
+
async def action_find(self) -> None:
|
|
404
|
+
editor = self.editor
|
|
405
|
+
result = await self.push_screen_wait(
|
|
406
|
+
SearchDialog(editor.program, self.profile, initial=editor.selected_text.strip())
|
|
407
|
+
)
|
|
408
|
+
if not isinstance(result, SearchRequest):
|
|
409
|
+
return
|
|
410
|
+
self.run_search(result)
|
|
411
|
+
|
|
412
|
+
@work
|
|
413
|
+
async def action_replace(self) -> None:
|
|
414
|
+
editor = self.editor
|
|
415
|
+
result = await self.push_screen_wait(
|
|
416
|
+
SearchDialog(editor.program, self.profile, replacing=True)
|
|
417
|
+
)
|
|
418
|
+
if not isinstance(result, SearchRequest) or result.to is None:
|
|
419
|
+
return
|
|
420
|
+
# keep the matches lit so the edit can be seen against the search
|
|
421
|
+
self.run_search(result, announce=False)
|
|
422
|
+
spec = ReplaceSpec(
|
|
423
|
+
query=result.query,
|
|
424
|
+
to=result.to,
|
|
425
|
+
digits=self.config.defaults.digits_or_none,
|
|
426
|
+
rounding=self.config.defaults.rounding,
|
|
427
|
+
only=result.only,
|
|
428
|
+
)
|
|
429
|
+
self.apply_op(replace(editor.program, spec, self.profile), "replace")
|
|
430
|
+
|
|
431
|
+
def run_search(self, request: SearchRequest, *, announce: bool = True) -> None:
|
|
432
|
+
"""Light up the matches, then land on the one the user picked."""
|
|
433
|
+
editor = self.editor
|
|
434
|
+
count = editor.search.run(editor.program, self.profile, request.query)
|
|
435
|
+
editor.refresh()
|
|
436
|
+
if not count:
|
|
437
|
+
self.status.search = f"match {editor.search.position}"
|
|
438
|
+
if announce:
|
|
439
|
+
self.say("no matches")
|
|
440
|
+
return
|
|
441
|
+
if request.start_at is not None:
|
|
442
|
+
line, col = request.start_at
|
|
443
|
+
editor.search.index = next(
|
|
444
|
+
(i for i, m in enumerate(editor.search.matches) if (m.line, m.col) == (line, col)),
|
|
445
|
+
-1,
|
|
446
|
+
)
|
|
447
|
+
if editor.search.current is not None:
|
|
448
|
+
editor.goto_match(editor.search.current)
|
|
449
|
+
else:
|
|
450
|
+
editor.find_next()
|
|
451
|
+
self.status.search = f"match {editor.search.position}"
|
|
452
|
+
if announce:
|
|
453
|
+
self.say(f"{count} matches")
|
|
454
|
+
|
|
455
|
+
@work
|
|
456
|
+
async def action_renumber(self) -> None:
|
|
457
|
+
spec = await self.push_screen_wait(RenumberDialog())
|
|
458
|
+
if not isinstance(spec, RenumberSpec):
|
|
459
|
+
return
|
|
460
|
+
editor = self.editor
|
|
461
|
+
self.apply_op(renumber(editor.program, spec, self.profile), "renumber")
|
|
462
|
+
|
|
463
|
+
@work
|
|
464
|
+
async def action_transform(self) -> None:
|
|
465
|
+
result = await self.push_screen_wait(TransformDialog(list(self.profile.axes)))
|
|
466
|
+
if not isinstance(result, TransformRequest):
|
|
467
|
+
return
|
|
468
|
+
self.apply_transform(result)
|
|
469
|
+
|
|
470
|
+
@work
|
|
471
|
+
async def action_snippet(self) -> None:
|
|
472
|
+
result = await self.push_screen_wait(SnippetDialog(self.snippets))
|
|
473
|
+
if not isinstance(result, SnippetRequest):
|
|
474
|
+
return
|
|
475
|
+
self.insert_snippet(result)
|
|
476
|
+
|
|
477
|
+
def action_check(self) -> None:
|
|
478
|
+
"""Run the same rules the CLI runs and report in the status bar."""
|
|
479
|
+
editor = self.editor
|
|
480
|
+
report = CheckReport.build(
|
|
481
|
+
check_program(editor.program, self.profile),
|
|
482
|
+
profile=self.profile.id,
|
|
483
|
+
lines=len(editor.program),
|
|
484
|
+
)
|
|
485
|
+
if not report.diagnostics:
|
|
486
|
+
self.say("check: no problems found")
|
|
487
|
+
return
|
|
488
|
+
self.say(f"check: {report.errors} errors, {report.warnings} warnings")
|
|
489
|
+
first = report.diagnostics[0]
|
|
490
|
+
if first.line:
|
|
491
|
+
editor.goto_line(first.line)
|
|
492
|
+
for diagnostic in report.diagnostics[:5]:
|
|
493
|
+
severity = "error" if diagnostic.severity == "error" else "warning"
|
|
494
|
+
where = f"{diagnostic.line}: " if diagnostic.line else ""
|
|
495
|
+
self.notify(f"{where}{diagnostic.message}", severity=severity)
|
|
496
|
+
|
|
497
|
+
def insert_snippet(self, request: SnippetRequest) -> None:
|
|
498
|
+
"""Put the rendered body at the cursor, or after the next tool change."""
|
|
499
|
+
editor = self.editor
|
|
500
|
+
row = editor.cursor_location[0]
|
|
501
|
+
if request.after_tool_change:
|
|
502
|
+
stops = [s.line for s in editor.tool_stops() if s.line >= row]
|
|
503
|
+
row = (stops[0] + 1) if stops else row
|
|
504
|
+
editor.insert(request.body, (row, 0))
|
|
505
|
+
editor.invalidate_program()
|
|
506
|
+
editor.goto_line(row, one_based=False)
|
|
507
|
+
self.mark_modified()
|
|
508
|
+
self.refresh_outline()
|
|
509
|
+
self.refresh_inspector()
|
|
510
|
+
self.say(f"inserted {request.snippet.title}")
|
|
511
|
+
|
|
512
|
+
# -- applying operations -------------------------------------------------
|
|
513
|
+
|
|
514
|
+
def apply_transform(self, request: TransformRequest) -> None:
|
|
515
|
+
editor = self.editor
|
|
516
|
+
program = editor.program
|
|
517
|
+
digits = self.config.defaults.digits_or_none
|
|
518
|
+
rounding = self.config.defaults.rounding
|
|
519
|
+
values = request.values
|
|
520
|
+
amount = values.get("amount", Decimal(1))
|
|
521
|
+
|
|
522
|
+
try:
|
|
523
|
+
if request.kind == "shift":
|
|
524
|
+
result = shift(
|
|
525
|
+
program,
|
|
526
|
+
ShiftSpec(
|
|
527
|
+
deltas={k: v for k, v in values.items() if k != "amount"},
|
|
528
|
+
also_incremental=request.also_incremental,
|
|
529
|
+
digits=digits,
|
|
530
|
+
rounding=rounding,
|
|
531
|
+
),
|
|
532
|
+
self.profile,
|
|
533
|
+
)
|
|
534
|
+
elif request.kind == "scale":
|
|
535
|
+
result = scale(
|
|
536
|
+
program,
|
|
537
|
+
ScaleSpec(
|
|
538
|
+
factor=amount,
|
|
539
|
+
about={k: v for k, v in values.items() if k != "amount"},
|
|
540
|
+
digits=digits,
|
|
541
|
+
rounding=rounding,
|
|
542
|
+
),
|
|
543
|
+
self.profile,
|
|
544
|
+
)
|
|
545
|
+
elif request.kind == "mirror":
|
|
546
|
+
result = mirror(
|
|
547
|
+
program,
|
|
548
|
+
MirrorSpec(
|
|
549
|
+
axis=request.axis,
|
|
550
|
+
about=values.get(request.axis, Decimal(0)),
|
|
551
|
+
digits=digits,
|
|
552
|
+
rounding=rounding,
|
|
553
|
+
),
|
|
554
|
+
self.profile,
|
|
555
|
+
)
|
|
556
|
+
elif request.kind == "rotate":
|
|
557
|
+
result = rotate(
|
|
558
|
+
program,
|
|
559
|
+
RotateSpec(
|
|
560
|
+
deg=amount,
|
|
561
|
+
cx=values.get("X", Decimal(0)),
|
|
562
|
+
cy=values.get("Y", Decimal(0)),
|
|
563
|
+
digits=digits,
|
|
564
|
+
rounding=rounding,
|
|
565
|
+
range=Range(),
|
|
566
|
+
),
|
|
567
|
+
self.profile,
|
|
568
|
+
)
|
|
569
|
+
else:
|
|
570
|
+
self.say(f"unknown transform {request.kind}")
|
|
571
|
+
return
|
|
572
|
+
except NctabError as e:
|
|
573
|
+
self.notify(str(e), severity="error")
|
|
574
|
+
return
|
|
575
|
+
self.apply_op(result, request.kind)
|
|
576
|
+
|
|
577
|
+
def apply_op(self, result: OpResult, label: str) -> None:
|
|
578
|
+
"""Put an operation's output into the editor, keeping undo working."""
|
|
579
|
+
editor = self.editor
|
|
580
|
+
if not result.changed:
|
|
581
|
+
self.say(f"{label}: nothing to change")
|
|
582
|
+
for warning in result.warnings:
|
|
583
|
+
self.notify(warning, severity="warning")
|
|
584
|
+
return
|
|
585
|
+
row, col = editor.cursor_location
|
|
586
|
+
editor.replace(
|
|
587
|
+
result.program.text,
|
|
588
|
+
(0, 0),
|
|
589
|
+
editor.document.end,
|
|
590
|
+
maintain_selection_offset=False,
|
|
591
|
+
)
|
|
592
|
+
editor.invalidate_program()
|
|
593
|
+
editor.goto_line(min(row, editor.document.line_count - 1), col, one_based=False)
|
|
594
|
+
self.mark_modified()
|
|
595
|
+
self.refresh_outline()
|
|
596
|
+
self.refresh_inspector()
|
|
597
|
+
self.say(f"{label}: {result.changed_lines} lines, {result.matches} words")
|
|
598
|
+
for warning in result.warnings:
|
|
599
|
+
self.notify(warning, severity="warning")
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def run(path: Path | None = None, profile: Profile | None = None, config: Config | None = None):
|
|
603
|
+
"""Entry point used by ``nctab edit``."""
|
|
604
|
+
NctabApp(path=path, profile=profile, config=config).run()
|
nctab/check/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Program validation (goal.md §6.3)."""
|
|
2
|
+
|
|
3
|
+
from nctab.check.model import CheckReport, Diagnostic, Severity
|
|
4
|
+
from nctab.check.rules import DEFAULT_ARC_TOLERANCE, check_program, rule_codes
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"DEFAULT_ARC_TOLERANCE",
|
|
8
|
+
"CheckReport",
|
|
9
|
+
"Diagnostic",
|
|
10
|
+
"Severity",
|
|
11
|
+
"check_program",
|
|
12
|
+
"rule_codes",
|
|
13
|
+
]
|
nctab/check/model.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Diagnostic model and the stable JSON report schema (goal.md §6.3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict
|
|
8
|
+
|
|
9
|
+
Severity = Literal["error", "warning", "info"]
|
|
10
|
+
_ORDER: dict[str, int] = {"error": 0, "warning": 1, "info": 2}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Diagnostic(BaseModel):
|
|
14
|
+
model_config = ConfigDict(frozen=True)
|
|
15
|
+
|
|
16
|
+
line: int
|
|
17
|
+
"""1-based line number; 0 for whole-program findings."""
|
|
18
|
+
severity: Severity
|
|
19
|
+
code: str
|
|
20
|
+
"""Stable kebab-case identifier, e.g. ``unclosed-comment``."""
|
|
21
|
+
message: str
|
|
22
|
+
block: int | None = None
|
|
23
|
+
text: str = ""
|
|
24
|
+
"""The source line, for context."""
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def sort_key(self) -> tuple[int, int, str]:
|
|
28
|
+
return (self.line, _ORDER[self.severity], self.code)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CheckReport(BaseModel):
|
|
32
|
+
"""JSON-stable report. Fields may be added; never renamed or removed."""
|
|
33
|
+
|
|
34
|
+
model_config = ConfigDict(frozen=True)
|
|
35
|
+
|
|
36
|
+
schema_version: int = 1
|
|
37
|
+
file: str | None = None
|
|
38
|
+
profile: str
|
|
39
|
+
lines: int
|
|
40
|
+
diagnostics: list[Diagnostic]
|
|
41
|
+
errors: int
|
|
42
|
+
warnings: int
|
|
43
|
+
infos: int
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def ok(self) -> bool:
|
|
47
|
+
return self.errors == 0
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def build(
|
|
51
|
+
cls, diagnostics: list[Diagnostic], *, profile: str, lines: int, file: str | None = None
|
|
52
|
+
) -> CheckReport:
|
|
53
|
+
ordered = sorted(diagnostics, key=lambda d: d.sort_key)
|
|
54
|
+
counts = {s: 0 for s in ("error", "warning", "info")}
|
|
55
|
+
for d in ordered:
|
|
56
|
+
counts[d.severity] += 1
|
|
57
|
+
return cls(
|
|
58
|
+
file=file,
|
|
59
|
+
profile=profile,
|
|
60
|
+
lines=lines,
|
|
61
|
+
diagnostics=ordered,
|
|
62
|
+
errors=counts["error"],
|
|
63
|
+
warnings=counts["warning"],
|
|
64
|
+
infos=counts["info"],
|
|
65
|
+
)
|