renpy-language-server 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.

Potentially problematic release.


This version of renpy-language-server might be problematic. Click here for more details.

Files changed (44) hide show
  1. renpy_language_server/__init__.py +6 -0
  2. renpy_language_server/__main__.py +5 -0
  3. renpy_language_server/analysis.py +230 -0
  4. renpy_language_server/assets.py +104 -0
  5. renpy_language_server/builtins.py +54 -0
  6. renpy_language_server/cli.py +190 -0
  7. renpy_language_server/code_actions.py +130 -0
  8. renpy_language_server/completion.py +1191 -0
  9. renpy_language_server/completion_data.py +74 -0
  10. renpy_language_server/dap.py +824 -0
  11. renpy_language_server/data/__init__.py +1 -0
  12. renpy_language_server/data/completion.json +756 -0
  13. renpy_language_server/data/renpy_api.json +8073 -0
  14. renpy_language_server/definition.py +77 -0
  15. renpy_language_server/diagnostics.py +895 -0
  16. renpy_language_server/docs.py +21 -0
  17. renpy_language_server/edits.py +70 -0
  18. renpy_language_server/folding.py +107 -0
  19. renpy_language_server/formatter.py +288 -0
  20. renpy_language_server/hover.py +238 -0
  21. renpy_language_server/index.py +1002 -0
  22. renpy_language_server/positions.py +28 -0
  23. renpy_language_server/py.typed +0 -0
  24. renpy_language_server/python_format.py +141 -0
  25. renpy_language_server/python_index.py +371 -0
  26. renpy_language_server/quotes.py +143 -0
  27. renpy_language_server/references.py +40 -0
  28. renpy_language_server/rename.py +293 -0
  29. renpy_language_server/resolve.py +807 -0
  30. renpy_language_server/scanner.py +86 -0
  31. renpy_language_server/semantic.py +488 -0
  32. renpy_language_server/server.py +770 -0
  33. renpy_language_server/settings.py +187 -0
  34. renpy_language_server/signature.py +371 -0
  35. renpy_language_server/spacing.py +261 -0
  36. renpy_language_server/strings.py +86 -0
  37. renpy_language_server/symbols.py +163 -0
  38. renpy_language_server/targets.py +51 -0
  39. renpy_language_server-0.2.0.dist-info/METADATA +434 -0
  40. renpy_language_server-0.2.0.dist-info/RECORD +44 -0
  41. renpy_language_server-0.2.0.dist-info/WHEEL +4 -0
  42. renpy_language_server-0.2.0.dist-info/entry_points.txt +3 -0
  43. renpy_language_server-0.2.0.dist-info/licenses/LICENSE +21 -0
  44. renpy_language_server-0.2.0.dist-info/licenses/NOTICE.md +41 -0
@@ -0,0 +1,1191 @@
1
+ """Context-aware completion for Ren'Py statements and symbols.
2
+
3
+ This is the light, file-local completion layer: statement keywords plus the
4
+ labels, images, screens and characters defined in the current document, and
5
+ member access through the workspace index. Workspace-wide statement contexts
6
+ are supplied by the server and expanded in Phase 4.
7
+ """
8
+
9
+ import re
10
+ from collections.abc import Iterable, Mapping, Sequence
11
+ from dataclasses import dataclass
12
+ from functools import lru_cache
13
+
14
+ from . import builtins as api
15
+ from .analysis import Block, analyze
16
+ from .completion_data import data as completion_data
17
+ from .index import mask_code
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Completion:
22
+ """One completion item, independent of the LSP data types."""
23
+
24
+ label: str
25
+ kind: str
26
+ detail: str
27
+ documentation: str = ""
28
+ insert_text: str = ""
29
+ sort_text: str = ""
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class CompletionResult:
34
+ """Completion items plus the offset where the typed text starts."""
35
+
36
+ replace_start: int
37
+ items: list[Completion]
38
+
39
+
40
+ _KEYWORDS: tuple[Completion, ...] = (
41
+ Completion("label", "keyword", "statement", "Define a label: `label name:`"),
42
+ Completion("screen", "keyword", "statement", "Define a screen: `screen name():`"),
43
+ Completion(
44
+ "transform", "keyword", "statement", "Define a transform: `transform name:`"
45
+ ),
46
+ Completion("style", "keyword", "statement", "Define or modify a style"),
47
+ Completion("init", "keyword", "statement", "Run a statement at startup"),
48
+ Completion("image", "keyword", "statement", "Define an image"),
49
+ Completion("define", "keyword", "statement", "Define a variable"),
50
+ Completion("default", "keyword", "statement", "Define a default variable"),
51
+ Completion("show", "keyword", "statement", "Show an image: `show eileen happy`"),
52
+ Completion("scene", "keyword", "statement", "Replace the scene"),
53
+ Completion("hide", "keyword", "statement", "Hide an image"),
54
+ Completion("with", "keyword", "statement", "Apply a transition"),
55
+ Completion("jump", "keyword", "statement", "Jump to a label"),
56
+ Completion("call", "keyword", "statement", "Call a label"),
57
+ Completion("expression", "keyword", "keyword", "Use a Python expression"),
58
+ Completion("text", "keyword", "keyword", "Show text or define a text element"),
59
+ Completion("return", "keyword", "statement", "Return from a label"),
60
+ Completion("menu", "keyword", "statement", "Show a choice menu"),
61
+ Completion("if", "keyword", "statement", "Conditional statement"),
62
+ Completion("elif", "keyword", "statement", "Else-if branch"),
63
+ Completion("else", "keyword", "statement", "Else branch"),
64
+ Completion("while", "keyword", "statement", "While loop"),
65
+ Completion("for", "keyword", "statement", "For loop"),
66
+ Completion("python", "keyword", "statement", "Inline Python block"),
67
+ Completion("python early", "keyword", "statement", "Early Python block"),
68
+ Completion("pass", "keyword", "statement", "Do nothing"),
69
+ Completion("pause", "keyword", "statement", "Pause the game"),
70
+ Completion("play", "keyword", "statement", "Play an audio channel"),
71
+ Completion("stop", "keyword", "statement", "Stop an audio channel"),
72
+ Completion("queue", "keyword", "statement", "Queue audio"),
73
+ Completion("voice", "keyword", "statement", "Play a voice line"),
74
+ Completion("window", "keyword", "statement", "Control the dialogue window"),
75
+ Completion("$", "keyword", "statement", "Run a Python statement"),
76
+ )
77
+
78
+ _AFTER_KEYWORD = {
79
+ "show": "image",
80
+ "scene": "image",
81
+ "hide": "image",
82
+ "jump": "label",
83
+ "call": "label",
84
+ }
85
+
86
+ _LABEL_RE = re.compile(r"^[ \t]*label[ \t]+([A-Za-z_.][\w.]*)", re.MULTILINE)
87
+ _IMAGE_RE = re.compile(r"^[ \t]*image[ \t]+([^=\n:]+?)[ \t]*(?:=|:)", re.MULTILINE)
88
+ _SCREEN_RE = re.compile(
89
+ r"^[ \t]*screen[ \t]+([A-Za-z_]\w*)[ \t]*(?:\(|:)", re.MULTILINE
90
+ )
91
+ _CHARACTER_RE = re.compile(
92
+ r"^[ \t]*(?:define|default)[ \t]+([A-Za-z_]\w*)[ \t]*=[ \t]*"
93
+ r"(?:Character|DynamicCharacter)[ \t]*\([ \t]*(?:\"([^\"]*)\"|'([^']*)')?",
94
+ re.MULTILINE,
95
+ )
96
+ _WORD_RE = re.compile(r"[A-Za-z0-9_.$]*$")
97
+ _TARGET_RE = re.compile(r"\S+\s+")
98
+ _MEMBER_RE = re.compile(r"(?<![\w.])([A-Za-z_]\w*)\.([A-Za-z_]\w*)?$")
99
+ _TRANSFORM_RE = re.compile(r"^[ \t]*transform[ \t]+([A-Za-z_]\w*)", re.MULTILINE)
100
+ _STYLE_RE = re.compile(r"^[ \t]*style[ \t]+([A-Za-z_]\w*)", re.MULTILINE)
101
+ _CHANNEL_RE = re.compile(r"register_channel\s*\(\s*[\"']([^\"']+)[\"']", re.MULTILINE)
102
+ _AUDIO_VAR_RE = re.compile(r"^[ \t]*define[ \t]+audio\.([A-Za-z_]\w*)", re.MULTILINE)
103
+ _TRANSITION_VAR_RE = re.compile(
104
+ r"^[ \t]*(?:define|default)[\w \t-]*?\s+([A-Za-z_]\w*)\s*=\s*"
105
+ r"(?:[\w.]*Transition\w*|Dissolve|Fade|Pixellate|Move|Swing)\b",
106
+ re.MULTILINE,
107
+ )
108
+ _CHARACTER_IMAGE_RE = re.compile(
109
+ r"^[ \t]*(?:define|default)[ \t]+([A-Za-z_]\w*)[ \t]*=[ \t]*"
110
+ r"(?:Character|DynamicCharacter)[ \t]*\((.*?)\)",
111
+ re.MULTILINE | re.DOTALL,
112
+ )
113
+ _IMAGE_TAG_RE = re.compile(r"\bimage\s*=\s*[\"']([^\"']+)[\"']")
114
+ _LAYEREDIMAGE_RE = re.compile(
115
+ r"^[ \t]*layeredimage[ \t]+([^:\n]+?)[ \t]*:", re.MULTILINE
116
+ )
117
+ _LAYERED_ATTRIBUTE_RE = re.compile(r"^[ \t]*(?:attribute|group)[ \t]+([A-Za-z_]\w*)")
118
+
119
+ _PYTHON_KEYWORDS = (
120
+ "and",
121
+ "as",
122
+ "assert",
123
+ "break",
124
+ "class",
125
+ "continue",
126
+ "def",
127
+ "del",
128
+ "elif",
129
+ "else",
130
+ "except",
131
+ "False",
132
+ "finally",
133
+ "for",
134
+ "from",
135
+ "global",
136
+ "if",
137
+ "import",
138
+ "in",
139
+ "is",
140
+ "lambda",
141
+ "None",
142
+ "nonlocal",
143
+ "not",
144
+ "or",
145
+ "pass",
146
+ "raise",
147
+ "return",
148
+ "True",
149
+ "try",
150
+ "while",
151
+ "with",
152
+ "yield",
153
+ )
154
+ _PYTHON_BUILTINS = (
155
+ "abs",
156
+ "all",
157
+ "any",
158
+ "bool",
159
+ "dict",
160
+ "enumerate",
161
+ "float",
162
+ "getattr",
163
+ "hasattr",
164
+ "int",
165
+ "isinstance",
166
+ "len",
167
+ "list",
168
+ "max",
169
+ "min",
170
+ "print",
171
+ "range",
172
+ "repr",
173
+ "reversed",
174
+ "set",
175
+ "setattr",
176
+ "sorted",
177
+ "str",
178
+ "sum",
179
+ "tuple",
180
+ "type",
181
+ "zip",
182
+ )
183
+ _ACTION_PROPERTIES = frozenset(
184
+ {
185
+ "action",
186
+ "alternate",
187
+ "hovered",
188
+ "unhovered",
189
+ "released",
190
+ "pressed",
191
+ "selected",
192
+ "insensitive",
193
+ }
194
+ )
195
+ _SCREEN_CONTROL_WORDS = frozenset(
196
+ {"if", "elif", "else", "for", "on", "showif", "python", "default", "style"}
197
+ )
198
+ _DISPLAYABLE_PROPERTIES = frozenset(
199
+ {
200
+ "background",
201
+ "foreground",
202
+ "idle",
203
+ "hover",
204
+ "selected_idle",
205
+ "selected_hover",
206
+ "insensitive",
207
+ "selected_insensitive",
208
+ "idle_background",
209
+ "hover_background",
210
+ "selected_background",
211
+ "insensitive_background",
212
+ "ground",
213
+ "left_bar",
214
+ "right_bar",
215
+ "thumb",
216
+ "thumb_shadow",
217
+ }
218
+ )
219
+
220
+
221
+ @lru_cache(maxsize=1)
222
+ def _builtin_items() -> tuple[Completion, ...]:
223
+ result: list[Completion] = []
224
+ for builtin in api.iter_builtins():
225
+ if builtin.type == "Action":
226
+ kind = "action"
227
+ elif builtin.kind in {"function", "class", "var", "image"}:
228
+ kind = builtin.kind
229
+ else:
230
+ kind = "variable"
231
+ insert = builtin.name
232
+ if builtin.args and builtin.kind in {"function", "class"}:
233
+ insert = f"{builtin.name}()"
234
+ result.append(
235
+ Completion(
236
+ label=builtin.name,
237
+ kind=kind,
238
+ detail=builtin.signature,
239
+ documentation=_builtin_documentation(builtin),
240
+ insert_text=insert,
241
+ )
242
+ )
243
+ return tuple(result)
244
+
245
+
246
+ def _builtin_documentation(builtin: api.Builtin) -> str:
247
+ text = builtin.documentation.strip()
248
+ if not text:
249
+ return f"```renpy\n{builtin.signature}\n```"
250
+ paragraph = text.split("\n\n", 1)[0].strip()
251
+ return f"```renpy\n{builtin.signature}\n```\n\n{_sanitize_markdown(paragraph)}"
252
+
253
+
254
+ _SPHINX_ROLE_RE = re.compile(r":[A-Za-z][\w:-]*:`([^`]*)`")
255
+ _BACKTICK_RUN_RE = re.compile(r"`+")
256
+
257
+
258
+ def _sanitize_markdown(text: str) -> str:
259
+ """Turn reStructuredText leftovers into plain Markdown.
260
+
261
+ Ren'Py's bundled API documentation is reStructuredText. Sphinx roles such
262
+ as ``:doc:`menu <menus>``` and stray unmatched backticks are not valid
263
+ Markdown, so the completion popup would otherwise show them verbatim.
264
+ Matched inline-code spans are preserved.
265
+ """
266
+ return _strip_unmatched_backticks(_SPHINX_ROLE_RE.sub(_plain_role, text))
267
+
268
+
269
+ def _plain_role(match: re.Match[str]) -> str:
270
+ content = match.group(1)
271
+ if content.endswith(">") and "<" in content:
272
+ content = content[: content.rfind("<")].rstrip()
273
+ return content
274
+
275
+
276
+ def _strip_unmatched_backticks(text: str) -> str:
277
+ runs = [(match.start(), match.end()) for match in _BACKTICK_RUN_RE.finditer(text)]
278
+ paired = [False] * len(runs)
279
+ for index, (start, end) in enumerate(runs):
280
+ if paired[index]:
281
+ continue
282
+ for other in range(index + 1, len(runs)):
283
+ other_start, other_end = runs[other]
284
+ if not paired[other] and other_end - other_start == end - start:
285
+ paired[index] = paired[other] = True
286
+ break
287
+
288
+ pieces: list[str] = []
289
+ position = 0
290
+ for index, (start, end) in enumerate(runs):
291
+ pieces.append(text[position:start])
292
+ if paired[index]:
293
+ pieces.append(text[start:end])
294
+ position = end
295
+ pieces.append(text[position:])
296
+ return "".join(pieces)
297
+
298
+
299
+ @lru_cache(maxsize=1)
300
+ def _python_items() -> tuple[Completion, ...]:
301
+ result = [
302
+ Completion(name, "keyword", "Python keyword") for name in _PYTHON_KEYWORDS
303
+ ]
304
+ result += [
305
+ Completion(name, "function", "Python built-in") for name in _PYTHON_BUILTINS
306
+ ]
307
+ return tuple(result)
308
+
309
+
310
+ def complete(
311
+ source: str,
312
+ prefix: str,
313
+ workspace: Mapping[str, Sequence[Completion]] | None = None,
314
+ container: str | None = None,
315
+ line_index: int = -1,
316
+ ) -> CompletionResult:
317
+ """Return completions for ``prefix``, the line text before the cursor.
318
+
319
+ ``workspace`` optionally supplies symbols from other files. Symbols in the
320
+ current document take precedence when both define the same name.
321
+ ``container`` is the enclosing Python class, used for ``self.`` members.
322
+ ``line_index`` enables block-aware screen and Python completion.
323
+ """
324
+ stripped = prefix.lstrip()
325
+ indentation = len(prefix) - len(stripped)
326
+ empty = len(prefix)
327
+
328
+ if not stripped:
329
+ if line_index >= 0:
330
+ screen = _screen_completion(
331
+ source, prefix, workspace, line_index, indentation
332
+ )
333
+ if screen is not None:
334
+ return screen
335
+ return CompletionResult(
336
+ empty,
337
+ _keyword_items() + _symbol_items("character", source, workspace),
338
+ )
339
+
340
+ if _inside_string_or_comment(prefix):
341
+ return CompletionResult(empty, [])
342
+
343
+ member = _member_completion(prefix, workspace, container)
344
+ if member is not None:
345
+ return member
346
+
347
+ namespace = _namespace_completion(prefix)
348
+ if namespace is not None:
349
+ return namespace
350
+
351
+ special = _statement_context(source, prefix, workspace, indentation)
352
+ if special is not None:
353
+ return special
354
+
355
+ screen = _screen_completion(source, prefix, workspace, line_index, indentation)
356
+ if screen is not None:
357
+ return screen
358
+
359
+ dialogue = _dialogue_completion(source, prefix, workspace)
360
+ if dialogue is not None:
361
+ return dialogue
362
+
363
+ python = _python_completion(source, prefix, workspace, line_index)
364
+ if python is not None:
365
+ return python
366
+
367
+ tokens = stripped.split()
368
+ first = tokens[0]
369
+ trailing_space = stripped[-1].isspace()
370
+
371
+ if first == "call" and len(tokens) >= 2 and tokens[1] == "screen":
372
+ if len(tokens) >= 3 or trailing_space:
373
+ start = _target_start(stripped, words=2) + indentation
374
+ return CompletionResult(
375
+ start,
376
+ _filter_kind(
377
+ _symbol_items("screen", source, workspace), prefix[start:]
378
+ ),
379
+ )
380
+ return CompletionResult(
381
+ _word_start(prefix),
382
+ _filter_items(_keyword_items("screen"), _current_word(prefix)),
383
+ )
384
+
385
+ kind = _AFTER_KEYWORD.get(first)
386
+ if kind is not None and (len(tokens) >= 2 or trailing_space):
387
+ start = _target_start(stripped, words=1) + indentation
388
+ items = _symbol_items(kind, source, workspace)
389
+ if first == "call":
390
+ items += _keyword_items("screen")
391
+ return CompletionResult(start, _filter_kind(items, prefix[start:]))
392
+
393
+ if len(tokens) == 1:
394
+ word = _current_word(prefix)
395
+ if not word:
396
+ # A token plus a space is a context we do not understand yet:
397
+ # ``add `` (screen language), ``$ `` (Python), ``e `` (dialogue).
398
+ # Do not dump every statement keyword here.
399
+ return CompletionResult(empty, [])
400
+ items = _filter_items(_keyword_items(), word)
401
+ items += _filter_kind(_symbol_items("character", source, workspace), word)
402
+ items += _filter_items(_top_level_builtin_items(), word)
403
+ return CompletionResult(len(prefix) - len(word), items)
404
+
405
+ return CompletionResult(empty, [])
406
+
407
+
408
+ def _top_level_builtin_items() -> list[Completion]:
409
+ """Return callable API names suitable at the start of a statement."""
410
+ return [
411
+ item
412
+ for item in _builtin_items()
413
+ if item.kind in {"class", "function"}
414
+ and "." not in item.label
415
+ and not item.label.startswith("_")
416
+ ]
417
+
418
+
419
+ def _namespace_completion(prefix: str) -> CompletionResult | None:
420
+ """Complete immediate children of a bundled API namespace."""
421
+ word = _current_word(prefix)
422
+ if "." not in word:
423
+ return None
424
+ namespace = word[: word.rfind(".") + 1]
425
+ if not namespace.startswith(("renpy.", "config.", "gui.", "persistent.")):
426
+ return None
427
+
428
+ typed = word[len(namespace) :]
429
+ children: dict[str, bool] = {}
430
+ for item in _builtin_items():
431
+ if not item.label.startswith(namespace):
432
+ continue
433
+ remainder = item.label[len(namespace) :]
434
+ child = remainder.split(".", 1)[0]
435
+ if not child:
436
+ continue
437
+ children[child] = children.get(child, False) or "." in remainder
438
+ if not children:
439
+ return None
440
+ items = [
441
+ Completion(
442
+ name,
443
+ "keyword" if nested else "builtin",
444
+ "API namespace" if nested else "Ren'Py API",
445
+ )
446
+ for name, nested in children.items()
447
+ ]
448
+ return CompletionResult(len(prefix) - len(typed), _filter_items(items, typed))
449
+
450
+
451
+ def _statement_context(
452
+ source: str,
453
+ prefix: str,
454
+ workspace: Mapping[str, Sequence[Completion]] | None,
455
+ indentation: int,
456
+ ) -> CompletionResult | None:
457
+ """Complete statement arguments and special statement values."""
458
+ stripped = prefix.lstrip()
459
+ tokens = stripped.split()
460
+ if not tokens:
461
+ return None
462
+ first = tokens[0]
463
+ trailing_space = stripped[-1].isspace()
464
+
465
+ if first == "call" and len(tokens) >= 2 and tokens[1] == "screen":
466
+ if len(tokens) >= 3 or trailing_space:
467
+ start = _target_start(stripped, words=2) + indentation
468
+ return CompletionResult(start, _screens(source, workspace, prefix[start:]))
469
+ return CompletionResult(
470
+ _word_start(prefix),
471
+ _filter_items(_keyword_items("screen"), _current_word(prefix)),
472
+ )
473
+
474
+ if first in {"show", "hide"} and len(tokens) >= 2 and tokens[1] == "screen":
475
+ if len(tokens) >= 3 or trailing_space:
476
+ start = _target_start(stripped, words=2) + indentation
477
+ return CompletionResult(start, _screens(source, workspace, prefix[start:]))
478
+ return CompletionResult(
479
+ _word_start(prefix),
480
+ _filter_items(_keyword_items("screen"), _current_word(prefix)),
481
+ )
482
+
483
+ if first == "use" and (len(tokens) >= 2 or trailing_space):
484
+ start = _target_start(stripped, words=1) + indentation
485
+ return CompletionResult(start, _screens(source, workspace, prefix[start:]))
486
+
487
+ if first in {"jump", "call"} and (len(tokens) >= 2 or trailing_space):
488
+ start = _target_start(stripped, words=1) + indentation
489
+ items = _labels(source, workspace)
490
+ items += _keyword_items("expression")
491
+ if first == "call":
492
+ items += _keyword_items("screen")
493
+ return CompletionResult(start, _filter_kind(items, prefix[start:]))
494
+
495
+ masked = mask_code(stripped)
496
+ at_match = (
497
+ re.search(r"\bat\b", masked)
498
+ if first in {"show", "scene", "hide", "label", "screen"}
499
+ else None
500
+ )
501
+ if at_match is not None:
502
+ at_end = at_match.end()
503
+ if at_end < len(stripped) or trailing_space:
504
+ start = at_end + indentation
505
+ while start < len(prefix) and prefix[start].isspace():
506
+ start += 1
507
+ tail = prefix[start:]
508
+ comma = tail.rfind(",")
509
+ if comma >= 0:
510
+ start += comma + 1
511
+ while start < len(prefix) and prefix[start].isspace():
512
+ start += 1
513
+ return CompletionResult(
514
+ start, _transforms(source, workspace, prefix[start:])
515
+ )
516
+
517
+ if first == "with" and (len(tokens) >= 2 or trailing_space):
518
+ start = _target_start(stripped, words=1) + indentation
519
+ return CompletionResult(start, _transitions(source, workspace, prefix[start:]))
520
+
521
+ if first in {"show", "scene", "hide"} and (len(tokens) >= 2 or trailing_space):
522
+ if len(tokens) >= 2 and tokens[1] in {"expression", "text"}:
523
+ return CompletionResult(len(prefix), [])
524
+ start = _target_start(stripped, words=1) + indentation
525
+ items = _images(source, workspace)
526
+ items += _keyword_items("expression")
527
+ items += _keyword_items("screen")
528
+ if first == "show":
529
+ items += _keyword_items("text")
530
+ return CompletionResult(start, _filter_kind(items, prefix[start:]))
531
+
532
+ if first in {"play", "queue", "stop"} and (len(tokens) >= 2 or trailing_space):
533
+ return _audio_statement(source, prefix, workspace, first, indentation)
534
+
535
+ return None
536
+
537
+
538
+ def _audio_statement(
539
+ source: str,
540
+ prefix: str,
541
+ workspace: Mapping[str, Sequence[Completion]] | None,
542
+ command: str,
543
+ indentation: int,
544
+ ) -> CompletionResult:
545
+ stripped = prefix.lstrip()
546
+ tokens = stripped.split()
547
+ trailing_space = stripped[-1].isspace()
548
+ data = completion_data()
549
+ channels = _unique(list(data.audio_channels) + _local_channels(source))
550
+
551
+ word = _current_word(prefix)
552
+ if word.startswith("audio."):
553
+ typed = word[len("audio.") :]
554
+ items = [
555
+ Completion(
556
+ item.label[len("audio.") :],
557
+ "audio",
558
+ "audio variable",
559
+ item.documentation,
560
+ insert_text=item.label,
561
+ )
562
+ for item in _audio_assets(source, workspace)
563
+ if item.label.startswith("audio.")
564
+ ]
565
+ return CompletionResult(len(prefix) - len(typed), _filter_items(items, typed))
566
+
567
+ if len(tokens) == 1 and trailing_space:
568
+ return CompletionResult(
569
+ len(prefix),
570
+ [Completion(name, "keyword", "audio channel") for name in channels],
571
+ )
572
+ if len(tokens) == 2 and not trailing_space:
573
+ start = _target_start(stripped, words=1) + indentation
574
+ return CompletionResult(
575
+ start,
576
+ _filter_items(
577
+ [Completion(name, "keyword", "audio channel") for name in channels],
578
+ tokens[1],
579
+ ),
580
+ )
581
+
582
+ start = _target_start(stripped, words=2) + indentation
583
+ if len(tokens) == 2:
584
+ options = (
585
+ ["fadeout"]
586
+ if command == "stop"
587
+ else [
588
+ "fadein",
589
+ "fadeout",
590
+ "loop",
591
+ "noloop",
592
+ "if_changed",
593
+ "volume",
594
+ ]
595
+ )
596
+ items = _audio_assets(source, workspace)
597
+ items += [Completion(name, "keyword", "audio option") for name in options]
598
+ return CompletionResult(start, items)
599
+
600
+ option_names = {
601
+ "fadein",
602
+ "fadeout",
603
+ "loop",
604
+ "noloop",
605
+ "if_changed",
606
+ "volume",
607
+ }
608
+ last = tokens[-1]
609
+ if last in option_names and trailing_space:
610
+ return CompletionResult(
611
+ len(prefix),
612
+ [
613
+ Completion(name, "value", "audio option value")
614
+ for name in completion_data().values_for(last)
615
+ ],
616
+ )
617
+ word = _current_word(prefix)
618
+ start = len(prefix) - len(word)
619
+ return CompletionResult(
620
+ start,
621
+ _filter_items(
622
+ [
623
+ Completion(name, "keyword", "audio option")
624
+ for name in (
625
+ ["fadeout"]
626
+ if command == "stop"
627
+ else [
628
+ "fadein",
629
+ "fadeout",
630
+ "loop",
631
+ "noloop",
632
+ "if_changed",
633
+ "volume",
634
+ ]
635
+ )
636
+ ],
637
+ word,
638
+ ),
639
+ )
640
+
641
+
642
+ def _keyword_items(word: str | None = None) -> list[Completion]:
643
+ return [item for item in _KEYWORDS if word is None or _matches(item.label, word)]
644
+
645
+
646
+ def _member_completion(
647
+ prefix: str,
648
+ workspace: Mapping[str, Sequence[Completion]] | None,
649
+ container: str | None,
650
+ ) -> CompletionResult | None:
651
+ """Complete members after ``Class.``, ``self.``, ``persistent.`` or ``store.``."""
652
+ if workspace is None:
653
+ return None
654
+ match = _MEMBER_RE.search(prefix)
655
+ if match is None:
656
+ return None
657
+
658
+ owner = match.group(1)
659
+ typed = match.group(2) or ""
660
+ if owner == "self":
661
+ if not container:
662
+ return None
663
+ key = f"member:{container}"
664
+ elif owner == "persistent":
665
+ key = "persistent"
666
+ elif owner == "store":
667
+ key = "variable"
668
+ else:
669
+ key = f"member:{owner}"
670
+
671
+ items = workspace.get(key, ())
672
+ if not items:
673
+ return None
674
+ start = match.start(2) if match.group(2) is not None else len(prefix)
675
+ return CompletionResult(start, _filter_items(list(items), typed))
676
+
677
+
678
+ def _symbol_items(
679
+ kind: str,
680
+ source: str,
681
+ workspace: Mapping[str, Sequence[Completion]] | None = None,
682
+ ) -> list[Completion]:
683
+ local = _local_symbol_items(kind, source)
684
+ if workspace is None:
685
+ return local
686
+ return _merge_items(local, workspace.get(kind, ()))
687
+
688
+
689
+ def _labels(
690
+ source: str, workspace: Mapping[str, Sequence[Completion]] | None
691
+ ) -> list[Completion]:
692
+ return _symbol_items("label", source, workspace)
693
+
694
+
695
+ def _images(
696
+ source: str, workspace: Mapping[str, Sequence[Completion]] | None
697
+ ) -> list[Completion]:
698
+ return _symbol_items("image", source, workspace)
699
+
700
+
701
+ def _screens(
702
+ source: str,
703
+ workspace: Mapping[str, Sequence[Completion]] | None,
704
+ typed: str,
705
+ ) -> list[Completion]:
706
+ return _filter_kind(_symbol_items("screen", source, workspace), typed)
707
+
708
+
709
+ def _transforms(
710
+ source: str,
711
+ workspace: Mapping[str, Sequence[Completion]] | None,
712
+ typed: str,
713
+ ) -> list[Completion]:
714
+ local = [
715
+ Completion(name, "transform", "transform")
716
+ for name in _unique(_TRANSFORM_RE.findall(source))
717
+ ]
718
+ builtins = [
719
+ Completion(name, "transform", "built-in transform")
720
+ for name in completion_data().transforms
721
+ ]
722
+ external = workspace.get("transform", ()) if workspace is not None else ()
723
+ items = _merge_items(local, builtins)
724
+ items = _merge_items(items, external)
725
+ return _filter_kind(items, typed)
726
+
727
+
728
+ def _transitions(
729
+ source: str,
730
+ workspace: Mapping[str, Sequence[Completion]] | None,
731
+ typed: str,
732
+ ) -> list[Completion]:
733
+ local = [
734
+ Completion(name, "transition", "transition")
735
+ for name in _unique(_TRANSITION_VAR_RE.findall(source))
736
+ ]
737
+ builtins = [
738
+ Completion(name, "transition", "built-in transition")
739
+ for name in completion_data().transitions
740
+ ]
741
+ external = workspace.get("transition", ()) if workspace is not None else ()
742
+ items = _merge_items(local, builtins)
743
+ items = _merge_items(items, external)
744
+ return _filter_kind(items, typed)
745
+
746
+
747
+ def _styles(
748
+ source: str, workspace: Mapping[str, Sequence[Completion]] | None
749
+ ) -> list[Completion]:
750
+ local = [
751
+ Completion(name, "style", "style")
752
+ for name in _unique(_STYLE_RE.findall(source))
753
+ ]
754
+ external = workspace.get("style", ()) if workspace is not None else ()
755
+ return _merge_items(local, external)
756
+
757
+
758
+ def _local_channels(source: str) -> list[str]:
759
+ return _unique(_CHANNEL_RE.findall(source))
760
+
761
+
762
+ def _audio_assets(
763
+ source: str, workspace: Mapping[str, Sequence[Completion]] | None
764
+ ) -> list[Completion]:
765
+ local = [
766
+ Completion(
767
+ f"audio.{name}",
768
+ "audio",
769
+ "audio variable",
770
+ f"`audio.{name}`",
771
+ insert_text=f"audio.{name}",
772
+ )
773
+ for name in _unique(_AUDIO_VAR_RE.findall(source))
774
+ ]
775
+ external = workspace.get("audio", ()) if workspace is not None else ()
776
+ return _merge_items(local, external)
777
+
778
+
779
+ def _local_symbol_items(kind: str, source: str) -> list[Completion]:
780
+ if kind == "label":
781
+ names = _parse_labels(source)
782
+ return [
783
+ Completion(name, "label", "label", f"Label `{name}` in this file")
784
+ for name in names
785
+ ]
786
+ if kind == "image":
787
+ names = _parse_images(source)
788
+ return [
789
+ Completion(name, "image", "image", f"Image `{name}` in this file")
790
+ for name in names
791
+ ]
792
+ if kind == "screen":
793
+ names = _parse_screens(source)
794
+ return [
795
+ Completion(name, "screen", "screen", f"Screen `{name}` in this file")
796
+ for name in names
797
+ ]
798
+ if kind == "character":
799
+ return [
800
+ Completion(
801
+ name,
802
+ "character",
803
+ f'character "{display}"' if display else "character",
804
+ f"Character `{name}` in this file",
805
+ )
806
+ for name, display in _parse_characters(source)
807
+ ]
808
+ return []
809
+
810
+
811
+ def _merge_items(
812
+ local: Sequence[Completion], external: Sequence[Completion]
813
+ ) -> list[Completion]:
814
+ result = list(local)
815
+ seen = {item.label for item in local}
816
+ for item in external:
817
+ if item.label not in seen:
818
+ seen.add(item.label)
819
+ result.append(item)
820
+ return result
821
+
822
+
823
+ def _screen_completion(
824
+ source: str,
825
+ prefix: str,
826
+ workspace: Mapping[str, Sequence[Completion]] | None,
827
+ line_index: int,
828
+ indentation: int,
829
+ ) -> CompletionResult | None:
830
+ """Complete screen elements, properties and property values."""
831
+ if line_index < 0:
832
+ return None
833
+ analysis = analyze(source)
834
+ probe = line_index if prefix.strip() else max(line_index - 1, 0)
835
+ block = analysis.block_at(probe)
836
+ screen = _screen_block(block)
837
+ if screen is None:
838
+ return None
839
+
840
+ stripped = prefix.lstrip()
841
+ data = completion_data()
842
+ enclosing = _enclosing_element(block)
843
+ elements = [
844
+ Completion(name, "keyword", "screen element") for name in data.screen_elements
845
+ ]
846
+
847
+ if not stripped:
848
+ items = list(elements)
849
+ if enclosing:
850
+ items += _property_items(enclosing)
851
+ return CompletionResult(len(prefix), items)
852
+
853
+ tokens = stripped.split()
854
+ trailing_space = stripped[-1].isspace()
855
+ first = tokens[0]
856
+ if first in _SCREEN_CONTROL_WORDS:
857
+ return None
858
+ if first == "use" and (len(tokens) >= 2 or trailing_space):
859
+ start = _target_start(stripped, words=1) + indentation
860
+ return CompletionResult(start, _screens(source, workspace, prefix[start:]))
861
+
862
+ element = first if first in data.screen_elements else enclosing
863
+ properties = _property_items(element) if element else []
864
+ property_names = {item.label for item in properties}
865
+ before = tokens if trailing_space else tokens[:-1]
866
+ last_property = next(
867
+ (token for token in reversed(before) if token in property_names), ""
868
+ )
869
+ if last_property:
870
+ start = _word_start(prefix)
871
+ return CompletionResult(
872
+ start,
873
+ _property_value_items(last_property, source, workspace, prefix[start:]),
874
+ )
875
+
876
+ if first in data.screen_elements:
877
+ if len(tokens) >= 2 or trailing_space:
878
+ start = _word_start(prefix)
879
+ return CompletionResult(
880
+ start, _filter_items(properties, prefix[start:].strip())
881
+ )
882
+ word = _current_word(prefix)
883
+ return CompletionResult(
884
+ len(prefix) - len(word),
885
+ _filter_items(elements + properties, word),
886
+ )
887
+
888
+ if first in property_names:
889
+ if len(tokens) >= 2 or trailing_space:
890
+ start = _word_start(prefix)
891
+ return CompletionResult(
892
+ start,
893
+ _property_value_items(first, source, workspace, prefix[start:]),
894
+ )
895
+ word = _current_word(prefix)
896
+ return CompletionResult(
897
+ len(prefix) - len(word), _filter_items(properties, word)
898
+ )
899
+
900
+ word = _current_word(prefix)
901
+ if word:
902
+ items = list(elements)
903
+ if enclosing:
904
+ items += properties
905
+ return CompletionResult(len(prefix) - len(word), _filter_items(items, word))
906
+ return CompletionResult(len(prefix), elements)
907
+
908
+
909
+ def _block_word(block: Block) -> str:
910
+ return block.line.first_word.rstrip(":")
911
+
912
+
913
+ def _screen_block(block: Block | None) -> Block | None:
914
+ current = block
915
+ while current is not None:
916
+ if _block_word(current) == "screen":
917
+ return current
918
+ current = current.parent
919
+ return None
920
+
921
+
922
+ def _enclosing_element(block: Block | None) -> str:
923
+ data = completion_data()
924
+ current = block
925
+ while current is not None:
926
+ word = _block_word(current)
927
+ if word == "screen":
928
+ return ""
929
+ if word in data.screen_elements and word not in _SCREEN_CONTROL_WORDS:
930
+ return word
931
+ current = current.parent
932
+ return ""
933
+
934
+
935
+ def _property_items(element: str) -> list[Completion]:
936
+ if not element:
937
+ return []
938
+ return [
939
+ Completion(name, "property", f"{element} property")
940
+ for name in completion_data().properties_for(element)
941
+ ]
942
+
943
+
944
+ def _property_value_items(
945
+ name: str,
946
+ source: str,
947
+ workspace: Mapping[str, Sequence[Completion]] | None,
948
+ typed: str,
949
+ ) -> list[Completion]:
950
+ if name in _ACTION_PROPERTIES:
951
+ items = _action_items()
952
+ elif name == "at":
953
+ return _transforms(source, workspace, typed)
954
+ elif name in {"with", "transition"}:
955
+ return _transitions(source, workspace, typed)
956
+ elif name == "style":
957
+ return _filter_items(_styles(source, workspace), typed)
958
+ elif name in _DISPLAYABLE_PROPERTIES:
959
+ items = [
960
+ Completion(value, "value", f"{name} value")
961
+ for value in completion_data().values_for(name)
962
+ ]
963
+ items += _images(source, workspace)
964
+ else:
965
+ items = [
966
+ Completion(value, "value", f"{name} value")
967
+ for value in completion_data().values_for(name)
968
+ ]
969
+ return _filter_items(items, typed)
970
+
971
+
972
+ def _action_items() -> list[Completion]:
973
+ return [item for item in _builtin_items() if item.kind == "action"]
974
+
975
+
976
+ def _dialogue_completion(
977
+ source: str,
978
+ prefix: str,
979
+ workspace: Mapping[str, Sequence[Completion]] | None,
980
+ ) -> CompletionResult | None:
981
+ """Complete image attributes after a character speaking tag."""
982
+ stripped = prefix.lstrip()
983
+ tokens = stripped.split()
984
+ if not tokens:
985
+ return None
986
+ trailing_space = stripped[-1].isspace()
987
+ if len(tokens) < 2 and not trailing_space:
988
+ return None
989
+ speaker = tokens[0]
990
+ characters = dict(_character_images(source))
991
+ tag = characters.get(speaker)
992
+ if not tag:
993
+ return None
994
+ attributes = _image_attributes(source, tag)
995
+ if not attributes:
996
+ return None
997
+ word = _current_word(prefix)
998
+ start = len(prefix) - len(word)
999
+ items = [Completion(name, "attribute", f"{tag} attribute") for name in attributes]
1000
+ return CompletionResult(start, _filter_items(items, word))
1001
+
1002
+
1003
+ def _python_completion(
1004
+ source: str,
1005
+ prefix: str,
1006
+ workspace: Mapping[str, Sequence[Completion]] | None,
1007
+ line_index: int,
1008
+ ) -> CompletionResult | None:
1009
+ """Complete Python keywords and built-ins in expression contexts."""
1010
+ stripped = prefix.lstrip()
1011
+ tokens = stripped.split()
1012
+ if not tokens:
1013
+ return None
1014
+ first = tokens[0]
1015
+ trailing_space = stripped[-1].isspace()
1016
+ word = _current_word(prefix)
1017
+ start = len(prefix) - len(word)
1018
+ extra = _python_symbol_items(source, workspace)
1019
+
1020
+ if first == "$" and (len(tokens) >= 2 or trailing_space):
1021
+ items = list(_python_items()) + _top_level_builtin_items() + extra
1022
+ return CompletionResult(start, _filter_items(items, word))
1023
+
1024
+ if first in {"if", "elif", "while"} and (len(tokens) >= 2 or trailing_space):
1025
+ return CompletionResult(
1026
+ start, _filter_items(list(_python_items()) + extra, word)
1027
+ )
1028
+
1029
+ if first in {"define", "default"} and "=" in stripped:
1030
+ start = _word_start(prefix)
1031
+ typed = prefix[start:]
1032
+ return CompletionResult(
1033
+ start, _filter_items(list(_builtin_items()) + extra, typed)
1034
+ )
1035
+
1036
+ if line_index >= 0 and _in_python_block(source, line_index):
1037
+ if "=" in prefix or stripped.startswith(("return ", "raise ")):
1038
+ return None
1039
+ return CompletionResult(start, _filter_items(list(_python_items()), word))
1040
+
1041
+ return None
1042
+
1043
+
1044
+ def _python_symbol_items(
1045
+ source: str, workspace: Mapping[str, Sequence[Completion]] | None
1046
+ ) -> list[Completion]:
1047
+ items = _symbol_items("variable", source, workspace)
1048
+ items += _symbol_items("class", source, workspace)
1049
+ items += _symbol_items("persistent", source, workspace)
1050
+ return items
1051
+
1052
+
1053
+ def _in_python_block(source: str, line_index: int) -> bool:
1054
+ analysis = analyze(source)
1055
+ block = analysis.block_at(line_index)
1056
+ while block is not None:
1057
+ text = block.line.text.strip()
1058
+ if (
1059
+ text == "python:"
1060
+ or text.startswith("python ")
1061
+ or text.endswith(" python:")
1062
+ or " python early" in f" {text}"
1063
+ ):
1064
+ return True
1065
+ block = block.parent
1066
+ return False
1067
+
1068
+
1069
+ def _character_images(source: str) -> list[tuple[str, str]]:
1070
+ result: list[tuple[str, str]] = []
1071
+ for match in _CHARACTER_IMAGE_RE.finditer(source):
1072
+ image = _IMAGE_TAG_RE.search(match.group(2))
1073
+ if image is not None:
1074
+ result.append((match.group(1), image.group(1)))
1075
+ return result
1076
+
1077
+
1078
+ def _image_attributes(source: str, tag: str) -> list[str]:
1079
+ result: list[str] = []
1080
+ for match in _IMAGE_RE.finditer(source):
1081
+ name = match.group(1).strip()
1082
+ if not name.startswith(f"{tag} "):
1083
+ continue
1084
+ result.extend(name[len(tag) + 1 :].split())
1085
+ for match in _LAYEREDIMAGE_RE.finditer(source):
1086
+ if match.group(1).strip() != tag:
1087
+ continue
1088
+ tail = source[match.end() :]
1089
+ for line in tail.splitlines():
1090
+ if line.strip() and not line[:1].isspace():
1091
+ break
1092
+ attribute = _LAYERED_ATTRIBUTE_RE.match(line)
1093
+ if attribute is not None:
1094
+ result.append(attribute.group(1))
1095
+ return _unique(result)
1096
+
1097
+
1098
+ def _parse_labels(source: str) -> list[str]:
1099
+ return _unique(match.group(1) for match in _LABEL_RE.finditer(source))
1100
+
1101
+
1102
+ def _parse_images(source: str) -> list[str]:
1103
+ return _unique(
1104
+ match.group(1).strip()
1105
+ for match in _IMAGE_RE.finditer(source)
1106
+ if match.group(1).strip()
1107
+ )
1108
+
1109
+
1110
+ def _parse_screens(source: str) -> list[str]:
1111
+ return _unique(match.group(1) for match in _SCREEN_RE.finditer(source))
1112
+
1113
+
1114
+ def _parse_characters(source: str) -> list[tuple[str, str | None]]:
1115
+ result: list[tuple[str, str | None]] = []
1116
+ seen: set[str] = set()
1117
+ for match in _CHARACTER_RE.finditer(source):
1118
+ name = match.group(1)
1119
+ if name in seen:
1120
+ continue
1121
+ seen.add(name)
1122
+ display = match.group(2) if match.group(2) is not None else match.group(3)
1123
+ result.append((name, display))
1124
+ return result
1125
+
1126
+
1127
+ def _unique(values: Iterable[str]) -> list[str]:
1128
+ result: list[str] = []
1129
+ seen: set[str] = set()
1130
+ for value in values:
1131
+ if value not in seen:
1132
+ seen.add(value)
1133
+ result.append(value)
1134
+ return result
1135
+
1136
+
1137
+ def _filter_items(items: list[Completion], typed: str) -> list[Completion]:
1138
+ if not typed:
1139
+ return items
1140
+ return [item for item in items if _matches(item.label, typed)]
1141
+
1142
+
1143
+ def _filter_kind(items: list[Completion], typed: str) -> list[Completion]:
1144
+ return _filter_items(items, typed)
1145
+
1146
+
1147
+ def _matches(name: str, typed: str) -> bool:
1148
+ name_lower = name.lower()
1149
+ typed_lower = typed.lower()
1150
+ return name_lower.startswith(typed_lower) or typed_lower in name_lower
1151
+
1152
+
1153
+ def _current_word(prefix: str) -> str:
1154
+ match = _WORD_RE.search(prefix)
1155
+ return match.group(0) if match else ""
1156
+
1157
+
1158
+ def _word_start(prefix: str) -> int:
1159
+ return len(prefix) - len(_current_word(prefix))
1160
+
1161
+
1162
+ def _target_start(stripped: str, words: int) -> int:
1163
+ """Offset in ``stripped`` after the first ``words`` tokens and whitespace."""
1164
+ offset = 0
1165
+ for _ in range(words):
1166
+ match = re.match(r"\S+", stripped[offset:])
1167
+ if match is None:
1168
+ return len(stripped)
1169
+ offset += match.end()
1170
+ while offset < len(stripped) and stripped[offset].isspace():
1171
+ offset += 1
1172
+ return offset
1173
+
1174
+
1175
+ def _inside_string_or_comment(prefix: str) -> bool:
1176
+ """True when the cursor is inside a quoted string or after a comment."""
1177
+ quote: str | None = None
1178
+ escaped = False
1179
+ for char in prefix:
1180
+ if quote is not None:
1181
+ if escaped:
1182
+ escaped = False
1183
+ elif char == "\\":
1184
+ escaped = True
1185
+ elif char == quote:
1186
+ quote = None
1187
+ elif char in "\"'":
1188
+ quote = char
1189
+ elif char == "#":
1190
+ return True
1191
+ return quote is not None