Skip to content

Commit

Permalink
Better sorting in picker in case of ties
Browse files Browse the repository at this point in the history
  • Loading branch information
matklad committed Dec 15, 2022
1 parent ec9aa66 commit 96359a6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
3 changes: 2 additions & 1 deletion helix-term/src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,14 @@ pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePi

// Cap the number of files if we aren't in a git project, preventing
// hangs when using the picker in your home directory
let files: Vec<_> = if root.join(".git").exists() {
let mut files: Vec<PathBuf> = if root.join(".git").exists() {
files.collect()
} else {
// const MAX: usize = 8192;
const MAX: usize = 100_000;
files.take(MAX).collect()
};
files.sort();

log::debug!("file_picker init {:?}", Instant::now().duration_since(now));

Expand Down
36 changes: 27 additions & 9 deletions helix-term/src/ui/picker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ use tui::{
use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
use tui::widgets::Widget;

use std::{cmp::Ordering, time::Instant};
use std::{
cmp::{self, Ordering},
time::Instant,
};
use std::{collections::HashMap, io::Read, path::PathBuf};

use crate::ui::{Prompt, PromptEvent};
Expand Down Expand Up @@ -344,11 +347,17 @@ impl<T: Item + 'static> Component for FilePicker<T> {

#[derive(PartialEq, Eq, Debug)]
struct PickerMatch {
index: usize,
score: i64,
index: usize,
len: usize,
}

impl PickerMatch {
fn key(&self) -> impl Ord {
(cmp::Reverse(self.score), self.index, self.len)
}
}

impl PartialOrd for PickerMatch {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
Expand All @@ -357,10 +366,7 @@ impl PartialOrd for PickerMatch {

impl Ord for PickerMatch {
fn cmp(&self, other: &Self) -> Ordering {
self.score
.cmp(&other.score)
.reverse()
.then_with(|| self.len.cmp(&other.len))
self.key().cmp(&other.key())
}
}

Expand Down Expand Up @@ -467,8 +473,7 @@ impl<T: Item> Picker<T> {
None => false,
}
});

self.matches.sort_unstable();
self.sort_matches();
} else {
self.force_score();
}
Expand Down Expand Up @@ -502,7 +507,20 @@ impl<T: Item> Picker<T> {
})
}),
);
self.matches.sort_unstable();
self.sort_matches();
}

/// Sort matches by (score, text).
fn sort_matches(&mut self) {
self.matches.sort_unstable_by(|l, r| {
l.cmp(r).then_with(|| {
let l_option = &self.options[l.index];
let l_text = l_option.filter_text(&self.editor_data);
let r_option = &self.options[r.index];
let r_text = r_option.filter_text(&self.editor_data);
l_text.cmp(&r_text)
})
});
}

/// Move the cursor by a number of lines, either down (`Forward`) or up (`Backward`)
Expand Down

0 comments on commit 96359a6

Please sign in to comment.