Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow configuration of multiline prompt color #531

Merged
merged 5 commits into from
Jan 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
2 changes: 1 addition & 1 deletion examples/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
4 changes: 2 additions & 2 deletions examples/custom_prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Prompt for CustomPrompt {
{
let old = self.0.get();
self.0.set(old + 1);
Cow::Owned(format!("[{}]", old))
Cow::Owned(format!("[{old}]"))
}
}

Expand Down Expand Up @@ -64,7 +64,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
4 changes: 2 additions & 2 deletions examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ fn main() -> Result<()> {
line_editor.print_history()?;
continue;
}
println!("Our buffer: {}", buffer);
println!("Our buffer: {buffer}");
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
if !buffer.is_empty() {
line_editor
Expand All @@ -165,7 +165,7 @@ fn main() -> Result<()> {
// Prompt has been cleared and should start on the next line
}
Err(err) => {
println!("Error: {:?}", err);
println!("Error: {err:?}");
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions examples/event_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,12 @@ fn print_events_helper() -> Result<()> {
}
_ => {
println!(
"Keycode: {:?}; Modifier {:?}; Flags {:#08b}\r",
code, modifiers, modifiers
"Keycode: {code:?}; Modifier {modifiers:?}; Flags {modifiers:#08b}\r"
);
}
}
} else {
println!("Event::{:?}\r", event);
println!("Event::{event:?}\r");
}

// hit the esc key to git out
Expand Down
6 changes: 3 additions & 3 deletions examples/external_printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn main() {
let mut i = 1;
loop {
sleep(Duration::from_secs(1));
assert!(p_clone.print(format!("Message {} delivered.", i)).is_ok());
assert!(p_clone.print(format!("Message {i} delivered.")).is_ok());
i += 1;
}
});
Expand All @@ -34,7 +34,7 @@ fn main() {
sleep(Duration::from_secs(3));
for _ in 0..10 {
sleep(Duration::from_millis(1));
assert!(p_sender.send(format!("Fast Hello !")).is_ok());
assert!(p_sender.send("Fast Hello !".to_string()).is_ok());
}
});

Expand All @@ -45,7 +45,7 @@ fn main() {
if let Ok(sig) = line_editor.read_line(&prompt) {
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
2 changes: 1 addition & 1 deletion examples/highlighter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
2 changes: 1 addition & 1 deletion examples/hinter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
2 changes: 1 addition & 1 deletion examples/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
15 changes: 6 additions & 9 deletions examples/list_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,31 @@ fn main() -> Result<()> {
fn get_all_keybinding_info() {
println!("--Key Modifiers--");
for mods in get_reedline_keybinding_modifiers().iter() {
println!("{}", mods);
println!("{mods}");
}

println!("\n--Modes--");
for modes in get_reedline_prompt_edit_modes().iter() {
println!("{}", modes);
println!("{modes}");
}

println!("\n--Key Codes--");
for kcs in get_reedline_keycodes().iter() {
println!("{}", kcs);
println!("{kcs}");
}

println!("\n--Reedline Events--");
for rle in get_reedline_reedline_events().iter() {
println!("{}", rle);
println!("{rle}");
}

println!("\n--Edit Commands--");
for edit in get_reedline_edit_commands().iter() {
println!("{}", edit);
println!("{edit}");
}

println!("\n--Default Keybindings--");
for (mode, modifier, code, event) in get_reedline_default_keybindings() {
println!(
"mode: {}, keymodifiers: {}, keycode: {}, event: {}",
mode, modifier, code, event
);
println!("mode: {mode}, keymodifiers: {modifier}, keycode: {code}, event: {event}");
}
}
2 changes: 1 addition & 1 deletion examples/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn main() -> io::Result<()> {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {}", buffer);
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
Expand Down
4 changes: 1 addition & 3 deletions src/completion/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ impl Span {
pub fn new(start: usize, end: usize) -> Span {
assert!(
end >= start,
"Can't create a Span whose end < start, start={}, end={}",
start,
end
"Can't create a Span whose end < start, start={start}, end={end}"
);

Span { start, end }
Expand Down
4 changes: 2 additions & 2 deletions src/completion/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl Completer for DefaultCompleter {
if span_line.is_empty() {
span_line = s.to_string();
} else {
span_line = format!("{} {}", s, span_line);
span_line = format!("{s} {span_line}");
}
if let Some(mut extensions) = self.root.complete(span_line.chars()) {
extensions.sort();
Expand All @@ -97,7 +97,7 @@ impl Completer for DefaultCompleter {
);

Suggestion {
value: format!("{}{}", span_line, ext),
value: format!("{span_line}{ext}"),
description: None,
extra: None,
span,
Expand Down
8 changes: 3 additions & 5 deletions src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ use {
event::{Event, KeyCode, KeyEvent, KeyModifiers},
terminal, Result,
},
std::{
borrow::Borrow, fs::File, io, io::Write, process::Command, time::Duration, time::SystemTime,
},
std::{fs::File, io, io::Write, process::Command, time::Duration, time::SystemTime},
};

// The POLL_WAIT is used to specify for how long the POLL should wait for
Expand Down Expand Up @@ -1338,7 +1336,7 @@ impl Reedline {
None => Ok(()),
Some(BufferEditor { editor, extension }) => {
let temp_directory = std::env::temp_dir();
let temp_file = temp_directory.join(format!("reedline_buffer.{}", extension));
let temp_file = temp_directory.join(format!("reedline_buffer.{extension}"));

{
let mut file = File::create(temp_file.clone())?;
Expand Down Expand Up @@ -1425,7 +1423,7 @@ impl Reedline {
.highlight(buffer_to_paint, cursor_position_in_buffer)
.render_around_insertion_point(
cursor_position_in_buffer,
prompt.render_prompt_multiline_indicator().borrow(),
prompt,
self.use_ansi_coloring,
);

Expand Down
8 changes: 4 additions & 4 deletions src/history/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,10 @@ mod tests {
let hfile = histfile.clone();
std::thread::spawn(move || {
let (mut hist, _) = create_history_at(cap, &hfile);
hist.save(HistoryItem::from_command_line(&format!("A{}", i)))
hist.save(HistoryItem::from_command_line(format!("A{i}")))
.unwrap();
hist.sync().unwrap();
hist.save(HistoryItem::from_command_line(&format!("B{}", i)))
hist.save(HistoryItem::from_command_line(format!("B{i}")))
.unwrap();
})
})
Expand All @@ -580,8 +580,8 @@ mod tests {
);

for i in 0..num_threads {
assert!(actual.contains(&format!("A{}", i)),);
assert!(actual.contains(&format!("B{}", i)),);
assert!(actual.contains(&format!("A{i}")),);
assert!(actual.contains(&format!("B{i}")),);
}

tmp.close().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/history/file_backed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl History for FileBackedHistory {
{
let mut writer = BufWriter::new(writer_guard.deref_mut());
if truncate {
writer.seek(SeekFrom::Start(0))?;
writer.rewind()?;

for line in &foreign_entries {
writer.write_all(encode_entry(line).as_bytes())?;
Expand Down
8 changes: 2 additions & 6 deletions src/history/sqlite_backed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,7 @@ impl History for SqliteBackedHistory {
fn map_sqlite_err(err: rusqlite::Error) -> ReedlineError {
// TODO: better error mapping
ReedlineError(ReedlineErrorVariants::HistoryDatabaseError(format!(
"{:?}",
err
"{err:?}"
)))
}

Expand All @@ -173,10 +172,7 @@ impl SqliteBackedHistory {
pub fn with_file(file: PathBuf) -> Result<Self> {
if let Some(base_dir) = file.parent() {
std::fs::create_dir_all(base_dir).map_err(|e| {
ReedlineError(ReedlineErrorVariants::HistoryDatabaseError(format!(
"{}",
e
)))
ReedlineError(ReedlineErrorVariants::HistoryDatabaseError(format!("{e}")))
})?;
}
let db = Connection::open(&file).map_err(map_sqlite_err)?;
Expand Down
4 changes: 2 additions & 2 deletions src/menu/list_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ impl ListMenu {
RESET
)
} else {
format!("({}) ", desc)
format!("({desc}) ")
}
});

Expand All @@ -339,7 +339,7 @@ impl ListMenu {
let line_str = if index == self.index() {
format!("{}{}>{}", row_number, description, line.to_uppercase())
} else {
format!("{}{}{}", row_number, description, line)
format!("{row_number}{description}{line}")
};

// Final string with formatting
Expand Down
23 changes: 15 additions & 8 deletions src/painting/styled_text.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use nu_ansi_term::Style;

use crate::Prompt;

use super::utils::strip_ansi;
use nu_ansi_term::{Color, Style};

/// A representation of a buffer with styling, used for doing syntax highlighting
pub struct StyledText {
Expand Down Expand Up @@ -34,18 +37,22 @@ impl StyledText {
pub fn render_around_insertion_point(
&self,
insertion_point: usize,
multiline_prompt: &str,
prompt: &dyn Prompt,
// multiline_prompt: &str,
use_ansi_coloring: bool,
) -> (String, String) {
let mut current_idx = 0;
let mut left_string = String::new();
let mut right_string = String::new();
let prompt_style = Style::new().fg(Color::LightBlue);

let multiline_prompt = prompt.render_prompt_multiline_indicator();
let prompt_style = Style::new().fg(prompt.get_prompt_multiline_color());
Comment on lines -43 to +49
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the heart of the change. Instead of fixing this to Color::LightBlue, it is instead configured in Prompt::get_prompt_multiline_color().


for pair in &self.buffer {
if current_idx >= insertion_point {
right_string.push_str(&render_as_string(pair, &prompt_style, multiline_prompt));
right_string.push_str(&render_as_string(pair, &prompt_style, &multiline_prompt));
} else if pair.1.len() + current_idx <= insertion_point {
left_string.push_str(&render_as_string(pair, &prompt_style, multiline_prompt));
left_string.push_str(&render_as_string(pair, &prompt_style, &multiline_prompt));
} else if pair.1.len() + current_idx > insertion_point {
let offset = insertion_point - current_idx;

Expand All @@ -55,12 +62,12 @@ impl StyledText {
left_string.push_str(&render_as_string(
&(pair.0, left_side),
&prompt_style,
multiline_prompt,
&multiline_prompt,
));
right_string.push_str(&render_as_string(
&(pair.0, right_side),
&prompt_style,
multiline_prompt,
&multiline_prompt,
));
}
current_idx += pair.1.len();
Expand Down Expand Up @@ -93,7 +100,7 @@ fn render_as_string(
multiline_prompt: &str,
) -> String {
let mut rendered = String::new();
let formatted_multiline_prompt = format!("\n{}", multiline_prompt);
let formatted_multiline_prompt = format!("\n{multiline_prompt}");
for (line_number, line) in renderable.1.split('\n').enumerate() {
if line_number != 0 {
rendered.push_str(&prompt_style.paint(&formatted_multiline_prompt).to_string());
Expand Down
7 changes: 6 additions & 1 deletion src/prompt/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use {

/// The default color for the prompt, indicator, and right prompt
pub static DEFAULT_PROMPT_COLOR: Color = Color::Green;
pub static DEFAULT_PROMPT_MULTILINE_COLOR: nu_ansi_term::Color = nu_ansi_term::Color::LightBlue;
pub static DEFAULT_INDICATOR_COLOR: Color = Color::Cyan;
pub static DEFAULT_PROMPT_RIGHT_COLOR: Color = Color::AnsiValue(5);

Expand Down Expand Up @@ -79,7 +80,7 @@ impl Display for PromptEditMode {
PromptEditMode::Default => write!(f, "Default"),
PromptEditMode::Emacs => write!(f, "Emacs"),
PromptEditMode::Vi(_) => write!(f, "Vi_Normal\nVi_Insert"),
PromptEditMode::Custom(s) => write!(f, "Custom_{}", s),
PromptEditMode::Custom(s) => write!(f, "Custom_{s}"),
}
}
}
Expand All @@ -105,6 +106,10 @@ pub trait Prompt: Send {
fn get_prompt_color(&self) -> Color {
DEFAULT_PROMPT_COLOR
}
/// Get the default multilince prompt color
fn get_prompt_multiline_color(&self) -> nu_ansi_term::Color {
DEFAULT_PROMPT_MULTILINE_COLOR
}
Comment on lines +110 to +112
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a new function to the Prompt to allow for it fetch a color. For now it uses a nu_ansi_term::Color unlike the others.

/// Get the default indicator color
fn get_indicator_color(&self) -> Color {
DEFAULT_INDICATOR_COLOR
Expand Down
Loading