From 77a6c146292c48457a8628c851059338ae0bc80f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 03:28:37 +0000 Subject: [PATCH 1/7] repl: keep multi-line history entries on one line of the history file History::save wrote each entry verbatim followed by '\n', so an entry that was typed over several lines occupied several lines of ~/.bun_repl_history, and History::load (which splits on '\n') brought it back as one entry per fragment in the next session. Store the newlines inside an entry as '\r' on save and turn them back on load, the encoding node's repl history uses. The line editor reads a typed '\r' as Enter, so no entry contains one and the decode cannot alter a real entry. load strips a CRLF line ending before decoding, so a file rewritten with CRLF endings does not gain a trailing newline per entry. In-memory entries are unchanged, so .history, recall and .save behave as before. Co-authored-by: Samuel --- src/runtime/cli/repl.rs | 29 ++++++++- test/js/bun/repl/repl.test.ts | 111 ++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+), 3 deletions(-) diff --git a/src/runtime/cli/repl.rs b/src/runtime/cli/repl.rs index 553d90cf2ba1..cbf354e4b9d8 100644 --- a/src/runtime/cli/repl.rs +++ b/src/runtime/cli/repl.rs @@ -172,6 +172,23 @@ struct History { modified: bool, } +/// Copies `entry` to `out`, replacing each `from` with `to`. +/// +/// The history file holds one entry per line, so `save` stores the newlines of +/// a multi-line entry as `\r` and `load` turns them back (the encoding node's +/// repl history uses). `\r` is free for this because the line editor reads a +/// typed `\r` as Enter, so no entry contains one. +fn append_swapping_line_breaks(out: &mut Vec, entry: &[u8], from: &[u8], to: u8) { + let mut segments = strings::split(entry, from); + if let Some(first) = segments.next() { + out.extend_from_slice(first); + } + for segment in segments { + out.push(to); + out.extend_from_slice(segment); + } +} + impl History { fn init() -> History { History { @@ -204,9 +221,15 @@ impl History { }; for line in strings::split(&content, b"\n") { - if !line.is_empty() { - self.entries.push(Box::<[u8]>::from(line)); + // A CRLF line ending (file rewritten on Windows) is not part of the + // entry; drop it before the remaining CRs are decoded as newlines. + let line = strings::trim_suffix(line, b"\r"); + if line.is_empty() { + continue; } + let mut entry: Vec = Vec::with_capacity(line.len()); + append_swapping_line_breaks(&mut entry, line, b"\r", b'\n'); + self.entries.push(entry.into_boxed_slice()); } // Trim to max size @@ -235,7 +258,7 @@ impl History { let mut content: Vec = Vec::new(); for entry in &self.entries[start..] { - content.extend_from_slice(entry); + append_swapping_line_breaks(&mut content, entry, b"\n", b'\r'); content.push(b'\n'); } diff --git a/test/js/bun/repl/repl.test.ts b/test/js/bun/repl/repl.test.ts index 403342009aa3..377bbdbe61ba 100644 --- a/test/js/bun/repl/repl.test.ts +++ b/test/js/bun/repl/repl.test.ts @@ -1266,6 +1266,117 @@ describe.skipIf(isWindows)("REPL history file permissions", () => { }); }); +describe.concurrent("REPL history file", () => { + // $HOME/.bun_repl_history holds one entry per line; the newlines inside a + // multi-line entry are written as '\r' so the entry survives a restart. + const ARROW_UP = "\x1b[A"; + + async function runReplWithHome(home: string, input: string[]) { + const { stdout, stderr, exitCode } = await runRepl(input, { env: { HOME: home, USERPROFILE: home } }); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + const out = stripAnsi(stdout); + // Everything after the banner. With piped stdin the input is not echoed; + // the output is a "> " prompt each time the REPL is back at top level + // plus whatever each input printed. + return out.slice(out.indexOf("> ")); + } + + // The physical lines of the history file (the last one is the "" after the + // final newline). + async function savedLines(home: string) { + const content = await Bun.file(path.join(home, ".bun_repl_history")).text(); + return content.split("\n"); + } + + test("multi-line entry is saved on one line and reloads as one entry", async () => { + using dir = tempDir("repl-history-multiline", {}); + const home = String(dir); + + await runReplWithHome(home, ["function f() {", " return 1", "}", ".exit"]); + + expect(await savedLines(home)).toEqual(["function f() {\r return 1\r}", ""]); + + // Next session: recall the entry with the up arrow and run it, then list + // the history. The recalled entry defines f, and re-running it does not + // add a duplicate entry. + const session = await runReplWithHome(home, [ARROW_UP, "f()", ".history", ".exit"]); + expect(session).toMatchInlineSnapshot(` + "> + undefined + > + 1 + > + + Command History: + 1 function f() { + return 1 + } + 2 f() + + > + " + `); + }); + + test("entries with blank lines round-trip in order", async () => { + using dir = tempDir("repl-history-mixed", {}); + const home = String(dir); + + await runReplWithHome(home, ["const a = 1", "function g() {", "", " return 2", "}", "const b = 3", ".exit"]); + + expect(await savedLines(home)).toEqual(["const a = 1", "function g() {\r\r return 2\r}", "const b = 3", ""]); + + const session = await runReplWithHome(home, [".history", ".exit"]); + expect(session).toMatchInlineSnapshot(` + "> + + Command History: + 1 const a = 1 + 2 function g() { + + return 2 + } + 3 const b = 3 + + > + " + `); + }); + + test("loads a CRLF history file without keeping the line endings", async () => { + // A history file rewritten with CRLF line endings (Windows, or a CRLF + // editor): the '\r' before each '\n' is part of the line ending, while + // the ones inside the second entry are its stored newlines. + using dir = tempDir("repl-history-crlf", { + ".bun_repl_history": "1 + 1\r\nfunction h() {\r return 3\r}\r\n", + }); + const home = String(dir); + + const session = await runReplWithHome(home, [".history", "2 + 2", ".exit"]); + // Snapshot matching tolerates CRLF, so check for a leaked '\r' explicitly. + expect(session).not.toContain("\r"); + expect(session).toMatchInlineSnapshot(` + "> + + Command History: + 1 1 + 1 + 2 function h() { + return 3 + } + + > + 4 + > + " + `); + + // Re-saved with plain '\n' line endings; the stored newlines inside the + // multi-line entry are kept. + expect(await savedLines(home)).toEqual(["1 + 1", "function h() {\r return 3\r}", "2 + 2", ""]); + }); +}); + // `bun --interactive` boots the full node:repl + readline + acorn stack; on a // debug+asan build that is ~4–5s per spawn, so the 5s default is too tight. const interactiveTimeout = 20_000; From 37012f89aba6b37b567edf36149ca9b586cce8db Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:30:59 +0000 Subject: [PATCH 2/7] repl: use strings::replace_owned for the history line-break encoding The local split-and-copy helper duplicated strings::replace_owned; both history sites now call that directly. The encoding and the invariants it relies on are documented once, at the save site, and the CRLF comments no longer attribute CRLF files to Windows (bun itself never writes CRLF to the history file; only an external editor does). --- src/runtime/cli/repl.rs | 32 +++++++++----------------------- test/js/bun/repl/repl.test.ts | 6 +++--- 2 files changed, 12 insertions(+), 26 deletions(-) diff --git a/src/runtime/cli/repl.rs b/src/runtime/cli/repl.rs index cbf354e4b9d8..3d782cb07ab8 100644 --- a/src/runtime/cli/repl.rs +++ b/src/runtime/cli/repl.rs @@ -172,23 +172,6 @@ struct History { modified: bool, } -/// Copies `entry` to `out`, replacing each `from` with `to`. -/// -/// The history file holds one entry per line, so `save` stores the newlines of -/// a multi-line entry as `\r` and `load` turns them back (the encoding node's -/// repl history uses). `\r` is free for this because the line editor reads a -/// typed `\r` as Enter, so no entry contains one. -fn append_swapping_line_breaks(out: &mut Vec, entry: &[u8], from: &[u8], to: u8) { - let mut segments = strings::split(entry, from); - if let Some(first) = segments.next() { - out.extend_from_slice(first); - } - for segment in segments { - out.push(to); - out.extend_from_slice(segment); - } -} - impl History { fn init() -> History { History { @@ -221,15 +204,14 @@ impl History { }; for line in strings::split(&content, b"\n") { - // A CRLF line ending (file rewritten on Windows) is not part of the - // entry; drop it before the remaining CRs are decoded as newlines. + // Tolerate a file re-saved with CRLF line endings: that CR is not part + // of the entry, unlike the ones inside the line (see save()). let line = strings::trim_suffix(line, b"\r"); if line.is_empty() { continue; } - let mut entry: Vec = Vec::with_capacity(line.len()); - append_swapping_line_breaks(&mut entry, line, b"\r", b'\n'); - self.entries.push(entry.into_boxed_slice()); + self.entries + .push(strings::replace_owned(line, b"\r", b"\n").into_boxed_slice()); } // Trim to max size @@ -258,7 +240,11 @@ impl History { let mut content: Vec = Vec::new(); for entry in &self.entries[start..] { - append_swapping_line_breaks(&mut content, entry, b"\n", b'\r'); + // One entry per line: the newlines of a multi-line entry are stored as + // CR, as node's repl history does. This is lossless because an entry + // never contains a CR (Key::from_byte reads it as Enter) and never ends + // in a newline (handle_enter trims them), so load() can undo it exactly. + content.extend_from_slice(&strings::replace_owned(entry, b"\n", b"\r")); content.push(b'\n'); } diff --git a/test/js/bun/repl/repl.test.ts b/test/js/bun/repl/repl.test.ts index 377bbdbe61ba..fc9e8bd19f5a 100644 --- a/test/js/bun/repl/repl.test.ts +++ b/test/js/bun/repl/repl.test.ts @@ -1345,9 +1345,9 @@ describe.concurrent("REPL history file", () => { }); test("loads a CRLF history file without keeping the line endings", async () => { - // A history file rewritten with CRLF line endings (Windows, or a CRLF - // editor): the '\r' before each '\n' is part of the line ending, while - // the ones inside the second entry are its stored newlines. + // A history file re-saved by a CRLF editor: the '\r' before each '\n' is + // part of the line ending, while the ones inside the second entry are its + // stored newlines. using dir = tempDir("repl-history-crlf", { ".bun_repl_history": "1 + 1\r\nfunction h() {\r return 3\r}\r\n", }); From d6575e21b85e92ecc922fedb3581836cdf2045f1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:11:52 +0000 Subject: [PATCH 3/7] repl: name the stored-newline byte and document it on the constant Both history sites now read the byte from HISTORY_STORED_NEWLINE, whose doc comment is the one place the file encoding is described; the inline comments at the save and load sites are gone, except a one-liner on the CRLF trim saying why it cannot eat entry content. --- src/runtime/cli/repl.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/runtime/cli/repl.rs b/src/runtime/cli/repl.rs index 3d782cb07ab8..a78555ded5f1 100644 --- a/src/runtime/cli/repl.rs +++ b/src/runtime/cli/repl.rs @@ -62,6 +62,10 @@ unsafe extern "C" { const MAX_HISTORY_SIZE: usize = 1000; const HISTORY_FILENAME: &[u8] = b".bun_repl_history"; +/// The history file holds one entry per line, so the newlines inside a +/// multi-line entry are stored as this byte instead (as node's repl history +/// does). Nothing else puts a CR in an entry: the line editor reads it as Enter. +const HISTORY_STORED_NEWLINE: &[u8] = b"\r"; // ANSI escape codes const CSI: &str = concat!("\x1b", "["); @@ -204,14 +208,13 @@ impl History { }; for line in strings::split(&content, b"\n") { - // Tolerate a file re-saved with CRLF line endings: that CR is not part - // of the entry, unlike the ones inside the line (see save()). + // A CRLF line ending; never entry content, since add() gets newline-trimmed input. let line = strings::trim_suffix(line, b"\r"); if line.is_empty() { continue; } - self.entries - .push(strings::replace_owned(line, b"\r", b"\n").into_boxed_slice()); + let entry = strings::replace_owned(line, HISTORY_STORED_NEWLINE, b"\n"); + self.entries.push(entry.into_boxed_slice()); } // Trim to max size @@ -240,11 +243,8 @@ impl History { let mut content: Vec = Vec::new(); for entry in &self.entries[start..] { - // One entry per line: the newlines of a multi-line entry are stored as - // CR, as node's repl history does. This is lossless because an entry - // never contains a CR (Key::from_byte reads it as Enter) and never ends - // in a newline (handle_enter trims them), so load() can undo it exactly. - content.extend_from_slice(&strings::replace_owned(entry, b"\n", b"\r")); + let stored = strings::replace_owned(entry, b"\n", HISTORY_STORED_NEWLINE); + content.extend_from_slice(&stored); content.push(b'\n'); } From aa5d213baf1381194d1d000adb6038d62f26b417 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:24:29 +0000 Subject: [PATCH 4/7] repl: shorten the HISTORY_STORED_NEWLINE doc comment to one line --- src/runtime/cli/repl.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/runtime/cli/repl.rs b/src/runtime/cli/repl.rs index a78555ded5f1..a5d5d33d39a9 100644 --- a/src/runtime/cli/repl.rs +++ b/src/runtime/cli/repl.rs @@ -62,9 +62,7 @@ unsafe extern "C" { const MAX_HISTORY_SIZE: usize = 1000; const HISTORY_FILENAME: &[u8] = b".bun_repl_history"; -/// The history file holds one entry per line, so the newlines inside a -/// multi-line entry are stored as this byte instead (as node's repl history -/// does). Nothing else puts a CR in an entry: the line editor reads it as Enter. +/// Replaces an entry's inner newlines in the one-entry-per-line file (entries never contain CR). const HISTORY_STORED_NEWLINE: &[u8] = b"\r"; // ANSI escape codes From 2c23b06e8440b8c37bc3e0bea18b5bfb8a311f5d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 11:19:39 +0000 Subject: [PATCH 5/7] ci: retrigger From 718d951f103c0f22dada99282da6de565429d030 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 19:23:46 +0000 Subject: [PATCH 6/7] test(repl): cover a CRLF history file of single-line entries The trailing-CR strip in History::load is the fix from #30293 (carried by #36510 until this PR superseded it). Add that PR's case as its own test: a history file of ordinary entries with CRLF line endings loads without a '\r' on any entry and is written back with LF endings. Co-authored-by: Samuel --- test/js/bun/repl/repl.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/test/js/bun/repl/repl.test.ts b/test/js/bun/repl/repl.test.ts index fc9e8bd19f5a..583df232bcee 100644 --- a/test/js/bun/repl/repl.test.ts +++ b/test/js/bun/repl/repl.test.ts @@ -1375,6 +1375,33 @@ describe.concurrent("REPL history file", () => { // multi-line entry are kept. expect(await savedLines(home)).toEqual(["1 + 1", "function h() {\r return 3\r}", "2 + 2", ""]); }); + + test("a CRLF file of single-line entries loads and is re-saved without the CRs", async () => { + // A history file written on Windows, or edited in a CRLF editor: every '\r' + // is part of a line ending, so none of them may end up in an entry, where + // it would show in recall and .history and be written back on every save. + using dir = tempDir("repl-history-crlf-single-line", { + ".bun_repl_history": "old_one\r\nold_two\r\n", + }); + const home = String(dir); + + const session = await runReplWithHome(home, [".history", "2 + 2", ".exit"]); + expect(session).not.toContain("\r"); + expect(session).toMatchInlineSnapshot(` + "> + + Command History: + 1 old_one + 2 old_two + + > + 4 + > + " + `); + + expect(await savedLines(home)).toEqual(["old_one", "old_two", "2 + 2", ""]); + }); }); // `bun --interactive` boots the full node:repl + readline + acorn stack; on a From 77b5eb966138d52bb07b96851149dc6381b0fbe1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 21 Oct 2026 08:41:36 +0000 Subject: [PATCH 7/7] test(repl): pass the history directory with the home option of runRepl runRepl sets HOME and USERPROFILE after it spreads options.env, so a HOME passed in env does not reach the REPL. The history file tests passed the directory in env, then read a directory that the REPL never used. The tests now pass the directory with the home option. They compare outputs with toEqual and check stderr, as the other tests in the file do. --- test/js/bun/repl/repl.test.ts | 122 +++++++++++----------------------- 1 file changed, 39 insertions(+), 83 deletions(-) diff --git a/test/js/bun/repl/repl.test.ts b/test/js/bun/repl/repl.test.ts index 5b629523be8c..574e8980b3b1 100644 --- a/test/js/bun/repl/repl.test.ts +++ b/test/js/bun/repl/repl.test.ts @@ -1873,22 +1873,11 @@ describe.skipIf(isWindows).concurrent("REPL history file permissions", () => { }); }); +// $HOME/.bun_repl_history holds one entry per line. The newlines inside a +// multi-line entry are written as '\r', so the entry survives a restart. describe.concurrent("REPL history file", () => { - // $HOME/.bun_repl_history holds one entry per line; the newlines inside a - // multi-line entry are written as '\r' so the entry survives a restart. const ARROW_UP = "\x1b[A"; - async function runReplWithHome(home: string, input: string[]) { - const { stdout, stderr, exitCode } = await runRepl(input, { env: { HOME: home, USERPROFILE: home } }); - expect(stderr).toBe(""); - expect(exitCode).toBe(0); - const out = stripAnsi(stdout); - // Everything after the banner. With piped stdin the input is not echoed; - // the output is a "> " prompt each time the REPL is back at top level - // plus whatever each input printed. - return out.slice(out.indexOf("> ")); - } - // The physical lines of the history file (the last one is the "" after the // final newline). async function savedLines(home: string) { @@ -1900,55 +1889,42 @@ describe.concurrent("REPL history file", () => { using dir = tempDir("repl-history-multiline", {}); const home = String(dir); - await runReplWithHome(home, ["function f() {", " return 1", "}", ".exit"]); - + const first = await runRepl(["function f() {", " return 1", "}", ".exit"], { home }); + expect(first.outputs).toEqual(["undefined"]); + expect(first.stderr).toBe(""); + expect(first.exitCode).toBe(0); expect(await savedLines(home)).toEqual(["function f() {\r return 1\r}", ""]); - // Next session: recall the entry with the up arrow and run it, then list - // the history. The recalled entry defines f, and re-running it does not - // add a duplicate entry. - const session = await runReplWithHome(home, [ARROW_UP, "f()", ".history", ".exit"]); - expect(session).toMatchInlineSnapshot(` - "> - undefined - > - 1 - > - - Command History: - 1 function f() { - return 1 - } - 2 f() - - > - " - `); + // Next session: the up arrow recalls the entry and Enter runs it, which + // defines f. Running it again adds no second entry. + const second = await runRepl([ARROW_UP, "f()", ".history", ".exit"], { home }); + expect(second.outputs).toEqual([ + "undefined", + "1", + "Command History:\n 1 function f() {\n return 1\n}\n 2 f()", + ]); + expect(second.stderr).toBe(""); + expect(second.exitCode).toBe(0); }); test("entries with blank lines round-trip in order", async () => { using dir = tempDir("repl-history-mixed", {}); const home = String(dir); - await runReplWithHome(home, ["const a = 1", "function g() {", "", " return 2", "}", "const b = 3", ".exit"]); - + const first = await runRepl(["const a = 1", "function g() {", "", " return 2", "}", "const b = 3", ".exit"], { + home, + }); + expect(first.outputs).toEqual(["1", "undefined", "3"]); + expect(first.stderr).toBe(""); + expect(first.exitCode).toBe(0); expect(await savedLines(home)).toEqual(["const a = 1", "function g() {\r\r return 2\r}", "const b = 3", ""]); - const session = await runReplWithHome(home, [".history", ".exit"]); - expect(session).toMatchInlineSnapshot(` - "> - - Command History: - 1 const a = 1 - 2 function g() { - - return 2 - } - 3 const b = 3 - - > - " - `); + const second = await runRepl([".history", ".exit"], { home }); + expect(second.outputs).toEqual([ + "Command History:\n 1 const a = 1\n 2 function g() {\n\n return 2\n}\n 3 const b = 3", + ]); + expect(second.stderr).toBe(""); + expect(second.exitCode).toBe(0); }); test("loads a CRLF history file without keeping the line endings", async () => { @@ -1960,23 +1936,12 @@ describe.concurrent("REPL history file", () => { }); const home = String(dir); - const session = await runReplWithHome(home, [".history", "2 + 2", ".exit"]); - // Snapshot matching tolerates CRLF, so check for a leaked '\r' explicitly. - expect(session).not.toContain("\r"); - expect(session).toMatchInlineSnapshot(` - "> - - Command History: - 1 1 + 1 - 2 function h() { - return 3 - } - - > - 4 - > - " - `); + const { stdout, outputs, stderr, exitCode } = await runRepl([".history", "2 + 2", ".exit"], { home }); + // A leaked '\r' does not show in the diff of a failed toEqual, so name it first. + expect(stdout).not.toContain("\r"); + expect(outputs).toEqual(["Command History:\n 1 1 + 1\n 2 function h() {\n return 3\n}", "4"]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); // Re-saved with plain '\n' line endings; the stored newlines inside the // multi-line entry are kept. @@ -1992,20 +1957,11 @@ describe.concurrent("REPL history file", () => { }); const home = String(dir); - const session = await runReplWithHome(home, [".history", "2 + 2", ".exit"]); - expect(session).not.toContain("\r"); - expect(session).toMatchInlineSnapshot(` - "> - - Command History: - 1 old_one - 2 old_two - - > - 4 - > - " - `); + const { stdout, outputs, stderr, exitCode } = await runRepl([".history", "2 + 2", ".exit"], { home }); + expect(stdout).not.toContain("\r"); + expect(outputs).toEqual(["Command History:\n 1 old_one\n 2 old_two", "4"]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); expect(await savedLines(home)).toEqual(["old_one", "old_two", "2 + 2", ""]); });