@dybai/dsh-editor 0.11.0 → 0.13.0

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.
package/client.js CHANGED
@@ -1343,7 +1343,61 @@ window.__ModuleLoader__.load({
1343
1343
  return Number.isFinite(px) && px > 0 ? px : null;
1344
1344
  }
1345
1345
 
1346
- Object.assign(module.exports, { activeLineRangeOf, activeLineBar, lineHeightPxOf });
1346
+ /**
1347
+ * Frame the line's glyph ink with the two hairline bands.
1348
+ *
1349
+ * The DOM layer measures (canvas TextMetrics) how the REAL font stack lays the
1350
+ * probe text out: `fontBoundingBoxAscent/Descent` locate the baseline inside
1351
+ * the line box (that placement is where the script asymmetry lives — Latin
1352
+ * fills the box roughly centered while CJK ideographs hang against the ascent
1353
+ * edge), and `actualBoundingBoxAscent/Descent` give the probe text's true ink
1354
+ * extents. This function turns those numbers into the two band positions:
1355
+ * `top` band's offset from the box top, `bottom` band's inset from the box
1356
+ * bottom — each flanking the ink by `padding`, clamped so the bands can never
1357
+ * cross, leave the box, or invade adjacent lines.
1358
+ *
1359
+ * `null` when any input is unusable: the caller keeps its static CSS fallback
1360
+ * (symmetric edge insets) instead of painting from a poison measurement.
1361
+ *
1362
+ * Band placement may extend past the line box into the inter-line whitespace,
1363
+ * bounded by `BAND_WINDOW_PX` (the clamp window; CJK lines keep their
1364
+ * descender zone empty, so bands up to 8px outside the box still sit between
1365
+ * the two text rows).
1366
+ * @param {any} metrics - `{ lineHeight, fontAscent, fontDescent, inkAscent,
1367
+ * inkDescent, paddingTop?, paddingBottom?, bandHeight? }` in CSS pixels.
1368
+ * @returns {{ top: number, bottom: number } | null}
1369
+ */
1370
+ const BAND_WINDOW_PX = 8;
1371
+ function glyphBandOffsets(metrics) {
1372
+ const source = metrics !== null && typeof metrics === 'object' ? metrics : {};
1373
+ const lineHeight = Number.isFinite(source.lineHeight) && source.lineHeight > 0 ? source.lineHeight : NaN;
1374
+ const fontAscent = Number.isFinite(source.fontAscent) ? source.fontAscent : NaN;
1375
+ const fontDescent = Number.isFinite(source.fontDescent) ? source.fontDescent : NaN;
1376
+ const inkAscent = Number.isFinite(source.inkAscent) && source.inkAscent >= 0 ? source.inkAscent : NaN;
1377
+ const inkDescent = Number.isFinite(source.inkDescent) && source.inkDescent >= 0 ? source.inkDescent : NaN;
1378
+ if (![lineHeight, fontAscent, fontDescent, inkAscent, inkDescent].every(Number.isFinite)) return null;
1379
+ const bandHeight = Number.isFinite(source.bandHeight) && source.bandHeight > 0 ? source.bandHeight : 2;
1380
+ const paddingTop = Number.isFinite(source.paddingTop) && source.paddingTop >= 0 ? source.paddingTop : 0;
1381
+ const paddingBottom = Number.isFinite(source.paddingBottom) && source.paddingBottom >= 0 ? source.paddingBottom : 0;
1382
+ // Bands may extend BEYOND the line box into the inter-line whitespace (a
1383
+ // box-edge clamp silently collapsed large paddings into identical paints,
1384
+ // making the tuning knobs feel dead). ±BAND_WINDOW_PX is the proven-safe
1385
+ // window: CJK lines keep their descender zone empty, so a band up to 8px
1386
+ // outside the box still lands between the two text rows.
1387
+ const windowFloor = -BAND_WINDOW_PX;
1388
+ const windowCeiling = lineHeight - bandHeight;
1389
+ const clamp = (value) => Math.max(windowFloor, Math.min(value, windowCeiling));
1390
+ const halfLeading = (lineHeight - (fontAscent + fontDescent)) / 2;
1391
+ const baseline = halfLeading + fontAscent;
1392
+ const inkTop = baseline - inkAscent;
1393
+ const inkBottom = baseline + inkDescent;
1394
+ return {
1395
+ top: clamp(inkTop - paddingTop),
1396
+ bottom: clamp(lineHeight - inkBottom - paddingBottom - bandHeight),
1397
+ };
1398
+ }
1399
+
1400
+ Object.assign(module.exports, { activeLineRangeOf, activeLineBar, lineHeightPxOf, glyphBandOffsets });
1347
1401
  return module.exports;
1348
1402
  })();
1349
1403
 
@@ -1583,10 +1637,636 @@ window.__ModuleLoader__.load({
1583
1637
  return module.exports;
1584
1638
  })();
1585
1639
 
1640
+ /* src/settings.js */
1641
+ const settings = (function () {
1642
+ var module = { exports: {} };
1643
+ var exports = module.exports;
1644
+ /**
1645
+ * Editor behavior settings — the pure model behind the settings panel.
1646
+ *
1647
+ * One GLOBAL user preference set (cross-tab, cross-mode), persisted through
1648
+ * the Host storage RPC bridge (`dshEditor/getSettings` / `dshEditor/setSettings`,
1649
+ * KV table `settings`, one record per setting name). The settings:
1650
+ *
1651
+ * - `autoReloadClean` — when a file WITHOUT unsaved changes is modified
1652
+ * externally, reload it silently instead of asking (default `false`:
1653
+ * 默认一律询问, per the feature ruling);
1654
+ * - `highlightActiveLine` — draw an active-line highlight behind the caret
1655
+ * (default `true`: a presentation affordance, on unless the user turns it
1656
+ * off). Modes honoring the active-line contract (descriptor `activeLine`,
1657
+ * contracts §5.1) read the same preference via their `highlightActiveLine`
1658
+ * component prop.
1659
+ * - `showLineNumbers` — render the line-number gutter beside the content
1660
+ * (default `true`: a presentation affordance, on unless the user turns it
1661
+ * off). Modes honoring the line-numbers contract (contracts §5.1) read the
1662
+ * same preference via their `showLineNumbers` component prop.
1663
+ * - `scrollBeyondLastLine` — keep scrollable blank space past the content end
1664
+ * so the last line can scroll to the viewport top (default `true`, a
1665
+ * presentation affordance; modes honoring it receive the live boolean via
1666
+ * their `scrollBeyondLastLine` component prop).
1667
+ * - `wordWrap` — whether the editor area soft-wraps long lines (explicit
1668
+ * default `false`). This default is the fallback for an EXPLICIT setting
1669
+ * only: a file whose stored settings never mention `wordWrap` is resolved
1670
+ * by `resolveWordWrap` (see `wrap-resolve.js`) against the builtin
1671
+ * extension defaults (the markdown family wraps by default), so "unset"
1672
+ * is not the same as "off".
1673
+ * - `showWhitespaceSpaces` — draw visible glyphs for space characters
1674
+ * (default `false`: whitespace display is opt-in). Modes honoring the
1675
+ * whitespace-display contract receive the live boolean via their
1676
+ * `showWhitespace` component prop.
1677
+ * - `showWhitespaceTabs` — draw visible glyphs for tab characters
1678
+ * (default `false`; delivered via the same `showWhitespace` component
1679
+ * prop).
1680
+ * - `showWhitespaceNewlines` — draw a visible glyph at line ends and blank
1681
+ * lines (default `false`; delivered via the same `showWhitespace`
1682
+ * component prop).
1683
+ * - `indentMode` — the unit a Tab press inserts: `auto` (default) detects the
1684
+ * current file's leading indentation and falls back to `indentWidth` when
1685
+ * the file carries no signal, `tabs` always inserts a tab, and `spaces`
1686
+ * always inserts `indentWidth` spaces.
1687
+ * - `indentWidth` — the spaces per indent level in `spaces` mode, and the
1688
+ * `auto` fallback width (default `4`; allowed values are 2, 4 and 8).
1689
+ *
1690
+ * `normalizeSettings` accepts the wire payload
1691
+ * `{ [name]: boolean | string | number }` (the Host reports only stored
1692
+ * settings) and merges it over the defaults. Unknown keys are IGNORED so a
1693
+ * newer Host's extra settings never invalidate this build's read — but a
1694
+ * KNOWN key carrying a value outside its per-key type (see
1695
+ * `isValidSettingValue`) invalidates the whole payload (`undefined`: the
1696
+ * caller keeps its current/default values).
1697
+ *
1698
+ * `buildSettingsWritePayload` is the write-side counterpart: it starts from
1699
+ * the RAW stored set (explicit settings only) and merges the caller's change,
1700
+ * so a write never materializes the builtin defaults. A key absent from
1701
+ * storage stays absent, which is what keeps the builtin per-file defaults
1702
+ * (e.g. the markdown family's wrap) reachable after unrelated toggles.
1703
+ *
1704
+ * Zero imports: pure functions only, unit-testable without DOM.
1705
+ *
1706
+ * @module @dybai/dsh-editor/settings
1707
+ */
1708
+
1709
+ /** Setting names this build knows (mirrors the Host validator's allow-list). */
1710
+ const SETTINGS_KEYS = ['autoReloadClean', 'highlightActiveLine', 'showLineNumbers', 'scrollBeyondLastLine', 'wordWrap', 'showWhitespaceSpaces', 'showWhitespaceTabs', 'showWhitespaceNewlines', 'indentMode', 'indentWidth'];
1711
+
1712
+ /** The valid `indentMode` values (mirrors the Host validator's type table). */
1713
+ const INDENT_MODES = ['auto', 'tabs', 'spaces'];
1714
+
1715
+ /** The valid `indentWidth` values (mirrors the Host validator's type table). */
1716
+ const INDENT_WIDTHS = [2, 4, 8];
1717
+
1718
+ /**
1719
+ * The per-key type table: whether `value` is legal for the known setting
1720
+ * `key`. The indent keys are enums; every other known setting is a boolean.
1721
+ * @param {string} key - a known setting name (`SETTINGS_KEYS`).
1722
+ * @param {any} value - the value to check.
1723
+ * @returns {boolean} true when the value matches the key's type.
1724
+ */
1725
+ function isValidSettingValue(key, value) {
1726
+ if (key === 'indentMode') return INDENT_MODES.includes(value);
1727
+ if (key === 'indentWidth') return INDENT_WIDTHS.includes(value);
1728
+ return typeof value === 'boolean';
1729
+ }
1730
+
1731
+ /**
1732
+ * The built-in settings: behavior opt-ins off, presentation defaults on,
1733
+ * indentation in auto-detect mode at width 4.
1734
+ * @returns a fresh settings object (callers may mutate their copy).
1735
+ */
1736
+ function defaultSettings() {
1737
+ return {
1738
+ autoReloadClean: false,
1739
+ highlightActiveLine: true,
1740
+ showLineNumbers: true,
1741
+ scrollBeyondLastLine: true,
1742
+ wordWrap: false,
1743
+ showWhitespaceSpaces: false,
1744
+ showWhitespaceTabs: false,
1745
+ showWhitespaceNewlines: false,
1746
+ indentMode: 'auto',
1747
+ indentWidth: 4
1748
+ };
1749
+ }
1750
+
1751
+ /**
1752
+ * Validate and normalize a settings payload (defaults merged).
1753
+ * @param {any} raw - the wire payload `{ [name]: boolean | string | number }`.
1754
+ * @returns the complete settings object, or `undefined` when the payload is
1755
+ * not an object or a known key carries a value outside its per-key type.
1756
+ */
1757
+ function normalizeSettings(raw) {
1758
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
1759
+ const normalized = defaultSettings();
1760
+ for (const key of SETTINGS_KEYS) {
1761
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
1762
+ if (!isValidSettingValue(key, raw[key])) return undefined;
1763
+ normalized[key] = raw[key];
1764
+ }
1765
+ return normalized;
1766
+ }
1767
+
1768
+ /**
1769
+ * Build the wire payload for one settings write: the RAW stored set (only
1770
+ * explicitly-stored keys) merged with the caller's change. Never fills
1771
+ * defaults — absence of a key IS the "never explicitly set" signal the
1772
+ * per-file resolution depends on. Returns undefined for any payload that
1773
+ * is not an object or carries a key outside SETTINGS_KEYS / a value outside
1774
+ * its per-key type. A non-object `rawSettings` (first frame, failed read)
1775
+ * is treated as the empty set, so the write stores exactly the change.
1776
+ * @param {any} rawSettings - the raw stored settings payload (`getRawSettings()`).
1777
+ * @param {any} input - the caller's change (`{ [knownName]: boolean | string | number }`).
1778
+ * @returns the complete explicit write payload, or `undefined` when invalid.
1779
+ */
1780
+ function buildSettingsWritePayload(rawSettings, input) {
1781
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) return undefined;
1782
+ const payload = {};
1783
+ if (rawSettings !== null && typeof rawSettings === 'object' && !Array.isArray(rawSettings)) {
1784
+ for (const key of Object.keys(rawSettings)) {
1785
+ if (!SETTINGS_KEYS.includes(key) || !isValidSettingValue(key, rawSettings[key])) return undefined;
1786
+ payload[key] = rawSettings[key];
1787
+ }
1788
+ }
1789
+ for (const key of Object.keys(input)) {
1790
+ if (!SETTINGS_KEYS.includes(key) || !isValidSettingValue(key, input[key])) return undefined;
1791
+ payload[key] = input[key];
1792
+ }
1793
+ return payload;
1794
+ }
1795
+
1796
+ Object.assign(module.exports, { SETTINGS_KEYS, INDENT_MODES, INDENT_WIDTHS, isValidSettingValue, defaultSettings, normalizeSettings, buildSettingsWritePayload });
1797
+ return module.exports;
1798
+ })();
1799
+
1800
+ /* src/indent.js */
1801
+ const indent = (function () {
1802
+ var module = { exports: {} };
1803
+ var exports = module.exports;
1804
+ const { INDENT_WIDTHS } = settings;
1805
+
1806
+ /**
1807
+ * Indentation detection and unit resolution — the pure decision layer behind
1808
+ * the `indentMode` / `indentWidth` settings (0.13.0 "Tab indent").
1809
+ *
1810
+ * `detectIndentUnit` reads a file's text and answers what indentation the
1811
+ * file itself uses: scan the first `SAMPLE_LIMIT` non-blank lines, and any
1812
+ * line starting with a tab decides tabs immediately; otherwise the most
1813
+ * frequent leading-space count in `1..MAX_COUNTED_LEADING` wins (ties pick
1814
+ * the SMALLER width; counts above the cap are treated as alignment noise and
1815
+ * skipped, as are blank / whitespace-only lines). No signal at all → `null`.
1816
+ *
1817
+ * `resolveIndentUnit` turns settings + text into the exact string one Tab
1818
+ * press inserts: explicit `tabs` / `spaces` modes win; anything else (auto,
1819
+ * or defensively invalid settings) detects from the text and falls back to
1820
+ * the valid-width-or-4 spaces when the file carries no signal. It never
1821
+ * throws and never returns anything but `'\t'` or a space run.
1822
+ *
1823
+ * CRLF safety is free: lines are split on `'\n'`, so a trailing `'\r'` sits
1824
+ * at line END and can never affect leading-whitespace counting or the
1825
+ * `startsWith('\t')` probe.
1826
+ *
1827
+ * `indentOp` / `outdentOp` apply one Tab / Shift+Tab press to a selection
1828
+ * (spec §6.3/§6.4): a collapsed caret inserts the unit; a single-line
1829
+ * selection is replaced by it; a selection whose text spans a `'\n'`
1830
+ * block-indents / block-outdents every touched line (`lineOf(start)` ..
1831
+ * `lineOf(max(start, end − 1))` — a collapsed caret outdent touches its
1832
+ * own line, column 0 included). `outdentOp` returns `null` when no touched
1833
+ * line has anything to remove, so the caller can swallow the key without
1834
+ * writing back. Their tiny line-scan helpers are module-local by design:
1835
+ * this file imports nothing else from the editor.
1836
+ *
1837
+ * Single import from `./settings.js` (`INDENT_WIDTHS` only; the `indentMode`
1838
+ * dispatch uses the literals `'tabs'` / `'spaces'` / else-auto), single-line
1839
+ * named import per the bundler's constraints.
1840
+ *
1841
+ * @module @dybai/dsh-editor/indent
1842
+ */
1843
+
1844
+
1845
+ /** How many non-blank lines are sampled for detection (spec §6.1). */
1846
+ const SAMPLE_LIMIT = 200;
1847
+
1848
+ /** Leading-space counts above this are alignment noise, not indentation (spec §6.1). */
1849
+ const MAX_COUNTED_LEADING = 16;
1850
+
1851
+ /**
1852
+ * Detect the indentation unit a text itself uses.
1853
+ *
1854
+ * Leading whitespace counts are computed as `line.length -
1855
+ * line.trimStart().length`, keeping only counts in `1..MAX_COUNTED_LEADING`:
1856
+ * zero-length (unindented) lines and over-long runs (>16, alignment noise)
1857
+ * never vote. The most frequent surviving count wins; ties pick the SMALLER
1858
+ * width. Blank / whitespace-only lines are not samples. A non-string `text`
1859
+ * is treated as `''` (no signal).
1860
+ * @param {any} text - the file text (any other type is treated as `''`).
1861
+ * @returns {{ mode: 'tabs' } | { mode: 'spaces', width: number } | null} the
1862
+ * detected unit, or `null` when no line carries any signal.
1863
+ */
1864
+ function detectIndentUnit(text) {
1865
+ const source = typeof text === 'string' ? text : '';
1866
+ const counts = new Array(MAX_COUNTED_LEADING + 1).fill(0);
1867
+ let samples = 0;
1868
+ for (const line of source.split('\n')) {
1869
+ if (!line.trim()) continue; // blank / whitespace-only: not a sample
1870
+ if (samples >= SAMPLE_LIMIT) break; // only the first 200 samples vote
1871
+ samples += 1;
1872
+ if (line.startsWith('\t')) return { mode: 'tabs' }; // any tab-prefixed sample decides immediately
1873
+ const leading = line.length - line.trimStart().length;
1874
+ if (leading >= 1 && leading <= MAX_COUNTED_LEADING) counts[leading] += 1;
1875
+ }
1876
+ let best = 0;
1877
+ for (let width = 1; width <= MAX_COUNTED_LEADING; width += 1) {
1878
+ if (counts[width] > counts[best]) best = width; // strict `>` keeps ties on the smaller width
1879
+ }
1880
+ return best === 0 ? null : { mode: 'spaces', width: best };
1881
+ }
1882
+
1883
+ /**
1884
+ * Resolve the exact string one Tab press should insert.
1885
+ *
1886
+ * Explicit modes win: `tabs` → `'\t'`; `spaces` → `indentWidth` spaces, with
1887
+ * an out-of-table width defensively falling back to 4. Anything else (auto,
1888
+ * a missing/invalid mode, or a non-object `settings`) detects the unit from
1889
+ * the text; when detection finds no signal the configured width — valid per
1890
+ * `INDENT_WIDTHS`, else 4 — spaces are used. Never throws: a non-string
1891
+ * `text` is treated as `''`, and a non-object `settings` as auto/width-4.
1892
+ * @param {any} settings - the settings object (`indentMode`, `indentWidth`).
1893
+ * @param {any} text - the current file text (any other type is treated as `''`).
1894
+ * @returns {string} `'\t'` or a run of spaces — never anything else.
1895
+ */
1896
+ function resolveIndentUnit(settings, text) {
1897
+ const source = typeof text === 'string' ? text : '';
1898
+ const isObject = settings !== null && typeof settings === 'object';
1899
+ const mode = isObject ? settings.indentMode : undefined;
1900
+ if (mode === 'tabs') return '\t';
1901
+ if (mode === 'spaces') {
1902
+ const width = INDENT_WIDTHS.includes(settings.indentWidth) ? settings.indentWidth : 4;
1903
+ return ' '.repeat(width);
1904
+ }
1905
+ const detected = detectIndentUnit(source);
1906
+ if (detected === null) {
1907
+ const fallback = isObject && INDENT_WIDTHS.includes(settings.indentWidth) ? settings.indentWidth : 4;
1908
+ return ' '.repeat(fallback);
1909
+ }
1910
+ return detected.mode === 'tabs' ? '\t' : ' '.repeat(detected.width);
1911
+ }
1912
+
1913
+ /**
1914
+ * Normalize one selection offset to an integer clamped into `[0, length]`.
1915
+ * Non-number input becomes 0; a `NaN` number also becomes 0 (it cannot be
1916
+ * clamped), while any other number — including infinities — clamps.
1917
+ * @param {any} value - a raw selection offset.
1918
+ * @param {number} length - the text length upper bound.
1919
+ * @returns {number} a safe integer offset in `[0, length]`.
1920
+ */
1921
+ function clampOffset(value, length) {
1922
+ const n = typeof value === 'number' && !Number.isNaN(value) ? Math.trunc(value) : 0;
1923
+ return Math.min(Math.max(n, 0), length);
1924
+ }
1925
+
1926
+ /**
1927
+ * Index of the first character of the line containing `offset` — a backward
1928
+ * scan to the nearest `'\n'` (offset 0 and empty text both yield 0).
1929
+ * @param {string} text - the text to scan.
1930
+ * @param {number} offset - an offset already clamped into `[0, text.length]`.
1931
+ * @returns {number} the offset's line-start index.
1932
+ */
1933
+ function lineStartOfIndex(text, offset) {
1934
+ let i = offset - 1;
1935
+ while (i >= 0 && text[i] !== '\n') i -= 1;
1936
+ return i + 1;
1937
+ }
1938
+
1939
+ /**
1940
+ * Zero-based number of the line containing `offset` — a count of `'\n'`
1941
+ * characters before it.
1942
+ * @param {string} text - the text to scan.
1943
+ * @param {number} offset - an offset already clamped into `[0, text.length]`.
1944
+ * @returns {number} the offset's line number.
1945
+ */
1946
+ function lineOfOffset(text, offset) {
1947
+ let line = 0;
1948
+ for (let i = 0; i < offset && i < text.length; i += 1) {
1949
+ if (text[i] === '\n') line += 1;
1950
+ }
1951
+ return line;
1952
+ }
1953
+
1954
+ /**
1955
+ * Visit every line touched by a clamped selection `[from, to)` — lines
1956
+ * `lineOf(from)` through `lineOf(max(from, to − 1))`. A collapsed caret
1957
+ * (`from === to`) touches its OWN line, column 0 included — the spec §2
1958
+ * terms-table reading that a collapsed caret is a single-line selection —
1959
+ * while a selection with `from < to` ending at column 0 of a line still
1960
+ * excludes that line (`max` keeps `to − 1`). Calls `visit(lineStart,
1961
+ * lineEnd)` per touched line, where `lineEnd` excludes the terminator.
1962
+ * Lines are split on `'\n'`, so a CRLF `'\r'` stays at line END and never
1963
+ * counts as indentation.
1964
+ * @param {string} text - the text to walk.
1965
+ * @param {number} from - clamped selection start.
1966
+ * @param {number} to - clamped selection end (`> from` is not required; an
1967
+ * empty walk simply never calls `visit`).
1968
+ * @param {(lineStart: number, lineEnd: number) => void} visit - per-line callback.
1969
+ * @returns {number} the start index of the first touched line.
1970
+ */
1971
+ function eachTouchedLine(text, from, to, visit) {
1972
+ const firstLineStart = lineStartOfIndex(text, from);
1973
+ const lastLine = lineOfOffset(text, Math.max(from, to - 1));
1974
+ let pos = firstLineStart;
1975
+ let line = lineOfOffset(text, from);
1976
+ while (line <= lastLine) {
1977
+ const nl = text.indexOf('\n', pos);
1978
+ const lineEnd = nl === -1 ? text.length : nl;
1979
+ visit(pos, lineEnd);
1980
+ if (nl === -1) break;
1981
+ pos = nl + 1;
1982
+ line += 1;
1983
+ }
1984
+ return firstLineStart;
1985
+ }
1986
+
1987
+ /**
1988
+ * Leading-whitespace removal for one line (spec §6.4): a `'\t'` unit removes
1989
+ * exactly one leading tab and never spaces; a space unit removes up to
1990
+ * `unit.length` leading spaces (0 when the line has none).
1991
+ * @param {string} line - one line's text without its terminator.
1992
+ * @param {string} unit - the indent unit (`'\t'` or a space run).
1993
+ * @returns {number} how many leading characters the line loses.
1994
+ */
1995
+ function outdentRemoval(line, unit) {
1996
+ if (unit === '\t') return line.startsWith('\t') ? 1 : 0;
1997
+ let spaces = 0;
1998
+ while (spaces < line.length && line[spaces] === ' ') spaces += 1;
1999
+ return Math.min(spaces, unit.length);
2000
+ }
2001
+
2002
+ /**
2003
+ * Apply one Tab press to a selection (spec §6.3). A collapsed caret inserts
2004
+ * the unit at the caret; a single-line selection is replaced by the unit; a
2005
+ * selection whose text spans a `'\n'` block-indents — the unit is inserted at
2006
+ * the start of every touched line (`lineOf(start)` .. `lineOf(end − 1)`), so
2007
+ * a selection covering `'a\n'` indents its first line only and keeps the
2008
+ * newline. The result selection starts after the unit on the first touched
2009
+ * line and ends at the old end shifted by every inserted unit. Inputs are
2010
+ * defensive: a non-string `text` is `''`, non-number (or `NaN`) offsets
2011
+ * become 0, all offsets are clamped into `[0, text.length]` and swapped when
2012
+ * `end < start` — never throws.
2013
+ * @param {any} text - the current file text (any other type is treated as `''`).
2014
+ * @param {any} start - selection start offset (normalized like `end`).
2015
+ * @param {any} end - selection end offset (normalized, swapped if `< start`).
2016
+ * @param {string} unit - the indent unit (`'\t'` or a space run; anything
2017
+ * else is treated as `''`).
2018
+ * @returns {{ text: string, start: number, end: number }} the new text and
2019
+ * selection.
2020
+ */
2021
+ function indentOp(text, start, end, unit) {
2022
+ const source = typeof text === 'string' ? text : '';
2023
+ const fill = typeof unit === 'string' ? unit : '';
2024
+ const a = clampOffset(start, source.length);
2025
+ const b = clampOffset(end, source.length);
2026
+ const from = Math.min(a, b);
2027
+ const to = Math.max(a, b);
2028
+ if (from === to) {
2029
+ // collapsed caret: just insert the unit
2030
+ return {
2031
+ text: source.slice(0, from) + fill + source.slice(from),
2032
+ start: from + fill.length,
2033
+ end: from + fill.length,
2034
+ };
2035
+ }
2036
+ if (!source.slice(from, to).includes('\n')) {
2037
+ // single-line selection: the selection itself becomes the unit
2038
+ return {
2039
+ text: source.slice(0, from) + fill + source.slice(to),
2040
+ start: from + fill.length,
2041
+ end: from + fill.length,
2042
+ };
2043
+ }
2044
+ // block indent: insert the unit at the start of every touched line
2045
+ const firstLineStart = lineStartOfIndex(source, from);
2046
+ let out = source.slice(0, firstLineStart);
2047
+ let prevEnd = firstLineStart;
2048
+ let count = 0;
2049
+ eachTouchedLine(source, from, to, (lineStart) => {
2050
+ out += source.slice(prevEnd, lineStart) + fill;
2051
+ prevEnd = lineStart;
2052
+ count += 1;
2053
+ });
2054
+ out += source.slice(prevEnd);
2055
+ return {
2056
+ text: out,
2057
+ start: firstLineStart + fill.length,
2058
+ end: to + fill.length * count,
2059
+ };
2060
+ }
2061
+
2062
+ /**
2063
+ * Apply one Shift+Tab press to a selection (spec §6.4). Touched lines follow
2064
+ * the shared rule (`lineOf(start)` .. `lineOf(max(start, end − 1))`): a
2065
+ * collapsed caret outdents its own line, column 0 included; a selection
2066
+ * ending at column 0 of a line excludes that line. Each touched line loses
2067
+ * one leading tab (for a `'\t'` unit) or up to `unit.length` leading spaces
2068
+ * (for a space unit). When every touched line has nothing to remove the
2069
+ * text is untouched and `null` is returned — the caller swallows the key
2070
+ * without writing back. Otherwise the removals are applied and each
2071
+ * selection bound shifts by only the removal portions strictly before it
2072
+ * (`Σ min(removal_i, max(0, bound − lineStart_i))`, clamped at 0): a bound
2073
+ * inside a removal window must not subtract the whole window, or the result
2074
+ * overshoots and the clamp pins the caret to offset 0. Same defensive
2075
+ * input handling as `indentOp`; never throws.
2076
+ * @param {any} text - the current file text (any other type is treated as `''`).
2077
+ * @param {any} start - selection start offset (normalized like `end`).
2078
+ * @param {any} end - selection end offset (normalized, swapped if `< start`).
2079
+ * @param {string} unit - the indent unit (`'\t'` or a space run; anything
2080
+ * else is treated as `''`).
2081
+ * @returns {{ text: string, start: number, end: number } | null} the new text
2082
+ * and selection, or `null` when there is nothing to remove.
2083
+ */
2084
+ function outdentOp(text, start, end, unit) {
2085
+ const source = typeof text === 'string' ? text : '';
2086
+ const fill = typeof unit === 'string' ? unit : '';
2087
+ const a = clampOffset(start, source.length);
2088
+ const b = clampOffset(end, source.length);
2089
+ const from = Math.min(a, b);
2090
+ const to = Math.max(a, b);
2091
+ const firstLineStart = lineStartOfIndex(source, from);
2092
+ let out = source.slice(0, firstLineStart);
2093
+ let prevEnd = firstLineStart;
2094
+ let totalRemoval = 0;
2095
+ const shifts = []; // [lineStart, removal] per touched line, in walk order
2096
+ eachTouchedLine(source, from, to, (lineStart, lineEnd) => {
2097
+ out += source.slice(prevEnd, lineStart);
2098
+ const removal = outdentRemoval(source.slice(lineStart, lineEnd), fill);
2099
+ totalRemoval += removal;
2100
+ shifts.push([lineStart, removal]);
2101
+ out += source.slice(lineStart + removal, lineEnd);
2102
+ prevEnd = lineEnd;
2103
+ });
2104
+ out += source.slice(prevEnd);
2105
+ if (totalRemoval === 0) return null;
2106
+ // Each bound shifts by only the removal portions strictly BEFORE it; a
2107
+ // bound inside a removal window must not subtract the whole window, or
2108
+ // the result overshoots backwards and the clamp pins it to offset 0.
2109
+ const deltaOf = (bound) => {
2110
+ let delta = 0;
2111
+ for (const [lineStart, removal] of shifts) {
2112
+ delta += Math.min(removal, Math.max(0, bound - lineStart));
2113
+ }
2114
+ return delta;
2115
+ };
2116
+ return {
2117
+ text: out,
2118
+ start: Math.max(0, from - deltaOf(from)),
2119
+ end: Math.max(0, to - deltaOf(to)),
2120
+ };
2121
+ }
2122
+
2123
+ /**
2124
+ * Judge and shape the DOM splice for one Shift+Tab press (spec §6.5). The
2125
+ * editor's primary write-back path replaces the source segment
2126
+ * `[segStart, to)` with the operator's rewritten text, which reproduces
2127
+ * `outdentOp`'s full document byte-identically only while `to` lies beyond
2128
+ * every removed run. Removals happen at line STARTS while `outdentOp`
2129
+ * reports `end: to − Σremovals`, so a `to` inside the last touched line's
2130
+ * removed run would under-replace — silently eating line heads or the
2131
+ * selection tail. This helper owns that shape judgment so the keydown
2132
+ * wiring stays thin.
2133
+ *
2134
+ * Runs `outdentOp` first: nothing to remove → `null` (the caller swallows
2135
+ * the key without writing back). The only reachable unsafe shape is the
2136
+ * LAST touched line's removed run straddling `end` — first and
2137
+ * intermediate runs always end before the last line's start, which is
2138
+ * itself `< end` — so the guard is `end < lastLineStart + removedLast`.
2139
+ * Safe shapes return `{ segStart, segEnd, segText }`: replacing the source
2140
+ * segment `[segStart, to)` with `segText` yields `op.text` exactly, with
2141
+ * `segStart` the start of `lineOf(start)` and `segEnd = to − Σremovals`
2142
+ * equal to `op.end`.
2143
+ *
2144
+ * Same defensive input handling as `outdentOp`; never throws.
2145
+ * @param {any} text - the current file text (any other type is treated as `''`).
2146
+ * @param {any} start - selection start offset (normalized like `end`).
2147
+ * @param {any} end - selection end offset (normalized, swapped if `< start`).
2148
+ * @param {string} unit - the indent unit (`'\t'` or a space run).
2149
+ * @returns {{ segStart: number, segEnd: number, segText: string } | null} the
2150
+ * splice plan, or `null` when there is nothing to remove or the shape is
2151
+ * unsafe for the segment splice.
2152
+ */
2153
+ function outdentSplice(text, start, end, unit) {
2154
+ const source = typeof text === 'string' ? text : '';
2155
+ const fill = typeof unit === 'string' ? unit : '';
2156
+ const op = outdentOp(source, start, end, fill);
2157
+ if (op === null) return null;
2158
+ const a = clampOffset(start, source.length);
2159
+ const b = clampOffset(end, source.length);
2160
+ const from = Math.min(a, b);
2161
+ const to = Math.max(a, b);
2162
+ const lastLineStart = lineStartOfIndex(source, Math.max(from, to - 1));
2163
+ let totalRemoval = 0;
2164
+ let removedLast = 0;
2165
+ eachTouchedLine(source, from, to, (lineStart, lineEnd) => {
2166
+ const removal = outdentRemoval(source.slice(lineStart, lineEnd), fill);
2167
+ totalRemoval += removal;
2168
+ removedLast = removal; // the walk runs first → last touched line, so this lands on it
2169
+ });
2170
+ if (to < lastLineStart + removedLast) return null; // unsafe: to inside the last line's removed run
2171
+ const segStart = lineStartOfIndex(source, from);
2172
+ return {
2173
+ segStart,
2174
+ segEnd: to - totalRemoval,
2175
+ segText: op.text.slice(segStart, op.end)
2176
+ };
2177
+ }
2178
+
2179
+ Object.assign(module.exports, { detectIndentUnit, resolveIndentUnit, indentOp, outdentOp, outdentSplice });
2180
+ return module.exports;
2181
+ })();
2182
+
2183
+ /* src/eol.js */
2184
+ const eol = (function () {
2185
+ var module = { exports: {} };
2186
+ var exports = module.exports;
2187
+ /**
2188
+ * End-of-line preservation — the pure policy that lets a CRLF/CR file keep
2189
+ * its line endings across an edit session. The editor's internal draft is
2190
+ * ALWAYS LF (the textarea normalizes its DOM value and every offset module
2191
+ * splits on '\n'), so preservation works in two halves: `detectEol` inspects
2192
+ * the RAW decoded file text at load and names the file's dominant line
2193
+ * ending; `applyEol` converts the LF draft back to that ending at the one
2194
+ * point where content leaves the machine — the write call. Display never
2195
+ * sees '\r' (a textarea cannot show it), which is exactly why the ink half
2196
+ * of the pair lives at the write boundary: the file on disk keeps its
2197
+ * endings while everything inside the editor stays LF.
2198
+ *
2199
+ * Dominant detection counts each break AT its position ('\r\n' is one crlf,
2200
+ * never a cr plus an lf) and the majority kind wins; ties and break-free
2201
+ * text degrade to 'lf' — the default for new files.
2202
+ *
2203
+ * Zero imports: pure functions only, unit-testable without DOM.
2204
+ *
2205
+ * @module @dybai/dsh-editor/eol
2206
+ */
2207
+
2208
+ /** The line-ending kinds this module names. */
2209
+ const EOLS = Object.freeze(['lf', 'crlf', 'cr']);
2210
+
2211
+ /**
2212
+ * Name the dominant line ending of a decoded file text. '\r\n' counts once
2213
+ * as crlf (a following '\n' is never double-counted as a lone lf); the kind
2214
+ * with the most occurrences wins, and a tie — or text with no breaks at all
2215
+ * — degrades to 'lf'. Never throws: any non-string input is 'lf'.
2216
+ * @param {any} text - the raw decoded file text.
2217
+ * @returns {'lf' | 'crlf' | 'cr'} the dominant line ending.
2218
+ */
2219
+ function detectEol(text) {
2220
+ if (typeof text !== 'string') return 'lf';
2221
+ let crlf = 0;
2222
+ let lf = 0;
2223
+ let cr = 0;
2224
+ for (let index = 0; index < text.length; index++) {
2225
+ const code = text.charCodeAt(index);
2226
+ if (code === 13) {
2227
+ if (text.charCodeAt(index + 1) === 10) {
2228
+ crlf++;
2229
+ index++;
2230
+ } else {
2231
+ cr++;
2232
+ }
2233
+ } else if (code === 10) {
2234
+ lf++;
2235
+ }
2236
+ }
2237
+ const max = Math.max(crlf, lf, cr);
2238
+ if (max === 0) return 'lf';
2239
+ const winners = [crlf, lf, cr].filter((count) => count === max).length;
2240
+ return winners > 1 ? 'lf' : (crlf === max ? 'crlf' : (cr === max ? 'cr' : 'lf'));
2241
+ }
2242
+
2243
+ /**
2244
+ * Convert an LF-only draft to the file's line ending at the write boundary.
2245
+ * The draft never carries '\r' (the machine normalizes at load), so this is
2246
+ * a single forward replacement; 'lf' — or anything unrecognized — returns
2247
+ * the text unchanged. Never throws: a non-string input degrades to ''.
2248
+ * @param {any} text - the LF-only draft text.
2249
+ * @param {any} eol - the file's line ending ('lf' | 'crlf' | 'cr').
2250
+ * @returns {string} the text with '\n' rewritten to the target ending.
2251
+ */
2252
+ function applyEol(text, eol) {
2253
+ if (typeof text !== 'string') return '';
2254
+ if (eol === 'crlf') return text.replace(/\n/g, '\r\n');
2255
+ if (eol === 'cr') return text.replace(/\n/g, '\r');
2256
+ return text;
2257
+ }
2258
+
2259
+ Object.assign(module.exports, { EOLS, detectEol, applyEol });
2260
+ return module.exports;
2261
+ })();
2262
+
1586
2263
  /* src/tab-machine.js */
1587
2264
  const tabMachine = (function () {
1588
2265
  var module = { exports: {} };
1589
2266
  var exports = module.exports;
2267
+ const { applyEol, EOLS } = eol;
2268
+
2269
+
1590
2270
  /**
1591
2271
  * Tab document-handle state machine and save queue — the editor framework core.
1592
2272
  *
@@ -1686,7 +2366,7 @@ window.__ModuleLoader__.load({
1686
2366
 
1687
2367
  /**
1688
2368
  * Create the per-tab controller.
1689
- * @param {{ address: string, sessionId: string, load(): Promise<{ text: string, version: string }>, write(content: string, baseVersion: string): Promise<{ operation: string, version: string }>, draftStore: { get(s,a), set(s,a,text,baseVersion), clear(s,a) }, signal?: AbortSignal, onStateChange?(fn): () => void, now?(): number, autoReloadClean?: () => boolean }} deps
2369
+ * @param {{ address: string, sessionId: string, load(): Promise<{ text: string, version: string, eol?: 'lf' | 'crlf' | 'cr' }>, write(content: string, baseVersion: string): Promise<{ operation: string, version: string }>, draftStore: { get(s,a), set(s,a,text,baseVersion), clear(s,a) }, signal?: AbortSignal, onStateChange?(fn): () => void, now?(): number, autoReloadClean?: () => boolean }} deps
1690
2370
  * @returns {{
1691
2371
  * getState(): { phase: 'loading'|'ready'|'saving'|'failed', text: string, draft: string, dirty: boolean, version: string, conflict: boolean, saving: boolean, failure: { kind: string, message: string } | null, lastError: string | null, selection: { start: number, end: number, lineStart: number, lineEnd: number, text: string } | null, modeId: string | undefined, external: 'modified'|'deleted'|null, externalNotice: 'modified'|'deleted'|null },
1692
2372
  * subscribe(fn): () => void, applyEdit(content): void, applySelection(sel): void, setContent(content, selection?): void,
@@ -1704,6 +2384,7 @@ window.__ModuleLoader__.load({
1704
2384
  let text = ''; // saved baseline (last loaded/written content)
1705
2385
  let draft = ''; // current in-editor content
1706
2386
  let version = ''; // last known file version (opaque token)
2387
+ let eol = 'lf'; // 文件行尾(load 探测,写线应用;机内恒为 LF——见 src/eol.js)
1707
2388
  let conflict = false;
1708
2389
  let saving = false;
1709
2390
  let failure = null; // load-phase failure { kind, message }
@@ -1740,6 +2421,7 @@ window.__ModuleLoader__.load({
1740
2421
  lastError,
1741
2422
  selection,
1742
2423
  modeId,
2424
+ eol,
1743
2425
  external,
1744
2426
  externalNotice,
1745
2427
  };
@@ -1791,6 +2473,7 @@ window.__ModuleLoader__.load({
1791
2473
  lastError = null;
1792
2474
  text = result.text;
1793
2475
  version = result.version;
2476
+ eol = EOLS.includes(result.eol) ? result.eol : 'lf';
1794
2477
  external = null; // fresh disk truth: any divergence marker is stale
1795
2478
  externalNotice = null;
1796
2479
  seenExternalVersion = '';
@@ -1904,7 +2587,11 @@ window.__ModuleLoader__.load({
1904
2587
  }
1905
2588
  let outcome;
1906
2589
  try {
1907
- outcome = write(content, baseVersion);
2590
+ // The wire carries the FILE's line ending (eol preservation): the draft
2591
+ // and the baseline stay LF internally — dirty checks and every offset
2592
+ // module must never see '\r' (see src/eol.js). settleWrite stores the
2593
+ // LF form as the baseline, so a saved tab reads clean immediately.
2594
+ outcome = write(applyEol(content, eol), baseVersion);
1908
2595
  } catch (error) {
1909
2596
  outcome = Promise.reject(error);
1910
2597
  }
@@ -2686,8 +3373,10 @@ window.__ModuleLoader__.load({
2686
3373
  * `{primary}` with `code ∈ {KeyW, KeyT, KeyN, KeyQ, Tab, PageUp, PageDown}`
2687
3374
  * (close/new tab, new window, quit, tab-cycle, tab-shift), or exactly
2688
3375
  * `{primary, shift}` with `code ∈ {KeyW, KeyN, KeyQ, KeyT}` (reopen-closed-
2689
- * tab and friends). Everything else — including bare keys without modifiers
2690
- * and combos carrying `alt`/`control`/`meta` extras — is recordable.
3376
+ * tab and friends). Bare Tab and Shift+Tab are ALSO reserved (0.13.0): the
3377
+ * editor owns them for indentation/outdent, so they are never recordable.
3378
+ * Everything else — including bare keys without modifiers and combos
3379
+ * carrying `alt`/`control`/`meta` extras — is recordable.
2691
3380
  * @param {{ code, ctrlKey, shiftKey, altKey, metaKey, isComposing }} eventLike
2692
3381
  * @param {string} [platform]
2693
3382
  * @returns {boolean}
@@ -2708,6 +3397,8 @@ window.__ModuleLoader__.load({
2708
3397
  const SHIFTED = new Set(['KeyW', 'KeyN', 'KeyQ', 'KeyT']);
2709
3398
  if (primary && !shift && !extras) return SINGLE.has(code);
2710
3399
  if (primary && shift && !extras) return SHIFTED.has(code);
3400
+ // Tab / Shift+Tab: editor-owned indentation (0.13.0)
3401
+ if (!primary && !extras && code === 'Tab') return true;
2711
3402
  return false;
2712
3403
  }
2713
3404
 
@@ -2808,10 +3499,14 @@ window.__ModuleLoader__.load({
2808
3499
  *
2809
3500
  * - `mirrorFactory()` → a mirror port
2810
3501
  * `{ setStyle(styleObj), setWidth(px), measure(text) → heightPx,
2811
- * measureWidth(text) → widthPx, detach() }`.
3502
+ * measureWidth(text) → widthPx, measureRowSlices(text) → string[],
3503
+ * detach() }`.
2812
3504
  * `measureWidth` answers the `chWidthPx` probe (the height-only
2813
3505
  * `measure` cannot report a width); a port without it makes `chWidthPx`
2814
3506
  * degrade to `0`, which the estimation layer treats as unusable.
3507
+ * `measureRowSlices` answers the per-visual-row text slices below; a
3508
+ * port without it makes the measurer's `measureRowSlices` answer `null`,
3509
+ * and the glyph layer skips that row for the round.
2815
3510
  * - `readStyles(area)` → a computed-style-like object; only
2816
3511
  * `paddingLeft`/`paddingRight` and the copied font properties are read.
2817
3512
  * - `schedule(callback)` → the frame scheduler (`requestAnimationFrame` by
@@ -2824,6 +3519,15 @@ window.__ModuleLoader__.load({
2824
3519
  * (`onDone(counts)`). The controller paints estimates for the not-yet-exact
2825
3520
  * tail, so first paint never stalls on a huge file.
2826
3521
  *
3522
+ * `measureRowSlices(text)` answers the per-visual-row TEXT slices of one
3523
+ * line — the whitespace glyph layer's query: painting glyphs per visual
3524
+ * row requires knowing which characters the browser actually put on each
3525
+ * row. The slices share `measureRange`'s source and width (the same
3526
+ * mirror, set to the same `usableWidth()`), so a slice boundary is
3527
+ * exactly where the counted rows break. Answers are cached per
3528
+ * `usableWidth()|text` key (FIFO, capped, cleared on `attach`) because
3529
+ * the glyph layer re-asks the same visible lines after every edit.
3530
+ *
2827
3531
  * Never-throw: every method degrades unusable state (detached, disposed,
2828
3532
  * unusable line height or width, a broken mirror port) to a safe answer —
2829
3533
  * `false`, `0`, `[]`, or one row per line — so the component layer can call
@@ -2890,6 +3594,37 @@ window.__ModuleLoader__.load({
2890
3594
  /** Default per-slice budget for `measureAll`, in milliseconds. */
2891
3595
  const DEFAULT_BUDGET_MS = 12;
2892
3596
 
3597
+ /** Upper bound of the row-slice cache: 128 `usableWidth|text` entries in
3598
+ * FIFO order — scrolling through a large file must not grow the cache
3599
+ * without limit, and the oldest slices belong to the lines least likely
3600
+ * to be asked again soon. */
3601
+ const ROW_SLICE_CACHE_MAX = 128;
3602
+
3603
+ /** Upper bound on the line text `measureRowSlices` will probe: the probe
3604
+ * builds one transient `<span>` per code point, so an unbounded line (a
3605
+ * minified 100 KB single-line JSON, a base64 blob) would build ~100K
3606
+ * spans per call — a seconds-scale freeze the documented 4 MiB envelope
3607
+ * makes realistic. An over-cap line answers `null` BEFORE any probe or
3608
+ * cache traffic, so the glyph layer's null-compensation chain skips it
3609
+ * for the round: no perceptible regression inside the envelope beats
3610
+ * glyph completeness on pathological lines (spec success standard 4).
3611
+ * Measured in UTF-16 units — a cheap over-approximation of code points
3612
+ * (a surrogate pair counts 2 here but renders as 1 span), so the probe
3613
+ * never sees more spans than the cap allows. Exported for tests and the
3614
+ * manual test matrix. */
3615
+ const ROW_SLICE_MAX_CHARS = 2048;
3616
+
3617
+ /**
3618
+ * The style properties the row-slice probe copies from the mirror element
3619
+ * on every call: the width the measurer last set (slices must be taken at
3620
+ * the width `measureRange` wraps at), the shared wrap rules, and the whole
3621
+ * typographic context — everything that decides where the browser breaks
3622
+ * lines. `tabSize` rides along in the font keys; `boxSizing` keeps the
3623
+ * copied width meaning content width on the probe too. The probe's own
3624
+ * hiding layout (`MIRROR_POSITION_STYLES`) is applied once at creation.
3625
+ */
3626
+ const PROBE_STYLE_KEYS = ['width', ...Object.keys(WRAP_LINE_STYLES), ...FONT_STYLE_KEYS, 'boxSizing'];
3627
+
2893
3628
  /**
2894
3629
  * Normalize a CSS px reading (`"12px"`, `12`, garbage) to a finite number.
2895
3630
  * @param {any} value - a computed-style value or a number.
@@ -2954,6 +3689,10 @@ window.__ModuleLoader__.load({
2954
3689
  if (document.body !== null && typeof document.body === 'object' && typeof document.body.appendChild === 'function') {
2955
3690
  document.body.appendChild(element);
2956
3691
  }
3692
+ // The row-slice probe, created lazily on the first `measureRowSlices`
3693
+ // call: it must be its own element — writing spans into the mirror would
3694
+ // change what `measure` sees — so it carries its own lifecycle here.
3695
+ let probeElement = null;
2957
3696
  return {
2958
3697
  /**
2959
3698
  * Apply a style object (camelCase CSSOM property names). `undefined`
@@ -3000,9 +3739,72 @@ window.__ModuleLoader__.load({
3000
3739
  element.style.width = previousWidth;
3001
3740
  return width;
3002
3741
  },
3003
- /** Remove the mirror from the document. */
3742
+ /**
3743
+ * The per-visual-row text slices of one line, in row order: every
3744
+ * code point (surrogate pairs kept whole — `for...of` iterates code
3745
+ * points) is wrapped in its own `<span>` inside the probe div, and a
3746
+ * change in the spans' `offsetTop` marks where the browser broke to
3747
+ * the next visual row; the original text is then cut at those code
3748
+ * point boundaries. The probe copies the mirror's width, wrap rules
3749
+ * and font at call time (`PROBE_STYLE_KEYS`), so the slices are
3750
+ * taken exactly where `measure` counts its rows. Any failure
3751
+ * degrades to `[text]` — the whole line as one slice: wrong, but
3752
+ * bounded and never a crash.
3753
+ * @param {string} text - the line's text.
3754
+ * @returns {string[]} one slice per visual row; `['']` for empty
3755
+ * text, answered without touching the probe.
3756
+ */
3757
+ measureRowSlices(text) {
3758
+ if (text === '') return [''];
3759
+ try {
3760
+ if (probeElement === null) {
3761
+ probeElement = document.createElement('div');
3762
+ probeElement.setAttribute('aria-hidden', 'true');
3763
+ for (const property of Object.keys(MIRROR_POSITION_STYLES)) {
3764
+ probeElement.style[property] = MIRROR_POSITION_STYLES[property];
3765
+ }
3766
+ if (document.body !== null && typeof document.body === 'object' && typeof document.body.appendChild === 'function') {
3767
+ document.body.appendChild(probeElement);
3768
+ }
3769
+ }
3770
+ for (const property of PROBE_STYLE_KEYS) {
3771
+ probeElement.style[property] = element.style[property];
3772
+ }
3773
+ const codePoints = [];
3774
+ for (const character of text) {
3775
+ codePoints.push(character);
3776
+ const span = document.createElement('span');
3777
+ span.textContent = character;
3778
+ probeElement.appendChild(span);
3779
+ }
3780
+ const spans = probeElement.children;
3781
+ const slices = [];
3782
+ let rowStart = 0;
3783
+ let previousTop = spans.length > 0 ? spans[0].offsetTop : 0;
3784
+ for (let index = 1; index < spans.length; index++) {
3785
+ const top = spans[index].offsetTop;
3786
+ if (top !== previousTop) {
3787
+ slices.push(codePoints.slice(rowStart, index).join(''));
3788
+ rowStart = index;
3789
+ previousTop = top;
3790
+ }
3791
+ }
3792
+ slices.push(codePoints.slice(rowStart).join(''));
3793
+ return slices;
3794
+ } catch {
3795
+ return [text];
3796
+ } finally {
3797
+ if (probeElement !== null) probeElement.textContent = '';
3798
+ }
3799
+ },
3800
+ /**
3801
+ * Remove the mirror — and its row-slice probe, if one was created —
3802
+ * from the document, so a detached mirror leaves nothing behind.
3803
+ */
3004
3804
  detach() {
3005
3805
  if (element.parentNode !== null) element.parentNode.removeChild(element);
3806
+ if (probeElement !== null && probeElement.parentNode !== null) probeElement.parentNode.removeChild(probeElement);
3807
+ probeElement = null;
3006
3808
  }
3007
3809
  };
3008
3810
  }
@@ -3023,7 +3825,8 @@ window.__ModuleLoader__.load({
3023
3825
  * @param {number} [deps.budgetMs] - per-slice time budget; non-finite or
3024
3826
  * negative falls back to 12.
3025
3827
  * @returns {object} the measurer — `attach`, `detach`, `ready`, `usableWidth`,
3026
- * `chWidthPx`, `measureRange`, `measureTextRows`, `measureAll`, `dispose`.
3828
+ * `chWidthPx`, `measureRange`, `measureTextRows`, `measureAll`,
3829
+ * `measureRowSlices`, `dispose`.
3027
3830
  */
3028
3831
  function createWrapMeasurer(deps) {
3029
3832
  const options = deps !== null && typeof deps === 'object' ? deps : {};
@@ -3042,6 +3845,7 @@ window.__ModuleLoader__.load({
3042
3845
  let lineHeightPx = NaN;
3043
3846
  let disposed = false;
3044
3847
  let cancelActive = null;
3848
+ let rowSliceCache = new Map();
3045
3849
 
3046
3850
  /** Whether an area and a mirror are currently held. */
3047
3851
  const isAttached = () => area !== null && mirror !== null;
@@ -3092,6 +3896,9 @@ window.__ModuleLoader__.load({
3092
3896
  function attach(nextArea, attachOptions) {
3093
3897
  if (disposed) return;
3094
3898
  detach();
3899
+ // a fresh mirror is a new metrics epoch: slices cached for the old
3900
+ // width and font must not leak into it
3901
+ rowSliceCache.clear();
3095
3902
  if (nextArea === null || typeof nextArea !== 'object') return;
3096
3903
  const settings = attachOptions !== null && typeof attachOptions === 'object' ? attachOptions : {};
3097
3904
  const nextLineHeightPx =
@@ -3316,6 +4123,58 @@ window.__ModuleLoader__.load({
3316
4123
  return cancel;
3317
4124
  }
3318
4125
 
4126
+ /**
4127
+ * The per-visual-row text slices of one source line — the whitespace
4128
+ * glyph layer's query (0.12.0). Same source and same width as
4129
+ * `measureRange`: the mirror is set to the current `usableWidth()`
4130
+ * before the port walks the line's code points, so slice boundaries
4131
+ * are exactly where the counted rows break. Every unusable state
4132
+ * (unattached, disposed, unusable width, a port without the method, a
4133
+ * throwing or garbage-answering port) answers `null` — the caller
4134
+ * skips that row for the round, which is bounded and safe. Empty text
4135
+ * is `['']`, answered without probing; a line longer than
4136
+ * `ROW_SLICE_MAX_CHARS` is ALSO `null`, answered before any probe or
4137
+ * cache traffic (the per-code-point probe would freeze the frame on
4138
+ * such a line); everything else is cached per
4139
+ * `usableWidth()|text` (FIFO, capped, cleared on `attach`) because the
4140
+ * glyph layer re-asks the same visible lines after every edit.
4141
+ * @param {string} text - the line's text.
4142
+ * @returns {string[] | null} one slice per visual row in row order, or
4143
+ * `null` when the slices cannot be answered.
4144
+ */
4145
+ function measureRowSlices(text) {
4146
+ if (disposed || !isAttached()) return null;
4147
+ const width = usableWidth();
4148
+ if (width <= 0) return null;
4149
+ if (typeof mirror.measureRowSlices !== 'function') return null;
4150
+ if (text === '') return [''];
4151
+ // The probe input cap, BEFORE any cache traffic: an over-cap line
4152
+ // is never probed (and so never cached) — `null` hands it to the
4153
+ // caller's skip-and-compensate chain instead.
4154
+ if (typeof text === 'string' && text.length > ROW_SLICE_MAX_CHARS) return null;
4155
+ const key = `${width}|${text}`;
4156
+ const cached = rowSliceCache.get(key);
4157
+ if (cached !== undefined) return cached;
4158
+ try {
4159
+ if (typeof mirror.setWidth === 'function') mirror.setWidth(width);
4160
+ } catch {
4161
+ return null;
4162
+ }
4163
+ let slices = null;
4164
+ try {
4165
+ slices = mirror.measureRowSlices(text);
4166
+ } catch {
4167
+ return null;
4168
+ }
4169
+ if (!Array.isArray(slices)) return null;
4170
+ rowSliceCache.set(key, slices);
4171
+ if (rowSliceCache.size > ROW_SLICE_CACHE_MAX) {
4172
+ // Map iterates in insertion order, so the first key is the oldest
4173
+ rowSliceCache.delete(rowSliceCache.keys().next().value);
4174
+ }
4175
+ return slices;
4176
+ }
4177
+
3319
4178
  /**
3320
4179
  * Release the mirror and make the measurer permanently inert (a disposed
3321
4180
  * measurer ignores a later `attach`). The component calls this on unmount;
@@ -3335,11 +4194,12 @@ window.__ModuleLoader__.load({
3335
4194
  measureRange,
3336
4195
  measureTextRows,
3337
4196
  measureAll,
4197
+ measureRowSlices,
3338
4198
  dispose
3339
4199
  };
3340
4200
  }
3341
4201
 
3342
- Object.assign(module.exports, { WRAP_LINE_STYLES, createWrapMeasurer });
4202
+ Object.assign(module.exports, { WRAP_LINE_STYLES, ROW_SLICE_MAX_CHARS, createWrapMeasurer });
3343
4203
  return module.exports;
3344
4204
  })();
3345
4205
 
@@ -3609,7 +4469,7 @@ window.__ModuleLoader__.load({
3609
4469
  };
3610
4470
  }
3611
4471
 
3612
- Object.assign(module.exports, { columnsOf, estimateRows, estimateAllRows, changedLineRange, buildWrapGeometry });
4472
+ Object.assign(module.exports, { codePointColumns, columnsOf, estimateRows, estimateAllRows, changedLineRange, buildWrapGeometry });
3613
4473
  return module.exports;
3614
4474
  })();
3615
4475
 
@@ -4728,32 +5588,325 @@ window.__ModuleLoader__.load({
4728
5588
  return module.exports;
4729
5589
  })();
4730
5590
 
4731
- /* src/components.js */
4732
- const components = (function () {
5591
+ /* src/whitespace.js */
5592
+ const whitespace = (function () {
4733
5593
  var module = { exports: {} };
4734
5594
  var exports = module.exports;
4735
- const { basenameOf, isEditablePath, parseFileAddress } = address;
4736
- const { activeLineBar, lineHeightPxOf } = activeLine;
4737
- const { endScrollTarget, scrollBeyondPadding } = scrollBeyond;
4738
- const { gutterWidthCh, contentPaddingCh, lineNumbersText } = lineNumbers;
4739
- const { lineOfOffset, lineOfOffsetFast, caretOffsetOfSelection, offsetOfLine } = lines;
4740
- const { createTabController } = tabMachine;
4741
- const { createDiskWatch } = diskWatch;
4742
- const { resolveModeId } = ranking;
4743
- const { matchAction, comboOf } = keymap;
4744
- const { parseGotoLine } = gotoLine;
4745
- const { canApplyScroll, scrollDiffers, selectionFromViewState, selectionRecordFromSnapshot, shouldFocusEditorOnOpen, shouldRestoreViewState, viewStateKey } = viewState;
4746
- const { createWrapMeasurer } = wrapMeasure;
4747
- const { createWrapController } = wrapController;
4748
- const { resolveWordWrap } = wrapResolve;
5595
+ const { codePointColumns } = wrapGeometry;
4749
5596
 
4750
5597
  /**
4751
- * Editor framework UI components — the browser half's React layer.
5598
+ * Whitespace rendering — the pure building layer behind the "show invisible
5599
+ * characters" affordance (spec §7.1): everything the DOM layer paints, it
5600
+ * paints from the fragments and numbers this module computes.
4752
5601
  *
4753
- * `createEditorComponents(runtime)` builds the component set the client entry
4754
- * wires into sidebar-right:
5602
+ * Four functions, no DOM:
4755
5603
  *
4756
- * - `EditorTab` — the `sidebar.right.pane.tab` body: owns ONE tab-machine
5604
+ * - `buildWhitespaceRow({ text, spaces, tabs, newlines, tabSize })` — one
5605
+ * source line as an ordered fragment list (`text` / `glyph` / `pad`), the
5606
+ * glyph forms taken from `WHITESPACE_GLYPHS`, tab stops from `tabAdvance`
5607
+ * over a running column counter that widths each code point via
5608
+ * `codePointColumns` (imported from `wrap-geometry.js`, exported there as
5609
+ * of this task).
5610
+ * - `tabAdvance(column, tabSize)` — the columns-to-next-stop arithmetic the
5611
+ * fragment builder (and any tab-width ruler) shares.
5612
+ * - `visibleWindow({ scrollTop, paddingTop, lineHeight, clientHeight,
5613
+ * lineCount, marginRows })` — the 0-based run of lines a viewport paints,
5614
+ * margin-widened and clamped into the document.
5615
+ * - `showsNewlineGlyph(lines, lineNumber)` — whether a line ends with a real
5616
+ * line break (every break paints, including a file's trailing newline).
5617
+ *
5618
+ * Everything normalizes defensively in the house style — no input shape
5619
+ * throws, and unusable input degrades to a safe value (an empty fragment
5620
+ * list, a full-width tab advance, `false`, the empty window) — so the DOM
5621
+ * layer can pipe untrusted switches and measurements straight in and a
5622
+ * malformed value can never corrupt a painted row.
5623
+ *
5624
+ * Pure functions only, unit-testable without DOM.
5625
+ *
5626
+ * @module @dybai/dsh-editor/whitespace
5627
+ */
5628
+
5629
+
5630
+ /**
5631
+ * The glyphs that stand in for invisible characters when whitespace display
5632
+ * is on: a middle dot for spaces, a rightwards arrow for tabs, a downwards
5633
+ * arrow with corner leftwards for the line break a row ends with. Frozen so
5634
+ * a consumer cannot re-point a glyph and corrupt every row painted after it.
5635
+ * @type {{space: string, tab: string, newline: string}}
5636
+ */
5637
+ const WHITESPACE_GLYPHS = Object.freeze({ space: '\u00B7', tab: '\u2192', newline: '\u21B5', carriage: '\u240D' });
5638
+
5639
+ /**
5640
+ * The tab stop width the whitespace layer falls back to when a caller's
5641
+ * `tabSize` is unusable — the editor's 4-column tab default.
5642
+ * @type {number}
5643
+ */
5644
+ const WHITESPACE_TAB_SIZE = 4;
5645
+
5646
+ /**
5647
+ * The value itself when it is a finite number, otherwise the fallback. The
5648
+ * one gate every arithmetic input in this module passes through, so DOM
5649
+ * measurements (or garbage) can be piped straight in and a `NaN` can never
5650
+ * leak into a painted row.
5651
+ * @param {any} value - caller-supplied number, maybe unusable.
5652
+ * @param {number} fallback - the safe answer for unusable input.
5653
+ * @returns {number} a finite number.
5654
+ */
5655
+ function finiteNumberOr(value, fallback) {
5656
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
5657
+ }
5658
+
5659
+ /**
5660
+ * How many columns a tab advances from `column` to reach the NEXT `tabSize`
5661
+ * stop: a tab sitting exactly on a stop still advances a full width, so the
5662
+ * result never stalls. `tabSize` that is not a finite number ≥ 1 falls back
5663
+ * to `WHITESPACE_TAB_SIZE`; a non-finite or negative `column` reads as
5664
+ * column `0`; a fractional one floors first — the answer is always an
5665
+ * integer ≥ 1 and at most the effective stop width.
5666
+ * @param {any} column - display columns already consumed on the row.
5667
+ * @param {any} tabSize - tab stop width in columns.
5668
+ * @returns {number} columns to the next stop, an integer ≥ 1.
5669
+ */
5670
+ function tabAdvance(column, tabSize) {
5671
+ const stops =
5672
+ typeof tabSize === 'number' && Number.isFinite(tabSize) && tabSize >= 1 ? Math.floor(tabSize) : WHITESPACE_TAB_SIZE;
5673
+ const at = Math.max(0, Math.floor(finiteNumberOr(column, 0)));
5674
+ return stops - (at % stops);
5675
+ }
5676
+
5677
+ /**
5678
+ * Whether source line `lineNumber` (1-based, from `draft.split('\n')`) ends
5679
+ * with a real line break and therefore paints a ↵ glyph when whitespace
5680
+ * display is on: EVERY line that has a following line does — including the
5681
+ * file's trailing newline (0.13.0 fix). The earlier "trailing newline draws
5682
+ * no glyph" exception made Enter at EOF invisible (the just-typed break was
5683
+ * always the trailing one, so it never painted until the next Enter) — the
5684
+ * rule now gives immediate feedback for every real break. A file WITHOUT a
5685
+ * trailing newline still shows nothing on its last line (no break there).
5686
+ * An invalid or out-of-range line number — or a non-array `lines` —
5687
+ * degrades to `false`, the no-glyph answer, never a throw.
5688
+ * @param {any} lines - the split lines of the draft.
5689
+ * @param {any} lineNumber - 1-based source line.
5690
+ * @returns {boolean} whether the line's break glyph shows.
5691
+ */
5692
+ function showsNewlineGlyph(lines, lineNumber) {
5693
+ if (!Array.isArray(lines)) return false;
5694
+ if (typeof lineNumber !== 'number' || !Number.isInteger(lineNumber) || lineNumber < 1 || lineNumber > lines.length) {
5695
+ return false;
5696
+ }
5697
+ return lineNumber < lines.length;
5698
+ }
5699
+
5700
+ /**
5701
+ * The 0-based run of source lines a viewport should paint: the lines the
5702
+ * scroll position covers, widened by `marginRows` beyond each edge so fast
5703
+ * scrolling paints a buffer around the visible region, then clamped into
5704
+ * the document. The measurements arrive from the DOM layer and normalize
5705
+ * defensively: a `lineHeight` that is not a finite number > 0 degrades to
5706
+ * the empty window `{ first0: 0, count: 0 }`, unusable numerics read as
5707
+ * `0`, a `marginRows` that is not a positive integer reads as `0`, and the
5708
+ * run never starts below 0 or runs past `lineCount`.
5709
+ * @param {any} options - `{ scrollTop, paddingTop, lineHeight,
5710
+ * clientHeight, lineCount, marginRows }` in px / rows, as measured.
5711
+ * @returns {{first0: number, count: number}} 0-based first line to paint
5712
+ * and how many lines to paint.
5713
+ */
5714
+ function visibleWindow(options) {
5715
+ const source = options !== null && typeof options === 'object' ? options : {};
5716
+ const lineHeight = source.lineHeight;
5717
+ if (typeof lineHeight !== 'number' || !Number.isFinite(lineHeight) || lineHeight <= 0) return { first0: 0, count: 0 };
5718
+ const scrollTop = finiteNumberOr(source.scrollTop, 0);
5719
+ const paddingTop = finiteNumberOr(source.paddingTop, 0);
5720
+ const clientHeight = finiteNumberOr(source.clientHeight, 0);
5721
+ const lineCount = Math.max(0, Math.floor(finiteNumberOr(source.lineCount, 0)));
5722
+ const margin = Number.isInteger(source.marginRows) && source.marginRows > 0 ? source.marginRows : 0;
5723
+ const first0 = Math.min(Math.max(Math.floor((scrollTop - paddingTop) / lineHeight) - margin, 0), lineCount);
5724
+ const count = Math.min(Math.max(Math.ceil(clientHeight / lineHeight) + 2 * margin, 0), lineCount - first0);
5725
+ return { first0, count };
5726
+ }
5727
+
5728
+ /**
5729
+ * Builds one rendered row's fragment list from a source line: plain text
5730
+ * stays text, and — per switch — a space becomes a · glyph, a tab becomes a
5731
+ * → glyph plus a `pad` covering the rest of its advance to the next stop,
5732
+ * and the row's line break becomes a trailing ↵ glyph. Fragments arrive in
5733
+ * paint order, each exactly `{ kind: 'text', text }`, `{ kind: 'glyph',
5734
+ * glyph }`, or `{ kind: 'pad', count }`, and adjacent text merges into one
5735
+ * fragment. Widths come from `codePointColumns` (wide code points count 2)
5736
+ * with tabs advancing per `tabAdvance`; the scan walks code points so
5737
+ * surrogate pairs survive whole. Unusable input degrades to an empty list —
5738
+ * never a throw, never a DOM read.
5739
+ * @param {any} options - `{ text, spaces, tabs, newlines, tabSize }`: the
5740
+ * source line and which whitespace kinds render visibly.
5741
+ * @returns {Array<{kind: string, text?: string, glyph?: string, count?: number}>}
5742
+ * the ordered fragments to paint.
5743
+ */
5744
+ function buildWhitespaceRow(options) {
5745
+ const source = options !== null && typeof options === 'object' ? options : {};
5746
+ const text = typeof source.text === 'string' ? source.text : '';
5747
+ const spaces = source.spaces === true;
5748
+ const tabs = source.tabs === true;
5749
+ const newlines = source.newlines === true;
5750
+ const fragments = [];
5751
+ let textChunk = '';
5752
+ let column = 0;
5753
+ const flushText = () => {
5754
+ if (textChunk === '') return;
5755
+ fragments.push({ kind: 'text', text: textChunk });
5756
+ textChunk = '';
5757
+ };
5758
+ for (const character of text) {
5759
+ if (spaces && character === ' ') {
5760
+ flushText();
5761
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.space });
5762
+ column += 1;
5763
+ continue;
5764
+ }
5765
+ if (tabs && character === '\t') {
5766
+ flushText();
5767
+ const advance = tabAdvance(column, source.tabSize);
5768
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.tab });
5769
+ fragments.push({ kind: 'pad', count: advance - 1 });
5770
+ column += advance;
5771
+ continue;
5772
+ }
5773
+ textChunk += character;
5774
+ column += codePointColumns(character.codePointAt(0));
5775
+ }
5776
+ flushText();
5777
+ if (newlines) {
5778
+ // 行尾保留显示(0.13.0):文件行尾决定断行记号的形状与数量——
5779
+ // lf 一个 ↵;crlf 一对 ␍+↵(与文件字节一对一);cr 只画 ␍。
5780
+ // 记号画在真实 advance 之外,不影响列计数。
5781
+ if (source.eol === 'crlf') {
5782
+ flushText();
5783
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.carriage });
5784
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.newline });
5785
+ } else if (source.eol === 'cr') {
5786
+ flushText();
5787
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.carriage });
5788
+ } else {
5789
+ fragments.push({ kind: 'glyph', glyph: WHITESPACE_GLYPHS.newline });
5790
+ }
5791
+ }
5792
+ return fragments;
5793
+ }
5794
+
5795
+ /**
5796
+ * Vector shape specs for the whitespace glyphs — the font-INDEPENDENT
5797
+ * replacement for drawing the literal characters. Rationale (0.12.0 fix):
5798
+ * the old rendering put the glyph character inside a 1ch inline-block and
5799
+ * trusted `text-align: center`, but a glyph's ink position lives in its
5800
+ * FONT: on environments whose resolved monospace lacks U+00B7/U+2192 the
5801
+ * browser falls back to full-width CJK glyphs (advance ≈ 2ch) and Chrome
5802
+ * left-anchors over-wide line-box content (measured: ink offset 0, ink
5803
+ * wider than the box), so the ink landed at font-specific offsets — dots
5804
+ * hugging the cell's right edge, arrows hugging the left. Drawing fixed
5805
+ * vector shapes removes the font from the equation entirely: every
5806
+ * environment paints the same geometry at the same position.
5807
+ *
5808
+ * Each spec: `viewBox` (a 12×12 design space, stroked/filled with
5809
+ * `currentColor` at the layer's opacity), `elements` (tag + SVG attributes
5810
+ * verbatim; camelCase attribute keys are kebab-cased by the DOM builder),
5811
+ * and `yCenterEm` — the shape's vertical center ABOVE the text baseline in
5812
+ * em (the glyph box has zero height, so its bottom edge sits on the
5813
+ * baseline; this is the deterministic replacement for the old glyph's
5814
+ * baseline-relative ink position).
5815
+ * @param {any} glyph - the glyph character (`WHITESPACE_GLYPHS` member).
5816
+ * @returns {object | null} `{ viewBox, elements, yCenterEm }`, or `null`
5817
+ * for unknown input (the DOM builder degrades to the literal character).
5818
+ */
5819
+ function glyphSvgShape(glyph) {
5820
+ if (glyph === WHITESPACE_GLYPHS.space) {
5821
+ return {
5822
+ viewBox: '0 0 12 12',
5823
+ yCenterEm: 0.32,
5824
+ elements: [{ tag: 'circle', cx: 6, cy: 6, r: 2.2, fill: 'currentColor' }]
5825
+ };
5826
+ }
5827
+ if (glyph === WHITESPACE_GLYPHS.tab) {
5828
+ return {
5829
+ viewBox: '0 0 12 12',
5830
+ yCenterEm: 0.3,
5831
+ elements: [{
5832
+ tag: 'path',
5833
+ d: 'M1.4,6 H10 M7.2,2.9 L10.3,6 L7.2,9.1',
5834
+ fill: 'none',
5835
+ stroke: 'currentColor',
5836
+ strokeWidth: 1.4,
5837
+ strokeLinecap: 'round',
5838
+ strokeLinejoin: 'round'
5839
+ }]
5840
+ };
5841
+ }
5842
+ if (glyph === WHITESPACE_GLYPHS.newline) {
5843
+ return {
5844
+ viewBox: '0 0 12 12',
5845
+ yCenterEm: 0.3,
5846
+ elements: [{
5847
+ tag: 'path',
5848
+ d: 'M10.6,3.4 H4.3 L2.7,5 V9.2 M1,7.6 L2.7,9.5 L4.4,7.6',
5849
+ fill: 'none',
5850
+ stroke: 'currentColor',
5851
+ strokeWidth: 1.4,
5852
+ strokeLinecap: 'round',
5853
+ strokeLinejoin: 'round'
5854
+ }]
5855
+ };
5856
+ }
5857
+ if (glyph === WHITESPACE_GLYPHS.carriage) {
5858
+ // The CR mark: a LEFT-pointing arrow — carriage return returns to the
5859
+ // line start. Deliberately the mirror image of the → tab mark so the
5860
+ // two are never confused at 25% opacity.
5861
+ return {
5862
+ viewBox: '0 0 12 12',
5863
+ yCenterEm: 0.3,
5864
+ elements: [{
5865
+ tag: 'path',
5866
+ d: 'M10.6,6 H1.9 M4.9,2.9 L1.8,6 L4.9,9.1',
5867
+ fill: 'none',
5868
+ stroke: 'currentColor',
5869
+ strokeWidth: 1.4,
5870
+ strokeLinecap: 'round',
5871
+ strokeLinejoin: 'round'
5872
+ }]
5873
+ };
5874
+ }
5875
+ return null;
5876
+ }
5877
+
5878
+ Object.assign(module.exports, { WHITESPACE_GLYPHS, WHITESPACE_TAB_SIZE, tabAdvance, showsNewlineGlyph, visibleWindow, buildWhitespaceRow, glyphSvgShape });
5879
+ return module.exports;
5880
+ })();
5881
+
5882
+ /* src/components.js */
5883
+ const components = (function () {
5884
+ var module = { exports: {} };
5885
+ var exports = module.exports;
5886
+ const { basenameOf, isEditablePath, parseFileAddress } = address;
5887
+ const { activeLineBar, glyphBandOffsets, lineHeightPxOf } = activeLine;
5888
+ const { endScrollTarget, scrollBeyondPadding } = scrollBeyond;
5889
+ const { gutterWidthCh, contentPaddingCh, lineNumbersText } = lineNumbers;
5890
+ const { lineOfOffset, lineOfOffsetFast, caretOffsetOfSelection, offsetOfLine } = lines;
5891
+ const { indentOp, outdentOp, outdentSplice, resolveIndentUnit } = indent;
5892
+ const { createTabController } = tabMachine;
5893
+ const { createDiskWatch } = diskWatch;
5894
+ const { resolveModeId } = ranking;
5895
+ const { matchAction, comboOf } = keymap;
5896
+ const { parseGotoLine } = gotoLine;
5897
+ const { canApplyScroll, scrollDiffers, selectionFromViewState, selectionRecordFromSnapshot, shouldFocusEditorOnOpen, shouldRestoreViewState, viewStateKey } = viewState;
5898
+ const { createWrapMeasurer } = wrapMeasure;
5899
+ const { createWrapController } = wrapController;
5900
+ const { resolveWordWrap } = wrapResolve;
5901
+ const { buildWhitespaceRow, glyphSvgShape, showsNewlineGlyph, visibleWindow, WHITESPACE_TAB_SIZE } = whitespace;
5902
+
5903
+ /**
5904
+ * Editor framework UI components — the browser half's React layer.
5905
+ *
5906
+ * `createEditorComponents(runtime)` builds the component set the client entry
5907
+ * wires into sidebar-right:
5908
+ *
5909
+ * - `EditorTab` — the `sidebar.right.pane.tab` body: owns ONE tab-machine
4757
5910
  * controller per (sessionId, path, occurrence), registers it with the
4758
5911
  * dshEditor service keyed by the dockkit tab id (registered once per
4759
5912
  * mounted tab; visibility/session flips flow through `notifyChange`),
@@ -4799,6 +5952,9 @@ window.__ModuleLoader__.load({
4799
5952
  /** CSS class prefix (also the debug-marker prefix). */
4800
5953
  const CLASS = 'dsh-editor';
4801
5954
 
5955
+ /** SVG namespace for the whitespace glyph shapes (createElementNS target). */
5956
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
5957
+
4802
5958
  /** Snapshot served while a tab has no controller yet (mirrors 'loading'). */
4803
5959
  const NO_CONTROLLER_SNAPSHOT = Object.freeze({
4804
5960
  phase: 'loading',
@@ -4984,6 +6140,16 @@ window.__ModuleLoader__.load({
4984
6140
  selectEnd: { code: 'End', modifiers: ['primary', 'shift'] }
4985
6141
  };
4986
6142
 
6143
+ /**
6144
+ * The Tab-key combos the plain-text mode owns (0.13.0): Tab indents,
6145
+ * Shift+Tab outdents. Fixed editor behavior, not user-keymap-bindable;
6146
+ * the recorder rejects bare/shifted Tab via isReservedCombo.
6147
+ */
6148
+ const INDENT_KEYS_KEYMAP = {
6149
+ indent: { code: 'Tab' },
6150
+ outdent: { code: 'Tab', modifiers: ['shift'] }
6151
+ };
6152
+
4987
6153
  /**
4988
6154
  * The built-in `plain-text` mode: one controlled textarea over an
4989
6155
  * active-line highlight backdrop and a line-number gutter.
@@ -5059,6 +6225,14 @@ window.__ModuleLoader__.load({
5059
6225
  // no "default true" semantics — the caller already resolved the effective
5060
6226
  // per-file value, so only a literal `true` turns wrapping on.
5061
6227
  const wrapEnabled = props.wordWrap === true;
6228
+ // Whitespace glyphs (0.12.0): three independent booleans, all default
6229
+ // false; the prop object is read defensively (null/primitive-safe) so a
6230
+ // caller that never assembles it degrades to all-off harmlessly.
6231
+ const wsProp = props.showWhitespace;
6232
+ const wsSpaces = wsProp !== null && typeof wsProp === 'object' && wsProp.spaces === true;
6233
+ const wsTabs = wsProp !== null && typeof wsProp === 'object' && wsProp.tabs === true;
6234
+ const wsNewlines = wsProp !== null && typeof wsProp === 'object' && wsProp.newlines === true;
6235
+ const wsAny = wsSpaces || wsTabs || wsNewlines;
5062
6236
  // View-state adapter (0.8.0): the one-shot restore target and the reporter
5063
6237
  // for the offset a user actually reached. `undefined` means "no restore",
5064
6238
  // exactly like `null`; the reporter is optional and type-guarded at every
@@ -5066,6 +6240,11 @@ window.__ModuleLoader__.load({
5066
6240
  const initialScroll = props.initialScroll === undefined ? null : props.initialScroll;
5067
6241
  const onScrollChange = props.onScrollChange;
5068
6242
  const state = useControllerState(controller);
6243
+ // EOL display (0.13.0): the machine probes the file's dominant line
6244
+ // ending at load and exposes it in the state; the glyph layer mirrors it
6245
+ // so CRLF breaks draw a ␍+↵ pair, CR files a lone ␍. Anything
6246
+ // unrecognized degrades to 'lf'.
6247
+ const fileEol = state.eol === 'crlf' || state.eol === 'cr' ? state.eol : 'lf';
5069
6248
  // Attached to the textarea below — the single DOM handle every selection
5070
6249
  // path reads (reportSelection, onNavigate, the mirror effect, and the
5071
6250
  // active-line sync). The v0.3.0/0.4.0 builds shipped WITHOUT this ref:
@@ -5074,6 +6253,11 @@ window.__ModuleLoader__.load({
5074
6253
  // synced — a latent wiring gap the active-line feature finally exposed.
5075
6254
  const areaRef = React.useRef(null);
5076
6255
  const barRef = React.useRef(null);
6256
+ // Whitespace glyph layer (0.12.0): the underlay div syncWhitespace fills
6257
+ // with windowed per-line rows. Only mounted while at least one of the
6258
+ // three switches is on, so `.current` is null — and every sync no-ops —
6259
+ // for editors that keep whitespace display off.
6260
+ const whitespaceRef = React.useRef(null);
5077
6261
  const metricsRef = React.useRef(null);
5078
6262
  // Gutter scroll sync: the inner text block translates against scrollTop.
5079
6263
  const gutterTextRef = React.useRef(null);
@@ -5145,6 +6329,58 @@ window.__ModuleLoader__.load({
5145
6329
  text.style.transform = `translateY(${-area.scrollTop}px)`;
5146
6330
  }, []);
5147
6331
 
6332
+ /* --------------------------------------- glyph-ink band metrics -- */
6333
+
6334
+ // The probe text measured on the canvas: '中' reaches the CJK ink top
6335
+ // (against the ascent edge — the source of the asymmetry), 'g' reaches a
6336
+ // Latin descender. The union frames BOTH scripts' glyphs.
6337
+ const GLYPH_PROBE_TEXT = '中g';
6338
+ // The hairline band geometry — keep in sync with the
6339
+ // `.dsh-editor-highlight-bar::before/::after` `height: 2px` CSS rules.
6340
+ const GLYPH_BAND_HEIGHT = 2;
6341
+ // Whitespace between each band and the glyph ink it frames. The top band
6342
+ // hugs the glyph tops; the bottom band sits a step farther below the
6343
+ // descender line — tune these two to taste.
6344
+ const GLYPH_BAND_PADDING_TOP = 4;
6345
+ const GLYPH_BAND_PADDING_BOTTOM = 1.5;
6346
+
6347
+ /**
6348
+ * Canvas TextMetrics probe for the REAL font stack: `fontBoundingBox*`
6349
+ * locate the baseline inside the line box (the script asymmetry lives in
6350
+ * the ascent/descent ratio), `actualBoundingBox*` bound the probe text's
6351
+ * true ink extents. `null` outside a browser, when canvas 2D or the
6352
+ * bounding-box metrics are unavailable, or on any failed read — the
6353
+ * caller then keeps its static CSS fallback.
6354
+ */
6355
+ function glyphInkOf(area) {
6356
+ if (typeof document === 'undefined' || document === null) return null;
6357
+ if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return null;
6358
+ try {
6359
+ const canvas = document.createElement('canvas');
6360
+ const context = canvas.getContext('2d');
6361
+ if (context === null || typeof context.measureText !== 'function') return null;
6362
+ const style = window.getComputedStyle(area);
6363
+ context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
6364
+ const probe = context.measureText(GLYPH_PROBE_TEXT);
6365
+ const { fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent, actualBoundingBoxDescent } = probe;
6366
+ if (
6367
+ ![fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent, actualBoundingBoxDescent].every(
6368
+ (value) => typeof value === 'number' && Number.isFinite(value)
6369
+ )
6370
+ ) {
6371
+ return null;
6372
+ }
6373
+ return {
6374
+ fontAscent: fontBoundingBoxAscent,
6375
+ fontDescent: fontBoundingBoxDescent,
6376
+ inkAscent: actualBoundingBoxAscent,
6377
+ inkDescent: actualBoundingBoxDescent,
6378
+ };
6379
+ } catch {
6380
+ return null;
6381
+ }
6382
+ }
6383
+
5148
6384
  // Measure the textarea's highlight geometry, at most once per rendered
5149
6385
  // mount. Every input is a computed value (rendering-independent — the
5150
6386
  // unitless `line-height: 1.5` computed form is "1.5" hidden AND rendered,
@@ -5166,7 +6402,31 @@ window.__ModuleLoader__.load({
5166
6402
  const paddingTop = parseFloat(style.paddingTop);
5167
6403
  const lineHeight = lineHeightPxOf(style.lineHeight, parseFloat(style.fontSize));
5168
6404
  if (Number.isFinite(paddingTop) && lineHeight !== null) {
5169
- metricsRef.current = { paddingTop, lineHeight };
6405
+ const measured = { paddingTop, lineHeight };
6406
+ // Glyph-ink probe (canvas TextMetrics): where the REAL font
6407
+ // stack puts the baseline and how far the probe text's ink
6408
+ // reaches — the script asymmetry (CJK hugs the ascent edge,
6409
+ // Latin centers) lives in exactly these numbers. The band
6410
+ // offsets frame the ink symmetrically; without them the
6411
+ // static CSS fallback (symmetric edge insets) applies.
6412
+ const glyph = glyphInkOf(area);
6413
+ if (glyph !== null) {
6414
+ const offsets = glyphBandOffsets({
6415
+ lineHeight,
6416
+ fontAscent: glyph.fontAscent,
6417
+ fontDescent: glyph.fontDescent,
6418
+ inkAscent: glyph.inkAscent,
6419
+ inkDescent: glyph.inkDescent,
6420
+ paddingTop: GLYPH_BAND_PADDING_TOP,
6421
+ paddingBottom: GLYPH_BAND_PADDING_BOTTOM,
6422
+ bandHeight: GLYPH_BAND_HEIGHT,
6423
+ });
6424
+ if (offsets !== null) {
6425
+ measured.bandTop = offsets.top;
6426
+ measured.bandBottomInset = offsets.bottom;
6427
+ }
6428
+ }
6429
+ metricsRef.current = measured;
5170
6430
  }
5171
6431
  } catch {
5172
6432
  // detached node: keep measuring lazily
@@ -5345,6 +6605,212 @@ window.__ModuleLoader__.load({
5345
6605
  wrapController.syncGutter(area.scrollTop, area.clientHeight);
5346
6606
  }, []);
5347
6607
 
6608
+ // Paint the whitespace glyph layer from the LIVE textarea, along two
6609
+ // paths that share the guard chain and the row renderer below: wrap-off
6610
+ // arithmetic (Task 6) — one absolutely-positioned row span per line
6611
+ // inside visibleWindow's margin-widened run — and the wrap-on window
6612
+ // (Task 7) — the controller names the visible source lines, the
6613
+ // measurer cuts each into its per-visual-row slices, and every slice
6614
+ // paints its own row span. Fragments come from buildWhitespaceRow
6615
+ // (Task 1's pure geometry) either way. Imperative writes in the
6616
+ // paintBar tradition: every caller (scroll handler, syncRef observer
6617
+ // path, draft commits, the mount effect) needs the repaint inside its
6618
+ // own event or commit, not one React render later.
6619
+ const syncWhitespace = React.useCallback(() => {
6620
+ const layer = whitespaceRef.current;
6621
+ const area = areaRef.current;
6622
+ if (layer === null || area === null) return;
6623
+ if (!wsAny) return;
6624
+ if (area.offsetParent === null || area.clientHeight <= 0) return;
6625
+ if (state.phase !== 'ready' && state.phase !== 'saving') return;
6626
+ const metrics = metricsOfArea();
6627
+ if (metrics === null) return;
6628
+ // Full clear, then windowed rebuild: a scroll moves EVERY row, so
6629
+ // no incremental patch could beat starting over (the window is tens
6630
+ // of rows; the value split below is the only O(document) cost, and
6631
+ // the scroll paths already pay the same read for the caret
6632
+ // arithmetic).
6633
+ const doc = layer.ownerDocument;
6634
+ // WHAT a row is, shared by both branches: each branch decides only
6635
+ // WHERE its rows sit (its top arithmetic), so the two paint paths
6636
+ // render fragments through one code path and cannot drift apart.
6637
+ // Every node comes from the layer's own document — never the
6638
+ // global — so a detached or foreign-document layer degrades to a
6639
+ // paint that simply never shows. A row with no fragments (an empty
6640
+ // last line, or a wholly plain line under an all-off pass) never
6641
+ // appends — an empty span would only add noise to the layer.
6642
+ const appendRow = (topPx, fragments) => {
6643
+ if (fragments.length === 0) return;
6644
+ const row = doc.createElement('span');
6645
+ row.className = `${CLASS}-whitespace-row`;
6646
+ row.style.top = `${topPx}px`;
6647
+ // Pinned to the band-width left edge the textarea's padding
6648
+ // reserves.
6649
+ row.style.left = `${bandWidth}ch`;
6650
+ for (const fragment of fragments) {
6651
+ if (fragment.kind === 'glyph') {
6652
+ const glyph = doc.createElement('span');
6653
+ glyph.className = `${CLASS}-whitespace-glyph`;
6654
+ // 0.12.0 fix: the ink is a fixed vector shape (SVG), never the
6655
+ // literal character. The character route depended on the resolved
6656
+ // font actually carrying ·/→/↵ with ~1ch advances; environments
6657
+ // whose monospace lacks them fall back to full-width CJK glyphs
6658
+ // whose ink lands at font-specific offsets inside the 1ch box
6659
+ // (dots hugging the cell's right edge — text-align: center cannot
6660
+ // rescue over-wide overflow, Chrome left-anchors it). Vector
6661
+ // shapes paint the same geometry everywhere. An unknown glyph
6662
+ // degrades to the literal character: a font-dependent mark beats
6663
+ // a missing one, and the shape table covers everything the
6664
+ // builder emits.
6665
+ const shape = glyphSvgShape(fragment.glyph);
6666
+ if (shape === null) {
6667
+ glyph.textContent = fragment.glyph;
6668
+ } else {
6669
+ const svg = doc.createElementNS(SVG_NAMESPACE, 'svg');
6670
+ svg.setAttribute('viewBox', shape.viewBox);
6671
+ svg.setAttribute('aria-hidden', 'true');
6672
+ for (const elementSpec of shape.elements) {
6673
+ const node = doc.createElementNS(SVG_NAMESPACE, elementSpec.tag);
6674
+ for (const [attr, value] of Object.entries(elementSpec)) {
6675
+ if (attr === 'tag') continue;
6676
+ // SVG attribute names are kebab-cased and case-sensitive:
6677
+ // the spec's camelCase keys map to stroke-width etc.
6678
+ node.setAttribute(attr.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`), String(value));
6679
+ }
6680
+ svg.appendChild(node);
6681
+ }
6682
+ glyph.appendChild(svg);
6683
+ // The box is zero-height with its bottom edge on the text
6684
+ // baseline; the shape centers itself on (50%, yCenterEm above
6685
+ // that baseline) — the deterministic replacement for the old
6686
+ // glyph's baseline-relative ink position.
6687
+ svg.style.left = '50%';
6688
+ svg.style.top = '0';
6689
+ svg.style.transform = `translate(-50%, calc(-50% - ${shape.yCenterEm}em))`;
6690
+ }
6691
+ row.appendChild(glyph);
6692
+ } else if (fragment.kind === 'pad') {
6693
+ // count 0 is a tab one column before its stop: nothing
6694
+ // to pad, and a zero-length text node would only churn —
6695
+ // skip it.
6696
+ if (fragment.count > 0) row.appendChild(doc.createTextNode(' '.repeat(fragment.count)));
6697
+ } else if (fragment.kind === 'text') {
6698
+ row.appendChild(doc.createTextNode(fragment.text));
6699
+ }
6700
+ // Any OTHER kind is skipped with no output: an unknown
6701
+ // fragment must degrade to nothing here, never render its
6702
+ // raw fields as the literal string "undefined". No log prop
6703
+ // reaches this closure, so the skip is silent.
6704
+ }
6705
+ layer.appendChild(row);
6706
+ };
6707
+ // Wrap-on needs both wrapped paint inputs: the controller for the
6708
+ // visible-line window, the measurer for the row slices. One source
6709
+ // line wrapped over several rows paints one span per visual row —
6710
+ // the arithmetic below cannot place those. Both inputs are created
6711
+ // by the wrap sync effects in the same commit that first needs
6712
+ // them, so the arithmetic fallback only covers the pre-creation
6713
+ // moment of that flush (the wrap effect repaints right after,
6714
+ // before the browser paints) and editors that never wrapped.
6715
+ if (wrapEnabled && wrapControllerRef.current !== null && wrapMeasurerRef.current !== null) {
6716
+ layer.textContent = '';
6717
+ const lines = area.value.split('\n');
6718
+ const rows = wrapControllerRef.current.visibleLines(area.scrollTop, area.clientHeight, 2);
6719
+ for (const entry of rows) {
6720
+ const lineText = entry.line >= 1 && entry.line <= lines.length ? lines[entry.line - 1] : '';
6721
+ const slices = wrapMeasurerRef.current.measureRowSlices(lineText);
6722
+ // null = the mirror cannot answer for this text yet (or the
6723
+ // line is over the probe cap): skip the line this pass — the
6724
+ // next trigger compensates.
6725
+ if (slices === null) continue;
6726
+ // A line's break glyph shows only when a real break follows
6727
+ // it — and under wrap it rides only the line's LAST visual
6728
+ // row.
6729
+ const terminal = wsNewlines && showsNewlineGlyph(lines, entry.line);
6730
+ // Viewport slice clamp: a line UNDER the probe cap can still
6731
+ // wrap into hundreds of visual rows (a 2000-char line over a
6732
+ // ~30-row viewport), and painting every slice would churn
6733
+ // hundreds of spans a pass for a few dozen visible ones. Row
6734
+ // k of this line sits at paddingTop + contentTop + k·line
6735
+ // against scrollTop, so only the k whose row intersects the
6736
+ // viewport — widened by the ±2 margin the layer's windowing
6737
+ // convention uses — paints. The clamp is viewport math only:
6738
+ // `terminal` still keys off the LAST slice of the line, so a
6739
+ // break glyph outside the window simply waits for the pass
6740
+ // that scrolls it in.
6741
+ const lineTopContent = metrics.paddingTop + entry.contentTop;
6742
+ const firstVisibleRow = Math.max(
6743
+ 0,
6744
+ Math.floor((area.scrollTop - lineTopContent) / metrics.lineHeight) - 2
6745
+ );
6746
+ const lastVisibleRow = Math.min(
6747
+ slices.length - 1,
6748
+ Math.ceil((area.scrollTop + area.clientHeight - lineTopContent) / metrics.lineHeight) + 2
6749
+ );
6750
+ for (let k = firstVisibleRow; k <= lastVisibleRow; k++) {
6751
+ const fragments = buildWhitespaceRow({
6752
+ text: slices[k],
6753
+ spaces: wsSpaces,
6754
+ tabs: wsTabs,
6755
+ newlines: terminal && k === slices.length - 1,
6756
+ eol: fileEol,
6757
+ // WHITESPACE_TAB_SIZE = the CSS tab-size, as in the
6758
+ // arithmetic branch.
6759
+ tabSize: WHITESPACE_TAB_SIZE
6760
+ });
6761
+ // Viewport-relative top in the wrap gutter layer's
6762
+ // convention: the controller's content-relative
6763
+ // contentTop against scrollTop, then k rows down inside
6764
+ // the line.
6765
+ appendRow(
6766
+ metrics.paddingTop + entry.contentTop - area.scrollTop + k * metrics.lineHeight,
6767
+ fragments
6768
+ );
6769
+ }
6770
+ }
6771
+ // Wrap never scrolls horizontally (rows reflow instead), so the
6772
+ // layer carries no scroll-left translation — and this reset
6773
+ // clears whatever a wrap-off pass last left behind when the
6774
+ // mode flipped.
6775
+ layer.style.transform = 'translateX(0px)';
6776
+ return;
6777
+ }
6778
+ layer.textContent = '';
6779
+ const lines = area.value.split('\n');
6780
+ const win = visibleWindow({
6781
+ scrollTop: area.scrollTop,
6782
+ paddingTop: metrics.paddingTop,
6783
+ lineHeight: metrics.lineHeight,
6784
+ clientHeight: area.clientHeight,
6785
+ lineCount: lines.length,
6786
+ marginRows: 2
6787
+ });
6788
+ for (let i = win.first0; i < win.first0 + win.count; i++) {
6789
+ const fragments = buildWhitespaceRow({
6790
+ text: lines[i],
6791
+ spaces: wsSpaces,
6792
+ tabs: wsTabs,
6793
+ // A line's break glyph shows only when a real break follows
6794
+ // it — a file's trailing newline draws no glyph anywhere.
6795
+ newlines: wsNewlines && showsNewlineGlyph(lines, i + 1),
6796
+ eol: fileEol,
6797
+ // WHITESPACE_TAB_SIZE = the CSS tab-size on the textarea
6798
+ // (and the fallback's own default): the underlay must stop
6799
+ // its tabs exactly where the real text does.
6800
+ tabSize: WHITESPACE_TAB_SIZE
6801
+ });
6802
+ // Same coordinate contract as the active-line band: content-box
6803
+ // rows against scrollTop, landing at paddingTop + line × height
6804
+ // (the left pin lives in appendRow).
6805
+ appendRow(metrics.paddingTop + i * metrics.lineHeight - area.scrollTop, fragments);
6806
+ }
6807
+ // Horizontal half of the scroll sync: rows sit at the content's
6808
+ // fixed left edge while the layer translates against scrollLeft —
6809
+ // the same translate-against-scroll contract paintBar carries (its
6810
+ // two-axis form, minus the axis this layer positions per row).
6811
+ layer.style.transform = `translateX(${-area.scrollLeft}px)`;
6812
+ }, [wsAny, wsSpaces, wsTabs, wsNewlines, wrapEnabled, fileEol, metricsOfArea, bandWidth, state.phase]);
6813
+
5348
6814
  // Paint the bar for an ALREADY-DERIVED line range. Pure imperative style
5349
6815
  // writes (sub-microsecond): the DOM event path (select/click/keyup) calls
5350
6816
  // this synchronously inside the handler, so caret moves land on the next
@@ -5389,6 +6855,16 @@ window.__ModuleLoader__.load({
5389
6855
  bar.style.height = `${geometry.height}px`;
5390
6856
  bar.style.width = `${Math.max(area.scrollWidth || 0, area.clientWidth || 0)}px`;
5391
6857
  bar.style.transform = `translate(${-area.scrollLeft}px, ${-area.scrollTop}px)`;
6858
+ // The glyph-framed band positions (canvas-measured, font-aware).
6859
+ // Absent metrics drop the properties so the stylesheet's static
6860
+ // symmetric insets take over as the fallback.
6861
+ if (metrics !== null && Number.isFinite(metrics.bandTop) && Number.isFinite(metrics.bandBottomInset)) {
6862
+ bar.style.setProperty('--dsh-editor-band-top', `${metrics.bandTop}px`);
6863
+ bar.style.setProperty('--dsh-editor-band-bottom', `${metrics.bandBottomInset}px`);
6864
+ } else {
6865
+ bar.style.removeProperty('--dsh-editor-band-top');
6866
+ bar.style.removeProperty('--dsh-editor-band-bottom');
6867
+ }
5392
6868
  },
5393
6869
  [metricsOfArea, wrapEnabled]
5394
6870
  );
@@ -5440,19 +6916,22 @@ window.__ModuleLoader__.load({
5440
6916
  paintCaretLine();
5441
6917
  }, [paintCaretLine]);
5442
6918
 
5443
- // Refresh the controller's paint hook with THIS render's repaint pair. A
6919
+ // Refresh the controller's paint hook with THIS render's repaint set. A
5444
6920
  // layout effect (declared before the wrap sync effect below) so the hook is
5445
6921
  // already current when the same commit creates the controller or streams a
5446
6922
  // synchronous completion — and so a wrap-preference flip, which re-makes
5447
- // `repaintBar`, never leaves the hook on the wrap-off arithmetic. Both
5448
- // callees are measurability-guarded DOM writes: no state, no render, no
5449
- // effect re-entry.
6923
+ // `repaintBar`, never leaves the hook on the wrap-off arithmetic. All
6924
+ // three callees are measurability-guarded DOM writes: no state, no
6925
+ // render, no effect re-entry. The whitespace repaint is the async
6926
+ // completion's compensation: a measurement chunk landing new row slices
6927
+ // moves the glyph rows, and no DOM event follows it.
5450
6928
  useLayoutEffectSafe(() => {
5451
6929
  wrapPaintRef.current = () => {
5452
6930
  syncWrapGutter();
5453
6931
  repaintBar();
6932
+ syncWhitespace();
5454
6933
  };
5455
- }, [syncWrapGutter, repaintBar]);
6934
+ }, [syncWrapGutter, repaintBar, syncWhitespace]);
5456
6935
 
5457
6936
  const reportSelection = React.useCallback(() => {
5458
6937
  const area = areaRef.current;
@@ -5544,17 +7023,36 @@ window.__ModuleLoader__.load({
5544
7023
 
5545
7024
  // The latest sync for passive observers — the ResizeObserver below must
5546
7025
  // not be torn down and rebuilt on every selection change. One sync for
5547
- // both paint surfaces: the caret-line bar AND the gutter's scroll
5548
- // translation (a hidden subtree can discard scrollTop without firing a
5549
- // scroll event on re-show — the observer retry must heal the gutter too).
7026
+ // every paint surface: the caret-line bar, the gutter's scroll
7027
+ // translation AND the whitespace rows (a hidden subtree can discard
7028
+ // scrollTop without firing a scroll event on re-show — the observer
7029
+ // retry must heal the gutter and the glyph window too).
5550
7030
  const syncRef = React.useRef(paintCaretLine);
5551
7031
  React.useEffect(() => {
5552
7032
  syncRef.current = () => {
5553
7033
  paintCaretLine();
5554
7034
  syncGutter();
5555
7035
  syncWrapGutter();
7036
+ syncWhitespace();
7037
+ };
7038
+ }, [paintCaretLine, syncGutter, syncWrapGutter, syncWhitespace]);
7039
+
7040
+ // Web fonts can land AFTER the first measurement pass, changing the ink
7041
+ // extents the bands frame: drop the cache and re-sync once the font set
7042
+ // settles. (Guarded — jsdom and older engines have no document.fonts.)
7043
+ React.useEffect(() => {
7044
+ const fonts = typeof document !== 'undefined' && document !== null ? document.fonts : null;
7045
+ if (fonts === null || typeof fonts.ready?.then !== 'function') return undefined;
7046
+ let cancelled = false;
7047
+ fonts.ready.then(() => {
7048
+ if (cancelled) return;
7049
+ metricsRef.current = null;
7050
+ syncRef.current();
7051
+ });
7052
+ return () => {
7053
+ cancelled = true;
5556
7054
  };
5557
- }, [paintCaretLine, syncGutter, syncWrapGutter]);
7055
+ }, []);
5558
7056
 
5559
7057
  // The restore observer must not rebuild on preference toggles (its deps stay
5560
7058
  // `[applyPendingScroll, healScrollOnReveal]`), so the padding writer reaches
@@ -5570,15 +7068,18 @@ window.__ModuleLoader__.load({
5570
7068
  // still be pending when the observer's first callback runs. The wrapper
5571
7069
  // repaints right after the width/attach work: a resize changes the wrapped
5572
7070
  // extents without moving the caret, so the observer's own paint
5573
- // (`syncRef`) would dedupe and leave a stale band. The repaint is skipped
5574
- // while wrapping is off, which keeps a wrap-off editor's observer
5575
- // behaviour exactly as it was.
7071
+ // (`syncRef`) would dedupe and leave a stale band — and the width
7072
+ // re-slices every wrapped row, so the whitespace window repaints from
7073
+ // the fresh geometry here too. Both repaints are skipped while wrapping
7074
+ // is off, which keeps a wrap-off editor's observer behaviour exactly as
7075
+ // it was.
5576
7076
  useLayoutEffectSafe(() => {
5577
7077
  wrapViewportRef.current = () => {
5578
7078
  syncWrapViewport();
5579
7079
  if (wrapEnabled) repaintBar();
7080
+ if (wrapEnabled) syncWhitespace();
5580
7081
  };
5581
- }, [syncWrapViewport, repaintBar, wrapEnabled]);
7082
+ }, [syncWrapViewport, repaintBar, wrapEnabled, syncWhitespace]);
5582
7083
 
5583
7084
  // One measurer and one controller per mount; both go with the component.
5584
7085
  // The controller's own `dispose()` deliberately leaves the measurer alone,
@@ -5620,6 +7121,17 @@ window.__ModuleLoader__.load({
5620
7121
  syncGutter();
5621
7122
  }, [gutterEnabled, syncGutter]);
5622
7123
 
7124
+ // The whitespace layer mounts (or re-mounts on a switch toggle) against
7125
+ // a possibly already-scrolled, already-loaded textarea: paint its first
7126
+ // window in the layout phase, before the first paint shows an empty
7127
+ // underlay — the same first-paint duty the gutter mount effect above
7128
+ // carries. The callback's own guard chain no-ops every non-ready state,
7129
+ // so mounting early costs one guarded call.
7130
+ useLayoutEffectSafe(() => {
7131
+ if (!wsAny) return;
7132
+ syncWhitespace();
7133
+ }, [wsAny, syncWhitespace]);
7134
+
5623
7135
  // Apply (or clear) the scroll-beyond padding in the layout phase on mount
5624
7136
  // and whenever the preference flips, before the first paint shows the old
5625
7137
  // extent.
@@ -5647,12 +7159,13 @@ window.__ModuleLoader__.load({
5647
7159
  }, [state.phase, state.draft, applyPendingScroll]);
5648
7160
 
5649
7161
  // Wrap measurement follows two inputs: the enable prop and the committed
5650
- // draft. Either one can change the row counts BOTH wrapped paint surfaces
5651
- // are drawn from — and neither moves the caret — so each path ends by
5652
- // repainting them from the fresh geometry: `syncWrapGutter()` (the
5653
- // windowed line-number layer, Task 8) and `repaintBar()` (the active-line
5654
- // band). Those are the only writers that can follow a geometry-only
5655
- // change:
7162
+ // draft. Either one can change the row counts every wrapped paint
7163
+ // surface is drawn from — and neither moves the caret — so each path
7164
+ // ends by repainting them from the fresh geometry: `syncWrapGutter()`
7165
+ // (the windowed line-number layer, Task 8), `repaintBar()` (the
7166
+ // active-line band) and `syncWhitespace()` (the glyph underlay, Task 7
7167
+ // — a no-op while every whitespace switch is off). Those are the only
7168
+ // writers that can follow a geometry-only change:
5656
7169
  //
5657
7170
  // - off → on: the controller resets, the first sync attaches the mirror,
5658
7171
  // restarts the measurement the attach cancelled (the width baseline was
@@ -5673,12 +7186,18 @@ window.__ModuleLoader__.load({
5673
7186
  //
5674
7187
  // `wrapDraftRef` records the same value for the DOM-driven observer
5675
7188
  // callback, whose closure cannot carry the latest render. Repainting here
5676
- // is loop-safe: `syncWrapGutter` and `repaintBar` write DOM styles only,
5677
- // so they cannot re-trigger this effect's dependencies. Order is
5678
- // syncDraft → syncWrapGutter → repaintBar: the gutter is painted from the
5679
- // geometry the sync just produced, and the bar (whose dedupe signature
5680
- // `repaintBar` resets) stays the last write — the two touch disjoint
5681
- // nodes, so the order carries no semantics beyond that.
7189
+ // is loop-safe: `syncWrapGutter`, `repaintBar` and `syncWhitespace`
7190
+ // write DOM styles only, so they cannot re-trigger this effect's
7191
+ // dependencies. Order is syncDraft → syncWrapGutter → repaintBar →
7192
+ // syncWhitespace: the gutter is painted from the geometry the sync just
7193
+ // produced, and the bar (whose dedupe signature `repaintBar` resets)
7194
+ // keeps its place before the glyph repaint — the three touch disjoint
7195
+ // nodes, so the order carries no semantics beyond that. Both branches
7196
+ // close with the glyph writer: `syncWhitespace` rebuilds the glyph
7197
+ // window from the fresh draft — typing is the most common way glyphs
7198
+ // appear and vanish, and under wrap a row-count move is a glyph move
7199
+ // too (the controller block is skipped entirely on an editor that
7200
+ // never wrapped).
5682
7201
  useLayoutEffectSafe(() => {
5683
7202
  wrapDraftRef.current = state.draft;
5684
7203
  if (!wrapEnabled) {
@@ -5688,16 +7207,19 @@ window.__ModuleLoader__.load({
5688
7207
  wrapController.syncGutter(0, 0);
5689
7208
  repaintBar();
5690
7209
  }
7210
+ syncWhitespace();
5691
7211
  return;
5692
7212
  }
5693
7213
  ensureWrapController().setEnabled(true);
5694
7214
  syncWrapDraft(state.draft);
5695
- // Repaint the windowed layer from the geometry just synced: a row-count
5696
- // change would otherwise leave the previous spans in place until the
5697
- // next scroll, and the enable path would wait for the observer.
7215
+ // Repaint the windowed layers from the geometry just synced: a
7216
+ // row-count change would otherwise leave the previous spans in
7217
+ // place until the next scroll, and the enable path would wait for
7218
+ // the observer.
5698
7219
  syncWrapGutter();
5699
7220
  repaintBar();
5700
- }, [state.draft, wrapEnabled, ensureWrapController, syncWrapDraft, syncWrapGutter, repaintBar]);
7221
+ syncWhitespace();
7222
+ }, [state.draft, wrapEnabled, ensureWrapController, syncWrapDraft, syncWrapGutter, repaintBar, syncWhitespace]);
5701
7223
 
5702
7224
  // Scroll restore/heal observer — deliberately INDEPENDENT of the
5703
7225
  // highlight/gutter observer above (that one is preference-gated and
@@ -5726,17 +7248,17 @@ window.__ModuleLoader__.load({
5726
7248
  // observer fires the retry the moment the textarea gains a real box —
5727
7249
  // session switch, sidebar reveal, pane resize — with no interaction.
5728
7250
  // observe() also dispatches an initial notification, doubling as a
5729
- // post-layout resync on the very first mount. Wrapping needs the same
5730
- // retry, hence the extra gate term (and dep, so a wrap-only editor still
5731
- // installs the observer).
7251
+ // post-layout resync on the very first mount. Wrapping and whitespace
7252
+ // need the same retry, hence the extra gate terms (and deps, so a
7253
+ // wrap-only or whitespace-only editor still installs the observer).
5732
7254
  React.useEffect(() => {
5733
- if (!highlightEnabled && !gutterEnabled && !wrapEnabled) return undefined;
7255
+ if (!highlightEnabled && !gutterEnabled && !wrapEnabled && !wsAny) return undefined;
5734
7256
  const area = areaRef.current;
5735
7257
  if (area === null || typeof ResizeObserver !== 'function') return undefined;
5736
7258
  const observer = new ResizeObserver(() => syncRef.current());
5737
7259
  observer.observe(area);
5738
7260
  return () => observer.disconnect();
5739
- }, [highlightEnabled, gutterEnabled, wrapEnabled]);
7261
+ }, [highlightEnabled, gutterEnabled, wrapEnabled, wsAny]);
5740
7262
 
5741
7263
  // THE caret-follower: document-level `selectionchange` fires synchronously
5742
7264
  // with EVERY caret move — arrow keys included. The element-level events
@@ -5872,6 +7394,60 @@ window.__ModuleLoader__.load({
5872
7394
  // (which sees this event after us — preventDefault does not stop
5873
7395
  // propagation) still matches nothing and ignores it.
5874
7396
  const onAreaKeyDown = (event) => {
7397
+ const indentAction = matchAction(event, INDENT_KEYS_KEYMAP);
7398
+ if (indentAction !== undefined) {
7399
+ event.preventDefault(); // 任何相位都吞键:焦点永不逃逸
7400
+ if (state.phase !== 'ready' && state.phase !== 'saving') return;
7401
+ const area = areaRef.current;
7402
+ if (area === null) return;
7403
+ const from = area.selectionStart;
7404
+ const to = area.selectionEnd;
7405
+ const unit = resolveIndentUnit(props.indentSettings, area.value);
7406
+ // 主路径轨迹:indent 恒可拼接(插入点全部位于触及行行首、严格先于 to);
7407
+ // outdent 交给 outdentSplice 裁决(spec §6.5)——op 无可删 → 吞键;形状
7408
+ // 不安全(拼接会少替换)→ fallback 机器写回。
7409
+ let plan = null;
7410
+ if (indentAction === 'indent') {
7411
+ const op = indentOp(area.value, from, to, unit);
7412
+ const segStart = offsetOfLine(area.value, lineOfOffset(area.value, from));
7413
+ plan = { op, segStart, segEnd: op.end, segText: op.text.slice(segStart, op.end) };
7414
+ } else {
7415
+ const op = outdentOp(area.value, from, to, unit);
7416
+ if (op === null) return; // 无可删:键已吞,无任何写回
7417
+ const splice = outdentSplice(area.value, from, to, unit);
7418
+ plan = splice === null
7419
+ ? { op, fallback: true } // 不安全形状(拼接会少替换)→ 直接走机器回退,行为符合 spec §6.5
7420
+ : { op, segStart: splice.segStart, segEnd: splice.segEnd, segText: splice.segText };
7421
+ }
7422
+ const useExec = plan.fallback !== true &&
7423
+ typeof document !== 'undefined' && typeof document.execCommand === 'function';
7424
+ if (useExec) {
7425
+ try { area.setSelectionRange(plan.segStart, to); } catch { /* detached node */ }
7426
+ }
7427
+ let applied = false;
7428
+ if (useExec) {
7429
+ try { applied = document.execCommand('insertText', false, plan.segText) === true; } catch { applied = false; }
7430
+ }
7431
+ if (applied !== true) {
7432
+ // 回退:execCommand 不可用/失败、或 outdent 形状不安全(拼接会少替换)——
7433
+ // 同 deleteLinesFor 模式(原生撤销失效,功能可用)。setContent 已把新选区
7434
+ // 提交给机器,镜像 effect 会在重渲染时落 DOM;此刻 DOM 仍是旧值/旧选区,
7435
+ // 绝不能 reportSelection()(会用旧偏移覆盖刚提交的选区)。
7436
+ const lineStart = lineOfOffset(plan.op.text, plan.op.start);
7437
+ const lineEnd = lineOfOffset(plan.op.text, plan.op.end);
7438
+ controller.setContent(plan.op.text, {
7439
+ start: plan.op.start,
7440
+ end: plan.op.end,
7441
+ lineStart,
7442
+ lineEnd,
7443
+ text: plan.op.start === plan.op.end ? null : plan.op.text.slice(plan.op.start, plan.op.end)
7444
+ });
7445
+ } else {
7446
+ try { area.setSelectionRange(plan.op.start, plan.op.end); } catch { /* detached node */ }
7447
+ reportSelection(); // 仅主路径:DOM 已是新值/新选区
7448
+ }
7449
+ return;
7450
+ }
5875
7451
  const action = matchAction(event, END_KEYS_KEYMAP);
5876
7452
  const area = areaRef.current;
5877
7453
  if (action === undefined || area === null) return;
@@ -5938,10 +7514,15 @@ window.__ModuleLoader__.load({
5938
7514
  reportSelection();
5939
7515
  };
5940
7516
 
5941
- // Wrap-off keeps the exact 0.9.0 string, so the class list (and every
5942
- // rule keyed off `.dsh-editor-area` / `-area-overlay`) is unchanged for
5943
- // every file that does not wrap.
5944
- const areaClassName = highlightEnabled ? `${CLASS}-area ${CLASS}-area-overlay` : `${CLASS}-area`;
7517
+ // The overlay treatment (transparent textarea above an underlay) is
7518
+ // needed when EITHER paint surface below the textarea is active: the
7519
+ // active-line highlight backdrop OR the whitespace glyph layer. When
7520
+ // neither is — and wrapping is off — the class string stays exactly the
7521
+ // historic `${CLASS}-area`, so the class list (and every rule keyed off
7522
+ // `.dsh-editor-area` / `-area-overlay`) is byte-identical for every
7523
+ // editor that paints no underlay.
7524
+ const overlayNeeded = highlightEnabled || wsAny;
7525
+ const areaClassName = overlayNeeded ? `${CLASS}-area ${CLASS}-area-overlay` : `${CLASS}-area`;
5945
7526
  const textareaClassName = wrapEnabled ? `${areaClassName} ${CLASS}-area-wrap` : areaClassName;
5946
7527
 
5947
7528
  return h(
@@ -5954,6 +7535,27 @@ window.__ModuleLoader__.load({
5954
7535
  h('div', { className: `${CLASS}-highlight-bar`, ref: barRef })
5955
7536
  )
5956
7537
  : null,
7538
+ // Whitespace glyph layer (0.12.0, Task 6): the viewport-sized underlay
7539
+ // syncWhitespace fills with windowed rows. DOM order is its stacking
7540
+ // order — after the highlight backdrop, before the gutter band, and
7541
+ // all beneath the overlay textarea (z-index 1) — so its rows keep the
7542
+ // textarea's exact metrics and the glyphs land under their characters.
7543
+ // Mounted only while any switch is on; unmounting clears the layer
7544
+ // wholesale and every sync no-ops on the null ref.
7545
+ wsAny
7546
+ ? h('div', {
7547
+ className: `${CLASS}-whitespace`,
7548
+ 'aria-hidden': true,
7549
+ ref: whitespaceRef,
7550
+ // The active-line bar lives in the highlight backdrop BELOW
7551
+ // this layer, so an opaque background here would cover it —
7552
+ // transparent whenever highlighting is on. Only when
7553
+ // whitespace is the sole underlay does this layer carry the
7554
+ // base background: it is then the bottom backdrop the
7555
+ // transparent textarea reads through.
7556
+ style: { background: highlightEnabled ? 'transparent' : 'var(--dsw-alias-bg-base)' }
7557
+ })
7558
+ : null,
5957
7559
  // The band ALWAYS paints — opaque cover + boundary rule persist
5958
7560
  // regardless of the preference, so toggling shows/hides ONLY the
5959
7561
  // numbers and never moves the layout. The band paints above the
@@ -6033,6 +7635,10 @@ window.__ModuleLoader__.load({
6033
7635
  paintCaretLine();
6034
7636
  syncGutter();
6035
7637
  syncWrapGutter();
7638
+ // Whitespace rows reposition per scroll pixel like the gutter
7639
+ // band does; the callback's own guards no-op it while the
7640
+ // layer is off, unmounted, or wrapping.
7641
+ syncWhitespace();
6036
7642
  // Report only a MEASURED, loaded textarea. While loading (or
6037
7643
  // hidden) the DOM offset is meaningless and must not overwrite
6038
7644
  // the last visible value the heal path depends on.
@@ -7066,6 +8672,21 @@ window.__ModuleLoader__.load({
7066
8672
  // honor a literal `props.wordWrap === true`; others ignore the
7067
8673
  // prop harmlessly.
7068
8674
  wordWrap: resolveWordWrap(runtime.getRawSettings(), targetPath, runtime.getWrapOverrides()),
8675
+ // The whitespace-glyph contract (0.12.0): three independent global
8676
+ // booleans, all default false; modes honoring them draw the glyph layer,
8677
+ // others ignore the prop harmlessly.
8678
+ showWhitespace: {
8679
+ spaces: runtime.getSettings().showWhitespaceSpaces === true,
8680
+ tabs: runtime.getSettings().showWhitespaceTabs === true,
8681
+ newlines: runtime.getSettings().showWhitespaceNewlines === true
8682
+ },
8683
+ // The indentation contract (0.13.0): the two indent settings ride to every
8684
+ // mounted mode as one additive prop; the built-in plain-text mode resolves
8685
+ // the unit at keypress, others ignore the prop harmlessly.
8686
+ indentSettings: {
8687
+ indentMode: runtime.getSettings().indentMode,
8688
+ indentWidth: runtime.getSettings().indentWidth
8689
+ },
7069
8690
  // The view-state adapter (0.8.0): the framework's read-once
7070
8691
  // restore target and the best-effort scroll reporter. Both are
7071
8692
  // optional; modes that ignore them are unaffected.
@@ -7591,13 +9212,17 @@ window.__ModuleLoader__.load({
7591
9212
  *
7592
9213
  * Built-in sections this release ships:
7593
9214
  * - `appearance` (order 1) — the three presentation toggles migrated from the
7594
- * 0.10.0 `SettingsPopover`: highlightActiveLine / showLineNumbers /
7595
- * scrollBeyondLastLine, in that order;
9215
+ * 0.10.0 `SettingsPopover` (highlightActiveLine / showLineNumbers /
9216
+ * scrollBeyondLastLine, in that order) plus the 0.12.0 whitespace trio
9217
+ * (spaces / tabs / newlines) under one `showWhitespaceGroup` group title;
7596
9218
  * - `behavior` (order 2) — autoReloadClean;
7597
- * - `wrap` (order 3) — the global `wordWrap` row plus the opener file type's
9219
+ * - `indent` (order 3) — the 0.13.0 indentation rows: the `indentMode`
9220
+ * segmented control (auto detect / tabs / spaces) plus the `indentWidth`
9221
+ * segmented control (2/4/8, enabled in spaces mode) and its note;
9222
+ * - `wrap` (order 4) — the global `wordWrap` row plus the opener file type's
7598
9223
  * three-state `*.<ext>` override row (follow global / force on / force off),
7599
9224
  * the settings-center face of the three-layer `resolveWordWrap` chain;
7600
- * - `keymap` (order 4) — the four self-managed bindings' recorder migrated
9225
+ * - `keymap` (order 5) — the four self-managed bindings' recorder migrated
7601
9226
  * from the retired status-bar keymap popover (record / restore defaults,
7602
9227
  * reserved-combo rejection, conflict / write-failure banners).
7603
9228
  *
@@ -7630,6 +9255,9 @@ window.__ModuleLoader__.load({
7630
9255
  /**
7631
9256
  * The appearance section's rows, in display order — the same label/title/note
7632
9257
  * stems the popover used, so the copy and the explanations stay identical.
9258
+ * The 0.12.0 whitespace trio appends after them; its FIRST entry carries
9259
+ * `groupTitleKey`, which `BooleanSettingsSection` renders as a group title
9260
+ * line before that row.
7633
9261
  */
7634
9262
  const APPEARANCE_ROWS = Object.freeze([
7635
9263
  {
@@ -7647,6 +9275,25 @@ window.__ModuleLoader__.load({
7647
9275
  key: 'scrollBeyondLastLine',
7648
9276
  labelKey: 'settings.scrollBeyondLastLine',
7649
9277
  titleKey: 'settings.scrollBeyondLastLineTitle'
9278
+ },
9279
+ {
9280
+ groupTitleKey: 'settings.showWhitespaceGroup',
9281
+ key: 'showWhitespaceSpaces',
9282
+ labelKey: 'settings.showWhitespaceSpaces',
9283
+ titleKey: 'settings.showWhitespaceSpacesTitle',
9284
+ noteKey: 'settings.showWhitespaceSpacesNote'
9285
+ },
9286
+ {
9287
+ key: 'showWhitespaceTabs',
9288
+ labelKey: 'settings.showWhitespaceTabs',
9289
+ titleKey: 'settings.showWhitespaceTabsTitle',
9290
+ noteKey: 'settings.showWhitespaceTabsNote'
9291
+ },
9292
+ {
9293
+ key: 'showWhitespaceNewlines',
9294
+ labelKey: 'settings.showWhitespaceNewlines',
9295
+ titleKey: 'settings.showWhitespaceNewlinesTitle',
9296
+ noteKey: 'settings.showWhitespaceNewlinesNote'
7650
9297
  }
7651
9298
  ]);
7652
9299
 
@@ -7718,7 +9365,16 @@ window.__ModuleLoader__.load({
7718
9365
  : null,
7719
9366
  rows.flatMap((row) => {
7720
9367
  const on = settings[row.key] === true;
7721
- const cells = [
9368
+ // An optional non-empty `groupTitleKey` renders a group title line
9369
+ // before its row (0.12.0 whitespace trio); rows without the field
9370
+ // render exactly as before.
9371
+ const cells = [];
9372
+ if (typeof row.groupTitleKey === 'string' && row.groupTitleKey.length > 0) {
9373
+ cells.push(
9374
+ h('div', { key: `${row.key}-group-title`, className: `${CLASS}-group-title` }, t(row.groupTitleKey))
9375
+ );
9376
+ }
9377
+ cells.push(
7722
9378
  h(
7723
9379
  'div',
7724
9380
  { key: row.key, className: `${CLASS}-row` },
@@ -7736,7 +9392,7 @@ window.__ModuleLoader__.load({
7736
9392
  on ? t('settings.on') : t('settings.off')
7737
9393
  )
7738
9394
  )
7739
- ];
9395
+ );
7740
9396
  if (typeof row.noteKey === 'string') {
7741
9397
  cells.push(h('div', { key: `${row.key}-note`, className: `${CLASS}-note` }, t(row.noteKey)));
7742
9398
  }
@@ -7745,6 +9401,128 @@ window.__ModuleLoader__.load({
7745
9401
  );
7746
9402
  }
7747
9403
 
9404
+ /**
9405
+ * The indentation section (0.13.0): two segmented controls over the global
9406
+ * indent settings, written through the typed settings cache.
9407
+ *
9408
+ * The mode row offers `auto` (detect the open file's leading indentation),
9409
+ * `tabs` and `spaces`; the selected state is the normalized global value
9410
+ * (`settings.indentMode`, always present after Task 1's defaults merge). The
9411
+ * width row offers 2/4/8 spaces per level; its buttons are enabled only when
9412
+ * the mode is `spaces` — the note under the row explains the width still
9413
+ * serves as the fallback when auto detect has no signal. A click writes the
9414
+ * single typed delta (`{ indentMode }` / `{ indentWidth }`) through
9415
+ * `runtime.setSettings`, a pending write disables every button in the
9416
+ * section, and a failure surfaces the shared
9417
+ * `{ kind: 'conflict' | 'write', message }` banner above the rows — the same
9418
+ * anatomy as the boolean sections.
9419
+ */
9420
+
9421
+ /** The mode segmented control's options, in display order. */
9422
+ const INDENT_MODE_OPTIONS = Object.freeze([
9423
+ { value: 'auto', labelKey: 'settings.indentModeAuto' },
9424
+ { value: 'tabs', labelKey: 'settings.indentModeTabs' },
9425
+ { value: 'spaces', labelKey: 'settings.indentModeSpaces' }
9426
+ ]);
9427
+
9428
+ /** The width segmented control's options (spaces per level), in display order. */
9429
+ const INDENT_WIDTH_OPTIONS = Object.freeze([2, 4, 8]);
9430
+
9431
+ function IndentSettingsSection(props) {
9432
+ const t = props.t;
9433
+ const runtime = props.runtime;
9434
+ const [busy, setBusy] = React.useState(false);
9435
+ // { kind: 'write' | 'conflict', message }
9436
+ const [error, setError] = React.useState(null);
9437
+
9438
+ // Re-render on settings cache changes (segment writes, conflict refetches,
9439
+ // cross-window announcements) — the same subscription the boolean sections
9440
+ // use.
9441
+ const [, setSettingsTick] = React.useState(0);
9442
+ React.useEffect(() => runtime.subscribeSettings(() => setSettingsTick((count) => count + 1)), [runtime]);
9443
+
9444
+ const settings = runtime.getSettings();
9445
+ const runWrite = (delta) => {
9446
+ setBusy(true);
9447
+ setError(null);
9448
+ runtime
9449
+ .setSettings(delta)
9450
+ .catch((writeError) => {
9451
+ setError({
9452
+ kind:
9453
+ writeError !== null && typeof writeError === 'object' && writeError.conflict === true
9454
+ ? 'conflict'
9455
+ : 'write',
9456
+ message: messageOfError(writeError)
9457
+ });
9458
+ })
9459
+ .finally(() => setBusy(false));
9460
+ };
9461
+
9462
+ return h(
9463
+ 'div',
9464
+ { className: `${CLASS}-section` },
9465
+ error !== null
9466
+ ? h(
9467
+ 'div',
9468
+ { key: 'error', className: `${CLASS}-error`, title: error.message },
9469
+ error.kind === 'conflict'
9470
+ ? t('settings.conflict')
9471
+ : `${t('settings.writeFailed')}: ${error.message}`
9472
+ )
9473
+ : null,
9474
+ h(
9475
+ 'div',
9476
+ { key: 'indentMode', className: `${CLASS}-row` },
9477
+ h('span', { className: `${CLASS}-label`, title: t('settings.indentModeTitle') }, t('settings.indentMode')),
9478
+ h(
9479
+ 'div',
9480
+ { className: `${CLASS}-seg`, role: 'group', 'aria-label': t('settings.indentMode') },
9481
+ INDENT_MODE_OPTIONS.map((mode) =>
9482
+ h(
9483
+ 'button',
9484
+ {
9485
+ key: mode.value,
9486
+ className: `${CLASS}-seg-btn${settings.indentMode === mode.value ? ' on' : ''}`,
9487
+ type: 'button',
9488
+ disabled: busy,
9489
+ title: t('settings.indentModeTitle'),
9490
+ 'aria-pressed': settings.indentMode === mode.value ? 'true' : 'false',
9491
+ onClick: () => runWrite({ indentMode: mode.value })
9492
+ },
9493
+ t(mode.labelKey)
9494
+ )
9495
+ )
9496
+ )
9497
+ ),
9498
+ h(
9499
+ 'div',
9500
+ { key: 'indentWidth', className: `${CLASS}-row` },
9501
+ h('span', { className: `${CLASS}-label`, title: t('settings.indentWidthTitle') }, t('settings.indentWidth')),
9502
+ h(
9503
+ 'div',
9504
+ { className: `${CLASS}-seg`, role: 'group', 'aria-label': t('settings.indentWidth') },
9505
+ INDENT_WIDTH_OPTIONS.map((width) =>
9506
+ h(
9507
+ 'button',
9508
+ {
9509
+ key: width,
9510
+ className: `${CLASS}-seg-btn${settings.indentWidth === width ? ' on' : ''}`,
9511
+ type: 'button',
9512
+ disabled: busy || settings.indentMode !== 'spaces',
9513
+ title: t('settings.indentWidthTitle'),
9514
+ 'aria-pressed': settings.indentWidth === width ? 'true' : 'false',
9515
+ onClick: () => runWrite({ indentWidth: width })
9516
+ },
9517
+ String(width)
9518
+ )
9519
+ )
9520
+ )
9521
+ ),
9522
+ h('div', { key: 'indentWidth-note', className: `${CLASS}-note` }, t('settings.indentWidthNote'))
9523
+ );
9524
+ }
9525
+
7748
9526
  /**
7749
9527
  * The wrap section: the GLOBAL `wordWrap` row plus the opener file type's
7750
9528
  * three-state override row.
@@ -7936,8 +9714,8 @@ window.__ModuleLoader__.load({
7936
9714
 
7937
9715
  /**
7938
9716
  * The section registry, in the fixed contract order (appearance 1, behavior 2,
7939
- * wrap 3, keymap 4). Frozen so a render can never mutate the menu out from
7940
- * under itself.
9717
+ * indent 3, wrap 4, keymap 5). Frozen so a render can never mutate the menu
9718
+ * out from under itself.
7941
9719
  */
7942
9720
  const SETTINGS_SECTION_REGISTRY = Object.freeze([
7943
9721
  {
@@ -7952,16 +9730,22 @@ window.__ModuleLoader__.load({
7952
9730
  order: 2,
7953
9731
  render: (ctx) => h(BooleanSettingsSection, { key: 'behavior', runtime: ctx.runtime, t: ctx.t, rows: BEHAVIOR_ROWS })
7954
9732
  },
9733
+ {
9734
+ id: 'indent',
9735
+ labelKey: 'settingsCenter.section.indent',
9736
+ order: 3,
9737
+ render: (ctx) => h(IndentSettingsSection, { key: 'indent', runtime: ctx.runtime, t: ctx.t })
9738
+ },
7955
9739
  {
7956
9740
  id: 'wrap',
7957
9741
  labelKey: 'settingsCenter.section.wrap',
7958
- order: 3,
9742
+ order: 4,
7959
9743
  render: (ctx) => h(WrapSection, { key: 'wrap', runtime: ctx.runtime, t: ctx.t, path: ctx.context.path })
7960
9744
  },
7961
9745
  {
7962
9746
  id: 'keymap',
7963
9747
  labelKey: 'settingsCenter.section.keymap',
7964
- order: 4,
9748
+ order: 5,
7965
9749
  render: (ctx) => h(KeymapSection, { key: 'keymap', runtime: ctx.runtime, t: ctx.t })
7966
9750
  }
7967
9751
  ]);
@@ -8095,123 +9879,6 @@ window.__ModuleLoader__.load({
8095
9879
  return module.exports;
8096
9880
  })();
8097
9881
 
8098
- /* src/settings.js */
8099
- const settings = (function () {
8100
- var module = { exports: {} };
8101
- var exports = module.exports;
8102
- /**
8103
- * Editor behavior settings — the pure model behind the settings panel.
8104
- *
8105
- * One GLOBAL user preference set (cross-tab, cross-mode), persisted through
8106
- * the Host storage RPC bridge (`dshEditor/getSettings` / `dshEditor/setSettings`,
8107
- * KV table `settings`, one record per setting name). The settings:
8108
- *
8109
- * - `autoReloadClean` — when a file WITHOUT unsaved changes is modified
8110
- * externally, reload it silently instead of asking (default `false`:
8111
- * 默认一律询问, per the feature ruling);
8112
- * - `highlightActiveLine` — draw an active-line highlight behind the caret
8113
- * (default `true`: a presentation affordance, on unless the user turns it
8114
- * off). Modes honoring the active-line contract (descriptor `activeLine`,
8115
- * contracts §5.1) read the same preference via their `highlightActiveLine`
8116
- * component prop.
8117
- * - `showLineNumbers` — render the line-number gutter beside the content
8118
- * (default `true`: a presentation affordance, on unless the user turns it
8119
- * off). Modes honoring the line-numbers contract (contracts §5.1) read the
8120
- * same preference via their `showLineNumbers` component prop.
8121
- * - `scrollBeyondLastLine` — keep scrollable blank space past the content end
8122
- * so the last line can scroll to the viewport top (default `true`, a
8123
- * presentation affordance; modes honoring it receive the live boolean via
8124
- * their `scrollBeyondLastLine` component prop).
8125
- * - `wordWrap` — whether the editor area soft-wraps long lines (explicit
8126
- * default `false`). This default is the fallback for an EXPLICIT setting
8127
- * only: a file whose stored settings never mention `wordWrap` is resolved
8128
- * by `resolveWordWrap` (see `wrap-resolve.js`) against the builtin
8129
- * extension defaults (the markdown family wraps by default), so "unset"
8130
- * is not the same as "off".
8131
- *
8132
- * `normalizeSettings` accepts the wire payload `{ [name]: boolean }` (the
8133
- * Host reports only stored settings) and merges it over the defaults.
8134
- * Unknown keys are IGNORED so a newer Host's extra settings never invalidate
8135
- * this build's read — but a KNOWN key carrying a non-boolean invalidates the
8136
- * whole payload (`undefined`: the caller keeps its current/default values).
8137
- *
8138
- * `buildSettingsWritePayload` is the write-side counterpart: it starts from
8139
- * the RAW stored set (explicit settings only) and merges the caller's change,
8140
- * so a write never materializes the builtin defaults. A key absent from
8141
- * storage stays absent, which is what keeps the builtin per-file defaults
8142
- * (e.g. the markdown family's wrap) reachable after unrelated toggles.
8143
- *
8144
- * Zero imports: pure functions only, unit-testable without DOM.
8145
- *
8146
- * @module @dybai/dsh-editor/settings
8147
- */
8148
-
8149
- /** Setting names this build knows (mirrors the Host validator's allow-list). */
8150
- const SETTINGS_KEYS = ['autoReloadClean', 'highlightActiveLine', 'showLineNumbers', 'scrollBeyondLastLine', 'wordWrap'];
8151
-
8152
- /**
8153
- * The built-in settings: behavior opt-ins off, presentation defaults on.
8154
- * @returns a fresh settings object (callers may mutate their copy).
8155
- */
8156
- function defaultSettings() {
8157
- return {
8158
- autoReloadClean: false,
8159
- highlightActiveLine: true,
8160
- showLineNumbers: true,
8161
- scrollBeyondLastLine: true,
8162
- wordWrap: false
8163
- };
8164
- }
8165
-
8166
- /**
8167
- * Validate and normalize a settings payload (defaults merged).
8168
- * @param {any} raw - the wire payload `{ [name]: boolean }`.
8169
- * @returns the complete settings object, or `undefined` when the payload is
8170
- * not an object or a known key carries a non-boolean value.
8171
- */
8172
- function normalizeSettings(raw) {
8173
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
8174
- const normalized = defaultSettings();
8175
- for (const key of SETTINGS_KEYS) {
8176
- if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
8177
- if (typeof raw[key] !== 'boolean') return undefined;
8178
- normalized[key] = raw[key];
8179
- }
8180
- return normalized;
8181
- }
8182
-
8183
- /**
8184
- * Build the wire payload for one settings write: the RAW stored set (only
8185
- * explicitly-stored keys) merged with the caller's change. Never fills
8186
- * defaults — absence of a key IS the "never explicitly set" signal the
8187
- * per-file resolution depends on. Returns undefined for any payload that
8188
- * is not an object or carries a key outside SETTINGS_KEYS / a
8189
- * non-boolean value. A non-object `rawSettings` (first frame, failed read)
8190
- * is treated as the empty set, so the write stores exactly the change.
8191
- * @param {any} rawSettings - the raw stored settings payload (`getRawSettings()`).
8192
- * @param {any} input - the caller's change (`{ [knownName]: boolean }`).
8193
- * @returns the complete explicit write payload, or `undefined` when invalid.
8194
- */
8195
- function buildSettingsWritePayload(rawSettings, input) {
8196
- if (input === null || typeof input !== 'object' || Array.isArray(input)) return undefined;
8197
- const payload = {};
8198
- if (rawSettings !== null && typeof rawSettings === 'object' && !Array.isArray(rawSettings)) {
8199
- for (const key of Object.keys(rawSettings)) {
8200
- if (!SETTINGS_KEYS.includes(key) || typeof rawSettings[key] !== 'boolean') return undefined;
8201
- payload[key] = rawSettings[key];
8202
- }
8203
- }
8204
- for (const key of Object.keys(input)) {
8205
- if (!SETTINGS_KEYS.includes(key) || typeof input[key] !== 'boolean') return undefined;
8206
- payload[key] = input[key];
8207
- }
8208
- return payload;
8209
- }
8210
-
8211
- Object.assign(module.exports, { SETTINGS_KEYS, defaultSettings, normalizeSettings, buildSettingsWritePayload });
8212
- return module.exports;
8213
- })();
8214
-
8215
9882
  /* src/prefs-bus.js */
8216
9883
  const prefsBus = (function () {
8217
9884
  var module = { exports: {} };
@@ -9180,6 +10847,7 @@ window.__ModuleLoader__.load({
9180
10847
  const { createLogChannel } = debugLog;
9181
10848
  const { createLogBuffer } = logBuffer;
9182
10849
  const { createLogFlusher } = logFlush;
10850
+ const { detectEol } = eol;
9183
10851
 
9184
10852
  /**
9185
10853
  * @dybai/dsh-editor — the editor framework's browser half (client entry).
@@ -9318,7 +10986,7 @@ window.__ModuleLoader__.load({
9318
10986
  'keymap.resetTitle': '把四个动作的键位恢复为默认(Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G)',
9319
10987
  'keymap.duplicate': '该组合已被其他动作占用,请换一个组合。',
9320
10988
  'keymap.reserved': '该组合被浏览器保留(如关闭/新建标签页),无法录制',
9321
- 'keymap.reservedHint': '浏览器保留组合(Ctrl/⌘+W、T、N、Q 等)无法录制',
10989
+ 'keymap.reservedHint': '浏览器保留组合(Ctrl/⌘+W、T、N、Q 等)与 Tab 缩进无法录制',
9322
10990
  'keymap.writeFailed': '保存快捷键失败',
9323
10991
  'keymap.conflict': '快捷键已被其他位置修改,已重新读取,请重试。',
9324
10992
  'goto.title': '跳转到行',
@@ -9350,8 +11018,26 @@ window.__ModuleLoader__.load({
9350
11018
  'settings.showLineNumbersTitle': '在内容左侧显示行号列',
9351
11019
  'settings.scrollBeyondLastLine': '滚动越过最后一行',
9352
11020
  'settings.scrollBeyondLastLineTitle': '在内容末尾之后保留可滚动空白,最后一行可滚动到视口顶部',
11021
+ 'settings.showWhitespaceGroup': '显示空白字符',
11022
+ 'settings.showWhitespaceSpaces': '显示空格',
11023
+ 'settings.showWhitespaceSpacesTitle': '把空格字符显示为浅色间隔号 ·',
11024
+ 'settings.showWhitespaceSpacesNote': '全局设置,对所有已挂载编辑器立即生效;默认关闭。',
11025
+ 'settings.showWhitespaceTabs': '显示制表符',
11026
+ 'settings.showWhitespaceTabsTitle': '把制表符显示为浅色箭头 → 并补位到停位',
11027
+ 'settings.showWhitespaceTabsNote': '全局设置,对所有已挂载编辑器立即生效;默认关闭。',
11028
+ 'settings.showWhitespaceNewlines': '显示换行符',
11029
+ 'settings.showWhitespaceNewlinesTitle': '在每个行断的行尾显示浅色回车符 ↵(文件末尾的尾随换行不显示)',
11030
+ 'settings.showWhitespaceNewlinesNote': '全局设置,对所有已挂载编辑器立即生效;默认关闭。',
9353
11031
  'settings.wordWrap': '自动换行',
9354
11032
  'settings.wordWrapTitle': '过长的行在编辑区宽度内自动折行显示',
11033
+ 'settings.indentMode': '缩进模式',
11034
+ 'settings.indentModeTitle': 'Tab 键插入的缩进单位:自动探测当前文件 / 固定制表符 / 固定空格',
11035
+ 'settings.indentModeAuto': '自动探测',
11036
+ 'settings.indentModeTabs': '制表符',
11037
+ 'settings.indentModeSpaces': '空格',
11038
+ 'settings.indentWidth': '缩进宽度',
11039
+ 'settings.indentWidthTitle': '空格模式下每级缩进的空格数',
11040
+ 'settings.indentWidthNote': '仅「空格」模式生效;自动探测无信号时也用它作回退宽度。',
9355
11041
  'settings.on': '开',
9356
11042
  'settings.off': '关',
9357
11043
  'settings.writeFailed': '保存设置失败',
@@ -9360,6 +11046,7 @@ window.__ModuleLoader__.load({
9360
11046
  'settingsCenter.close': '关闭',
9361
11047
  'settingsCenter.section.appearance': '外观',
9362
11048
  'settingsCenter.section.behavior': '行为',
11049
+ 'settingsCenter.section.indent': '缩进',
9363
11050
  'settingsCenter.section.wrap': '换行',
9364
11051
  'settingsCenter.section.keymap': '快捷键',
9365
11052
  'settingsCenter.wordWrapGlobalNote': '未设置时按扩展名默认(md 系开)',
@@ -9421,7 +11108,7 @@ window.__ModuleLoader__.load({
9421
11108
  'keymap.resetTitle': 'Restore the default keys (Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G)',
9422
11109
  'keymap.duplicate': 'That combo is already used by another action; pick another one.',
9423
11110
  'keymap.reserved': 'This combination is reserved by the browser (e.g. close/new tab) and cannot be recorded',
9424
- 'keymap.reservedHint': 'Browser-reserved combos (Ctrl/⌘+W, T, N, Q, …) cannot be recorded',
11111
+ 'keymap.reservedHint': 'Browser-reserved combos (Ctrl/⌘+W, T, N, Q, etc.) and Tab indentation cannot be recorded',
9425
11112
  'keymap.writeFailed': 'Failed to save shortcuts',
9426
11113
  'keymap.conflict': 'Shortcuts changed elsewhere; reloaded, please retry.',
9427
11114
  'goto.title': 'Go to line',
@@ -9453,8 +11140,26 @@ window.__ModuleLoader__.load({
9453
11140
  'settings.showLineNumbersTitle': 'Draw the line-number column beside the content',
9454
11141
  'settings.scrollBeyondLastLine': 'Scroll past last line',
9455
11142
  'settings.scrollBeyondLastLineTitle': 'Keep scrollable blank space past the end of content so the last line can scroll to the top of the viewport',
11143
+ 'settings.showWhitespaceGroup': 'Show whitespace',
11144
+ 'settings.showWhitespaceSpaces': 'Show spaces',
11145
+ 'settings.showWhitespaceSpacesTitle': 'Render space characters as a light middle dot (·)',
11146
+ 'settings.showWhitespaceSpacesNote': 'Global setting; applies to every mounted editor immediately. Off by default.',
11147
+ 'settings.showWhitespaceTabs': 'Show tabs',
11148
+ 'settings.showWhitespaceTabsTitle': 'Render tab characters as a light arrow (→), padded to the next stop',
11149
+ 'settings.showWhitespaceTabsNote': 'Global setting; applies to every mounted editor immediately. Off by default.',
11150
+ 'settings.showWhitespaceNewlines': 'Show newlines',
11151
+ 'settings.showWhitespaceNewlinesTitle': 'Render each line break as a light return glyph (↵) at the end of its line; the trailing newline at end of file is not drawn',
11152
+ 'settings.showWhitespaceNewlinesNote': 'Global setting; applies to every mounted editor immediately. Off by default.',
9456
11153
  'settings.wordWrap': 'Word wrap',
9457
11154
  'settings.wordWrapTitle': 'Wrap overly long lines within the editor width',
11155
+ 'settings.indentMode': 'Indent style',
11156
+ 'settings.indentModeTitle': 'The indent unit the Tab key inserts: auto-detect the current file / fixed tabs / fixed spaces',
11157
+ 'settings.indentModeAuto': 'Auto detect',
11158
+ 'settings.indentModeTabs': 'Tabs',
11159
+ 'settings.indentModeSpaces': 'Spaces',
11160
+ 'settings.indentWidth': 'Indent width',
11161
+ 'settings.indentWidthTitle': 'Spaces per indent level in spaces mode',
11162
+ 'settings.indentWidthNote': 'Only applies in Spaces mode; also used as the fallback width when auto detect has no signal.',
9458
11163
  'settings.on': 'On',
9459
11164
  'settings.off': 'Off',
9460
11165
  'settings.writeFailed': 'Failed to save settings',
@@ -9463,6 +11168,7 @@ window.__ModuleLoader__.load({
9463
11168
  'settingsCenter.close': 'Close',
9464
11169
  'settingsCenter.section.appearance': 'Appearance',
9465
11170
  'settingsCenter.section.behavior': 'Behavior',
11171
+ 'settingsCenter.section.indent': 'Indent',
9466
11172
  'settingsCenter.section.wrap': 'Word wrap',
9467
11173
  'settingsCenter.section.keymap': 'Shortcuts',
9468
11174
  'settingsCenter.wordWrapGlobalNote': 'When unset, the per-extension default applies (md-like files wrap)',
@@ -9516,7 +11222,40 @@ window.__ModuleLoader__.load({
9516
11222
  .dsh-editor-area { flex: 1 1 auto; min-height: 0; width: 100%; resize: none; border: none; outline: none; padding: 10px 12px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 13px; line-height: 1.5; white-space: pre; overflow: auto; tab-size: 4; }
9517
11223
  .dsh-editor-inputwrap { position: relative; flex: 1 1 auto; min-height: 0; display: flex; }
9518
11224
  .dsh-editor-highlight { position: absolute; inset: 0; overflow: hidden; pointer-events: none; background: var(--dsw-alias-bg-base); }
9519
- .dsh-editor-highlight-bar { position: absolute; left: 0; min-width: 100%; box-sizing: border-box; border-top: 2px solid color-mix(in srgb, var(--dsw-alias-brand-primary) 20%, var(--dsw-alias-bg-base)); border-bottom: 2px solid color-mix(in srgb, var(--dsw-alias-brand-primary) 20%, var(--dsw-alias-bg-base)); opacity: 0.3; }
11225
+ .dsh-editor-highlight-bar { position: absolute; left: 0; min-width: 100%; box-sizing: border-box; --dsh-editor-active-line-inset: -2px; opacity: 0.3; }
11226
+ .dsh-editor-highlight-bar::before, .dsh-editor-highlight-bar::after { content: ""; position: absolute; left: 0; right: 0; height: 2px; background: color-mix(in srgb, var(--dsw-alias-brand-primary) 20%, var(--dsw-alias-bg-base)); }
11227
+ /* The band offsets are canvas-measured (font-aware: the bands frame the real
11228
+ * glyph ink, set per paint as --dsh-editor-band-top/-bottom custom props);
11229
+ * the static --dsh-editor-active-line-inset fallback applies only on engines
11230
+ * without TextMetrics bounding boxes. */
11231
+ .dsh-editor-highlight-bar::before { top: var(--dsh-editor-band-top, var(--dsh-editor-active-line-inset, -2px)); }
11232
+ .dsh-editor-highlight-bar::after { bottom: var(--dsh-editor-band-bottom, var(--dsh-editor-active-line-inset, -2px)); }
11233
+ /* Whitespace glyph layer (0.12.0): the viewport-sized underlay PlainTextMode
11234
+ * mounts between the highlight backdrop and the gutter band while any of the
11235
+ * three switches (spaces/tabs/newlines) is on, below the overlay textarea.
11236
+ * Its font metrics mirror .dsh-editor-area declaration for declaration
11237
+ * (family, 13px, line-height 1.5, tab-size 4) so the underlay rows keep the
11238
+ * textarea's exact advance widths — a glyph drifting off its column would be
11239
+ * worse than no glyph at all. pointer-events: none keeps every pointer path
11240
+ * on the textarea; overflow: hidden bounds the windowed rows to the viewport
11241
+ * (rows position against scrollTop, never against the scroll extent). */
11242
+ .dsh-editor-whitespace { position: absolute; inset: 0; overflow: hidden; pointer-events: none; font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 13px; line-height: 1.5; tab-size: 4; color: var(--dsw-alias-label-primary); }
11243
+ /* The row's text nodes exist ONLY for advance: they carry the real line
11244
+ * text so the glyph boxes land on their exact columns, but their INK must
11245
+ * never paint — the textarea renders the same text on top, and two
11246
+ * text-rendering paths rasterize with subpixel differences, so visible
11247
+ * under-ink reads as a double-struck (bolder/blurry) font. Transparent
11248
+ * color keeps the layout and kills the ink; the glyph spans restore the
11249
+ * label color explicitly because their SVG strokes/fills use currentColor. */
11250
+ .dsh-editor-whitespace-row { position: absolute; white-space: pre; color: transparent; }
11251
+ /* The glyph box is a zero-height inline-block: its bottom edge sits on the
11252
+ * text baseline and its width carries the 1ch advance. The ink itself is an
11253
+ * SVG (font-independent geometry — see glyphSvgShape in src/whitespace.js:
11254
+ * font fallbacks drew ·/→ with full-width advances whose ink landed at
11255
+ * font-specific offsets), centered at (50%, yCenterEm above the baseline)
11256
+ * via the per-instance transform the builder sets. */
11257
+ .dsh-editor-whitespace-glyph { display: inline-block; width: 1ch; height: 0; position: relative; opacity: 0.25; color: var(--dsw-alias-label-primary); }
11258
+ .dsh-editor-whitespace-glyph svg { position: absolute; width: 1ch; height: 1ch; overflow: visible; }
9520
11259
  .dsh-editor-area.dsh-editor-area-overlay { position: relative; z-index: 1; background: transparent; }
9521
11260
  /* Word wrap (0.10.0): PlainTextMode appends this class when the wordWrap
9522
11261
  * prop is literally true and switches the textarea's wrap attribute to
@@ -9572,6 +11311,7 @@ window.__ModuleLoader__.load({
9572
11311
  .dsh-editor-settings-dialog-menu-item.active { background: color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent); color: var(--dsw-alias-brand-primary); font-weight: 500; }
9573
11312
  .dsh-editor-settings-dialog-content { flex: 1 1 auto; min-width: 0; min-height: 0; overflow-y: auto; padding: 14px; }
9574
11313
  .dsh-editor-settings-dialog-section { display: flex; flex-direction: column; gap: 2px; }
11314
+ .dsh-editor-settings-dialog-group-title { margin-top: 8px; padding: 0 10px; font-size: 11px; color: var(--dsw-alias-label-secondary); }
9575
11315
  .dsh-editor-settings-dialog-row { display: flex; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 6px; font-size: 12px; }
9576
11316
  .dsh-editor-settings-dialog-row:hover { background: var(--dsw-alias-bg-layer-1); }
9577
11317
  .dsh-editor-settings-dialog-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-primary); }
@@ -9579,6 +11319,16 @@ window.__ModuleLoader__.load({
9579
11319
  .dsh-editor-settings-dialog-toggle:hover:not(:disabled) { color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-border-l2); }
9580
11320
  .dsh-editor-settings-dialog-toggle.on { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }
9581
11321
  .dsh-editor-settings-dialog-toggle:disabled { opacity: 0.45; cursor: default; }
11322
+ /* Indentation section (0.13.0): the segmented controls (-seg / -seg-btn).
11323
+ * One bordered pill per row; the selected option is tinted with the brand
11324
+ * color, like the active section menu item. The width control is disabled
11325
+ * outside spaces mode and falls back to this opacity. */
11326
+ .dsh-editor-settings-dialog-seg { flex: none; display: inline-flex; border: 1px solid var(--dsw-alias-border-l1); border-radius: 5px; overflow: hidden; }
11327
+ .dsh-editor-settings-dialog-seg-btn { height: 22px; padding: 0 10px; border: none; background: transparent; color: var(--dsw-alias-label-secondary); font-size: 11px; cursor: pointer; white-space: nowrap; }
11328
+ .dsh-editor-settings-dialog-seg-btn + .dsh-editor-settings-dialog-seg-btn { border-left: 1px solid var(--dsw-alias-border-l1); }
11329
+ .dsh-editor-settings-dialog-seg-btn:hover:not(:disabled) { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-2); }
11330
+ .dsh-editor-settings-dialog-seg-btn.on { background: color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent); color: var(--dsw-alias-brand-primary); }
11331
+ .dsh-editor-settings-dialog-seg-btn:disabled { opacity: 0.45; cursor: default; }
9582
11332
  .dsh-editor-settings-dialog-note { padding: 2px 10px 8px; font-size: 11px; color: var(--dsw-alias-label-secondary); opacity: 0.8; }
9583
11333
  .dsh-editor-settings-dialog-error { margin-bottom: 8px; padding: 8px 10px; border-radius: 6px; background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent); font-size: 11px; color: var(--dsw-alias-state-error-primary); overflow: hidden; text-overflow: ellipsis; }
9584
11334
  /* Keymap section (0.11.0): the recorder rows that used to live in the
@@ -9780,7 +11530,10 @@ window.__ModuleLoader__.load({
9780
11530
  }
9781
11531
  return {
9782
11532
  text: text.replace(/\r\n?/g, '\n'),
9783
- version: value !== null && typeof value.version === 'string' ? value.version : ''
11533
+ version: value !== null && typeof value.version === 'string' ? value.version : '',
11534
+ // 行尾保留(0.12.x):在归一化之前探测原始行尾,写线时由机器还原
11535
+ // (applyEol)——机内与显示层恒为 LF,磁盘文件保持自己的行尾。
11536
+ eol: detectEol(text)
9784
11537
  };
9785
11538
  }
9786
11539