fix(editor): new files use the owning host's line ending; add End of Line setting (#43253)

* fix(editor): give new files the owning host's line ending, add End of Line setting

A file with no line breaks yet took the ending of the OS the window runs on,
so a Windows client wrote CRLF into files on WSL hosts and Linux SSH hosts.
Such models now adopt the ending of the host that owns the file (LF on Linux
and macOS, CRLF on native Windows), and Settings > General > Editor gains an
End of Line choice (Auto, LF, CRLF). Files with line breaks keep theirs.

Fixes #43216

* fix(editor): resolve paired-host files by endpoint and keep new-file EOL through undo

- Resolve a file's host from its endpoint-relative authority, so a file on a
  WSL host or paired server reads that host's OS instead of this client's.
- Only a WSL host's own files fall back to Linux; SSH targets behind it do not.
- Track whether a model was loaded with line breaks, and keep a new model on
  its chosen ending through undo, late host reports, and setting changes.
- A model without line breaks adopts the ending of external text written in.
- Read remote OS facts directly so the selector builds no translated strings.
- Docs describe Auto by where the workspace runs (Windows projects in WSL get LF).

* fix(editor): keep undo valid across late EOL conversion; respect text written while unmounted

- Convert typed lines with an undoable pushEOL step instead of a bare setEOL,
  whose stale offsets corrupted Undo. Only a new choice (late host report or
  setting change) converts multiline text, so Undo of the conversion sticks.
- Record outside text with line breaks on the model from the content-sync
  paths, so a remounted editor never converts text the user did not type.

* fix(editor): never convert a new file's line endings once its lines are saved

A clean buffer with line breaks matches the file on disk, so it is treated as
an existing file: changing End of Line later no longer converts it, marks it
dirty, and lets autosave rewrite it. Only typed, unsaved lines are converted.

* fix(editor): treat a new file as saved only when its bytes match disk

The dirty flag ignores Markdown trailing whitespace, so a clean flag did not
prove typed line breaks were saved. Compare the model text with the buffer's
last known disk signature instead. Also type the line-ending state by its
model shape for the anti-slop lint, localize the LF/CRLF labels, and note in
the docs that autosaved lines keep their ending if the host reports later.

* fix(editor): only set a new file's line ending while it has at most one line

Converting text that already has line breaks kept running into cases where
saved or in-flight lines were rewritten. The editor now sets the ending only
while the model has at most one line, at mount and whenever the choice
changes, and re-applies it when Undo returns to one line. Text with line
breaks is never converted. This removes the multi-line conversion, its undo
step, the per-model state and the disk-signature check.

* fix(editor): keep an existing file's line ending after it is emptied

A model that already had line breaks when the editor mounted, or got them
from a programmatic or outside write, is flagged as an existing file and
never has its ending set again, so emptying and retyping it keeps the file's
ending. Line breaks the user typed do not set the flag, so Undo back to one
line still restores the chosen ending. Scope the docs sentence on outside text.

* fix(editor): carry a buffer's line ending through model rekeys and renames

A replacement model was built from text and language alone, so an emptied
or one-line existing file lost its ending and existing-file status. The rekey
carry now copies both to the model it creates. A rename remounts the editor
under a new view id, so the rename records the old model and the remount
carries an unsaved draft the same way. Existing models at the destination are
never touched.

* fix(editor): hand a renamed buffer's line ending over as a snapshot

The rename handoff stored the old model's address, which model cleanup could
dispose before the renamed tab mounted, and records were never cleared. The
rename now snapshots { ending, existing-file } from the old model, only for a
tab with an unsaved draft, keyed by the new tab id. The tab-close cleanup
drops it, and the remount applies it only to the model it builds from the
draft. Same-view re-keys still carry from the live model.
This commit is contained in:
Neil
2026-11-16 14:49:08 -08:00
committed by GitHub
parent 2b6661aa1c
commit c097acc64e
26 changed files with 1105 additions and 2 deletions
@@ -12,6 +12,10 @@ Files save on blur and after short idle periods. There is no "dirty" dot because
Enable **Insert Final Newline** under [Settings → General → Editor](/docs/settings) to add a missing line break when saving a non-empty file from the code editor. It is off by default, keeps the file's LF or CRLF line endings, and leaves the cursor in place. Rich Markdown, notebook, and CSV editors are unchanged.
## Line endings
New files, and files that have no line breaks yet, use the line ending of the system that runs the file's workspace: LF on Linux and macOS hosts, WSL hosts, and Windows projects that run in WSL; CRLF on Windows otherwise. Choose LF or CRLF under **End of Line** in [Settings → General → Editor](/docs/settings) to always use one. The ending is set only while the file has at most one line. Once it has line breaks, Orca never changes them, so lines you typed keep their ending. A file that opened with line breaks, or got them from text written outside the editor, keeps its ending even if you empty it. When outside text with line breaks lands in a file that has at most one line, the file takes that text's ending. If you type several lines before a remote SSH host or Orca server reports its system, those lines keep the editor's starting ending. WSL hosts are treated as Linux from the start, so they are not affected. Shell scripts always start with LF.
## Multi-cursor, go-to, find
- `Cmd-D` — select next occurrence.
+1
View File
@@ -20,6 +20,7 @@ Settings are grouped into panes. Everything here is searchable with `Cmd-,` then
- **Default new-worktree name** — custom prefix or marine creatures.
- **Editor Word Wrap** — default wrap for file editors (on by default). Toggle from a file tab's **⋯** menu or `Alt+Z`. Separate from **Diff Word Wrap**.
- **Insert Final Newline** — add a missing line break when saving a non-empty file from the code editor; off by default.
- **End of Line** — line ending for new files and files with no line breaks yet: Auto (follows the system that runs the file's workspace: LF for Linux, macOS, and WSL, CRLF for Windows), LF, or CRLF. Files with line breaks keep theirs.
## Appearance
@@ -0,0 +1,193 @@
// @vitest-environment happy-dom
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { afterEach, describe, expect, it } from 'vitest'
import { applyNewModelLineEnding, trackNewModelLineEnding } from './editor-new-model-line-ending'
import { syncContentOnMount, syncContentUpdate } from './monaco-content-sync'
import {
beginProgrammaticContentSync,
endProgrammaticContentSync,
isProgrammaticContentSyncInFlight,
resetProgrammaticContentSyncForTests
} from './monaco-programmatic-sync'
const CRLF = monaco.editor.EndOfLineSequence.CRLF
const models: monaco.editor.ITextModel[] = []
/** An empty model on a Windows client, where the editor defaults to CRLF. */
function windowsModel(text = ''): monaco.editor.ITextModel {
const model = monaco.editor.createModel(text, 'plaintext')
model.setEOL(CRLF)
models.push(model)
return model
}
function type(model: monaco.editor.ITextModel, text: string): void {
model.pushStackElement()
model.pushEditOperations([], [{ range: model.getFullModelRange(), text }], () => null)
model.pushStackElement()
}
const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve))
function writeExternally(
model: monaco.editor.ITextModel,
content: string,
path: 'mount' | 'update'
): void {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this editor double delegates model edits and undo to a real Monaco model.
const editorHost = {
getModel: () => model,
saveViewState: () => null,
pushUndoStop: () => {
model.pushStackElement()
return true
}
} as unknown as monaco.editor.IStandaloneCodeEditor
beginProgrammaticContentSync('key')
try {
if (path === 'mount') {
syncContentOnMount(editorHost, content)
} else {
syncContentUpdate(editorHost, content)
}
} finally {
endProgrammaticContentSync('key')
}
}
afterEach(() => {
resetProgrammaticContentSyncForTests()
models.splice(0).forEach((model) => model.dispose())
})
describe('line ending of a new model', () => {
it('switches a one-line model without registering as a user edit', () => {
const model = windowsModel()
let echoed = false
model.onDidChangeContent(() => {
echoed = !isProgrammaticContentSyncInFlight('key')
})
applyNewModelLineEnding(model, '\n', 'key')
expect(model.getEOL()).toBe('\n')
expect(echoed).toBe(false)
})
it('keeps the ending of a file loaded with line breaks', () => {
const model = windowsModel('a\r\nb\r\n')
const tracker = trackNewModelLineEnding(model, '\n', 'key')
expect(model.getValue()).toBe('a\r\nb\r\n')
tracker.dispose()
})
it('restores the chosen ending when Undo returns to one line', async () => {
const model = windowsModel()
type(model, 'typed')
const tracker = trackNewModelLineEnding(model, '\n', 'key')
model.undo()
await settle()
expect(model.getEOL()).toBe('\n')
type(model, 'next\nline')
expect(model.getValue()).toBe('next\nline')
tracker.dispose()
})
it('leaves lines typed before a late host report untouched and clean of edits', async () => {
const model = windowsModel()
trackNewModelLineEnding(model, null, 'key').dispose()
// Typed while an in-flight save of `one\ntwo` is still writing.
type(model, 'one\ntwo')
type(model, 'one\ntwoX')
let events = 0
model.onDidChangeContent(() => {
events += 1
})
const reported = trackNewModelLineEnding(model, '\n', 'key')
await settle()
expect(model.getValue()).toBe('one\r\ntwoX')
expect(events).toBe(0)
model.undo()
await settle()
expect(model.getValue()).toBe('one\r\ntwo')
reported.dispose()
})
it('never converts saved lines when End of Line changes', () => {
const model = windowsModel()
trackNewModelLineEnding(model, '\r\n', 'key').dispose()
type(model, 'one\ntwo')
const changed = trackNewModelLineEnding(model, '\n', 'key')
expect(model.getValue()).toBe('one\r\ntwo')
changed.dispose()
})
it('adopts the ending of external text written into a new file', async () => {
const model = windowsModel()
const tracker = trackNewModelLineEnding(model, '\n', 'key')
writeExternally(model, 'a\r\nb', 'update')
await settle()
expect(model.getValue()).toBe('a\r\nb')
tracker.dispose()
})
it('keeps external text written while no editor was mounted', async () => {
const model = windowsModel()
trackNewModelLineEnding(model, null, 'key').dispose()
let userEdits = 0
model.onDidChangeContent(() => {
userEdits += isProgrammaticContentSyncInFlight('key') ? 0 : 1
})
writeExternally(model, 'a\nb', 'mount')
const remount = trackNewModelLineEnding(model, '\r\n', 'key')
await settle()
expect(model.getValue()).toBe('a\nb')
expect(userEdits).toBe(0)
remount.dispose()
})
it('keeps an LF file on LF after it is emptied and retyped', async () => {
const model = windowsModel()
model.setValue('a\nb\n')
model.setEOL(monaco.editor.EndOfLineSequence.LF)
const tracker = trackNewModelLineEnding(model, '\r\n', 'key')
type(model, '')
await settle()
type(model, 'x\ny')
expect(model.getValue()).toBe('x\ny')
tracker.dispose()
})
it('keeps a CRLF file on CRLF after it is emptied and retyped', async () => {
const model = windowsModel('a\r\nb\r\n')
const tracker = trackNewModelLineEnding(model, '\n', 'key')
type(model, '')
await settle()
type(model, 'x\ny')
expect(model.getValue()).toBe('x\r\ny')
tracker.dispose()
})
it('still re-applies the choice when Undo empties lines typed into a new file', async () => {
const model = windowsModel()
type(model, 'x')
const tracker = trackNewModelLineEnding(model, '\n', 'key')
type(model, 'one\ntwo')
model.undo()
await settle()
model.undo()
await settle()
expect(model.getValue()).toBe('')
expect(model.getEOL()).toBe('\n')
tracker.dispose()
})
it('keeps the ending of text written while hidden after the file is emptied', async () => {
const model = windowsModel()
trackNewModelLineEnding(model, null, 'key').dispose()
writeExternally(model, 'a\nb', 'mount')
const remount = trackNewModelLineEnding(model, '\r\n', 'key')
type(model, '')
await settle()
type(model, 'x\ny')
expect(model.getValue()).toBe('x\ny')
remount.dispose()
})
})
@@ -0,0 +1,117 @@
import { useEffect } from 'react'
import type { editor } from 'monaco-editor'
import type { AppState } from '@/store/types'
import { useAppStore } from '@/store/index'
import {
resolveNewModelLineEnding,
type EditorLineEnding
} from '../../../../../../shared/editor/saving/editor-end-of-line'
import { resolveEditorFileHostPlatform } from '../identity/editor-file-host-platform'
import { isExistingFileModel, markExistingFileModel } from './existing-file-line-ending'
import {
beginProgrammaticContentSync,
endProgrammaticContentSync,
isProgrammaticContentSyncInFlight
} from './monaco-programmatic-sync'
export function resolveOpenFileNewModelLineEnding(
state: AppState,
fileId: string,
language: string
): EditorLineEnding | null {
const file = state.openFiles?.find((entry) => entry.id === fileId)
if (!file) {
return null
}
const setting = state.settings?.editorEndOfLine
return resolveNewModelLineEnding({
setting,
// Explicit LF/CRLF needs no host lookup.
hostPlatform:
setting === 'lf' || setting === 'crlf' ? null : resolveEditorFileHostPlatform(state, file),
language
})
}
type LineEndingModel = Pick<
editor.ITextModel,
'getLineCount' | 'getEOL' | 'setEOL' | 'onDidChangeContent' | 'isDisposed'
>
/**
* Sets the ending of a model that has at most one line. A model with line breaks is never
* converted: its text and undo history already carry its ending.
*/
export function applyNewModelLineEnding(
model: LineEndingModel,
lineEnding: EditorLineEnding | null,
modelKey: string
): void {
if (
!lineEnding ||
isExistingFileModel(model) ||
model.getLineCount() > 1 ||
model.getEOL() === lineEnding
) {
return
}
// A one-line switch changes no text or undo offsets; keep its event from marking the file dirty.
beginProgrammaticContentSync(modelKey)
try {
// Literal EndOfLineSequence values (LF = 0, CRLF = 1) keep this free of the Monaco runtime.
model.setEOL(lineEnding === '\r\n' ? 1 : 0)
} finally {
endProgrammaticContentSync(modelKey)
}
}
/** Applies the ending now and again whenever an edit (such as Undo) leaves one line. */
export function trackNewModelLineEnding(
model: LineEndingModel,
lineEnding: EditorLineEnding | null,
modelKey: string
): { dispose(): void } {
// Mount-time breaks came from disk or an outside write; emptying the file must not switch them.
if (model.getLineCount() > 1) {
markExistingFileModel(model)
}
applyNewModelLineEnding(model, lineEnding, modelKey)
let disposed = false
const subscription = model.onDidChangeContent(() => {
if (isProgrammaticContentSyncInFlight(modelKey) && model.getLineCount() > 1) {
markExistingFileModel(model)
return
}
// Why deferred: re-entrant edits would reach later listeners out of order.
queueMicrotask(() => {
if (!disposed && !model.isDisposed()) {
applyNewModelLineEnding(model, lineEnding, modelKey)
}
})
})
return {
dispose() {
disposed = true
subscription.dispose()
}
}
}
export function useNewModelLineEnding(
mountedEditor: editor.IStandaloneCodeEditor | null,
modelUri: string,
fileId: string,
language: string
): void {
const lineEnding = useAppStore((state) =>
resolveOpenFileNewModelLineEnding(state, fileId, language)
)
useEffect(() => {
const model = mountedEditor?.getModel()
if (!model || model.uri.toString() !== modelUri) {
return
}
const tracker = trackNewModelLineEnding(model, lineEnding, modelUri)
return () => tracker.dispose()
}, [mountedEditor, modelUri, lineEnding])
}
@@ -0,0 +1,41 @@
import type { editor } from 'monaco-editor'
import type { EditorLineEnding } from '../../../../../../shared/editor/saving/editor-end-of-line'
type EolModel = Pick<editor.ITextModel, 'getEOL'>
// Models that held line breaks the user did not type (loaded or written in); their ending is the file's.
// Why per model: retained models outlive editor mounts and are shared by split panes.
const existingFileModels = new WeakMap<EolModel, true>()
export function isExistingFileModel(model: EolModel): boolean {
return existingFileModels.has(model)
}
export function markExistingFileModel(model: EolModel): void {
existingFileModels.set(model, true)
}
/** What a buffer's replacement model must keep: its ending and existing-file status. */
export type BufferLineEndingSnapshot = { eol: EditorLineEnding; existingFile: boolean }
export function snapshotBufferLineEnding(model: EolModel): BufferLineEndingSnapshot {
return {
eol: model.getEOL() === '\r\n' ? '\r\n' : '\n',
existingFile: existingFileModels.has(model)
}
}
/** Applies a snapshot to a freshly created replacement model for the same buffer. */
export function applyBufferLineEnding(
model: Pick<editor.ITextModel, 'getLineCount' | 'getEOL' | 'setEOL'>,
snapshot: BufferLineEndingSnapshot
): void {
// Why one line only: a multi-line replacement already carries its text's ending.
if (model.getLineCount() <= 1 && model.getEOL() !== snapshot.eol) {
// Literal EndOfLineSequence values (LF = 0, CRLF = 1) keep this free of the Monaco runtime.
model.setEOL(snapshot.eol === '\r\n' ? 1 : 0)
}
if (snapshot.existingFile) {
existingFileModels.set(model, true)
}
}
@@ -16,6 +16,19 @@ export function normalizeToModelEol(
return content.replace(separators, eol)
}
/** A model without line breaks takes the ending of incoming text that has them, as a fresh load would. */
function adoptIncomingLineEnding(model: editor.ITextModel, content: string): void {
const firstBreak = content.search(/\r\n|\n|\r/)
if (firstBreak === -1 || model.getLineCount() > 1) {
return
}
const eol = content.startsWith('\r\n', firstBreak) ? '\r\n' : '\n'
if (model.getEOL() !== eol) {
// Literal EndOfLineSequence values (LF = 0, CRLF = 1) keep this free of the Monaco runtime.
model.setEOL(eol === '\r\n' ? 1 : 0)
}
}
function applyModelEdit(
editorInstance: editor.IStandaloneCodeEditor,
model: editor.ITextModel,
@@ -68,6 +81,7 @@ export function syncContentOnMount(
return false
}
const modelContent = currentContentSnapshot ?? model.getValue()
adoptIncomingLineEnding(model, content)
const normalizedContent = normalizeToModelEol(content, model, modelContent)
if (modelContent === normalizedContent) {
return false
@@ -88,6 +102,7 @@ export function syncContentUpdate(
return
}
const currentContent = model.getValue()
adoptIncomingLineEnding(model, content)
const normalizedContent = normalizeToModelEol(content, model, currentContent)
if (currentContent.length === normalizedContent.length) {
replaceModelContent(editorInstance, model, currentContent, normalizedContent, mode, true)
@@ -0,0 +1,164 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from 'vitest'
// Why hoisted: the client platform is read once when the workspace module loads.
vi.hoisted(() => {
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', platform: 'Win32' }
})
})
import { createTestStore, seedStore } from '@/store/testing/app-store-test-fixture'
import { TEST_REPO } from '@/store/repos/repo.test-fixture'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
import type { OpenFile } from '@/store/slices/editor/types/open-file'
import type { WorktreeOperationRoute } from '@/lib/workspace/ownership/worktree-operation-route'
import { captureEditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance'
import {
connectedRuntimeStatus,
publicRuntimeEnvironment
} from '@/runtime/rpc/testing/paired-runtime-environment-test-fixture'
import { getDefaultSettings } from '../../../../../../shared/orca-profiles/constants'
import type { HostAuthority } from '../../../../../../shared/execution-host/host-authority'
import type { SshConnectionState } from '../../../../../../shared/remote-runtime/ssh/ssh-types'
import { resolveOpenFileNewModelLineEnding } from '../buffer-text/editor-new-model-line-ending'
import { resolveEditorFileHostPlatform } from './editor-file-host-platform'
const WORKTREE_ID = 'repo::/home/me/repo'
const WSL_HOST = publicRuntimeEnvironment({
id: 'wsl-ubuntu',
orcadDeployment: { kind: 'wsl', distro: 'Ubuntu', localPort: 4100, remotePort: 4200 }
})
function file(
route: WorktreeOperationRoute,
filePath = '/home/me/repo/new.txt',
authority?: HostAuthority
): OpenFile {
return {
id: 'file-1',
worktreeId: WORKTREE_ID,
filePath,
relativePath: 'new.txt',
mode: 'edit',
language: 'plaintext',
isDirty: false,
runtimeEnvironmentId: route.runtimeEnvironmentId,
operationProvenance: {
ownershipProjection: 'explicit',
generation: {
route,
...(authority ? { authority } : {}),
runtimeConnectionGeneration: null,
runtimePairingRevision: undefined,
runtimeSshGeneration: null,
nestedSshGeneration: null,
directSshGeneration: null
}
}
}
}
function storeWith(openFile: OpenFile | null, endOfLine?: 'auto' | 'lf' | 'crlf') {
const store = createTestStore()
seedStore(store, {
openFiles: openFile ? [openFile] : [],
settings: { ...getDefaultSettings('/home/me'), editorEndOfLine: endOfLine }
})
return store
}
function sshState(remotePlatform?: 'linux'): SshConnectionState {
return { targetId: 'box', status: 'connected', error: null, reconnectAttempt: 0, remotePlatform }
}
const eolOf = (store: ReturnType<typeof createTestStore>) =>
resolveOpenFileNewModelLineEnding(store.getState(), 'file-1', 'plaintext')
const wslRoute = {
executionHostId: 'runtime:wsl-ubuntu',
runtimeEnvironmentId: 'wsl-ubuntu'
} as const
const sshRoute = { executionHostId: 'ssh:box', runtimeEnvironmentId: null } as const
const localRoute = { executionHostId: 'local', runtimeEnvironmentId: null } as const
describe('host OS of an open file, from a Windows client', () => {
it('reads a WSL-host file opened through the app as Linux, before and after it reports', () => {
const store = storeWith(null)
const live = connectedRuntimeStatus('wsl-runtime', 1)
store.setState({
repos: [
{ ...TEST_REPO, id: 'repo', path: '/home/me/repo', executionHostId: 'runtime:wsl-ubuntu' }
],
worktreesByRepo: {
repo: [
makeWorktree({
id: WORKTREE_ID,
repoId: 'repo',
path: '/home/me/repo',
hostId: 'runtime:wsl-ubuntu'
})
]
},
runtimeEnvironments: [WSL_HOST]
})
const operationProvenance = captureEditorFileOperationProvenance(
store.getState(),
WORKTREE_ID,
'wsl-ubuntu',
true,
'runtime:wsl-ubuntu'
)
// Captured authority is endpoint-relative: `local` means local to the WSL host.
expect(operationProvenance.generation.authority).toEqual({
endpoint: { kind: 'environment', environmentId: 'wsl-ubuntu' },
at: 'local'
})
store.setState({ openFiles: [{ ...file(wslRoute), operationProvenance }] })
expect(eolOf(store)).toBe('\n')
store.setState({
runtimeStatusByEnvironmentId: new Map([
[
'wsl-ubuntu',
{ ...live, status: live.status && { ...live.status, hostPlatform: 'linux' } }
]
])
})
expect(eolOf(store)).toBe('\n')
})
it('does not treat an SSH target reached through a WSL host as the distro', () => {
const nested = file(
{ executionHostId: 'ssh:box', runtimeEnvironmentId: 'wsl-ubuntu' },
'/srv/a',
{
endpoint: { kind: 'environment', environmentId: 'wsl-ubuntu' },
at: 'ssh:box'
}
)
const store = storeWith(nested)
store.setState({ runtimeEnvironments: [WSL_HOST] })
expect(resolveEditorFileHostPlatform(store.getState(), nested)).toBeNull()
})
it('reads a direct Linux SSH file once the host reports its OS', () => {
const store = storeWith(file(sshRoute))
store.setState({ sshConnectionStates: new Map([['box', sshState()]]) })
expect(eolOf(store)).toBeNull()
store.setState({ sshConnectionStates: new Map([['box', sshState('linux')]]) })
expect(eolOf(store)).toBe('\n')
})
it('uses CRLF for a native Windows file and LF for a local WSL path', () => {
expect(eolOf(storeWith(file(localRoute, 'C:\\repo\\new.txt')))).toBe('\r\n')
const wslPath = file(localRoute, '\\\\wsl.localhost\\Ubuntu\\home\\me\\new.txt')
expect(eolOf(storeWith(wslPath))).toBe('\n')
})
it('lets the End of Line setting override the host', () => {
expect(eolOf(storeWith(file(localRoute, 'C:\\repo\\new.txt'), 'lf'))).toBe('\n')
expect(eolOf(storeWith(file(wslRoute), 'crlf'))).toBe('\r\n')
})
})
@@ -0,0 +1,87 @@
import type { AppState } from '@/store/types'
import type { OpenFile } from '@/store/slices/editor/types/open-file'
import { resolveHostPlatform } from '@/runtime/hosts/platform/execution-host-facts'
import { getLocalProjectExecutionRuntimeContext } from '@/runtime/hosts/preflight/local-preflight-context'
import { parseExecutionHostId } from '../../../../../../shared/execution-host/execution-host'
import {
hostAuthorityFromOperationRoute,
type HostAuthority
} from '../../../../../../shared/execution-host/host-authority'
import { lastVerifiedRuntimeStatus } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status'
import { isWslHostRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments'
import { isWslUncPath } from '../../../../../../shared/file-access/wsl-paths'
import { resolveEditorModelOwner } from './editor-model-owner'
type EditorFileHostRef = Pick<
OpenFile,
'worktreeId' | 'filePath' | 'runtimeEnvironmentId' | 'externalSshTargetId' | 'operationProvenance'
>
/** Serving endpoint plus location; a captured `at: 'local'` is local to that endpoint, not this client. */
export function resolveEditorFileHostAuthority(
state: AppState,
file: EditorFileHostRef
): HostAuthority | null {
const captured = file.operationProvenance?.generation.authority
if (captured) {
return captured
}
const owner = resolveEditorModelOwner(file, state)
if (!owner.hostId) {
return null
}
const authority = hostAuthorityFromOperationRoute({
executionHostId: owner.hostId,
runtimeEnvironmentId: owner.environmentId
})
return authority === 'contradictory' ? null : authority
}
/** OS of the host that owns an open file; null while that host has not reported it. */
export function resolveEditorFileHostPlatform(
state: AppState,
file: EditorFileHostRef
): NodeJS.Platform | null {
const authority = resolveEditorFileHostAuthority(state, file)
if (!authority) {
return null
}
const environmentId =
authority.endpoint.kind === 'environment' ? authority.endpoint.environmentId : null
const sshHost = parseExecutionHostId(authority.at)
// Remote facts are read directly: this runs in a store selector, and the shared resolver
// builds translated "not reported yet" reasons on every miss.
if (sshHost?.kind === 'ssh') {
const sshState = environmentId
? state.sshStateByEnvironment.get(environmentId)?.connectionStates.get(sshHost.targetId)
: state.sshConnectionStates.get(sshHost.targetId)
return sshState?.remotePlatform ?? null
}
if (environmentId) {
return resolveServerPlatform(state, environmentId, file.filePath)
}
const local = resolveHostPlatform(state, {
host: { kind: 'local', id: 'local' },
nestedSshTargetId: null,
sshOwnerEnvironmentId: null,
workspacePath: file.filePath,
projectRuntime: () => getLocalProjectExecutionRuntimeContext(state, file.worktreeId)
})
return local.kind === 'known' ? local.platform : null
}
function resolveServerPlatform(
state: AppState,
environmentId: string,
filePath: string
): NodeJS.Platform | null {
const status = lastVerifiedRuntimeStatus(state.runtimeStatusByEnvironmentId.get(environmentId))
const hostPlatform = status?.hostPlatform
if (hostPlatform) {
// Why: a WSL UNC path on a Windows server lives inside that distro.
return hostPlatform === 'win32' && isWslUncPath(filePath) ? 'linux' : hostPlatform
}
const environment = state.runtimeEnvironments?.find((entry) => entry.id === environmentId)
// Why: a WSL host's server always runs inside the distro, even before it reports its OS.
return environment && isWslHostRuntimeEnvironment(environment) ? 'linux' : null
}
@@ -0,0 +1,91 @@
// @vitest-environment happy-dom
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { afterEach, describe, expect, it } from 'vitest'
import { trackNewModelLineEnding } from '../buffer-text/editor-new-model-line-ending'
import { resetProgrammaticContentSyncForTests } from '../buffer-text/monaco-programmatic-sync'
import { carryEditorModelText } from './editor-model-rekey-carry'
const models: monaco.editor.ITextModel[] = []
const trackers: { dispose(): void }[] = []
const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve))
function model(text: string, uri: string): monaco.editor.ITextModel {
const created = monaco.editor.createModel(text, 'plaintext', monaco.Uri.parse(uri))
models.push(created)
return created
}
function modelAt(uri: string): monaco.editor.ITextModel {
const found = monaco.editor.getModel(monaco.Uri.parse(uri))
if (!found) {
throw new Error(`no model at ${uri}`)
}
models.push(found)
return found
}
/** Native Windows with Auto: the choice is CRLF. */
function track(target: monaco.editor.ITextModel, uri: string): void {
trackers.push(trackNewModelLineEnding(target, '\r\n', uri))
}
function type(target: monaco.editor.ITextModel, text: string): void {
target.pushStackElement()
target.pushEditOperations([], [{ range: target.getFullModelRange(), text }], () => null)
target.pushStackElement()
}
afterEach(() => {
trackers.splice(0).forEach((tracker) => tracker.dispose())
models.splice(0).forEach((entry) => {
if (!entry.isDisposed()) {
entry.dispose()
}
})
resetProgrammaticContentSyncForTests()
})
describe('model rekey keeps an existing file on its line ending', () => {
it('carries an emptied LF file to its replacement model', async () => {
const from = 'file:///rekey/before.txt'
const to = 'file:///rekey/after.txt'
const old = model('a\nb\n', from)
track(old, from)
type(old, '')
await settle()
expect(carryEditorModelText(monaco, from, to, '')).toBe(true)
const next = modelAt(to)
track(next, to)
type(next, 'x\ny')
expect(next.getValue()).toBe('x\ny')
})
it('carries an LF file reduced to one line to its replacement model', async () => {
const from = 'file:///rekey/one-before.txt'
const to = 'file:///rekey/one-after.txt'
const old = model('a\nb\n', from)
track(old, from)
type(old, 'a')
await settle()
expect(carryEditorModelText(monaco, from, to, 'a')).toBe(true)
const next = modelAt(to)
track(next, to)
type(next, 'a\ny')
expect(next.getValue()).toBe('a\ny')
})
it('leaves an unrelated model already at the destination untouched', async () => {
const from = 'file:///rekey/source.txt'
const to = 'file:///rekey/taken.txt'
const old = model('a\nb\n', from)
track(old, from)
type(old, '')
await settle()
const taken = model('', to)
taken.setEOL(monaco.editor.EndOfLineSequence.CRLF)
expect(carryEditorModelText(monaco, from, to, '')).toBe(false)
track(taken, to)
type(taken, 'x\ny')
expect(taken.getValue()).toBe('x\r\ny')
})
})
@@ -1,6 +1,11 @@
import { useLayoutEffect, useRef } from 'react'
import { useAppStore } from '@/store/index'
import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry'
import {
applyBufferLineEnding,
snapshotBufferLineEnding
} from '../buffer-text/existing-file-line-ending'
import { takeRenamedBufferLineEnding } from './editor-model-rename-handoff'
type ModelRegistry = NonNullable<ReturnType<typeof editorModelRegistry.get>>
@@ -16,7 +21,8 @@ export function carryEditorModelText(
if (!from || from.isDisposed() || registry.editor.getModel(target)) {
return false
}
registry.editor.createModel(draft ?? from.getValue(), from.getLanguageId(), target)
const to = registry.editor.createModel(draft ?? from.getValue(), from.getLanguageId(), target)
applyBufferLineEnding(to, snapshotBufferLineEnding(from))
return true
}
@@ -27,6 +33,18 @@ export function useEditorModelRekeyCarry(viewId: string, modelUri: string): void
const from = previous.current
previous.current = { viewId, modelUri }
const registry = editorModelRegistry.get()
// A rename remounts the editor under a new view id; the rename left its unsaved buffer's ending.
const renamed = takeRenamedBufferLineEnding(viewId)
const renamedDraft = renamed ? useAppStore.getState().editorDrafts[viewId] : undefined
if (renamed && renamedDraft !== undefined && registry) {
const target = registry.Uri.parse(modelUri)
// An existing model at the destination is the file's own; only a model built here takes it.
if (!registry.editor.getModel(target)) {
// Language is left to the editor, which applies the file's language on mount.
applyBufferLineEnding(registry.editor.createModel(renamedDraft, undefined, target), renamed)
}
return
}
// Carry only within one view; reused mounts must not transfer text between files.
if (from.viewId === viewId && from.modelUri !== modelUri && registry) {
const draft = useAppStore.getState().editorDrafts[viewId]
@@ -0,0 +1,156 @@
// @vitest-environment happy-dom
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { cleanup, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
// Why: the carry hook reads drafts from the app store; point it at the fixture's editor store.
const storeState = vi.hoisted(() => {
const holder: { current: (() => unknown) | null } = { current: null }
return holder
})
vi.mock('@/store/index', () => ({
useAppStore: { getState: () => storeState.current?.() }
}))
import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry'
import {
createModelLifetimeFixture,
resetModelLifetimeFixtures
} from '../retention/editor-model-lifetime-fixture'
import { trackNewModelLineEnding } from '../buffer-text/editor-new-model-line-ending'
import { resetProgrammaticContentSyncForTests } from '../buffer-text/monaco-programmatic-sync'
import { useEditorModelRekeyCarry } from './editor-model-rekey-carry'
import { takeRenamedBufferLineEnding } from './editor-model-rename-handoff'
import { getEditorModelOwnerKey } from './editor-model-owner'
import { toEditorModelUri } from './editor-model-uri'
const models: monaco.editor.ITextModel[] = []
const trackers: { dispose(): void }[] = []
const unregisters: (() => void)[] = []
const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve))
function type(target: monaco.editor.ITextModel, text: string): void {
target.pushStackElement()
target.pushEditOperations([], [{ range: target.getFullModelRange(), text }], () => null)
target.pushStackElement()
}
/** Native Windows with Auto: the choice is CRLF. */
function track(target: monaco.editor.ITextModel): void {
trackers.push(trackNewModelLineEnding(target, '\r\n', target.uri.toString()))
}
function setup() {
const fixture = createModelLifetimeFixture()
unregisters.push(editorModelRegistry.register(monaco))
storeState.current = () => fixture.store.getState()
return fixture
}
type FixtureStore = ReturnType<typeof setup>['store']
function rename(store: FixtureStore, fileId: string, newFileId: string, newFilePath: string) {
const file = store.getState().openFiles.find((entry) => entry.id === fileId)
if (!file) {
throw new Error(`no open file ${fileId}`)
}
return store.getState().rekeyOpenFilesForPathChange({
rekeys: [
{
oldFileId: fileId,
newFileId,
oldFilePath: file.filePath,
newFilePath,
newRelativePath: newFilePath.split('/').pop() ?? newFilePath
}
]
})
}
/** Mounts the renamed tab's editor: the carry hook, then the editor library's own model. */
function mount(store: FixtureStore, viewId: string): monaco.editor.ITextModel {
const state = store.getState()
const file = state.openFiles.find((entry) => entry.id === viewId)
if (!file) {
throw new Error(`no open file ${viewId}`)
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the editor store fixture holds every editor slice the owner key reads.
const uri = toEditorModelUri(file.filePath, getEditorModelOwnerKey(file, state as AppState))
renderHook(() => useEditorModelRekeyCarry(viewId, uri))
const target =
monaco.editor.getModel(monaco.Uri.parse(uri)) ??
monaco.editor.createModel(state.editorDrafts[viewId] ?? '', 'plaintext', monaco.Uri.parse(uri))
models.push(target)
track(target)
return target
}
afterEach(() => {
cleanup()
trackers.splice(0).forEach((tracker) => tracker.dispose())
unregisters.splice(0).forEach((unregister) => unregister())
resetModelLifetimeFixtures()
models.splice(0).forEach((entry) => {
if (!entry.isDisposed()) {
entry.dispose()
}
})
storeState.current = null
resetProgrammaticContentSyncForTests()
})
describe('rename handoff of a buffer line ending', () => {
it('keeps an emptied LF file on LF after a background rename disposed its model', async () => {
const { store, add, attach } = setup()
const { file, model } = add('background')
model.setValue('a\nb\n')
model.setEOL(monaco.editor.EndOfLineSequence.LF)
track(model)
type(model, '')
store.getState().setEditorDraft(file.id, '')
store.getState().markFileDirty(file.id, true)
await settle()
attach()
expect(rename(store, file.id, 'renamed', '/fixture/workspace/renamed.txt').ok).toBe(true)
await settle()
await settle()
expect(model.isDisposed()).toBe(true)
const next = mount(store, 'renamed')
type(next, 'x\ny')
expect(next.getValue()).toBe('x\ny')
})
it('drops a closed tab’s snapshot so a reused id starts fresh', async () => {
const { store, add, attach } = setup()
const { file, model } = add('closing')
model.setValue('a\nb\n')
model.setEOL(monaco.editor.EndOfLineSequence.LF)
track(model)
type(model, '')
store.getState().setEditorDraft(file.id, '')
store.getState().markFileDirty(file.id, true)
await settle()
attach()
const reused = '/fixture/workspace/reused.txt'
expect(rename(store, file.id, reused, reused).ok).toBe(true)
store.getState().closeFile(reused)
await settle()
expect(takeRenamedBufferLineEnding(reused)).toBeUndefined()
// A new one-line draft at the same id and path follows the editor's choice.
store.setState({
openFiles: [{ ...file, id: reused, filePath: reused, isDirty: true }],
editorDrafts: { [reused]: 'new draft' }
})
const next = mount(store, reused)
type(next, 'new draft\nsecond')
expect(next.getValue()).toBe('new draft\r\nsecond')
})
it('records nothing for a clean tab', () => {
const { store, add } = setup()
const { file } = add('clean')
expect(rename(store, file.id, 'clean-renamed', '/fixture/workspace/clean.txt').ok).toBe(true)
expect(takeRenamedBufferLineEnding('clean-renamed')).toBeUndefined()
})
})
@@ -0,0 +1,60 @@
import type { AppState } from '@/store/types'
import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry'
import {
snapshotBufferLineEnding,
type BufferLineEndingSnapshot
} from '../buffer-text/existing-file-line-ending'
import { getEditorModelOwnerKey } from './editor-model-owner'
import { toEditorModelUri } from './editor-model-uri'
/** New tab id → the unsaved buffer's line ending, until that tab's editor mounts or it closes. */
const renamedLineEndingByViewId = new Map<string, BufferLineEndingSnapshot>()
/**
* A rename gives a tab a new id and path, which remounts its editor on a new model, possibly after
* the old model is disposed. Snapshot the unsaved buffer's ending now so the remount keeps it.
*/
export function handOffRenamedEditorModels(
state: Pick<AppState, 'openFiles' | 'editorDrafts'> &
Parameters<typeof getEditorModelOwnerKey>[1],
rekeys: readonly { oldFileId: string; newFileId: string }[]
): void {
const registry = editorModelRegistry.get()
const files = new Map(state.openFiles.map((file) => [file.id, file]))
const handoffs = rekeys.flatMap(({ oldFileId, newFileId }) => {
// A tab renamed again before it mounted keeps its first snapshot.
const pending = renamedLineEndingByViewId.get(oldFileId)
if (pending) {
return [{ oldFileId, newFileId, snapshot: pending }]
}
const file = files.get(oldFileId)
// A clean tab reloads from disk, so only an unsaved draft continues the buffer.
if (file?.mode !== 'edit' || state.editorDrafts[oldFileId] === undefined || !registry) {
return []
}
const model = registry.editor.getModel(
registry.Uri.parse(toEditorModelUri(file.filePath, getEditorModelOwnerKey(file, state)))
)
return model && !model.isDisposed()
? [{ oldFileId, newFileId, snapshot: snapshotBufferLineEnding(model) }]
: []
})
// Why two passes: a swap of two ids must not delete the entry it just wrote.
for (const { oldFileId } of handoffs) {
renamedLineEndingByViewId.delete(oldFileId)
}
for (const { newFileId, snapshot } of handoffs) {
renamedLineEndingByViewId.set(newFileId, snapshot)
}
}
export function takeRenamedBufferLineEnding(viewId: string): BufferLineEndingSnapshot | undefined {
const snapshot = renamedLineEndingByViewId.get(viewId)
renamedLineEndingByViewId.delete(viewId)
return snapshot
}
/** A closed tab's snapshot must never reach a later tab that reuses its id. */
export function dropRenamedBufferLineEnding(viewId: string): void {
renamedLineEndingByViewId.delete(viewId)
}
@@ -1,4 +1,5 @@
import { disposeGitGraphHistory } from '../../git-graph/git-graph-tab-controllers'
import { dropRenamedBufferLineEnding } from '../identity/editor-model-rename-handoff'
import type { StoreApi } from 'zustand'
import type { editor } from 'monaco-editor'
import type { OpenFile } from '@/store/slices/editor/types/open-file'
@@ -264,6 +265,9 @@ export function attachClosedEditorTabCleanup(
if (file.mode === 'git-graph') {
disposeGitGraphHistory(file.id)
}
if (!liveFile) {
dropRenamedBufferLineEnding(file.id)
}
pendingFiles.set(ownerKey(descriptor), descriptor)
removed = true
if (file.mode === 'edit' && registry) {
@@ -36,6 +36,7 @@ import {
} from '@/lib/monaco-languages/plugin-syntax-editor-options'
import { useMonacoTheme } from '@/hooks/use-monaco-theme'
import { useEditorModelRekeyCarry } from '../model-lifetime/identity/editor-model-rekey-carry'
import { useNewModelLineEnding } from '../model-lifetime/buffer-text/editor-new-model-line-ending'
type MonacoEditorProps = {
fileId: string
@@ -129,6 +130,7 @@ export default function MonacoEditor({
[filePath, modelOwnerKey]
)
useEditorModelRekeyCarry(fileId, modelUri)
useNewModelLineEnding(mountedEditor, modelUri, fileId, language)
const estimatedAutoHeight = useMemo(() => {
if (!autoHeight) {
return null
@@ -0,0 +1,63 @@
import { GENERAL_SETTING_ANCHORS } from '../general/general-setting-anchors'
import type { GlobalSettings } from '../../../../../shared/settings/global-settings-types'
import {
normalizeEditorEndOfLine,
type EditorEndOfLine
} from '../../../../../shared/editor/saving/editor-end-of-line'
import { translate } from '@/i18n/i18n'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { Label } from '../../ui/label'
import { SearchableSetting } from '../section-layout/SearchableSetting'
import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls'
import { translateSearchKeyword } from '../search/settings-search-keywords'
export function getEndOfLineSearchEntry(t: Translate = translate) {
return {
title: t('settings.editorEndOfLine.title', 'End of line'),
description: t(
'settings.editorEndOfLine.description',
'Line ending for new files and files with no line breaks yet. Auto follows the system that runs the file’s workspace: LF for Linux, macOS, and WSL, CRLF for Windows. Files with line breaks keep theirs.'
),
keywords: [
...translateSearchKeyword(
'settings.editorEndOfLine.keywordLineEnding',
'line ending',
{ aliases: ['eol', 'lf', 'crlf', 'newline'] },
t
)
]
}
}
export function EditorEndOfLineSetting({
settings,
updateSettings
}: {
settings: GlobalSettings
updateSettings: (updates: Partial<GlobalSettings>) => void
}): React.JSX.Element {
const t = useTranslate()
const entry = getEndOfLineSearchEntry(t)
return (
<SearchableSetting
id={GENERAL_SETTING_ANCHORS.endOfLine}
{...entry}
className="flex items-center justify-between gap-4 py-3"
>
<div className="min-w-0 flex-1 space-y-0.5">
<Label>{entry.title}</Label>
<p className="text-xs text-muted-foreground">{entry.description}</p>
</div>
<SettingsSegmentedControl<EditorEndOfLine>
ariaLabel={entry.title}
value={normalizeEditorEndOfLine(settings.editorEndOfLine)}
onChange={(editorEndOfLine) => updateSettings({ editorEndOfLine })}
options={[
{ value: 'auto', label: t('settings.editorEndOfLine.auto', 'Auto') },
{ value: 'lf', label: t('settings.editorEndOfLine.lf', 'LF') },
{ value: 'crlf', label: t('settings.editorEndOfLine.crlf', 'CRLF') }
]}
/>
</SearchableSetting>
)
}
@@ -20,6 +20,7 @@ import { EditorWordWrapSetting } from './EditorWordWrapSetting'
import { EditorFontFamilySetting } from './EditorFontFamilySetting'
import { EditorFormatOnSaveSetting } from './EditorFormatOnSaveSetting'
import { EditorInsertFinalNewlineSetting } from './EditorInsertFinalNewlineSetting'
import { EditorEndOfLineSetting } from './EditorEndOfLineSetting'
import { EditorTypographySettings } from './EditorTypographySettings'
import {
createAutoSaveDelayDraftState,
@@ -96,6 +97,7 @@ export function GeneralEditorSettingsSection({
<SettingsGroup title={t('settings.general.editorGroups.saving', 'Saving')}>
<EditorFormatOnSaveSetting settings={settings} updateSettings={updateSettings} />
<EditorInsertFinalNewlineSetting settings={settings} updateSettings={updateSettings} />
<EditorEndOfLineSetting settings={settings} updateSettings={updateSettings} />
<SearchableSetting
id={GENERAL_SETTING_ANCHORS.autoSaveDelay}
title={t(
@@ -6,10 +6,12 @@ import { createLocalizedCatalog } from '@/i18n/localized-catalog'
import { getVisibleEditorTypographySearchDescriptors } from './editor-typography-search'
import { getFormatOnSaveSearchEntry } from './EditorFormatOnSaveSetting'
import { getInsertFinalNewlineSearchEntry } from './EditorInsertFinalNewlineSetting'
import { getEndOfLineSearchEntry } from './EditorEndOfLineSetting'
export const getGeneralEditorSearchDescriptors = createLocalizedCatalog(() => [
generalSetting(GENERAL_SETTING_ANCHORS.formatOnSave, getFormatOnSaveSearchEntry()),
generalSetting(GENERAL_SETTING_ANCHORS.finalNewline, getInsertFinalNewlineSearchEntry()),
generalSetting(GENERAL_SETTING_ANCHORS.endOfLine, getEndOfLineSearchEntry()),
generalSetting(GENERAL_SETTING_ANCHORS.autoSave, getAutoSaveSearchEntry()),
generalSetting(GENERAL_SETTING_ANCHORS.autoSaveDelay, {
title: translate('auto.components.settings.general.search.d9168badd2', 'Auto save delay'),
@@ -11,6 +11,7 @@ export const GENERAL_SETTING_ANCHORS = {
autoSaveDelay: 'general-editor-auto-save-delay',
formatOnSave: 'general-editor-format-on-save',
finalNewline: 'general-editor-final-newline',
endOfLine: 'general-editor-end-of-line',
fontFamily: 'general-editor-font-family',
fontSize: 'general-editor-font-size',
fontWeight: 'general-editor-font-weight',
@@ -46,6 +47,7 @@ export const GENERAL_SETTING_OWNERS: Readonly<Record<string, GeneralSubPage | nu
[GENERAL_SETTING_ANCHORS.autoSaveDelay]: 'editor',
[GENERAL_SETTING_ANCHORS.formatOnSave]: 'editor',
[GENERAL_SETTING_ANCHORS.finalNewline]: 'editor',
[GENERAL_SETTING_ANCHORS.endOfLine]: 'editor',
[GENERAL_SETTING_ANCHORS.fontFamily]: 'editor',
[GENERAL_SETTING_ANCHORS.fontSize]: 'editor',
[GENERAL_SETTING_ANCHORS.fontWeight]: 'editor',
+8
View File
@@ -1459,6 +1459,14 @@
"keywordEndOfFile": "end of file",
"62aa3336d9": "Insert final newline"
},
"editorEndOfLine": {
"title": "End of line",
"description": "Line ending for new files and files with no line breaks yet. Auto follows the system that runs the file’s workspace: LF for Linux, macOS, and WSL, CRLF for Windows. Files with line breaks keep theirs.",
"keywordLineEnding": "line ending",
"auto": "Auto",
"lf": "LF",
"crlf": "CRLF"
},
"repositoryFormatter": {
"description": "Use this project’s formatter for Format on Save.",
"saveFailed": "Could not save formatter settings.",
@@ -101,7 +101,7 @@ export type ExecutionHostTarget = {
sshOwnerEnvironmentId: string | null
}
function resolveHostPlatform(
export function resolveHostPlatform(
state: HostFactsState,
args: ExecutionHostTarget & {
workspacePath: string | null | undefined
@@ -8,6 +8,7 @@ import { migrateHydratedEditorTabsAndGroups } from './hydrated-editor-file-ids'
import { renameEditorFilesThroughLayoutOwner } from '../tabs/editor-file-rename-through-layout-owner'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/workspace-layout/layout-owner-switch'
import { rekeyEditorBytesDocuments } from '@/components/editor/save/bytes/editor-bytes-document-boxes'
import { handOffRenamedEditorModels } from '@/components/editor/model-lifetime/identity/editor-model-rename-handoff'
// The store change is pure, so a layout-owner build applies it in the frame that shows main's rename.
export type RekeyOpenFilesPatch =
@@ -170,6 +171,7 @@ export function createRekeyOpenFilesAction(
return s
}
rekeyEditorBytesDocuments(rekeys)
handOffRenamedEditorModels(s, rekeys)
return next.patch
})
return result
@@ -19,6 +19,7 @@ import { isEditorTabContentType } from './editor-tab-content-type'
import { restorableEditorFile } from './editor-tab-layout-owner'
import { layoutEditorViewOfOpenFile } from './open-file-layout-view'
import { rekeyEditorBytesDocuments } from '@/components/editor/save/bytes/editor-bytes-document-boxes'
import { handOffRenamedEditorModels } from '@/components/editor/model-lifetime/identity/editor-model-rename-handoff'
/** Main's renames: an edit-mode file's record moves from its old path; a view takes the new one. */
function renamesOf(
@@ -90,6 +91,7 @@ export function renameEditorFilesThroughLayoutOwner(
}
// Why here: this runs as the rename lands, so the old tab's close never frees its bytes.
rekeyEditorBytesDocuments(own)
handOffRenamedEditorModels(s, own)
return next.patch
}
// Each file's own workspace: the same path can be open in more than one.
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { normalizeEditorEndOfLine, resolveNewModelLineEnding } from './editor-end-of-line'
describe('resolveNewModelLineEnding', () => {
it('follows the owning host on auto', () => {
const resolve = (hostPlatform: NodeJS.Platform | null) =>
resolveNewModelLineEnding({ setting: 'auto', hostPlatform, language: 'plaintext' })
expect(resolve('linux')).toBe('\n')
expect(resolve('darwin')).toBe('\n')
expect(resolve('win32')).toBe('\r\n')
expect(resolve(null)).toBeNull()
})
it('lets an explicit choice override the host', () => {
expect(
resolveNewModelLineEnding({ setting: 'lf', hostPlatform: 'win32', language: 'typescript' })
).toBe('\n')
expect(
resolveNewModelLineEnding({ setting: 'crlf', hostPlatform: 'linux', language: 'typescript' })
).toBe('\r\n')
})
it('keeps the built-in LF default for shell scripts', () => {
expect(
resolveNewModelLineEnding({ setting: 'crlf', hostPlatform: 'win32', language: 'shellscript' })
).toBeNull()
})
it('treats missing or unknown settings as auto', () => {
expect(normalizeEditorEndOfLine(undefined)).toBe('auto')
expect(normalizeEditorEndOfLine('cr')).toBe('auto')
})
})
@@ -0,0 +1,31 @@
export type EditorEndOfLine = 'auto' | 'lf' | 'crlf'
export type EditorLineEnding = '\n' | '\r\n'
export const DEFAULT_EDITOR_END_OF_LINE: EditorEndOfLine = 'auto'
export function normalizeEditorEndOfLine(value: unknown): EditorEndOfLine {
return value === 'lf' || value === 'crlf' ? value : DEFAULT_EDITOR_END_OF_LINE
}
/**
* The ending a model with no line breaks yet should adopt; null keeps the editor's default.
* Auto follows the OS of the host that owns the file, not the OS this window runs on.
*/
export function resolveNewModelLineEnding(args: {
setting: unknown
hostPlatform: NodeJS.Platform | null
language: string
}): EditorLineEnding | null {
// Why: the editor's built-in [shellscript] default is LF and outranks the global choice.
if (args.language === 'shellscript') {
return null
}
const setting = normalizeEditorEndOfLine(args.setting)
if (setting !== 'auto') {
return setting === 'crlf' ? '\r\n' : '\n'
}
if (!args.hostPlatform) {
return null
}
return args.hostPlatform === 'win32' ? '\r\n' : '\n'
}
@@ -1,4 +1,8 @@
import type { EditorEndOfLine } from './editor-end-of-line'
export type EditorSaveSettings = {
editorFormatOnSave?: boolean
editorInsertFinalNewline?: boolean
/** Line ending for files with no line breaks yet; absent means auto. */
editorEndOfLine?: EditorEndOfLine
}
@@ -64,6 +64,7 @@ export function buildDefaultSettings(args: {
editorAutoSave: false,
editorFormatOnSave: false,
editorInsertFinalNewline: false,
editorEndOfLine: 'auto',
editorAutoSaveDelayMs: args.editorAutoSaveDelayMs,
editorMinimapEnabled: false,
// Why empty: the editor keeps following the terminal font unless the user opts in.