Creates a new interactive line editor and renders its initial state.
(
console: &'a mut dyn Console,
prompt: &str,
previous: &str,
mut history: Option<&'h mut Vec<String>>,
echo: bool,
)
| 337 | |
| 338 | /// Creates a new interactive line editor and renders its initial state. |
| 339 | fn new( |
| 340 | console: &'a mut dyn Console, |
| 341 | prompt: &str, |
| 342 | previous: &str, |
| 343 | mut history: Option<&'h mut Vec<String>>, |
| 344 | echo: bool, |
| 345 | ) -> io::Result<Self> { |
| 346 | let console_width = { |
| 347 | let console_size = console.size_chars()?; |
| 348 | usize::from(console_size.x) |
| 349 | }; |
| 350 | |
| 351 | let mut prompt = Cow::from(prompt); |
| 352 | let mut prompt_len = prompt.len(); |
| 353 | if prompt_len >= console_width { |
| 354 | // TODO(jmmv): This slices by bytes and can split non-ASCII prompts. |
| 355 | if console_width >= 5 { |
| 356 | prompt = Cow::from(format!("{}...", &prompt[0..console_width - 5])); |
| 357 | } else { |
| 358 | prompt = Cow::from(""); |
| 359 | } |
| 360 | prompt_len = prompt.len(); |
| 361 | } |
| 362 | |
| 363 | let input_width = { |
| 364 | // Assumes that the prompt was printed at column 0. If that was not the case, line |
| 365 | // length calculation does not work. |
| 366 | let width = console_width - prompt_len; |
| 367 | width.saturating_sub(1) |
| 368 | }; |
| 369 | |
| 370 | let line = LineBuffer::from(previous); |
| 371 | let pos = line.len(); |
| 372 | let view_start = if input_width == 0 { 0 } else { pos.saturating_sub(input_width) }; |
| 373 | let history_pos = match history.as_mut() { |
| 374 | Some(history) => { |
| 375 | history.push(line.to_string()); |
| 376 | history.len() - 1 |
| 377 | } |
| 378 | None => 0, |
| 379 | }; |
| 380 | |
| 381 | let mut readline = Self { |
| 382 | console, |
| 383 | history, |
| 384 | echo, |
| 385 | input_width, |
| 386 | line, |
| 387 | pos, |
| 388 | view_start, |
| 389 | rendered: String::new(), |
| 390 | rendered_len: 0, |
| 391 | history_pos, |
| 392 | }; |
| 393 | readline.view_start = readline.adjust_view(readline.pos, readline.view_start); |
| 394 | readline.sync_rendered(); |
| 395 | |
| 396 | if !prompt.is_empty() || !readline.rendered.is_empty() { |
nothing calls this directly
no test coverage detected