diff --git a/README.md b/README.md
index 76fe9c4..d523b32 100644
--- a/README.md
+++ b/README.md
@@ -1,116 +1,116 @@
# ivy.nvim
An [ivy-mode](https://github.com/abo-abo/swiper#ivy) port to neovim. Ivy is a
generic completion mechanism for ~~Emacs~~ Nvim
## Installation
### Manually
```sh
git clone https://github.com/AdeAttwood/ivy.nvim ~/.config/nvim/pack/bundle/start/ivy.nvim
```
### Plugin managers
TODO: Add docs in the plugin managers I don't use any
### Compiling
For the native searching, you will need to compile the shard library. You can
do that by running the below command in the root of the plugin.
```sh
cargo build --release
```
You will need to have the rust toolchain installed. You can find more about
that [here](https://www.rust-lang.org/tools/install)
## Features
### Commands
A command can be run that will launch the completion UI
| Command | Key Map | Description |
| ---------- | ----------- | ------------------------------------------------------ |
| IvyFd | \p | Find files in your project with the fd cli file finder |
| IvyAg | \/ | Find content in files using the silver searcher |
| IvyBuffers | \b | Search though open buffers |
| IvyLines | | Search the lines in the current buffer |
### Actions
Action can be run on selected candidates provide functionality
| Action | Description |
| -------- | ------------------------------------------------------------------------------ |
| Complete | Run the completion function, usually this will be opening a file |
| Peek | Run the completion function on a selection, but don't close the results window |
## API
```lua
vim.ivy.run(
-- The name given to the results window and displayed to the user
"Title",
-- Call back function to get all the candidates that will be displayed in
-- the results window, The `input` will be passed in, so you can filter
-- your results with the value from the prompt
function(input) return { "One", "Two", Three } end,
-- Action callback that will be called on the completion or peek actions.
-- The currently selected item is passed in as the result.
function(result) vim.cmd("edit " .. result) end
)
```
## Benchmarks
Benchmarks are of various tasks that ivy will do. The purpose of the benchmarks
are to give us a baseline on where to start when trying to optimize performance
in the matching and sorting, not to put ivy against other tools. When starting
to optimize, you will probably need to get a baseline on your hardware.
There are fixtures provided that will create the directory structure of the
[kubernetes](https://github.com/kubernetes/kubernetes) source code, from
-somewhere arround commit sha 985c9202ccd250a5fe22c01faf0d8f83d804b9f3. This will
+somewhere around commit sha 985c9202ccd250a5fe22c01faf0d8f83d804b9f3. This will
create a directory tree of 23511 files a relative large source tree to get a
good idea of performance. To create the source tree under
`/tmp/ivy-trees/kubernetes` run the following command. This will need to be run
for the benchmarks to run.
```bash
# Create the source trees
bash ./scripts/fixtures.bash
# Run the benchmark script
luajit ./scripts/benchmark.lua
```
Current benchmark status running on a `e2-standard-2` 2 vCPU + 8 GB memory VM
running on GCP.
-Rust
+Rust
-| Name | Total | Adverage | Min | Max |
+| Name | Total | Average | Min | Max |
|--------------------------------|---------------|---------------|---------------|---------------|
| ivy_match(file.lua) 1000000x | 03.961640 (s) | 00.000004 (s) | 00.000003 (s) | 00.002146 (s) |
| ivy_files(kubernetes) 100x | 03.895758 (s) | 00.038958 (s) | 00.034903 (s) | 00.043660 (s) |
CPP
-| Name | Total | Adverage | Min | Max |
+| Name | Total | Average | Min | Max |
|--------------------------------|---------------|---------------|---------------|---------------|
| ivy_match(file.lua) 1000000x | 01.855197 (s) | 00.000002 (s) | 00.000001 (s) | 00.000177 (s) |
| ivy_files(kubernetes) 100x | 14.696396 (s) | 00.146964 (s) | 00.056604 (s) | 00.168478 (s) |
## Other stuff you might like
- [ivy-mode](https://github.com/abo-abo/swiper#ivy) - An emacs package that was the inspiration for this nvim plugin
- [Command-T](https://github.com/wincent/command-t) - Vim plugin I used before I started this one
- [telescope.nvim](https://github.com/nvim-telescope/telescope.nvim) - Another competition plugin, lots of people are using
diff --git a/rust/finder.rs b/rust/finder.rs
index 4a3ccf5..3a4dd31 100644
--- a/rust/finder.rs
+++ b/rust/finder.rs
@@ -1,26 +1,26 @@
use ignore::WalkBuilder;
use std::fs;
pub struct Options {
pub directory: String,
}
pub fn find_files(options: Options) -> Vec {
let mut files: Vec = Vec::new();
let base_path = &fs::canonicalize(options.directory).unwrap();
let mut builder = WalkBuilder::new(base_path);
builder.ignore(true).hidden(true);
for result in builder.build() {
let absolute_candidate = result.unwrap();
let candidate_path = absolute_candidate.path().strip_prefix(base_path).unwrap();
if candidate_path.is_dir() {
continue;
}
files.push(candidate_path.to_str().unwrap().to_string());
}
- return files;
+ files
}
diff --git a/rust/lib.rs b/rust/lib.rs
index 7baaad6..db271bf 100644
--- a/rust/lib.rs
+++ b/rust/lib.rs
@@ -1,71 +1,76 @@
-mod matcher;
mod finder;
+mod matcher;
mod sorter;
mod thread_pool;
-use std::sync::Mutex;
use std::collections::HashMap;
-use std::os::raw::{c_int, c_char};
-use std::ffi::CString;
use std::ffi::CStr;
+use std::ffi::CString;
+use std::os::raw::{c_char, c_int};
+use std::sync::Mutex;
#[macro_use]
extern crate lazy_static;
lazy_static! {
- static ref GLOBAL_FILE_CACHE: Mutex>> = return Mutex::new(HashMap::new()) ;
+ static ref GLOBAL_FILE_CACHE: Mutex>> = Mutex::new(HashMap::new());
}
fn to_string(input: *const c_char) -> String {
- return unsafe { CStr::from_ptr(input) }.to_str().unwrap().to_string();
+ unsafe { CStr::from_ptr(input) }
+ .to_str()
+ .unwrap()
+ .to_string()
}
fn get_files(directory: &String) -> Vec {
let mut cache = GLOBAL_FILE_CACHE.lock().unwrap();
if !cache.contains_key(directory) {
- let finder_options = finder::Options{ directory: directory.clone() };
- cache.insert( directory.clone(), finder::find_files(finder_options));
+ let finder_options = finder::Options {
+ directory: directory.clone(),
+ };
+ cache.insert(directory.clone(), finder::find_files(finder_options));
}
return cache.get(directory).unwrap().to_vec();
}
#[no_mangle]
pub extern "C" fn ivy_init(c_base_dir: *const c_char) {
let directory = to_string(c_base_dir);
get_files(&directory);
}
#[no_mangle]
pub extern "C" fn ivy_match(c_pattern: *const c_char, c_text: *const c_char) -> c_int {
let pattern = to_string(c_pattern);
let text = to_string(c_text);
- let m = matcher::Matcher::new( pattern );
- return m.score(text) as i32;
+ let m = matcher::Matcher::new(pattern);
+
+ m.score(text) as i32
}
#[no_mangle]
pub extern "C" fn ivy_files(c_pattern: *const c_char, c_base_dir: *const c_char) -> *const c_char {
let pattern = to_string(c_pattern);
let directory = to_string(c_base_dir);
// Bail out early if the pattern is empty its never going to find anything
if pattern.is_empty() {
- return CString::new("").unwrap().into_raw()
+ return CString::new("").unwrap().into_raw();
}
let files = get_files(&directory);
let mut output = String::new();
let sorter_options = sorter::Options::new(pattern);
let files = sorter::sort_strings(sorter_options, files);
for file in files.lock().unwrap().iter() {
output.push_str(&file.content);
output.push('\n');
}
- return CString::new(output).unwrap().into_raw()
+ CString::new(output).unwrap().into_raw()
}
-
diff --git a/rust/matcher.rs b/rust/matcher.rs
index 28eac59..0560717 100644
--- a/rust/matcher.rs
+++ b/rust/matcher.rs
@@ -1,25 +1,24 @@
-use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
+use fuzzy_matcher::FuzzyMatcher;
pub struct Matcher {
/// The search pattern that we want to match against some text
pub pattern: String,
matcher: SkimMatcherV2,
}
impl Matcher {
pub fn new(pattern: String) -> Self {
- return Self {
+ Self {
pattern,
matcher: SkimMatcherV2::default(),
}
}
- pub fn score(self: &Self, text: String) -> i64 {
- if let Some((score, _indices)) = self.matcher.fuzzy_indices(&text, &self.pattern) {
- return score;
- }
-
- return 0;
+ pub fn score(&self, text: String) -> i64 {
+ self.matcher
+ .fuzzy_indices(&text, &self.pattern)
+ .map(|(score, _indices)| score)
+ .unwrap_or_default()
}
}
diff --git a/rust/sorter.rs b/rust/sorter.rs
index eccb179..cdb9983 100644
--- a/rust/sorter.rs
+++ b/rust/sorter.rs
@@ -1,48 +1,52 @@
use super::matcher;
use super::thread_pool;
-
-use std::sync::Mutex;
use std::sync::Arc;
+use std::sync::Mutex;
pub struct Match {
pub score: i64,
pub content: String,
}
pub struct Options {
pub pattern: String,
pub minimun_score: i64,
}
impl Options {
pub fn new(pattern: String) -> Self {
- return Self { pattern, minimun_score: 20 };
+ Self {
+ pattern,
+ minimun_score: 20,
+ }
}
}
pub fn sort_strings(options: Options, strings: Vec) -> Arc>> {
let matches: Arc>> = Arc::new(Mutex::new(Vec::new()));
let matcher = Arc::new(Mutex::new(matcher::Matcher::new(options.pattern)));
let pool = thread_pool::ThreadPool::new(std::thread::available_parallelism().unwrap().get());
for string in strings {
let thread_matcher = Arc::clone(&matcher);
let thread_matches = Arc::clone(&matches);
pool.execute(move || {
let score = thread_matcher.lock().unwrap().score(string.to_string());
if score > 25 {
let mut tmp = thread_matches.lock().unwrap();
let content = string.clone();
- tmp.push(Match{ score, content });
+ tmp.push(Match { score, content });
}
})
}
drop(pool);
- matches.lock().unwrap().sort_by(|a, b| a.score.cmp(&b.score));
- return matches;
+ matches
+ .lock()
+ .unwrap()
+ .sort_by(|a, b| a.score.cmp(&b.score));
+ matches
}
-
diff --git a/rust/thread_pool.rs b/rust/thread_pool.rs
index df49872..d2d287e 100644
--- a/rust/thread_pool.rs
+++ b/rust/thread_pool.rs
@@ -1,87 +1,87 @@
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
enum Message {
NewJob(Job),
Terminate,
}
pub struct ThreadPool {
jobs: mpsc::Sender,
threads: Vec,
}
trait FnBox {
fn call_box(self: Box);
}
impl FnBox for F {
fn call_box(self: Box) {
(*self)()
}
}
type Job = Box;
impl ThreadPool {
pub fn new(thread_count: usize) -> Self {
let (jobs, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut threads: Vec = Vec::new();
for id in 1..thread_count {
threads.push(Worker::new(id, Arc::clone(&receiver)));
}
- return ThreadPool { jobs, threads };
+ ThreadPool { jobs, threads }
}
pub fn execute(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.jobs.send(Message::NewJob(job)).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
for _ in &mut self.threads {
self.jobs.send(Message::Terminate).unwrap();
}
for worker in &mut self.threads {
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
- id: usize,
+ _id: usize,
thread: Option>,
}
impl Worker {
fn new(id: usize, receiver: Arc>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv().unwrap();
match message {
Message::NewJob(job) => job.call_box(),
Message::Terminate => {
break;
}
}
});
- return Worker {
- id,
+ Worker {
+ _id: id,
thread: Some(thread),
- };
+ }
}
}
diff --git a/scripts/benchmark.lua b/scripts/benchmark.lua
index 2f1937b..457b671 100644
--- a/scripts/benchmark.lua
+++ b/scripts/benchmark.lua
@@ -1,48 +1,48 @@
package.path = "lua/?.lua;" .. package.path
local libivy = require "ivy.libivy"
local benchmark = function(name, n, callback)
local status = {
running_total = 0,
min = 999999999999999999,
max = -0000000000000000,
}
for _ = 1, n do
local start_time = os.clock()
callback()
local running_time = os.clock() - start_time
status.running_total = status.running_total + running_time
if status.min > running_time then
status.min = running_time
end
if status.max < running_time then
status.max = running_time
end
end
print(
string.format(
"| %-30s | %09.6f (s) | %09.6f (s) | %09.6f (s) | %09.6f (s) |",
name,
status.running_total,
status.running_total / n,
status.min,
status.max
)
)
end
-print "| Name | Total | Adverage | Min | Max |"
+print "| Name | Total | Average | Min | Max |"
print "|--------------------------------|---------------|---------------|---------------|---------------|"
benchmark("ivy_match(file.lua) 1000000x", 1000000, function()
libivy.ivy_match("file.lua", "some/long/path/to/file/file.lua")
end)
libivy.ivy_init "/tmp/ivy-trees/kubernetes"
benchmark("ivy_files(kubernetes) 100x", 100, function()
libivy.ivy_files("file.go", "/tmp/ivy-trees/kubernetes")
end)