pycforge 0.15.2__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.
Files changed (221) hide show
  1. pycforge/__init__.py +8 -0
  2. pycforge/__main__.py +2 -0
  3. pycforge/_version.py +1 -0
  4. pycforge/converter/__init__.py +0 -0
  5. pycforge/converter/analysis/__init__.py +5 -0
  6. pycforge/converter/analysis/functions.py +723 -0
  7. pycforge/converter/analysis/model.py +158 -0
  8. pycforge/converter/analysis/planning.py +464 -0
  9. pycforge/converter/analysis/stage.py +1976 -0
  10. pycforge/converter/analysis/symbols.py +237 -0
  11. pycforge/converter/analysis/validation.py +2166 -0
  12. pycforge/converter/c_output/__init__.py +2 -0
  13. pycforge/converter/c_output/conformance.py +297 -0
  14. pycforge/converter/c_output/renderer.py +220 -0
  15. pycforge/converter/conditional_regions/__init__.py +71 -0
  16. pycforge/converter/conditional_regions/analysis.py +481 -0
  17. pycforge/converter/conditional_regions/lowering.py +579 -0
  18. pycforge/converter/conditional_regions/model.py +243 -0
  19. pycforge/converter/conditional_regions/validation.py +690 -0
  20. pycforge/converter/containers/__init__.py +19 -0
  21. pycforge/converter/containers/analysis.py +542 -0
  22. pycforge/converter/containers/lowering.py +290 -0
  23. pycforge/converter/containers/model.py +146 -0
  24. pycforge/converter/contracts/__init__.py +0 -0
  25. pycforge/converter/contracts/configuration.py +178 -0
  26. pycforge/converter/contracts/identifiers.py +68 -0
  27. pycforge/converter/contracts/versions.py +71 -0
  28. pycforge/converter/core/__init__.py +0 -0
  29. pycforge/converter/core/artifact_io.py +87 -0
  30. pycforge/converter/core/cancellation.py +7 -0
  31. pycforge/converter/core/canonicalization.py +254 -0
  32. pycforge/converter/core/context.py +13 -0
  33. pycforge/converter/core/diagnostics.py +95 -0
  34. pycforge/converter/core/enums.py +23 -0
  35. pycforge/converter/core/fingerprint.py +22 -0
  36. pycforge/converter/core/pipeline.py +8 -0
  37. pycforge/converter/core/progress.py +25 -0
  38. pycforge/converter/core/request.py +50 -0
  39. pycforge/converter/core/resource_policy.py +31 -0
  40. pycforge/converter/core/result.py +23 -0
  41. pycforge/converter/core/serialization.py +36 -0
  42. pycforge/converter/core/stage.py +10 -0
  43. pycforge/converter/core/stage_artifact.py +80 -0
  44. pycforge/converter/core/stage_outcome.py +15 -0
  45. pycforge/converter/decision_trace/__init__.py +0 -0
  46. pycforge/converter/decision_trace/recorder.py +52 -0
  47. pycforge/converter/facade.py +459 -0
  48. pycforge/converter/frontend/__init__.py +4 -0
  49. pycforge/converter/frontend/normalizer.py +59 -0
  50. pycforge/converter/frontend/parser.py +20 -0
  51. pycforge/converter/frontend/source_document.py +93 -0
  52. pycforge/converter/frontend/stages.py +518 -0
  53. pycforge/converter/frontend/validation.py +76 -0
  54. pycforge/converter/io/__init__.py +0 -0
  55. pycforge/converter/io/atomic_writer.py +33 -0
  56. pycforge/converter/ir/__init__.py +1 -0
  57. pycforge/converter/ir/c_ir/__init__.py +4 -0
  58. pycforge/converter/ir/c_ir/builder.py +26 -0
  59. pycforge/converter/ir/c_ir/model.py +318 -0
  60. pycforge/converter/ir/c_ir/serialization.py +88 -0
  61. pycforge/converter/ir/c_ir/validation.py +834 -0
  62. pycforge/converter/ir/python_ir/__init__.py +17 -0
  63. pycforge/converter/ir/python_ir/nodes.py +86 -0
  64. pycforge/converter/keyword_calls/__init__.py +68 -0
  65. pycforge/converter/keyword_calls/analysis.py +458 -0
  66. pycforge/converter/keyword_calls/lowering.py +271 -0
  67. pycforge/converter/keyword_calls/model.py +304 -0
  68. pycforge/converter/keyword_calls/validation.py +802 -0
  69. pycforge/converter/keyword_only_calls/__init__.py +68 -0
  70. pycforge/converter/keyword_only_calls/analysis.py +640 -0
  71. pycforge/converter/keyword_only_calls/lowering.py +376 -0
  72. pycforge/converter/keyword_only_calls/model.py +328 -0
  73. pycforge/converter/keyword_only_calls/validation.py +1357 -0
  74. pycforge/converter/lowering.py +1000 -0
  75. pycforge/converter/modules/__init__.py +13 -0
  76. pycforge/converter/modules/analysis.py +1250 -0
  77. pycforge/converter/modules/lowering.py +200 -0
  78. pycforge/converter/modules/model.py +73 -0
  79. pycforge/converter/modules/stage.py +192 -0
  80. pycforge/converter/numeric_semantics/__init__.py +23 -0
  81. pycforge/converter/numeric_semantics/analysis.py +420 -0
  82. pycforge/converter/numeric_semantics/lowering.py +153 -0
  83. pycforge/converter/numeric_semantics/model.py +123 -0
  84. pycforge/converter/records/__init__.py +34 -0
  85. pycforge/converter/records/analysis.py +1394 -0
  86. pycforge/converter/records/lowering.py +393 -0
  87. pycforge/converter/records/model.py +319 -0
  88. pycforge/converter/rules/__init__.py +3 -0
  89. pycforge/converter/support_templates/__init__.py +49 -0
  90. pycforge/converter/support_templates/assembly.py +106 -0
  91. pycforge/converter/support_templates/factories.py +348 -0
  92. pycforge/converter/support_templates/model.py +159 -0
  93. pycforge/converter/support_templates/registry.py +388 -0
  94. pycforge/converter/telemetry/__init__.py +0 -0
  95. pycforge/converter/telemetry/sink.py +39 -0
  96. pycforge/ide/__init__.py +19 -0
  97. pycforge/ide/__main__.py +5 -0
  98. pycforge/ide/_worker_event_codec.py +276 -0
  99. pycforge/ide/_worker_protocol_json.py +197 -0
  100. pycforge/ide/_worker_protocol_types.py +90 -0
  101. pycforge/ide/_worker_request_codec.py +200 -0
  102. pycforge/ide/_worker_request_data.py +260 -0
  103. pycforge/ide/_worker_result_data.py +343 -0
  104. pycforge/ide/action_contract.py +469 -0
  105. pycforge/ide/action_validation.py +229 -0
  106. pycforge/ide/command_palette.py +223 -0
  107. pycforge/ide/controller.py +904 -0
  108. pycforge/ide/controller_conversion.py +546 -0
  109. pycforge/ide/controller_io.py +205 -0
  110. pycforge/ide/editor.py +951 -0
  111. pycforge/ide/editor_commands_qt.py +274 -0
  112. pycforge/ide/editor_lexical.py +43 -0
  113. pycforge/ide/editor_sidebars.py +236 -0
  114. pycforge/ide/editor_syntax.py +243 -0
  115. pycforge/ide/find_replace.py +535 -0
  116. pycforge/ide/icons.py +91 -0
  117. pycforge/ide/io_service.py +196 -0
  118. pycforge/ide/model.py +164 -0
  119. pycforge/ide/panels.py +903 -0
  120. pycforge/ide/positions.py +220 -0
  121. pycforge/ide/process_worker.py +130 -0
  122. pycforge/ide/qt.py +230 -0
  123. pycforge/ide/qt_actions.py +418 -0
  124. pycforge/ide/qt_close.py +169 -0
  125. pycforge/ide/qt_command_palette.py +297 -0
  126. pycforge/ide/qt_contract.py +220 -0
  127. pycforge/ide/qt_documents.py +590 -0
  128. pycforge/ide/qt_editor_buffers.py +113 -0
  129. pycforge/ide/qt_editor_surfaces.py +112 -0
  130. pycforge/ide/qt_menus.py +324 -0
  131. pycforge/ide/qt_projection.py +500 -0
  132. pycforge/ide/qt_shell.py +348 -0
  133. pycforge/ide/qt_shell_interactions.py +320 -0
  134. pycforge/ide/qt_state.py +393 -0
  135. pycforge/ide/qt_workspace_features.py +398 -0
  136. pycforge/ide/qt_workspace_navigation.py +208 -0
  137. pycforge/ide/qt_workspace_observers.py +173 -0
  138. pycforge/ide/qt_workspace_panels.py +545 -0
  139. pycforge/ide/qt_workspace_widgets.py +228 -0
  140. pycforge/ide/resources/icons/about.svg +1 -0
  141. pycforge/ide/resources/icons/add-document.svg +1 -0
  142. pycforge/ide/resources/icons/brand-mark.svg +1 -0
  143. pycforge/ide/resources/icons/bundle-search.svg +1 -0
  144. pycforge/ide/resources/icons/cancel.svg +1 -0
  145. pycforge/ide/resources/icons/check.svg +1 -0
  146. pycforge/ide/resources/icons/chevron-right.svg +1 -0
  147. pycforge/ide/resources/icons/close.svg +1 -0
  148. pycforge/ide/resources/icons/collapse-all.svg +1 -0
  149. pycforge/ide/resources/icons/command-palette.svg +1 -0
  150. pycforge/ide/resources/icons/convert.svg +1 -0
  151. pycforge/ide/resources/icons/copy.svg +1 -0
  152. pycforge/ide/resources/icons/cut.svg +1 -0
  153. pycforge/ide/resources/icons/decision-trace.svg +1 -0
  154. pycforge/ide/resources/icons/details.svg +1 -0
  155. pycforge/ide/resources/icons/diagnostics.svg +1 -0
  156. pycforge/ide/resources/icons/duplicate-line.svg +1 -0
  157. pycforge/ide/resources/icons/exit.svg +1 -0
  158. pycforge/ide/resources/icons/expand-all.svg +1 -0
  159. pycforge/ide/resources/icons/export.svg +1 -0
  160. pycforge/ide/resources/icons/find.svg +1 -0
  161. pycforge/ide/resources/icons/go-to-line.svg +1 -0
  162. pycforge/ide/resources/icons/go-to-output.svg +1 -0
  163. pycforge/ide/resources/icons/go-to-source.svg +1 -0
  164. pycforge/ide/resources/icons/history.svg +1 -0
  165. pycforge/ide/resources/icons/indent.svg +1 -0
  166. pycforge/ide/resources/icons/link-c.svg +1 -0
  167. pycforge/ide/resources/icons/mappings.svg +1 -0
  168. pycforge/ide/resources/icons/module.svg +1 -0
  169. pycforge/ide/resources/icons/move-down.svg +1 -0
  170. pycforge/ide/resources/icons/move-line-down.svg +1 -0
  171. pycforge/ide/resources/icons/move-line-up.svg +1 -0
  172. pycforge/ide/resources/icons/move-up.svg +1 -0
  173. pycforge/ide/resources/icons/next.svg +1 -0
  174. pycforge/ide/resources/icons/open.svg +1 -0
  175. pycforge/ide/resources/icons/outdent.svg +1 -0
  176. pycforge/ide/resources/icons/outline.svg +1 -0
  177. pycforge/ide/resources/icons/paste.svg +1 -0
  178. pycforge/ide/resources/icons/previous.svg +1 -0
  179. pycforge/ide/resources/icons/primary-module.svg +1 -0
  180. pycforge/ide/resources/icons/redo.svg +1 -0
  181. pycforge/ide/resources/icons/remove-document.svg +1 -0
  182. pycforge/ide/resources/icons/replace.svg +1 -0
  183. pycforge/ide/resources/icons/save-as.svg +1 -0
  184. pycforge/ide/resources/icons/save.svg +1 -0
  185. pycforge/ide/resources/icons/select-all.svg +1 -0
  186. pycforge/ide/resources/icons/settings.svg +1 -0
  187. pycforge/ide/resources/icons/show-c.svg +1 -0
  188. pycforge/ide/resources/icons/split-view.svg +1 -0
  189. pycforge/ide/resources/icons/summary.svg +1 -0
  190. pycforge/ide/resources/icons/telemetry.svg +1 -0
  191. pycforge/ide/resources/icons/toggle-comment.svg +1 -0
  192. pycforge/ide/resources/icons/toggle-fold.svg +1 -0
  193. pycforge/ide/resources/icons/undo.svg +1 -0
  194. pycforge/ide/resources/icons/whitespace.svg +1 -0
  195. pycforge/ide/revisions.py +400 -0
  196. pycforge/ide/search_service.py +280 -0
  197. pycforge/ide/session_history.py +150 -0
  198. pycforge/ide/source_editing.py +417 -0
  199. pycforge/ide/source_structure.py +558 -0
  200. pycforge/ide/source_structure_async.py +191 -0
  201. pycforge/ide/supervisor.py +503 -0
  202. pycforge/ide/theme.py +119 -0
  203. pycforge/ide/theme_stylesheet.py +598 -0
  204. pycforge/ide/theme_workspace_stylesheet.py +155 -0
  205. pycforge/ide/visual_tokens.py +142 -0
  206. pycforge/ide/worker_protocol.py +80 -0
  207. pycforge/ide/workspace_search.py +462 -0
  208. pycforge/ide/workspace_session.py +256 -0
  209. pycforge/laboratory/__init__.py +6 -0
  210. pycforge/laboratory/audits.py +2244 -0
  211. pycforge/laboratory/checkpoint_e.py +2685 -0
  212. pycforge/laboratory/cli.py +119 -0
  213. pycforge/laboratory/exit_codes.py +11 -0
  214. pycforge/laboratory/keyword_audit.py +661 -0
  215. pycforge/laboratory/keyword_only_audit.py +481 -0
  216. pycforge-0.15.2.dist-info/METADATA +209 -0
  217. pycforge-0.15.2.dist-info/RECORD +221 -0
  218. pycforge-0.15.2.dist-info/WHEEL +5 -0
  219. pycforge-0.15.2.dist-info/entry_points.txt +5 -0
  220. pycforge-0.15.2.dist-info/licenses/LICENSE +674 -0
  221. pycforge-0.15.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,150 @@
1
+ """Bounded, payload-free conversion history for the current application session.
2
+
3
+ History is a presentation observer. It records only immutable identities and
4
+ small terminal-state facts. It deliberately has no source text, generated C,
5
+ diagnostic bodies, artifacts, timestamps, or persistence contract.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ import re
12
+
13
+
14
+ MAX_CONVERSION_HISTORY_ENTRIES = 64
15
+ _FINGERPRINT = re.compile(r"^[0-9a-f]{64}$")
16
+ _MAX_STATUS_CHARS = 64
17
+ _MAX_STAGE_CHARS = 128
18
+ _MAX_REASON_CHARS = 128
19
+
20
+
21
+ def _require_count(value: object, label: str, *, positive: bool = False) -> None:
22
+ if (
23
+ not isinstance(value, int)
24
+ or isinstance(value, bool)
25
+ or value < (1 if positive else 0)
26
+ ):
27
+ qualifier = "positive" if positive else "non-negative"
28
+ raise ValueError(f"{label} must be a {qualifier} integer")
29
+
30
+
31
+ def _require_fingerprint(value: object, label: str, *, optional: bool) -> None:
32
+ if value is None and optional:
33
+ return
34
+ if not isinstance(value, str) or _FINGERPRINT.fullmatch(value) is None:
35
+ raise ValueError(f"{label} must be a canonical SHA-256 value")
36
+
37
+
38
+ def _require_label(
39
+ value: object,
40
+ label: str,
41
+ *,
42
+ maximum: int,
43
+ optional: bool,
44
+ ) -> None:
45
+ if value is None and optional:
46
+ return
47
+ if (
48
+ not isinstance(value, str)
49
+ or not value
50
+ or len(value) > maximum
51
+ or any(ord(character) < 32 for character in value)
52
+ ):
53
+ raise ValueError(f"{label} is empty, oversized, or contains controls")
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class ConversionHistoryEntry:
58
+ """One accepted terminal observation for the current request."""
59
+
60
+ request_sequence: int
61
+ revision_generation: int
62
+ bundle_fingerprint: str
63
+ request_fingerprint: str | None
64
+ output_fingerprint: str | None
65
+ status: str
66
+ diagnostic_count: int
67
+ completed_stage_count: int
68
+ total_stage_count: int
69
+ stage: str | None
70
+ published: bool
71
+ reason: str | None
72
+
73
+ def __post_init__(self) -> None:
74
+ _require_count(
75
+ self.request_sequence,
76
+ "request sequence",
77
+ positive=True,
78
+ )
79
+ _require_count(self.revision_generation, "revision generation")
80
+ _require_fingerprint(
81
+ self.bundle_fingerprint,
82
+ "bundle fingerprint",
83
+ optional=False,
84
+ )
85
+ _require_fingerprint(
86
+ self.request_fingerprint,
87
+ "request fingerprint",
88
+ optional=True,
89
+ )
90
+ _require_fingerprint(
91
+ self.output_fingerprint,
92
+ "output fingerprint",
93
+ optional=True,
94
+ )
95
+ _require_label(
96
+ self.status,
97
+ "status",
98
+ maximum=_MAX_STATUS_CHARS,
99
+ optional=False,
100
+ )
101
+ _require_count(self.diagnostic_count, "diagnostic count")
102
+ _require_count(
103
+ self.completed_stage_count,
104
+ "completed stage count",
105
+ )
106
+ _require_count(self.total_stage_count, "total stage count")
107
+ if self.completed_stage_count > self.total_stage_count:
108
+ raise ValueError(
109
+ "completed stage count cannot exceed total stage count"
110
+ )
111
+ _require_label(
112
+ self.stage,
113
+ "stage",
114
+ maximum=_MAX_STAGE_CHARS,
115
+ optional=True,
116
+ )
117
+ if not isinstance(self.published, bool):
118
+ raise TypeError("published must be a boolean")
119
+ _require_label(
120
+ self.reason,
121
+ "reason",
122
+ maximum=_MAX_REASON_CHARS,
123
+ optional=True,
124
+ )
125
+
126
+
127
+ def append_conversion_history(
128
+ history: tuple[ConversionHistoryEntry, ...],
129
+ entry: ConversionHistoryEntry,
130
+ ) -> tuple[ConversionHistoryEntry, ...]:
131
+ """Append one request exactly once and retain the newest 64 entries."""
132
+
133
+ if not isinstance(history, tuple) or any(
134
+ not isinstance(item, ConversionHistoryEntry) for item in history
135
+ ):
136
+ raise TypeError("conversion history must be an entry tuple")
137
+ if not isinstance(entry, ConversionHistoryEntry):
138
+ raise TypeError("conversion history entry has the wrong type")
139
+ if any(
140
+ item.request_sequence == entry.request_sequence for item in history
141
+ ):
142
+ return history
143
+ return (history + (entry,))[-MAX_CONVERSION_HISTORY_ENTRIES:]
144
+
145
+
146
+ __all__ = [
147
+ "MAX_CONVERSION_HISTORY_ENTRIES",
148
+ "ConversionHistoryEntry",
149
+ "append_conversion_history",
150
+ ]
@@ -0,0 +1,417 @@
1
+ """Pure, immutable Python source-editing operations for the workspace.
2
+
3
+ The functions in this module know nothing about Qt, files, or conversion.
4
+ They accept one exact text value and an ordered selection, and return a new
5
+ text value with the exact selection to install in an editor. Line endings are
6
+ preserved; a newly required line ending follows the surrounding document and
7
+ defaults to LF for an empty single-line document.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from bisect import bisect_right
13
+ from dataclasses import dataclass
14
+
15
+
16
+ INDENT_WIDTH = 4
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class SourceEditResult:
21
+ """One complete immutable result of a source-editing operation."""
22
+
23
+ text: str
24
+ selection_start: int
25
+ selection_end: int
26
+
27
+ def __post_init__(self) -> None:
28
+ if not isinstance(self.text, str):
29
+ raise TypeError("edited source must be text")
30
+ for name, value in (
31
+ ("selection_start", self.selection_start),
32
+ ("selection_end", self.selection_end),
33
+ ):
34
+ if isinstance(value, bool) or not isinstance(value, int):
35
+ raise TypeError(f"{name} must be an integer")
36
+ if not (
37
+ 0 <= self.selection_start <= self.selection_end <= len(self.text)
38
+ ):
39
+ raise ValueError("edited source selection is outside the text")
40
+
41
+ @property
42
+ def selection(self) -> tuple[int, int]:
43
+ return self.selection_start, self.selection_end
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class _Line:
48
+ start: int
49
+ content: str
50
+ newline: str
51
+
52
+ @property
53
+ def content_end(self) -> int:
54
+ return self.start + len(self.content)
55
+
56
+ @property
57
+ def end(self) -> int:
58
+ return self.content_end + len(self.newline)
59
+
60
+
61
+ def _selection(text: str, start: int, end: int) -> tuple[int, int]:
62
+ if not isinstance(text, str):
63
+ raise TypeError("source must be text")
64
+ for name, value in (("selection start", start), ("selection end", end)):
65
+ if isinstance(value, bool) or not isinstance(value, int):
66
+ raise TypeError(f"{name} must be an integer")
67
+ limit = len(text)
68
+ first = min(limit, max(0, start))
69
+ last = min(limit, max(0, end))
70
+ return (first, last) if first <= last else (last, first)
71
+
72
+
73
+ def _lines(text: str) -> tuple[_Line, ...]:
74
+ records: list[_Line] = []
75
+ start = 0
76
+ while True:
77
+ newline_at = text.find("\n", start)
78
+ if newline_at < 0:
79
+ records.append(_Line(start, text[start:], ""))
80
+ break
81
+ content_end = (
82
+ newline_at - 1
83
+ if newline_at > start and text[newline_at - 1] == "\r"
84
+ else newline_at
85
+ )
86
+ records.append(
87
+ _Line(
88
+ start,
89
+ text[start:content_end],
90
+ text[content_end : newline_at + 1],
91
+ )
92
+ )
93
+ start = newline_at + 1
94
+ if start == len(text):
95
+ records.append(_Line(start, "", ""))
96
+ break
97
+ return tuple(records)
98
+
99
+
100
+ def _line_index(records: tuple[_Line, ...], offset: int) -> int:
101
+ starts = tuple(line.start for line in records)
102
+ return max(0, min(len(records) - 1, bisect_right(starts, offset) - 1))
103
+
104
+
105
+ def _selected_line_indexes(
106
+ records: tuple[_Line, ...],
107
+ start: int,
108
+ end: int,
109
+ ) -> tuple[int, int]:
110
+ first = _line_index(records, start)
111
+ if end > start and end == records[_line_index(records, end)].start:
112
+ last = max(first, _line_index(records, end) - 1)
113
+ else:
114
+ last = _line_index(records, end)
115
+ return first, max(first, last)
116
+
117
+
118
+ def _render(
119
+ contents: tuple[str, ...],
120
+ records: tuple[_Line, ...],
121
+ ) -> str:
122
+ return "".join(
123
+ content + record.newline
124
+ for content, record in zip(contents, records, strict=True)
125
+ )
126
+
127
+
128
+ def _preferred_newline(text: str, offset: int) -> str:
129
+ before = text.rfind("\n", 0, offset)
130
+ if before >= 0:
131
+ return "\r\n" if before > 0 and text[before - 1] == "\r" else "\n"
132
+ after = text.find("\n", offset)
133
+ if after >= 0:
134
+ return "\r\n" if after > 0 and text[after - 1] == "\r" else "\n"
135
+ return "\n"
136
+
137
+
138
+ def _map_point(
139
+ old_records: tuple[_Line, ...],
140
+ new_records: tuple[_Line, ...],
141
+ offset: int,
142
+ column_mapper,
143
+ ) -> int:
144
+ index = _line_index(old_records, offset)
145
+ column = offset - old_records[index].start
146
+ mapped = column_mapper(index, column)
147
+ new_line = new_records[index]
148
+ return new_line.start + min(
149
+ len(new_line.content) + len(new_line.newline),
150
+ max(0, mapped),
151
+ )
152
+
153
+
154
+ def duplicate_lines(
155
+ text: str,
156
+ selection_start: int,
157
+ selection_end: int,
158
+ ) -> SourceEditResult:
159
+ """Duplicate every line touched by the selection.
160
+
161
+ A non-empty selection is recreated over the duplicate. An empty selection
162
+ places the caret at the same column in the duplicated line. If the
163
+ duplicated block has no terminal newline, one matching the surrounding
164
+ document is inserted between the original and duplicate.
165
+ """
166
+
167
+ start, end = _selection(text, selection_start, selection_end)
168
+ records = _lines(text)
169
+ first, last = _selected_line_indexes(records, start, end)
170
+ block_start = records[first].start
171
+ block_end = records[last].end
172
+ block = text[block_start:block_end]
173
+ if records[last].newline:
174
+ insertion = block
175
+ duplicate_start = block_end
176
+ else:
177
+ separator = _preferred_newline(text, block_end)
178
+ insertion = separator + block
179
+ duplicate_start = block_end + len(separator)
180
+ edited = text[:block_end] + insertion + text[block_end:]
181
+ shift = duplicate_start - block_start
182
+ return SourceEditResult(edited, start + shift, end + shift)
183
+
184
+
185
+ def _move_lines(
186
+ text: str,
187
+ selection_start: int,
188
+ selection_end: int,
189
+ *,
190
+ direction: int,
191
+ ) -> SourceEditResult:
192
+ start, end = _selection(text, selection_start, selection_end)
193
+ records = _lines(text)
194
+ first, last = _selected_line_indexes(records, start, end)
195
+ if direction < 0 and first == 0:
196
+ return SourceEditResult(text, start, end)
197
+ if direction > 0 and last >= len(records) - 1:
198
+ return SourceEditResult(text, start, end)
199
+
200
+ contents = [line.content for line in records]
201
+ count = last - first + 1
202
+ if direction < 0:
203
+ moved = contents[first : last + 1]
204
+ previous = contents[first - 1]
205
+ contents[first - 1 : last + 1] = [*moved, previous]
206
+ new_first = first - 1
207
+ else:
208
+ moved = contents[first : last + 1]
209
+ following = contents[last + 1]
210
+ contents[first : last + 2] = [following, *moved]
211
+ new_first = first + 1
212
+
213
+ edited = _render(tuple(contents), records)
214
+ new_records = _lines(edited)
215
+ old_block_start = records[first].start
216
+ old_block_end = records[last].end
217
+ new_block_start = new_records[new_first].start
218
+ new_block_end = new_records[new_first + count - 1].end
219
+ relative_start = start - old_block_start
220
+ relative_end = end - old_block_start
221
+ new_block_length = new_block_end - new_block_start
222
+ return SourceEditResult(
223
+ edited,
224
+ new_block_start + min(new_block_length, relative_start),
225
+ new_block_start + min(new_block_length, relative_end),
226
+ )
227
+
228
+
229
+ def move_lines_up(
230
+ text: str,
231
+ selection_start: int,
232
+ selection_end: int,
233
+ ) -> SourceEditResult:
234
+ """Move the selected logical lines one position earlier."""
235
+
236
+ return _move_lines(
237
+ text,
238
+ selection_start,
239
+ selection_end,
240
+ direction=-1,
241
+ )
242
+
243
+
244
+ def move_lines_down(
245
+ text: str,
246
+ selection_start: int,
247
+ selection_end: int,
248
+ ) -> SourceEditResult:
249
+ """Move the selected logical lines one position later."""
250
+
251
+ return _move_lines(
252
+ text,
253
+ selection_start,
254
+ selection_end,
255
+ direction=1,
256
+ )
257
+
258
+
259
+ def _rewrite_selected_lines(
260
+ text: str,
261
+ selection_start: int,
262
+ selection_end: int,
263
+ rewrite,
264
+ ) -> SourceEditResult:
265
+ start, end = _selection(text, selection_start, selection_end)
266
+ old_records = _lines(text)
267
+ first, last = _selected_line_indexes(old_records, start, end)
268
+ contents = [line.content for line in old_records]
269
+ mappers = [lambda column: column for _line in old_records]
270
+ for index in range(first, last + 1):
271
+ contents[index], mappers[index] = rewrite(contents[index])
272
+ edited = _render(tuple(contents), old_records)
273
+ new_records = _lines(edited)
274
+ return SourceEditResult(
275
+ edited,
276
+ _map_point(
277
+ old_records,
278
+ new_records,
279
+ start,
280
+ lambda index, column: mappers[index](column),
281
+ ),
282
+ _map_point(
283
+ old_records,
284
+ new_records,
285
+ end,
286
+ lambda index, column: mappers[index](column),
287
+ ),
288
+ )
289
+
290
+
291
+ def indent_lines(
292
+ text: str,
293
+ selection_start: int,
294
+ selection_end: int,
295
+ ) -> SourceEditResult:
296
+ """Indent selected source by four spaces.
297
+
298
+ Blank lines inside a multi-line selection remain blank. An empty
299
+ selection on a blank line inserts one indentation unit at the caret.
300
+ """
301
+
302
+ prefix = " " * INDENT_WIDTH
303
+ start, end = _selection(text, selection_start, selection_end)
304
+ indent_empty_caret_line = start == end
305
+
306
+ def rewrite(content: str):
307
+ if not content and not indent_empty_caret_line:
308
+ return content, lambda column: column
309
+ return prefix + content, lambda column: column + INDENT_WIDTH
310
+
311
+ return _rewrite_selected_lines(
312
+ text,
313
+ start,
314
+ end,
315
+ rewrite,
316
+ )
317
+
318
+
319
+ def outdent_lines(
320
+ text: str,
321
+ selection_start: int,
322
+ selection_end: int,
323
+ ) -> SourceEditResult:
324
+ """Remove one leading tab or up to four leading spaces per selected line."""
325
+
326
+ def rewrite(content: str):
327
+ if content.startswith("\t"):
328
+ removed = 1
329
+ else:
330
+ removed = min(
331
+ INDENT_WIDTH,
332
+ len(content) - len(content.lstrip(" ")),
333
+ )
334
+ if not removed:
335
+ return content, lambda column: column
336
+
337
+ def map_column(column: int) -> int:
338
+ return max(0, column - removed)
339
+
340
+ return content[removed:], map_column
341
+
342
+ return _rewrite_selected_lines(
343
+ text,
344
+ selection_start,
345
+ selection_end,
346
+ rewrite,
347
+ )
348
+
349
+
350
+ def toggle_python_line_comment(
351
+ text: str,
352
+ selection_start: int,
353
+ selection_end: int,
354
+ ) -> SourceEditResult:
355
+ """Comment or uncomment every non-blank selected Python line."""
356
+
357
+ start, end = _selection(text, selection_start, selection_end)
358
+ records = _lines(text)
359
+ first, last = _selected_line_indexes(records, start, end)
360
+ selected = records[first : last + 1]
361
+ nonblank = tuple(line for line in selected if line.content.strip())
362
+ uncomment = bool(nonblank) and all(
363
+ line.content[len(line.content) - len(line.content.lstrip()) :].startswith(
364
+ "#"
365
+ )
366
+ for line in nonblank
367
+ )
368
+
369
+ def rewrite(content: str):
370
+ if not content.strip():
371
+ return content, lambda column: column
372
+ indent = len(content) - len(content.lstrip())
373
+ if uncomment:
374
+ removed = 2 if content[indent:].startswith("# ") else 1
375
+
376
+ def map_column(column: int) -> int:
377
+ if column <= indent:
378
+ return column
379
+ return indent + max(0, column - indent - removed)
380
+
381
+ return content[:indent] + content[indent + removed :], map_column
382
+
383
+ def map_column(column: int) -> int:
384
+ return column if column < indent else column + 2
385
+
386
+ return content[:indent] + "# " + content[indent:], map_column
387
+
388
+ return _rewrite_selected_lines(text, start, end, rewrite)
389
+
390
+
391
+ def clamped_go_to_line_offset(text: str, line: int) -> int:
392
+ """Return the start offset of a one-based line, clamped to the document."""
393
+
394
+ if not isinstance(text, str):
395
+ raise TypeError("source must be text")
396
+ if isinstance(line, bool) or not isinstance(line, int):
397
+ raise TypeError("line must be an integer")
398
+ records = _lines(text)
399
+ index = min(len(records) - 1, max(0, line - 1))
400
+ return records[index].start
401
+
402
+
403
+ go_to_line_offset = clamped_go_to_line_offset
404
+
405
+
406
+ __all__ = [
407
+ "INDENT_WIDTH",
408
+ "SourceEditResult",
409
+ "clamped_go_to_line_offset",
410
+ "duplicate_lines",
411
+ "go_to_line_offset",
412
+ "indent_lines",
413
+ "move_lines_down",
414
+ "move_lines_up",
415
+ "outdent_lines",
416
+ "toggle_python_line_comment",
417
+ ]