1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-09-26 20:29:03 +00:00

feat: set a continuation prompt for supporting shells (#3322)

* feat: set a continuation prompt for supporting shells (#3134)

* docs: fixed wording of documentation

* fix: continuation prompt is now only set once

* fix(docs): fixed typo in advanced-config/README.md

Co-authored-by: Segev Finer <segev208@gmail.com>

* fix: update --continuation argument

Co-authored-by: David Knaack <davidkna@users.noreply.github.com>

* fix: updated continuation prompt

- PROMPT2 was fixed to be set only once in zsh.
- `continuation_symbol` and `continuation_format` were removed in
  place of a single variable; `continuation_prompt`.
- The continuation prompt was moved out of the character module.

* fix: ran rustfmt

* docs: updated continuation prompt docs

Co-authored-by: Segev Finer <segev208@gmail.com>
Co-authored-by: David Knaack <davidkna@users.noreply.github.com>
This commit is contained in:
Ryan Cohen 2022-01-01 08:12:11 -05:00 committed by GitHub
parent 3f97068538
commit 4deaa02d6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 289 additions and 205 deletions

View File

@ -141,6 +141,28 @@ Produces a prompt like the following:
▶ starship on  rprompt [!] is 📦 v0.57.0 via 🦀 v1.54.0 took 17s
```
## Continuation Prompt
Some shells support a continuation prompt along with the normal prompt. This prompt is rendered instead of the normal prompt when the user has entered an incomplete statement (such as a single left parenthesis or quote).
Starship can set the continuation prompt using the `continuation_prompt` option. The default prompt is `"[](bold yellow)"`.
Note: `continuation_prompt` should be set to a literal string without any variables.
Note: Continuation prompts are only available in the following shells:
- `bash`
- `zsh`
- `PowerShell`
### Example
```toml
# ~/.config/starship.toml
# A continuation prompt that displays two filled in arrows
continuation_prompt = "▶▶"
```
## Style Strings

View File

@ -80,6 +80,7 @@ pub struct FullConfig<'a> {
// Root config
pub format: String,
pub right_format: String,
pub continuation_prompt: String,
pub scan_timeout: u64,
pub command_timeout: u64,
pub add_newline: bool,
@ -158,6 +159,7 @@ impl<'a> Default for FullConfig<'a> {
Self {
format: "$all".to_string(),
right_format: "".to_string(),
continuation_prompt: "[](bold yellow)".to_string(),
scan_timeout: 30,
command_timeout: 500,
add_newline: true,

View File

@ -8,6 +8,7 @@ use std::cmp::Ordering;
pub struct StarshipRootConfig {
pub format: String,
pub right_format: String,
pub continuation_prompt: String,
pub scan_timeout: u64,
pub command_timeout: u64,
pub add_newline: bool,
@ -95,6 +96,7 @@ impl<'a> Default for StarshipRootConfig {
StarshipRootConfig {
format: "$all".to_string(),
right_format: "".to_string(),
continuation_prompt: "[](bold yellow)".to_string(),
scan_timeout: 30,
command_timeout: 500,
add_newline: true,
@ -108,6 +110,7 @@ impl<'a> ModuleConfig<'a> for StarshipRootConfig {
config.iter().for_each(|(k, v)| match k.as_str() {
"format" => self.format.load_config(v),
"right_format" => self.right_format.load_config(v),
"continuation_prompt" => self.continuation_prompt.load_config(v),
"scan_timeout" => self.scan_timeout.load_config(v),
"command_timeout" => self.command_timeout.load_config(v),
"add_newline" => self.add_newline.load_config(v),
@ -122,6 +125,7 @@ impl<'a> ModuleConfig<'a> for StarshipRootConfig {
// Root options
"format",
"right_format",
"continuation_prompt",
"scan_timeout",
"command_timeout",
"add_newline",

View File

@ -51,6 +51,9 @@ pub struct Context<'a> {
/// Construct the right prompt instead of the left prompt
pub right: bool,
/// Construct the continuation prompt instead of the normal prompt
pub continuation: bool,
/// Width of terminal, or zero if width cannot be detected.
pub width: usize,
@ -134,6 +137,7 @@ impl<'a> Context<'a> {
.map_or_else(StarshipRootConfig::default, StarshipRootConfig::load);
let right = arguments.is_present("right");
let continuation = arguments.is_present("continuation");
let width = arguments
.value_of("terminal_width")
@ -151,6 +155,7 @@ impl<'a> Context<'a> {
repo: OnceCell::new(),
shell,
right,
continuation,
width,
#[cfg(test)]
env: HashMap::new(),

View File

@ -100,3 +100,7 @@ export STARSHIP_SHELL="bash"
STARSHIP_SESSION_KEY="$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM"; # Random generates a number b/w 0 - 32767
STARSHIP_SESSION_KEY="${STARSHIP_SESSION_KEY}0000000000000000" # Pad it to 16+ chars.
export STARSHIP_SESSION_KEY=${STARSHIP_SESSION_KEY:0:16}; # Trim to 16-digits if excess.
# Set the continuation prompt
PS2="$(::STARSHIP:: prompt --continuation)"

76
src/init/starship.ps1 Normal file → Executable file
View File

@ -1,7 +1,6 @@
#!/usr/bin/env pwsh
function global:prompt {
function Get-Arguments {
function Get-Cwd {
$cwd = Get-Location
$provider_prefix = "$($cwd.Provider.ModuleName)\$($cwd.Provider.Name)::"
@ -22,6 +21,39 @@ function global:prompt {
}
}
# @ makes sure the result is an array even if single or no values are returned
$jobs = @(Get-Job | Where-Object { $_.State -eq 'Running' }).Count
$cwd = Get-Cwd
$arguments = @(
"prompt"
"--path=$($cwd.Path)",
"--logical-path=$($cwd.LogicalPath)",
"--terminal-width=$($Host.UI.RawUI.WindowSize.Width)",
"--jobs=$($jobs)"
)
# Whe start from the premise that the command executed correctly, which covers also the fresh console.
$lastExitCodeForPrompt = 0
if ($lastCmd = Get-History -Count 1) {
# In case we have a False on the Dollar hook, we know there's an error.
if (-not $origDollarQuestion) {
# We retrieve the InvocationInfo from the most recent error using $error[0]
$lastCmdletError = try { $error[0] | Where-Object { $_ -ne $null } | Select-Object -ExpandProperty InvocationInfo } catch { $null }
# We check if the last command executed matches the line that caused the last error, in which case we know
# it was an internal Powershell command, otherwise, there MUST be an error code.
$lastExitCodeForPrompt = if ($null -ne $lastCmdletError -and $lastCmd.CommandLine -eq $lastCmdletError.Line) { 1 } else { $origLastExitCode }
}
$duration = [math]::Round(($lastCmd.EndExecutionTime - $lastCmd.StartExecutionTime).TotalMilliseconds)
$arguments += "--cmd-duration=$($duration)"
}
$arguments += "--status=$($lastExitCodeForPrompt)"
return $arguments
}
function Invoke-Native {
param($Executable, $Arguments)
$startInfo = New-Object System.Diagnostics.ProcessStartInfo -ArgumentList $Executable -Property @{
@ -63,6 +95,7 @@ function global:prompt {
$process.StandardOutput.ReadToEnd();
}
function global:prompt {
$origDollarQuestion = $global:?
$origLastExitCode = $global:LASTEXITCODE
@ -73,35 +106,8 @@ function global:prompt {
}
} catch {}
# @ makes sure the result is an array even if single or no values are returned
$jobs = @(Get-Job | Where-Object { $_.State -eq 'Running' }).Count
$cwd = Get-Cwd
$arguments = @(
"prompt"
"--path=$($cwd.Path)",
"--logical-path=$($cwd.LogicalPath)",
"--terminal-width=$($Host.UI.RawUI.WindowSize.Width)",
"--jobs=$($jobs)"
)
# Whe start from the premise that the command executed correctly, which covers also the fresh console.
$lastExitCodeForPrompt = 0
if ($lastCmd = Get-History -Count 1) {
# In case we have a False on the Dollar hook, we know there's an error.
if (-not $origDollarQuestion) {
# We retrieve the InvocationInfo from the most recent error using $error[0]
$lastCmdletError = try { $error[0] | Where-Object { $_ -ne $null } | Select-Object -ExpandProperty InvocationInfo } catch { $null }
# We check if the last command executed matches the line that caused the last error, in which case we know
# it was an internal Powershell command, otherwise, there MUST be an error code.
$lastExitCodeForPrompt = if ($null -ne $lastCmdletError -and $lastCmd.CommandLine -eq $lastCmdletError.Line) { 1 } else { $origLastExitCode }
}
$duration = [math]::Round(($lastCmd.EndExecutionTime - $lastCmd.StartExecutionTime).TotalMilliseconds)
$arguments += "--cmd-duration=$($duration)"
}
$arguments += "--status=$($lastExitCodeForPrompt)"
# Get arguments for starship prompt
$arguments = Get-Arguments
# Invoke Starship
Invoke-Native -Executable ::STARSHIP:: -Arguments $arguments
@ -130,6 +136,14 @@ function global:prompt {
}
# Get arguments for starship continuation prompt
$arguments = Get-Arguments
$arguments += "--continuation"
# Invoke Starship and set continuation prompt
$continuation = Invoke-Native -Executable ::STARSHIP:: -Arguments $arguments
Set-PSReadLineOption -ContinuationPrompt $continuation
# Disable virtualenv prompt, it breaks starship
$ENV:VIRTUAL_ENV_DISABLE_PROMPT=1

View File

@ -94,4 +94,5 @@ setopt promptsubst
PROMPT='$(::STARSHIP:: prompt --terminal-width="$COLUMNS" --keymap="${KEYMAP:-}" --status="$STARSHIP_CMD_STATUS" --pipestatus="${STARSHIP_PIPE_STATUS[*]}" --cmd-duration="${STARSHIP_DURATION:-}" --jobs="$STARSHIP_JOBS_COUNT")'
RPROMPT='$(::STARSHIP:: prompt --right --terminal-width="$COLUMNS" --keymap="${KEYMAP:-}" --status="$STARSHIP_CMD_STATUS" --pipestatus="${STARSHIP_PIPE_STATUS[*]}" --cmd-duration="${STARSHIP_DURATION:-}" --jobs="$STARSHIP_JOBS_COUNT")'
PROMPT2="$(::STARSHIP:: prompt --continuation)"

View File

@ -88,8 +88,7 @@ fn main() {
.help("Print the main initialization script (as opposed to the init stub)");
let long_version = crate::shadow::clap_version();
let mut app =
App::new("starship")
let mut app = App::new("starship")
.about("The cross-shell prompt for astronauts. ☄🌌️")
// pull the version number from Cargo.toml
.version(shadow::PKG_VERSION)
@ -112,6 +111,12 @@ fn main() {
.long("right")
.help("Print the right prompt (instead of the standard left prompt)"),
)
.arg(
Arg::with_name("continuation")
.long("continuation")
.help("Print the continuation prompt (instead of the standard left prompt)")
.conflicts_with("right"),
)
.arg(&status_code_arg)
.arg(&pipestatus_arg)
.arg(&terminal_width_arg)
@ -189,9 +194,11 @@ fn main() {
.required_unless("name"),
),
)
.subcommand(SubCommand::with_name("bug-report").about(
.subcommand(
SubCommand::with_name("bug-report").about(
"Create a pre-populated GitHub issue with information about your configuration",
))
),
)
.subcommand(
SubCommand::with_name("time")
.about("Prints time in milliseconds")

View File

@ -114,7 +114,8 @@ pub fn get_prompt(context: Context) -> String {
);
let module_strings = root_module.ansi_strings_for_shell(context.shell, Some(context.width));
if config.add_newline {
if config.add_newline && !context.continuation {
// continuation prompts normally do not include newlines, but they can
writeln!(buf).unwrap();
}
write!(buf, "{}", ANSIStrings(&module_strings)).unwrap();
@ -416,19 +417,27 @@ fn load_formatter_and_modules<'a>(context: &'a Context) -> (StringFormatter<'a>,
let lformatter = StringFormatter::new(&config.format);
let rformatter = StringFormatter::new(&config.right_format);
let cformatter = StringFormatter::new(&config.continuation_prompt);
if lformatter.is_err() {
log::error!("Error parsing `format`")
}
if rformatter.is_err() {
log::error!("Error parsing `right_format`")
}
if cformatter.is_err() {
log::error!("Error parsing `continuation_prompt`")
}
match (lformatter, rformatter) {
(Ok(lf), Ok(rf)) => {
match (lformatter, rformatter, cformatter) {
(Ok(lf), Ok(rf), Ok(cf)) => {
let mut modules: BTreeSet<String> = BTreeSet::new();
if !context.continuation {
modules.extend(lf.get_variables());
modules.extend(rf.get_variables());
if context.right {
}
if context.continuation {
(cf, modules)
} else if context.right {
(rf, modules)
} else {
(lf, modules)
@ -461,4 +470,20 @@ mod test {
let actual = get_prompt(context);
assert_eq!(expected, actual);
}
#[test]
fn continuation_prompt() {
let mut context = default_context();
context.config = StarshipConfig {
config: Some(toml::toml! {
continuation_prompt="><>"
}),
};
context.root_config.continuation_prompt = "><>".to_string();
context.continuation = true;
let expected = String::from("><>");
let actual = get_prompt(context);
assert_eq!(expected, actual);
}
}