Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Ask zsh which prompt it shows, and name the function that sets it

Țugui Dragoș5fc8d43175bc
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 48ca0766..bc5f2b34 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -295,6 +295,8 @@ macOS asks the user to approve it once. It talks to the app over XPC.
since as it is, and returns a setting the person made themselves to Git's default.
- A setting is offered only when the tool on the Mac knows it: zsh lists its options and functions
(`ZshRequirements`), Git its keys (`git help --config`), and ssh accepts the options on its own command line.
+ zsh is also asked which `.zshrc` it reads and, while Peel's prompt is on, which prompt a new window shows
+ (`ShellSessions`), by running it with the person's startup files as Terminal does; Peel changes none of them.
The Tools tab installs nothing: `TerminalTool` gives each tool's Homebrew formulae and the lines its
documentation gives, and Homebrew is asked whether it still offers them.
- **Peel's own updates.** Sparkle, built from its source by `Scripts/build_sparkle.sh`, reads Peel's signed feed
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 3ba14495..df5cf843 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -9021,6 +9021,112 @@
}
}
},
+ "A function your zsh runs before each command, %@, sets its own prompt, so zsh shows that one." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Funkce %@, kterou váš zsh spouští před každým příkazem, nastavuje vlastní výzvu, takže zsh zobrazuje tu její."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Die Funktion %@, die deine zsh vor jedem Befehl ausführt, legt eine eigene Eingabeaufforderung fest, daher zeigt zsh diese an."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Una función que tu zsh ejecuta antes de cada comando, %@, establece su propio indicador, así que zsh muestra ese."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Une fonction que votre zsh exécute avant chaque commande, %@, définit sa propre invite de commande : c’est donc celle-ci que zsh affiche."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Una funzione che il tuo zsh esegue prima di ogni comando, %@, imposta un proprio prompt, quindi zsh mostra quel prompt."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "お使いのzshが各コマンドの前に実行する%@という関数は、独自のプロンプトを設定しているため、zshはそちらのプロンプトを表示します。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "사용자의 zsh가 명령을 입력하기 전에 매번 실행하는 %@ 함수가 자체 프롬프트를 설정하므로 zsh는 그 프롬프트를 표시합니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Een functie die je zsh vóór elk commando uitvoert, %@, stelt een eigen prompt in, dus zsh toont die prompt."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Funkcja %@, którą Twoja powłoka zsh uruchamia przed każdym poleceniem, ustawia własny znak zachęty, więc zsh wyświetla właśnie ten."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Uma função que o seu zsh executa antes de cada comando, %@, define um prompt próprio, então é esse que o zsh mostra."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O funcție pe care zsh‑ul dvs. o rulează înaintea fiecărei comenzi, %@, își stabilește propriul prompt, așa că zsh îl afișează pe acesta."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Функция %@, которую Ваш zsh выполняет перед каждой командой, задает собственное приглашение ввода, поэтому zsh показывает именно его."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "En funktion som din zsh kör före varje kommando, %@, ställer in sin egen prompt, så det är den som zsh visar."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "zsh kabuğunuzun her komuttan önce çalıştırdığı %@ işlevi kendi bilgi istemini ayarlıyor, bu yüzden zsh o bilgi istemini gösteriyor."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Функція %@, яку ваш zsh виконує перед кожною командою, задає власне запрошення, тож zsh показує саме його."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的zsh在每条命令前运行的函数%@设置了自己的提示符,因此zsh会显示那个提示符。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的zsh在每個指令之前執行的函式%@設定了它自己的提示行,因此zsh會顯示該提示行。"
+ }
+ }
+ }
+ },
"A group the app belongs to" : {
"localizations" : {
"cs" : {
@@ -188886,6 +188992,112 @@
}
}
},
+ "Your zsh sets its own prompt after Peel’s file is read, so zsh shows that one." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Váš zsh nastavuje vlastní výzvu až po přečtení souboru Peelu, takže zsh zobrazuje tu svou."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Deine zsh legt nach dem Einlesen der Datei von Peel eine eigene Eingabeaufforderung fest, daher zeigt zsh diese an."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tu zsh establece su propio indicador después de leer el archivo de Peel, así que zsh muestra ese."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Votre zsh définit sa propre invite de commande après la lecture du fichier de Peel : c’est donc celle-ci que zsh affiche."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Il tuo zsh imposta un proprio prompt dopo aver letto il file di Peel, quindi zsh mostra quel prompt."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "お使いのzshは、Peelのファイルを読み込んだ後で独自のプロンプトを設定しているため、zshはそちらのプロンプトを表示します。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "사용자의 zsh가 Peel의 파일을 읽은 뒤에 자체 프롬프트를 설정하므로 zsh는 그 프롬프트를 표시합니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Je zsh stelt een eigen prompt in nadat het bestand van Peel is gelezen, dus zsh toont die prompt."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Twoja powłoka zsh ustawia własny znak zachęty po odczytaniu pliku Peel, więc zsh wyświetla właśnie ten."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O seu zsh define um prompt próprio depois que o arquivo do Peel é lido, então é esse que o zsh mostra."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "zsh‑ul dvs. își stabilește propriul prompt după citirea fișierului Peel, așa că zsh îl afișează pe acesta."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ваш zsh задает собственное приглашение ввода после чтения файла Peel, поэтому zsh показывает именно его."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Din zsh ställer in sin egen prompt efter att Peels fil har lästs, så det är den som zsh visar."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "zsh kabuğunuz, Peel’in dosyası okunduktan sonra kendi bilgi istemini ayarlıyor, bu yüzden zsh o bilgi istemini gösteriyor."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ваш zsh задає власне запрошення після того, як прочитає файл Peel, тож zsh показує саме його."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的zsh在读取Peel的文件之后设置了自己的提示符,因此zsh会显示那个提示符。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的zsh在讀取Peel的檔案之後設定了它自己的提示行,因此zsh會顯示該提示行。"
+ }
+ }
+ }
+ },
"You’re all set" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/Prompt.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/Prompt.swift
index ea7f48d0..73a5e5b5 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/Prompt.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/Prompt.swift
@@ -79,7 +79,9 @@ public struct Prompt: Hashable, Sendable {
"setopt PROMPT_SUBST",
]
- public var lines: [String] {
+ /// What `PROMPT` holds once zsh has read Peel's line: the prompt's codes, with the symbol on a line of its own
+ /// after a newline when it is.
+ public var value: String {
let before = switch start {
case .folder: "%F{cyan}%1~%f"
case .path: "%F{cyan}%~%f"
@@ -88,9 +90,12 @@ public struct Prompt: Hashable, Sendable {
let branch = showsBranch ? "${vcs_info_msg_0_}" : ""
let mark = symbol == .percent ? "%%" : symbol.rawValue
let symbol = turnsRedAfterAFailure ? "%(?.%F{green}.%F{red})\(mark)%f" : "%F{green}\(mark)%f"
- let prompt = isOnItsOwnLine
- ? "PROMPT=$'\(before)\(branch)\\n\(symbol) '"
- : "PROMPT='\(before)\(branch) \(symbol) '"
+ return "\(before)\(branch)\(isOnItsOwnLine ? "\n" : " ")\(symbol) "
+ }
+
+ /// The lines that set `PROMPT` to `value`: a newline is written as `\n` in `$'…'`, which zsh reads as one.
+ public var lines: [String] {
+ let prompt = isOnItsOwnLine ? "PROMPT=$'\(value.replacing("\n", with: "\\n"))'" : "PROMPT='\(value)'"
return (showsBranch ? Self.branchLines : []) + [prompt]
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
index dd3e64fb..abc4bd89 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
@@ -59,6 +59,56 @@ public enum ShellSessions: Sendable, Equatable {
.appending(path: ".zshrc", directoryHint: .notDirectory)
}
+ /// The prompt a new zsh shows, as zsh itself answers.
+ public struct ShownPrompt: Equatable, Sendable {
+ /// What `PROMPT` holds once every startup file has run and the hooks zsh runs before a prompt have run.
+ public let prompt: String
+ /// The functions zsh runs before each prompt that changed it, in the order they ran: a prompt they set wins
+ /// over any `PROMPT=` line, wherever it stands.
+ public let setBeforeEachCommandBy: [String]
+ }
+
+ public func promptShown(home: URL = .homeDirectory) async -> ShownPrompt? {
+ await promptShown(home: home, zdotdir: Self.sessionZDOTDIR)
+ }
+
+ /// Asks zsh for the prompt it shows: a login shell started as Terminal starts one, with the same environment,
+ /// that reads every startup file, runs the `precmd` hooks as it would before its first prompt and prints
+ /// `PROMPT` between marks, so what the startup files print before and `.zlogout` after is passed over. Nil when
+ /// the shell is not zsh or zsh did not answer in time.
+ func promptShown(home: URL, zdotdir: String?) async -> ShownPrompt? {
+ guard case .zsh = self else { return nil }
+ var environment = [
+ "HOME": (home.path(percentEncoded: false) as NSString).standardizingPath,
+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",
+ "TERM": "xterm-256color",
+ ]
+ if let zdotdir, !zdotdir.isEmpty {
+ environment["ZDOTDIR"] = (zdotdir as NSString).standardizingPath
+ }
+ let script = """
+ typeset -g peel_was="$PROMPT"; typeset -ga peel_by=()
+ for peel_f in $precmd_functions; do
+ "$peel_f" 2>/dev/null
+ if [[ "$PROMPT" != "$peel_was" ]]; then peel_by+=("$peel_f"); peel_was="$PROMPT"; fi
+ done
+ if (( $+functions[precmd] )); then
+ precmd 2>/dev/null
+ if [[ "$PROMPT" != "$peel_was" ]]; then peel_by+=(precmd); fi
+ fi
+ print -rn -- $'\\0Peel\\0'"$PROMPT"; for peel_f in $peel_by; do print -rn -- $'\\0'"$peel_f"; done
+ print -rn -- $'\\0End\\0'
+ """
+ let answer = await Subprocess.run("/bin/zsh", ["-l", "-i", "-c", script], environment: environment, timeout: 10)
+ guard case .success(let output) = answer, output.status == 0 else { return nil }
+ let fields = output.standardOutput.split(separator: 0, omittingEmptySubsequences: false)
+ guard let end = fields.lastIndex(of: Data("End".utf8)), let start = fields[..<end].lastIndex(of: Data("Peel".utf8)),
+ start + 1 < end
+ else { return nil }
+ let texts = fields[(start + 1)..<end].map { String(decoding: $0, as: UTF8.self) }
+ return ShownPrompt(prompt: texts[0], setBeforeEachCommandBy: Array(texts.dropFirst()))
+ }
+
public var name: String {
switch self {
case .zsh: "zsh"
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PromptTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PromptTests.swift
index eca8fc3c..4945ba4c 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PromptTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PromptTests.swift
@@ -20,10 +20,11 @@ struct PromptTests {
#expect(ShellFile.write(.init(prompt: prompt), to: shell.peelFile))
let shown = try shell.output(
of: "cd ~/Projects/peel; (( $+functions[vcs_info] )) && vcs_info; true; print -rnP -- \"${(e)PROMPT}\"; "
- + "print -n '|'; false; print -rnP -- \"${(e)PROMPT}\""
+ + "print -n '|'; false; print -rnP -- \"${(e)PROMPT}\"; print -n '|'; print -rn -- \"$PROMPT\""
)
let parts = shown.split(separator: "|", omittingEmptySubsequences: false).map(String.init)
- #expect(parts.count == 2)
+ #expect(parts.count == 3)
+ #expect(parts.last == prompt.value)
for (part, failed) in zip(parts, [false, true]) {
let sample = prompt.sample(
user: NSUserName(),
@@ -72,6 +73,34 @@ struct PromptTests {
#expect(!ShellFile.setsItsOwnPrompt(after: before.peelFile, in: startup, home: before.home))
}
+ @Test func zshSaysWhichPromptItShowsAndWhatSetItBeforeEachCommand() async throws {
+ let peels = Prompt(start: .path, showsBranch: false, symbol: .dollar, turnsRedAfterAFailure: false)
+ for (lines, prompt, setters) in [
+ ([], peels.value, []),
+ (["precmd() { PROMPT='mine> ' }"], "mine> ", ["precmd"]),
+ (["mine() { PROMPT='hooked> ' }", "autoload -Uz add-zsh-hook", "add-zsh-hook precmd mine"], "hooked> ", ["mine"]),
+ (["first() { PROMPT='one> ' }", "second() { PROMPT='two> ' }", "precmd_functions=(first second)"], "two> ", ["first", "second"]),
+ (["print noise before"], peels.value, []),
+ ] {
+ let shell = try ZshHome(before: lines)
+ try "print noise after\n".write(to: shell.home.appending(path: ".zlogout"), atomically: true, encoding: .utf8)
+ #expect(ShellFile.write(.init(prompt: peels), to: shell.peelFile))
+ let zsh = ShellSessions.zsh(startupFile: shell.home.appending(path: ".zshenv"))
+ let zdotdir = shell.home.path(percentEncoded: false)
+ let shown = try #require(await zsh.promptShown(home: shell.home, zdotdir: zdotdir))
+ #expect(shown.prompt == prompt, "\(lines)")
+ #expect(shown.setBeforeEachCommandBy == setters, "\(lines)")
+ }
+ let after = try ZshHome(thenRun: ["PROMPT='static> '"])
+ #expect(ShellFile.write(.init(prompt: peels), to: after.peelFile))
+ let zsh = ShellSessions.zsh(startupFile: after.home.appending(path: ".zshenv"))
+ let zdotdir = after.home.path(percentEncoded: false)
+ let shown = try #require(await zsh.promptShown(home: after.home, zdotdir: zdotdir))
+ #expect(shown.prompt == "static> ")
+ #expect(shown.setBeforeEachCommandBy.isEmpty)
+ #expect(await ShellSessions.bash.promptShown(home: after.home, zdotdir: nil) == nil)
+ }
+
@Test func aBranchNeedsVcsInfoAndNothingElseNeedsAnything() async throws {
let known = try #require(await ShellFile.knownToZsh())
for prompt in Prompt.all {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift b/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift
index 3b67cfa0..552c6488 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift
@@ -2,16 +2,17 @@ import Foundation
@testable import PeelCore
import Testing
-/// A made-up home whose `.zshrc` sources Peel's file, the way a person's does once they add Peel's line.
+/// A made-up home whose `.zshrc` sources Peel's file, the way a person's does once they add Peel's line, with
+/// `before` above that line and `thenRun` below it.
struct ZshHome {
let home: URL
let peelFile: URL
- init(thenRun lines: [String] = []) throws {
+ init(before: [String] = [], thenRun lines: [String] = []) throws {
home = FileManager.default.temporaryDirectory.appending(path: "ZshHome-\(UUID().uuidString)", directoryHint: .isDirectory)
peelFile = ShellFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
- try ([ShellFile.line(sourcing: peelFile, home: home)] + lines).joined(separator: "\n").appending("\n")
+ try (before + [ShellFile.line(sourcing: peelFile, home: home)] + lines).joined(separator: "\n").appending("\n")
.write(to: home.appending(path: ".zshrc"), atomically: true, encoding: .utf8)
}
diff --git a/Peel/Model/ShellLibrary.swift b/Peel/Model/ShellLibrary.swift
index 5ba38823..2b0882f3 100644
--- a/Peel/Model/ShellLibrary.swift
+++ b/Peel/Model/ShellLibrary.swift
@@ -10,6 +10,8 @@ final class ShellLibrary {
var choices: ShellFile.Choices?
var isSourced: Bool
var setsItsOwnPrompt: Bool
+ /// What zsh answered when asked which prompt it shows, asked only while Peel's prompt is on and its line read.
+ var shownPrompt: ShellSessions.ShownPrompt?
var known: Set<String>?
}
@@ -42,12 +44,19 @@ final class ShellLibrary {
let shell = ShellSessions.inTerminal(TerminalSettings(), home: home)
let startupFile = await shell?.zshrc(home: home)
let choices = ShellFile.read(file)
+ let isSourced = startupFile.map { ShellFile.isSourced(file, from: $0, home: home) } ?? false
+ let shownPrompt: ShellSessions.ShownPrompt? = if choices?.prompt != nil, isSourced {
+ await shell?.promptShown(home: home)
+ } else {
+ nil
+ }
state = State(
shell: shell,
startupFile: startupFile,
choices: choices,
- isSourced: startupFile.map { ShellFile.isSourced(file, from: $0, home: home) } ?? false,
+ isSourced: isSourced,
setsItsOwnPrompt: startupFile.map { ShellFile.setsItsOwnPrompt(after: file, in: $0, home: home) } ?? false,
+ shownPrompt: shownPrompt,
known: known
)
if let prompt = choices?.prompt {
diff --git a/Peel/Views/Terminal/ShellTab.swift b/Peel/Views/Terminal/ShellTab.swift
index b31c3c8b..810146f7 100644
--- a/Peel/Views/Terminal/ShellTab.swift
+++ b/Peel/Views/Terminal/ShellTab.swift
@@ -175,20 +175,10 @@ private struct PromptSection: View {
} header: {
Text("Prompt")
} footer: {
- if prompt != nil, !state.isSourced, let startupFile = state.startupFile {
- StatusLabel(
- title: Text("zsh shows this prompt once Peel’s line is in \(startupFile.abbreviatedPath)."),
- tint: .accentColor
- )
- .font(.caption)
- .foregroundStyle(.secondary)
- } else if prompt != nil, state.setsItsOwnPrompt, let startupFile = state.startupFile {
- StatusLabel(
- title: Text("Your \(startupFile.abbreviatedPath) sets its own prompt after Peel’s line, so zsh shows that one."),
- tint: .accentColor
- )
- .font(.caption)
- .foregroundStyle(.secondary)
+ if let notice = prompt.flatMap({ Self.notice(for: $0, in: state) }) {
+ StatusLabel(title: notice, tint: .accentColor)
+ .font(.caption)
+ .foregroundStyle(.secondary)
} else {
Text("The colors are the Terminal theme’s.")
.font(.caption)
@@ -197,6 +187,25 @@ private struct PromptSection: View {
}
}
+ /// Why zsh shows another prompt than Peel's, as zsh itself answered: Peel's line not read yet, a function that
+ /// sets the prompt before each command, or a line after Peel's. When zsh did not answer, what the startup file
+ /// says.
+ private static func notice(for prompt: Prompt, in state: ShellLibrary.State) -> Text? {
+ guard let startupFile = state.startupFile else { return nil }
+ guard state.isSourced else {
+ return Text("zsh shows this prompt once Peel’s line is in \(startupFile.abbreviatedPath).")
+ }
+ let afterPeels = Text("Your \(startupFile.abbreviatedPath) sets its own prompt after Peel’s line, so zsh shows that one.")
+ guard let shown = state.shownPrompt else { return state.setsItsOwnPrompt ? afterPeels : nil }
+ guard shown.prompt != prompt.value else { return nil }
+ if let function = shown.setBeforeEachCommandBy.last {
+ return Text("A function your zsh runs before each command, \(function), sets its own prompt, so zsh shows that one.")
+ }
+ return state.setsItsOwnPrompt
+ ? afterPeels
+ : Text("Your zsh sets its own prompt after Peel’s file is read, so zsh shows that one.")
+ }
+
private func partTitle(_ title: LocalizedStringResource, isOn: Bool) -> some View {
Text(title)
.font(.body.weight(.semibold))
diff --git a/PeelTests/TerminalLibrariesTests.swift b/PeelTests/TerminalLibrariesTests.swift
index 3362ea3f..62f7bff2 100644
--- a/PeelTests/TerminalLibrariesTests.swift
+++ b/PeelTests/TerminalLibrariesTests.swift
@@ -77,6 +77,25 @@ struct TerminalLibrariesTests {
#expect(try size(of: library.file) == bytes)
}
+ @Test func theShellTabAsksZshWhichPromptItShowsOnlyWhilePeelsPromptIsOn() async throws {
+ let home = try madeUpHome()
+ defer { try? FileManager.default.removeItem(at: home) }
+ let folder = home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory)
+ let library = ShellLibrary(folder: folder, home: home)
+ try ("precmd() { PROMPT='mine> ' }\n" + library.line + "\n")
+ .write(to: home.appending(path: ".zshrc"), atomically: true, encoding: .utf8)
+ try "export ZDOTDIR=\"$HOME\"\n".write(to: home.appending(path: ".zshenv"), atomically: true, encoding: .utf8)
+
+ await library.refresh()
+ #expect(library.state?.isSourced == true)
+ #expect(library.state?.shownPrompt == nil)
+
+ library.setPrompt(Prompt())
+ await library.refresh()
+ #expect(library.state?.shownPrompt?.setBeforeEachCommandBy == ["precmd"])
+ #expect(library.state?.shownPrompt?.prompt == "mine> ")
+ }
+
@Test func theTerminalTabKnowsFromTheStartWhenTerminalsProfilesCannotBeRead() throws {
let home = try madeUpHome()
defer { try? FileManager.default.removeItem(at: home) }
diff --git a/SAFETY.md b/SAFETY.md
index bd5dfccc..35013b32 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -553,7 +553,8 @@ bell in the Peel theme in use, and can keep Terminal from reopening its windows.
Leaving out the "Last login" line makes an empty `~/.hushlogin`, the file `login` looks for, and turning it off again
moves that file to the Trash, recorded in History. Peel never edits your shell's files: to stop the shell from saving
-its sessions, it shows the line to add yourself.
+its sessions, it shows the line to add yourself. To know which `.zshrc` zsh reads and, with Peel's prompt on, which
+prompt a new window shows, Peel runs zsh with your startup files, as a new window does, and changes nothing in them.
The Shell and SSH tabs write only two files of Peel's own, in its folder. zsh and ssh read them only through the line
you add to `~/.zshrc` and the two lines you add at the end of `~/.ssh/config`, and Peel never edits those files. Turn
diff --git a/TERMINAL.md b/TERMINAL.md
index 4d922a33..e0482073 100644
--- a/TERMINAL.md
+++ b/TERMINAL.md
@@ -159,8 +159,10 @@ what comes before the symbol, the Git branch, the symbol, whether the symbol tur
and whether the symbol and the command start a line of their own. The colors are the Terminal theme's, and the branch
comes from zsh's own
[vcs_info](https://zsh.sourceforge.io/Doc/Release/User-Contributions.html#Version-Control-Information).
-Peel writes no prompt until you turn on **Use Peel's prompt**. A prompt your `~/.zshrc` sets after Peel's line is the
-one zsh shows, and the Shell tab says so when a line after Peel's sets `PROMPT` or `PS1`.
+Peel writes no prompt until you turn on **Use Peel's prompt**. With it on, Peel asks zsh which prompt a new window
+shows, starting one as Terminal does, with your startup files: a prompt your `~/.zshrc` sets after Peel's line, or
+one a function sets before each command, as Starship and Powerlevel10k do, is the one zsh shows, and the Shell tab
+says so and names the function.
<table>
<tr>