WIP - Run substring search when typing in find bar

Max Brunsfeld and Nathan Sobo created

Co-Authored-By: Nathan Sobo <nathan@zed.dev>

Change summary

Cargo.lock              |  1 
crates/find/Cargo.toml  |  1 
crates/find/src/find.rs | 44 ++++++++++++++++++++++++++++++++++++++----
3 files changed, 41 insertions(+), 5 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -1723,6 +1723,7 @@ dependencies = [
 name = "find"
 version = "0.1.0"
 dependencies = [
+ "aho-corasick",
  "editor",
  "gpui",
  "postage",

crates/find/Cargo.toml 🔗

@@ -7,6 +7,7 @@ edition = "2021"
 path = "src/find.rs"
 
 [dependencies]
+aho-corasick = "0.7"
 editor = { path = "../editor" }
 gpui = { path = "../gpui" }
 workspace = { path = "../workspace" }

crates/find/src/find.rs 🔗

@@ -1,3 +1,4 @@
+use aho_corasick::AhoCorasick;
 use editor::{Editor, EditorSettings};
 use gpui::{
     action, elements::*, keymap::Binding, Entity, MutableAppContext, RenderContext, View,
@@ -8,14 +9,15 @@ use std::sync::Arc;
 use workspace::{ItemViewHandle, Settings, Toolbar, Workspace};
 
 action!(Deploy);
+action!(Cancel);
 
 pub fn init(cx: &mut MutableAppContext) {
-    cx.add_bindings([Binding::new(
-        "cmd-f",
-        Deploy,
-        Some("Editor && mode == full"),
-    )]);
+    cx.add_bindings([
+        Binding::new("cmd-f", Deploy, Some("Editor && mode == full")),
+        Binding::new("escape", Cancel, Some("FindBar")),
+    ]);
     cx.add_action(FindBar::deploy);
+    cx.add_action(FindBar::cancel);
 }
 
 struct FindBar {
@@ -33,6 +35,10 @@ impl View for FindBar {
         "FindBar"
     }
 
+    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
+        cx.focus(&self.query_editor);
+    }
+
     fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
         ChildView::new(&self.query_editor)
             .contained()
@@ -95,4 +101,32 @@ impl FindBar {
             .active_pane()
             .update(cx, |pane, cx| pane.hide_toolbar(cx));
     }
+
+    fn on_query_editor_event(
+        &mut self,
+        _: ViewHandle<Editor>,
+        _: &editor::Event,
+        cx: &mut ViewContext<Self>,
+    ) {
+        if let Some(editor) = &self.active_editor {
+            let search = self.query_editor.read(cx).text(cx);
+            if search.is_empty() {
+                return;
+            }
+            let search = AhoCorasick::new_auto_configured(&[search]);
+            editor.update(cx, |editor, cx| {
+                let buffer = editor.buffer().read(cx).snapshot(cx);
+                let mut ranges = search
+                    .stream_find_iter(buffer.bytes_in_range(0..buffer.len()))
+                    .map(|mat| {
+                        let mat = mat.unwrap();
+                        mat.start()..mat.end()
+                    })
+                    .peekable();
+                if ranges.peek().is_some() {
+                    editor.select_ranges(ranges, None, cx);
+                }
+            });
+        }
+    }
 }