Skip to content

Commit

Permalink
Fixed rust fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
BogdanPaul15 committed Jan 8, 2024
1 parent 1de9295 commit c4cbd60
Show file tree
Hide file tree
Showing 11 changed files with 51 additions and 124 deletions.
5 changes: 2 additions & 3 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use std::process::Command;

fn main() {
let version = match Command::new("git").args(["describe", "--tags", "--match=v*"]).output() {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout[1..]).replacen('-', ".r", 1).replace('-', ".")
}
Ok(output) if output.status.success() =>
String::from_utf8_lossy(&output.stdout[1..]).replacen('-', ".r", 1).replace('-', "."),
_ => env!("CARGO_PKG_VERSION").into(),
};
println!("cargo:rustc-env=KIBI_VERSION={version}");
Expand Down
13 changes: 4 additions & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ impl Config {
tab_stop => conf.tab_stop = tab_stop,
},
"quit_times" => conf.quit_times = parse_value(value)?,
"message_duration" => {
conf.message_dur = Duration::from_secs_f32(parse_value(value)?)
}
"message_duration" =>
conf.message_dur = Duration::from_secs_f32(parse_value(value)?),
"show_line_numbers" => conf.show_line_num = parse_value(value)?,
_ => return Err(format!("Invalid key: {key}")),
};
Expand All @@ -74,9 +73,7 @@ impl Config {
/// The `kv_fn` function will be called for each key-value pair in the file. Typically, this
/// function will update a configuration instance.
pub fn process_ini_file<F>(path: &Path, kv_fn: &mut F) -> Result<(), Error>
where
F: FnMut(&str, &str) -> Result<(), String>,
{
where F: FnMut(&str, &str) -> Result<(), String> {
let file = File::open(path).map_err(|e| ConfErr(path.into(), 0, e.to_string()))?;
for (i, line) in BufReader::new(file).lines().enumerate() {
let (i, line) = (i + 1, line?);
Expand Down Expand Up @@ -113,9 +110,7 @@ mod tests {
use super::*;

fn ini_processing_helper<F>(ini_content: &str, kv_fn: &mut F) -> Result<(), Error>
where
F: FnMut(&str, &str) -> Result<(), String>,
{
where F: FnMut(&str, &str) -> Result<(), String> {
let tmp_dir = TempDir::new().expect("Could not create temporary directory");
let file_path = tmp_dir.path().join("test_config.ini");
fs::write(&file_path, ini_content).expect("Could not write INI file");
Expand Down
39 changes: 12 additions & 27 deletions src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ use std::{fs::File, path::Path, process::Command, thread, time::Instant};
use crate::row::{HlState, Row};
use crate::{ansi_escape::*, syntax::Conf as SyntaxConf, sys, terminal, Config, Error};

const fn ctrl_key(key: u8) -> u8 {
key & 0x1f
}
const fn ctrl_key(key: u8) -> u8 { key & 0x1f }
const EXIT: u8 = ctrl_key(b'Q');
const DELETE_BIS: u8 = ctrl_key(b'H');
const REFRESH_SCREEN: u8 = ctrl_key(b'L');
Expand Down Expand Up @@ -74,9 +72,7 @@ struct CursorState {
}

impl CursorState {
fn move_to_next_line(&mut self) {
(self.x, self.y) = (0, self.y + 1);
}
fn move_to_next_line(&mut self) { (self.x, self.y) = (0, self.y + 1); }

/// Scroll the terminal window vertically and horizontally (i.e. adjusting the row offset and
/// the column offset) so that the cursor can be shown.
Expand Down Expand Up @@ -138,9 +134,7 @@ struct StatusMessage {

impl StatusMessage {
/// Create a new status message and set time to the current date/time.
fn new(msg: String) -> Self {
Self { msg, time: Instant::now() }
}
fn new(msg: String) -> Self { Self { msg, time: Instant::now() } }
}

/// Pretty-format a size in bytes.
Expand Down Expand Up @@ -186,15 +180,11 @@ impl Editor {
}

/// Return the current row if the cursor points to an existing row, `None` otherwise.
fn current_row(&self) -> Option<&Row> {
self.rows.get(self.cursor.y)
}
fn current_row(&self) -> Option<&Row> { self.rows.get(self.cursor.y) }

/// Return the position of the cursor, in terms of rendered characters (as opposed to
/// `self.cursor.x`, which is the position of the cursor in terms of bytes).
fn rx(&self) -> usize {
self.current_row().map_or(0, |r| r.cx2rx[self.cursor.x])
}
fn rx(&self) -> usize { self.current_row().map_or(0, |r| r.cx2rx[self.cursor.x]) }

/// Move the cursor following an arrow key (← → ↑ ↓).
fn move_cursor(&mut self, key: &AKey, ctrl: bool) {
Expand All @@ -210,9 +200,8 @@ impl Editor {
// ← at the beginning of the line: move to the end of the previous line. The x
// position will be adjusted after this `match` to accommodate the current row
// length, so we can just set here to the maximum possible value here.
(AKey::Left, _) if self.cursor.y > 0 => {
(self.cursor.y, cursor_x) = (self.cursor.y - 1, usize::MAX)
}
(AKey::Left, _) if self.cursor.y > 0 =>
(self.cursor.y, cursor_x) = (self.cursor.y - 1, usize::MAX),
(AKey::Right, Some(row)) if self.cursor.x < row.chars.len() => {
cursor_x += row.get_char_size(row.cx2rx[cursor_x]);
// → moving to next word
Expand Down Expand Up @@ -539,9 +528,7 @@ impl Editor {

/// Return whether the file being edited is empty or not. If there is more than one row, even if
/// all the rows are empty, `is_empty` returns `false`, since the text contains new lines.
fn is_empty(&self) -> bool {
self.rows.len() <= 1 && self.n_bytes == 0
}
fn is_empty(&self) -> bool { self.rows.len() <= 1 && self.n_bytes == 0 }

/// Draw rows of text and empty rows on the terminal, by adding characters to the buffer.
fn draw_rows(&self, buffer: &mut String) -> Result<(), Error> {
Expand Down Expand Up @@ -658,9 +645,8 @@ impl Editor {
}
None => prompt_mode = Some(PromptMode::Save(String::new())),
},
Key::Char(FIND) => {
prompt_mode = Some(PromptMode::Find(String::new(), self.cursor.clone(), None))
}
Key::Char(FIND) =>
prompt_mode = Some(PromptMode::Find(String::new(), self.cursor.clone(), None)),
Key::Char(GOTO) => prompt_mode = Some(PromptMode::GoTo(String::new())),
Key::Char(DUPLICATE) => self.duplicate_current_row(),
Key::Char(CUT) => {
Expand Down Expand Up @@ -786,9 +772,8 @@ impl PromptMode {
match process_prompt_keypress(b, key) {
PromptState::Active(query) => {
let (last_match, forward) = match key {
Key::Arrow(AKey::Right | AKey::Down) | Key::Char(FIND) => {
(last_match, true)
}
Key::Arrow(AKey::Right | AKey::Down) | Key::Char(FIND) =>
(last_match, true),
Key::Arrow(AKey::Left | AKey::Up) => (last_match, false),
_ => (None, true),
};
Expand Down
8 changes: 2 additions & 6 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,10 @@ pub enum Error {

impl From<std::io::Error> for Error {
/// Convert an IO Error into a Kibi Error.
fn from(err: std::io::Error) -> Self {
Self::Io(err)
}
fn from(err: std::io::Error) -> Self { Self::Io(err) }
}

impl From<std::fmt::Error> for Error {
/// Convert an Fmt Error into a Kibi Error.
fn from(err: std::fmt::Error) -> Self {
Self::Fmt(err)
}
fn from(err: std::fmt::Error) -> Self { Self::Fmt(err) }
}
24 changes: 8 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,13 @@ mod row;
mod syntax;
mod terminal;

#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as sys;
#[cfg(windows)] mod windows;
#[cfg(windows)] use windows as sys;

#[cfg(unix)]
mod unix;
#[cfg(unix)]
mod xdg;
#[cfg(unix)]
use unix as sys;
#[cfg(unix)] mod unix;
#[cfg(unix)] mod xdg;
#[cfg(unix)] use unix as sys;

#[cfg(target_os = "wasi")]
mod wasi;
#[cfg(target_os = "wasi")]
mod xdg;
#[cfg(target_os = "wasi")]
use wasi as sys;
#[cfg(target_os = "wasi")] mod wasi;
#[cfg(target_os = "wasi")] mod xdg;
#[cfg(target_os = "wasi")] use wasi as sys;
4 changes: 1 addition & 3 deletions src/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ pub struct Row {

impl Row {
/// Create a new row, containing characters `chars`.
pub fn new(chars: Vec<u8>) -> Self {
Self { chars, cx2rx: vec![0], ..Self::default() }
}
pub fn new(chars: Vec<u8>) -> Self { Self { chars, cx2rx: vec![0], ..Self::default() } }

// TODO: Combine update and update_syntax
/// Update the row: convert tabs into spaces and compute highlight symbols
Expand Down
14 changes: 5 additions & 9 deletions src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ pub enum HlType {

impl Display for HlType {
/// Write the ANSI color escape sequence for the `HLType` using the given formatter.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "\x1b[{}m", (*self as u32) % 100)
}
fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "\x1b[{}m", (*self as u32) % 100) }
}

/// Configuration for syntax highlighting.
Expand Down Expand Up @@ -55,14 +53,13 @@ impl Conf {
pub fn get(ext: &str) -> Result<Option<Self>, Error> {
for conf_dir in sys::data_dirs() {
match PathBuf::from(conf_dir).join("syntax.d").read_dir() {
Ok(dir_entries) => {
Ok(dir_entries) =>
for dir_entry in dir_entries {
let (sc, extensions) = Self::from_file(&dir_entry?.path())?;
if extensions.into_iter().any(|e| e == ext) {
return Ok(Some(sc));
};
}
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e.into()),
}
Expand All @@ -79,12 +76,11 @@ impl Conf {
"highlight_numbers" => sc.highlight_numbers = pv(val)?,
"singleline_string_quotes" => sc.sl_string_quotes = pvs(val)?,
"singleline_comment_start" => sc.sl_comment_start = pvs(val)?,
"multiline_comment_delims" => {
"multiline_comment_delims" =>
sc.ml_comment_delims = match &val.split(',').collect::<Vec<_>>()[..] {
[v1, v2] => Some((pv(v1)?, pv(v2)?)),
d => return Err(format!("Expected 2 delimiters, got {}", d.len())),
}
}
},
"multiline_string_delim" => sc.ml_string_delim = Some(pv(val)?),
"keywords_1" => sc.keywords.push((HlType::Keyword1, pvs(val)?)),
"keywords_2" => sc.keywords.push((HlType::Keyword2, pvs(val)?)),
Expand Down
16 changes: 4 additions & 12 deletions src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ pub fn get_window_size() -> Result<(usize, usize), Error> {
static WSC: AtomicBool = AtomicBool::new(false);

/// Handle a change in window size.
extern "C" fn handle_wsize(_: c_int, _: *mut siginfo_t, _: *mut c_void) {
WSC.store(true, Relaxed)
}
extern "C" fn handle_wsize(_: c_int, _: *mut siginfo_t, _: *mut c_void) { WSC.store(true, Relaxed) }

/// Register a signal handler that sets a global variable when the window size changes.
/// After calling this function, use `has_window_size_changed` to query the global variable.
Expand All @@ -56,9 +54,7 @@ pub fn register_winsize_change_signal_handler() -> Result<(), Error> {

/// Check if the windows size has changed since the last call to this function.
/// The `register_winsize_change_signal_handler` needs to be called before this function.
pub fn has_window_size_changed() -> bool {
WSC.swap(false, Relaxed)
}
pub fn has_window_size_changed() -> bool { WSC.swap(false, Relaxed) }

/// Set the terminal mode.
pub fn set_term_mode(term: &TermMode) -> Result<(), Error> {
Expand All @@ -82,10 +78,6 @@ pub fn enable_raw_mode() -> Result<TermMode, Error> {
}

#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn stdin() -> std::io::Result<std::io::Stdin> {
Ok(std::io::stdin())
}
pub fn stdin() -> std::io::Result<std::io::Stdin> { Ok(std::io::stdin()) }

pub fn path(filename: &str) -> std::path::PathBuf {
std::path::PathBuf::from(filename)
}
pub fn path(filename: &str) -> std::path::PathBuf { std::path::PathBuf::from(filename) }
24 changes: 6 additions & 18 deletions src/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,26 @@ pub struct TermMode {}

/// Return the current window size as (rows, columns).
/// By returning an error we cause kibi to fall back to another method of getting the window size
pub fn get_window_size() -> Result<(usize, usize), Error> {
Err(Error::InvalidWindowSize)
}
pub fn get_window_size() -> Result<(usize, usize), Error> { Err(Error::InvalidWindowSize) }

/// Register a signal handler that sets a global variable when the window size changes. On WASI
/// platforms, this does nothing.
#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn register_winsize_change_signal_handler() -> Result<(), Error> {
Ok(())
}
pub fn register_winsize_change_signal_handler() -> Result<(), Error> { Ok(()) }

/// Check if the windows size has changed since the last call to this function. On WASI platforms,
/// this always return false.
pub fn has_window_size_changed() -> bool {
false
}
pub fn has_window_size_changed() -> bool { false }

/// Set the terminal mode. On WASI platforms, this does nothing.
#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn set_term_mode(_term: &TermMode) -> Result<(), Error> {
Ok(())
}
pub fn set_term_mode(_term: &TermMode) -> Result<(), Error> { Ok(()) }

// Opening the file /dev/tty is effectively the same as `raw_mode`
#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn enable_raw_mode() -> Result<TermMode, Error> {
Ok(TermMode {})
}
pub fn enable_raw_mode() -> Result<TermMode, Error> { Ok(TermMode {}) }

pub fn stdin() -> std::io::Result<std::fs::File> {
std::fs::File::open("/dev/tty")
}
pub fn stdin() -> std::io::Result<std::fs::File> { std::fs::File::open("/dev/tty") }

pub fn path(filename: &str) -> std::path::PathBuf {
// If the filename is absolute then it starts with a forward slash and we
Expand Down
24 changes: 6 additions & 18 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,10 @@ use crate::Error;
pub type TermMode = (u32, u32);

/// Return configuration directories for Windows systems
pub fn conf_dirs() -> Vec<String> {
var("APPDATA").map(|d| d + "/Kibi").into_iter().collect()
}
pub fn conf_dirs() -> Vec<String> { var("APPDATA").map(|d| d + "/Kibi").into_iter().collect() }

/// Return data directories for Windows systems
pub fn data_dirs() -> Vec<String> {
conf_dirs()
}
pub fn data_dirs() -> Vec<String> { conf_dirs() }

/// Return the current window size as (rows, columns).
pub fn get_window_size() -> Result<(usize, usize), Error> {
Expand All @@ -35,13 +31,9 @@ pub fn get_window_size() -> Result<(usize, usize), Error> {
}

#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn register_winsize_change_signal_handler() -> Result<(), Error> {
Ok(())
}
pub fn register_winsize_change_signal_handler() -> Result<(), Error> { Ok(()) }

pub fn has_window_size_changed() -> bool {
false
}
pub fn has_window_size_changed() -> bool { false }

/// Set the terminal mode.
#[allow(clippy::trivially_copy_pass_by_ref)]
Expand Down Expand Up @@ -69,10 +61,6 @@ pub fn enable_raw_mode() -> Result<TermMode, Error> {
}

#[allow(clippy::unnecessary_wraps)] // Result required on other platforms
pub fn stdin() -> std::io::Result<std::io::Stdin> {
Ok(std::io::stdin())
}
pub fn stdin() -> std::io::Result<std::io::Stdin> { Ok(std::io::stdin()) }

pub fn path(filename: &str) -> std::path::PathBuf {
std::path::PathBuf::from(filename)
}
pub fn path(filename: &str) -> std::path::PathBuf { std::path::PathBuf::from(filename) }
4 changes: 1 addition & 3 deletions src/xdg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ pub(crate) fn xdg_dirs(xdg_type: &str, def_home_suffix: &str, def_dirs: &str) ->
}

/// Return configuration directories for UNIX systems
pub fn conf_dirs() -> Vec<String> {
xdg_dirs("CONFIG", "/.config", "/etc/xdg:/etc")
}
pub fn conf_dirs() -> Vec<String> { xdg_dirs("CONFIG", "/.config", "/etc/xdg:/etc") }

/// Return syntax directories for UNIX systems
pub fn data_dirs() -> Vec<String> {
Expand Down

0 comments on commit c4cbd60

Please sign in to comment.