Repository: kkawakam/rustyline
Pull request #345 (2020-03-07 08:59:23)

Rustfmt


Patch:
diff --git a/examples/example.rs b/examples/example.rs
index 37582e1..9614fc0 100644
--- a/examples/example.rs
+++ b/examples/example.rs
@@ -3,10 +3,9 @@ use std::borrow::Cow::{self, Borrowed, Owned};
 use rustyline::completion::{Completer, FilenameCompleter, Pair};
 use rustyline::config::OutputStreamType;
 use rustyline::error::ReadlineError;
-use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
-use rustyline::highlight::{PromptInfo};
-use rustyline::validate::{self, Validator, MatchingBracketValidator};
+use rustyline::highlight::{Highlighter, MatchingBracketHighlighter, PromptInfo};
 use rustyline::hint::{Hinter, HistoryHinter};
+use rustyline::validate::{self, MatchingBracketValidator, Validator};
 use rustyline::{Cmd, CompletionType, Config, Context, EditMode, Editor, KeyPress};
 use rustyline_derive::Helper;
 
@@ -20,7 +19,6 @@ struct MyHelper {
     continuation_prompt: String,
 }
 
-
 impl Completer for MyHelper {
     type Candidate = Pair;
 
@@ -58,7 +56,7 @@ impl Highlighter for MyHelper {
     }
 
     fn has_continuation_prompt(&self) -> bool {
-        return true;
+        true
     }
 
     fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
@@ -75,7 +73,10 @@ impl Highlighter for MyHelper {
 }
 
 impl Validator for MyHelper {
-    fn validate(&self, ctx: &mut validate::ValidationContext) -> rustyline::Result<validate::ValidationResult> {
+    fn validate(
+        &self,
+        ctx: &mut validate::ValidationContext,
+    ) -> rustyline::Result<validate::ValidationResult> {
         self.validator.validate(ctx)
     }
 
diff --git a/src/edit.rs b/src/edit.rs
index 902da6f..0c93725 100644
--- a/src/edit.rs
+++ b/src/edit.rs
@@ -152,7 +152,9 @@ impl<'out, 'prompt, H: Helper> State<'out, 'prompt, H> {
 
         // calculate the desired position of the cursor
         let pos = self.line.pos();
-        let cursor = self.out.calculate_position(&self.line[..pos], Position::default());
+        let cursor = self
+            .out
+            .calculate_position(&self.line[..pos], Position::default());
         // calculate the position of the end of the input line
         let mut end = if pos == self.line.len() {
             cursor
diff --git a/src/highlight.rs b/src/highlight.rs
index 830125c..07475f0 100644
--- a/src/highlight.rs
+++ b/src/highlight.rs
@@ -246,9 +246,7 @@ fn is_close_bracket(bracket: u8) -> bool {
     memchr(bracket, CLOSES).is_some()
 }
 
-pub(crate) fn split_highlight<'a>(src: &'a str, offset: usize)
-    -> (Cow<'a, str>, Cow<'a, str>)
-{
+pub(crate) fn split_highlight(src: &str, offset: usize) -> (Cow<'_, str>, Cow<'_, str>) {
     let mut style_buffer = String::with_capacity(32);
     let mut iter = src.char_indices();
     let mut non_escape_idx = 0;
@@ -261,7 +259,7 @@ pub(crate) fn split_highlight<'a>(src: &'a str, offset: usize)
             while let Some((end_idx, c)) = iter.next() {
                 match c {
                     'm' => {
-                        let slice = &src[idx..end_idx+1];
+                        let slice = &src[idx..end_idx + 1];
                         if slice == "\x1b[0m" {
                             style_buffer.clear();
                         } else {
@@ -270,7 +268,7 @@ pub(crate) fn split_highlight<'a>(src: &'a str, offset: usize)
                         break;
                     }
                     ';' | '0'..='9' => continue,
-                    _ => break,  // unknown escape, skip
+                    _ => break, // unknown escape, skip
                 }
             }
             continue;
@@ -282,8 +280,7 @@ pub(crate) fn split_highlight<'a>(src: &'a str, offset: usize)
                 let mut left = String::with_capacity(idx + 4);
                 left.push_str(&src[..idx]);
                 left.push_str("\x1b[0m");
-                let mut right = String::with_capacity(
-                    src.len() - idx + style_buffer.len());
+                let mut right = String::with_capacity(src.len() - idx + style_buffer.len());
                 right.push_str(&style_buffer);
                 right.push_str(&src[idx..]);
                 return (left.into(), right.into());
@@ -291,7 +288,7 @@ pub(crate) fn split_highlight<'a>(src: &'a str, offset: usize)
         }
         non_escape_idx += c.len_utf8();
     }
-    return (src.into(), "".into());
+    (src.into(), "".into())
 }
 
 impl PromptInfo<'_> {
@@ -299,6 +296,7 @@ impl PromptInfo<'_> {
     pub fn default(&self) -> bool {
         self.default
     }
+
     /// Returns the byte offset where prompt is shown in the initial text
     ///
     /// This is a position right after the newline of the previous line
diff --git a/src/history.rs b/src/history.rs
index 81fb520..fcb464e 100644
--- a/src/history.rs
+++ b/src/history.rs
@@ -27,6 +27,10 @@ pub struct History {
 }
 
 impl History {
+    // New multiline-aware history files start with `#V2\n` and have newlines
+    // and backslashes escaped in them.
+    const FILE_VERSION_V2: &'static str = "#V2";
+
     pub fn new() -> Self {
         Self::with_config(Config::default())
     }
@@ -110,10 +114,6 @@ impl History {
         }
     }
 
-    // New multiline-aware history files start with `#V2\n` and have newlines
-    // and backslashes escaped in them.
-    const FILE_VERSION_V2: &'static str = "#V2";
-
     /// Save the history in the specified file.
     // TODO append_history
     // http://cnswww.cns.cwru.edu/php/chet/readline/history.html#IDX30
diff --git a/src/keymap.rs b/src/keymap.rs
index 987dc35..abc1022 100644
--- a/src/keymap.rs
+++ b/src/keymap.rs
@@ -690,8 +690,8 @@ impl InputState {
             // KeyPress::Char('U') => Cmd::???, // revert-line
             KeyPress::Char('w') => Cmd::Move(Movement::ForwardWord(n, At::Start, Word::Vi)), /* vi-next-word */
             KeyPress::Char('W') => Cmd::Move(Movement::ForwardWord(n, At::Start, Word::Big)), /* vi-next-word */
-            KeyPress::Char('x') => Cmd::Kill(Movement::ForwardChar(n)), /* vi-delete: TODO move
-                                                                          * backward if eol */
+            // TODO move backward if eol
+            KeyPress::Char('x') => Cmd::Kill(Movement::ForwardChar(n)), // vi-delete
             KeyPress::Char('X') => Cmd::Kill(Movement::BackwardChar(n)), // vi-rubout
             KeyPress::Char('y') => match self.vi_cmd_motion(rdr, wrt, key, n)? {
                 Some(mvt) => Cmd::ViYankTo(mvt),
diff --git a/src/line_buffer.rs b/src/line_buffer.rs
index d0dd26a..59c4cc5 100644
--- a/src/line_buffer.rs
+++ b/src/line_buffer.rs
@@ -570,16 +570,13 @@ impl LineBuffer {
                         break;
                     }
                     dest_end = dest_start - 1;
-                    dest_start = self.buf[..dest_end].rfind('\n').map(|n| n + 1)
-                        .unwrap_or(0);
+                    dest_start = self.buf[..dest_end].rfind('\n').map(|n| n + 1).unwrap_or(0);
                 }
-                let gidx =self.buf[dest_start..dest_end]
+                let gidx = self.buf[dest_start..dest_end]
                     .grapheme_indices(true)
                     .nth(column);
 
-                self.pos = gidx
-                    .map(|(idx, _)| dest_start + idx)
-                    .unwrap_or(off); // if there's no enough columns
+                self.pos = gidx.map(|(idx, _)| dest_start + idx).unwrap_or(off); // if there's no enough columns
                 true
             }
             None => false,
@@ -635,13 +632,9 @@ impl LineBuffer {
     pub fn move_to_line_down(&mut self, n: RepeatCount) -> bool {
         match self.buf[self.pos..].find('\n') {
             Some(off) => {
-                let line_start = self.buf[..self.pos]
-                    .rfind('\n')
-                    .map(|n| n + 1)
-                    .unwrap_or(0);
-                let column = self.buf[line_start..self.pos]
-                    .graphemes(true).count();
-                let mut dest_start = self.pos + off+1;
+                let line_start = self.buf[..self.pos].rfind('\n').map(|n| n + 1).unwrap_or(0);
+                let column = self.buf[line_start..self.pos].graphemes(true).count();
+                let mut dest_start = self.pos + off + 1;
                 let mut dest_end = self.buf[dest_start..]
                     .find('\n')
                     .map(|v| dest_start + v)
@@ -912,7 +905,7 @@ impl LineBuffer {
                 } else {
                     Some(self.buf[start..self.pos].to_owned())
                 }
-            },
+            }
             Movement::BeginningOfLine => {
                 let start = self.start_of_line();
                 if self.pos == start {
diff --git a/src/tty/mod.rs b/src/tty/mod.rs
index e5ba272..51fe160 100644
--- a/src/tty/mod.rs
+++ b/src/tty/mod.rs
@@ -1,6 +1,6 @@
 //! This module implements and describes common TTY methods & traits
 use crate::config::{BellStyle, ColorMode, Config, OutputStreamType};
-use crate::highlight::{Highlighter, PromptInfo, split_highlight};
+use crate::highlight::Highlighter;
 use crate::keys::KeyPress;
 use crate::layout::{Layout, Position};
 use crate::line_buffer::LineBuffer;
@@ -156,24 +156,34 @@ pub trait Term {
     fn create_writer(&self) -> Self::Writer;
 }
 
+#[cfg(not(any(test, target_arch = "wasm32")))]
 fn add_prompt_and_highlight(
-    buffer: &mut String, highlighter: Option<&dyn Highlighter>,
-    line: &LineBuffer, prompt: &str, default_prompt: bool, layout: &Layout,
-    cursor: &mut Position)
-{
+    buffer: &mut String,
+    highlighter: Option<&dyn Highlighter>,
+    line: &LineBuffer,
+    prompt: &str,
+    default_prompt: bool,
+    layout: &Layout,
+    cursor: &mut Position,
+) {
+    use crate::highlight::{split_highlight, PromptInfo};
+
     if let Some(highlighter) = highlighter {
         if highlighter.has_continuation_prompt() {
             if &line[..] == "" {
                 // line.lines() is an empty iterator for empty line so
                 // we need to treat it as a special case
-                let prompt = highlighter.highlight_prompt(prompt, PromptInfo {
-                    default: default_prompt,
-                    offset: 0,
-                    cursor: Some(0),
-                    input: "",
-                    line: "",
-                    line_no: 0,
-                });
+                let prompt = highlighter.highlight_prompt(
+                    prompt,
+                    PromptInfo {
+                        default: default_prompt,
+                        offset: 0,
+                        cursor: Some(0),
+                        input: "",
+                        line: "",
+                        line_no: 0,
+                    },
+                );
                 buffer.push_str(&prompt);
             } else {
                 let highlighted = highlighter.highlight(line, line.pos());
@@ -181,20 +191,22 @@ fn add_prompt_and_highlight(
                 let mut highlighted_left = highlighted.to_string();
                 let mut offset = 0;
                 for (line_no, orig) in lines.enumerate() {
-                    let (hl, tail) = split_highlight(&highlighted_left,
-                        orig.len()+1);
-                    let prompt = highlighter.highlight_prompt(prompt, PromptInfo {
-                        default: default_prompt,
-                        offset,
-                        cursor: if line.pos() > offset && line.pos() < orig.len() {
-                            Some(line.pos() - offset)
-                        } else {
-                            None
+                    let (hl, tail) = split_highlight(&highlighted_left, orig.len() + 1);
+                    let prompt = highlighter.highlight_prompt(
+                        prompt,
+                        PromptInfo {
+                            default: default_prompt,
+                            offset,
+                            cursor: if line.pos() > offset && line.pos() < orig.len() {
+                                Some(line.pos() - offset)
+                            } else {
+                                None
+                            },
+                            input: line,
+                            line: orig,
+                            line_no,
                         },
-                        input: line,
-                        line: orig,
-                        line_no,
-                    });
+                    );
                     buffer.push_str(&prompt);
                     buffer.push_str(&hl);
                     highlighted_left = tail.to_string();
@@ -204,18 +216,19 @@ fn add_prompt_and_highlight(
             cursor.col += layout.prompt_size.col;
         } else {
             // display the prompt
-            buffer
-                .push_str(&highlighter.highlight_prompt(prompt, PromptInfo {
+            buffer.push_str(&highlighter.highlight_prompt(
+                prompt,
+                PromptInfo {
                     default: default_prompt,
                     offset: 0,
                     cursor: Some(line.pos()),
                     input: line,
-                    line: line,
+                    line,
                     line_no: 0,
-                }));
+                },
+            ));
             // display the input line
-            buffer
-                .push_str(&highlighter.highlight(line, line.pos()));
+            buffer.push_str(&highlighter.highlight(line, line.pos()));
             // we have to generate our own newline on line wrap
             if layout.end.col == 0 && layout.end.row > 0 && !buffer.ends_with('\n') {
                 buffer.push_str("\n");
diff --git a/src/tty/unix.rs b/src/tty/unix.rs
index 84ca8e4..80c4543 100644
--- a/src/tty/unix.rs
+++ b/src/tty/unix.rs
@@ -21,8 +21,8 @@ use crate::highlight::Highlighter;
 use crate::keys::{self, KeyPress};
 use crate::layout::{Layout, Position};
 use crate::line_buffer::LineBuffer;
-use crate::Result;
 use crate::tty::add_prompt_and_highlight;
+use crate::Result;
 
 const STDIN_FILENO: RawFd = libc::STDIN_FILENO;
 
@@ -561,8 +561,15 @@ impl Renderer for PosixRenderer {
         // clear the line
         self.buffer.push_str("\r\x1b[0K");
 
-        add_prompt_and_highlight(&mut self.buffer, highlighter,
-            line, prompt, default_prompt, &new_layout, &mut cursor);
+        add_prompt_and_highlight(
+            &mut self.buffer,
+            highlighter,
+            line,
+            prompt,
+            default_prompt,
+            &new_layout,
+            &mut cursor,
+        );
         // display hint
         if let Some(hint) = hint {
             if let Some(highlighter) = highlighter {
diff --git a/src/tty/windows.rs b/src/tty/windows.rs
index c74b61f..f4f852d 100644
--- a/src/tty/windows.rs
+++ b/src/tty/windows.rs
@@ -16,8 +16,8 @@ use crate::highlight::Highlighter;
 use crate::keys::{self, KeyPress};
 use crate::layout::{Layout, Position};
 use crate::line_buffer::LineBuffer;
-use crate::Result;
 use crate::tty::add_prompt_and_highlight;
+use crate::Result;
 
 const STDIN_FILENO: DWORD = winbase::STD_INPUT_HANDLE;
 const STDOUT_FILENO: DWORD = winbase::STD_OUTPUT_HANDLE;
@@ -333,8 +333,15 @@ impl Renderer for ConsoleRenderer {
         let old_rows = old_layout.end.row;
 
         self.buffer.clear();
-        add_prompt_and_highlight(&mut self.buffer, highlighter,
-            line, prompt, default_prompt, &new_layout, &mut cursor);
+        add_prompt_and_highlight(
+            &mut self.buffer,
+            highlighter,
+            line,
+            prompt,
+            default_prompt,
+            &new_layout,
+            &mut cursor,
+        );
 
         // append hint
         if let Some(hint) = hint {


Test patch:
diff --git a/src/test/emacs.rs b/src/test/emacs.rs
index b9d9e99..9fd395e 100644
--- a/src/test/emacs.rs
+++ b/src/test/emacs.rs
@@ -178,7 +178,6 @@ fn ctrl_k() {
     );
 }
 
-
 #[test]
 fn ctrl_u() {
     assert_cursor(
diff --git a/src/test/mod.rs b/src/test/mod.rs
index ad7fc34..3ed6e8c 100644
--- a/src/test/mod.rs
+++ b/src/test/mod.rs
@@ -15,10 +15,10 @@ use crate::{Context, Editor, Helper, Result};
 
 mod common;
 mod emacs;
+mod highlight;
 mod history;
 mod vi_cmd;
 mod vi_insert;
-mod highlight;
 
 fn init_editor(mode: EditMode, keys: &[KeyPress]) -> Editor<()> {
     let config = Config::builder().edit_mode(mode).build();