https://github.com/medismailben created 
https://github.com/llvm/llvm-project/pull/237516

This patch lets the user filter the picker's rows by pressing `/` and
typing a query. A row is shown if any of its columns contains the query,
ignoring case. While the search prompt is open, printable keys edit the
query and the arrow keys keep moving through the matches. Enter applies
the filter and returns to navigation, ESC clears it, and Backspace on an
empty query leaves the prompt.

The footer shows the active filter and how many rows it hides. In
multi-select mode, rows hidden by the filter keep their checked state and
are still returned on confirm.

To support this, `ReadKey` now returns printable characters as-is, and the
mapping of `j`, `k`, `s`, and Space to actions moves into `HandleKey`. A
read failure or Ctrl+C always cancels the picker, even while searching.

Assisted-by: Claude
Signed-off-by: Med Ismail Bennani <[email protected]>

---

<sub>Stack created with <a href="https://github.com/github/gh-stack";>GitHub 
Stacks CLI</a> • <a href="https://gh.io/stacks-feedback";>Give Feedback 
💬</a></sub>

>From 16e328b2128373748a2deb0f303db998eb3c15bd Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani <[email protected]>
Date: Mon, 5 Oct 2026 17:45:49 -0700
Subject: [PATCH] [lldb] Add search to IOHandlerPicker

This patch lets the user filter the picker's rows by pressing `/` and
typing a query. A row is shown if any of its columns contains the query,
ignoring case. While the search prompt is open, printable keys edit the
query and the arrow keys keep moving through the matches. Enter applies
the filter and returns to navigation, ESC clears it, and Backspace on an
empty query leaves the prompt.

The footer shows the active filter and how many rows it hides. In
multi-select mode, rows hidden by the filter keep their checked state and
are still returned on confirm.

To support this, `ReadKey` now returns printable characters as-is, and the
mapping of `j`, `k`, `s`, and Space to actions moves into `HandleKey`. A
read failure or Ctrl+C always cancels the picker, even while searching.

Assisted-by: Claude
Signed-off-by: Med Ismail Bennani <[email protected]>
---
 lldb/include/lldb/Core/IOHandlerPicker.h      |  33 ++-
 lldb/source/Core/IOHandlerPicker.cpp          | 245 ++++++++++++------
 .../iohandler/picker/TestIOHandlerPicker.py   |  51 ++++
 3 files changed, 238 insertions(+), 91 deletions(-)

diff --git a/lldb/include/lldb/Core/IOHandlerPicker.h 
b/lldb/include/lldb/Core/IOHandlerPicker.h
index 21736eef586e4..e7d4d14d44f48 100644
--- a/lldb/include/lldb/Core/IOHandlerPicker.h
+++ b/lldb/include/lldb/Core/IOHandlerPicker.h
@@ -38,10 +38,10 @@ struct PickerResult {
 
 /// An interactive ANSI-based picker IOHandler.
 ///
-/// Supports single-select and multi-select modes, column sorting, vim-style
-/// navigation, and scrolling. Works in any terminal that supports basic ANSI
-/// escape codes. Reports a canceled result if the input is not an interactive
-/// terminal.
+/// Supports single-select and multi-select modes, column sorting, filtering
+/// rows by a search query, vim-style navigation, and scrolling. Works in any
+/// terminal that supports basic ANSI escape codes. Reports a canceled result
+/// if the input is not an interactive terminal.
 class IOHandlerPicker : public IOHandler {
 public:
   IOHandlerPicker(Debugger &debugger, llvm::StringRef header,
@@ -66,15 +66,23 @@ class IOHandlerPicker : public IOHandler {
     PageDown,
     Home,
     End,
-    Space,
     Enter,
-    Sort,
+    Backspace,
+    Escape,
+    /// Ctrl+C or a read failure, which always cancel the picker.
+    Abort,
     /// A byte arrived on m_wakeup_pipe.
     Wakeup,
-    Escape,
+    /// A printable character, stored in KeyPress::ch.
+    Char,
     Unknown,
   };
 
+  struct KeyPress {
+    Key key;
+    char ch = 0;
+  };
+
   struct SortOrder {
     size_t column;
     bool ascending;
@@ -86,14 +94,16 @@ class IOHandlerPicker : public IOHandler {
   bool EnterRawMode();
   void RestoreTerminalMode();
 
-  Key ReadKey();
+  KeyPress ReadKey();
   Input WaitForInput();
   std::optional<char> ReadByte();
   Key ReadEscapeSequence();
-  static Key DecodeByte(char c);
+  static KeyPress DecodeByte(char c);
   static Key DecodeEscapeSequence(llvm::StringRef params, char final_byte);
   void WakeUp();
 
+  void HandleKey(KeyPress press);
+  void HandleSearchKey(KeyPress press);
   void Render();
   void ScrollToCursor();
   void CycleSort();
@@ -117,11 +127,14 @@ class IOHandlerPicker : public IOHandler {
   /// Bit i is set if m_items[i] is checked.
   llvm::BitVector m_checked;
 
-  /// Indices into m_items of the rows to show, in display order.
+  /// Indices into m_items of the rows that match m_query, in display order.
   llvm::SmallVector<size_t, 0> m_visible_indices;
   /// Sort column and direction, or std::nullopt for the original order.
   std::optional<SortOrder> m_sort_order;
 
+  std::string m_query;
+  bool m_searching = false;
+
   llvm::SmallVector<size_t> m_column_widths;
 
   /// Cached with m_column_widths so a frame never mixes two terminal sizes.
diff --git a/lldb/source/Core/IOHandlerPicker.cpp 
b/lldb/source/Core/IOHandlerPicker.cpp
index 240227d465448..d6a52c589409c 100644
--- a/lldb/source/Core/IOHandlerPicker.cpp
+++ b/lldb/source/Core/IOHandlerPicker.cpp
@@ -15,6 +15,7 @@
 #include "lldb/Utility/Log.h"
 #include "lldb/Utility/SelectHelper.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Locale.h"
@@ -26,7 +27,6 @@
 #include <algorithm>
 #include <cassert>
 #include <chrono>
-#include <numeric>
 
 using namespace lldb;
 using namespace lldb_private;
@@ -49,6 +49,7 @@ static constexpr size_t g_reserved_lines = 5;
 
 static constexpr char g_ctrl_c = 0x03;
 static constexpr char g_escape = 0x1b;
+static constexpr char g_delete = 0x7f; // Backspace on most terminals.
 
 static constexpr std::chrono::milliseconds g_escape_sequence_timeout(100);
 
@@ -159,21 +160,21 @@ void IOHandlerPicker::RestoreTerminalMode() {
   }
 }
 
-IOHandlerPicker::Key IOHandlerPicker::ReadKey() {
+IOHandlerPicker::KeyPress IOHandlerPicker::ReadKey() {
   switch (WaitForInput()) {
   case Input::Ready:
     break;
   case Input::Wakeup:
-    return Key::Wakeup;
+    return {Key::Wakeup};
   case Input::Error:
-    return Key::Escape;
+    return {Key::Abort};
   }
 
   std::optional<char> c = ReadByte();
   if (!c)
-    return Key::Escape;
+    return {Key::Abort};
   if (*c == g_escape)
-    return ReadEscapeSequence();
+    return {ReadEscapeSequence()};
   return DecodeByte(*c);
 }
 
@@ -228,28 +229,24 @@ IOHandlerPicker::Key 
IOHandlerPicker::ReadEscapeSequence() {
     final_byte = ReadByte();
   }
   if (!final_byte)
-    return Key::Escape;
+    return Key::Abort;
   return DecodeEscapeSequence(params, *final_byte);
 }
 
-IOHandlerPicker::Key IOHandlerPicker::DecodeByte(char c) {
+IOHandlerPicker::KeyPress IOHandlerPicker::DecodeByte(char c) {
   switch (c) {
   case '\r':
   case '\n':
-    return Key::Enter;
-  case ' ':
-    return Key::Space;
-  case 'k':
-    return Key::Up;
-  case 'j':
-    return Key::Down;
-  case 's':
-  case 'S':
-    return Key::Sort;
+    return {Key::Enter};
+  case '\b':
+  case g_delete:
+    return {Key::Backspace};
   case g_ctrl_c: // Raw mode disables SIGINT, so Ctrl+C arrives as a byte.
-    return Key::Escape;
+    return {Key::Abort};
   default:
-    return Key::Unknown;
+    if (llvm::isPrint(c))
+      return {Key::Char, c};
+    return {Key::Unknown};
   }
 }
 
@@ -303,12 +300,18 @@ void IOHandlerPicker::CycleSort() {
 
 void IOHandlerPicker::UpdateVisibleIndices() {
   // Start from the item order, which the stable sort keeps for ties.
-  m_visible_indices.resize(m_items.size());
-  std::iota(m_visible_indices.begin(), m_visible_indices.end(), 0);
+  m_visible_indices.clear();
+  for (auto [i, item] : llvm::enumerate(m_items)) {
+    if (m_query.empty() ||
+        llvm::any_of(item.values, [&](llvm::StringRef value) {
+          return value.contains_insensitive(m_query);
+        }))
+      m_visible_indices.push_back(i);
+  }
   if (m_sort_order)
     SortVisibleIndices(*m_sort_order);
 
-  // Jump to the top so the new order is visible.
+  // Jump to the top so the new order or matches are visible.
   m_cursor_index = 0;
   m_viewport_start = 0;
 }
@@ -349,12 +352,18 @@ void IOHandlerPicker::Render() {
 
   write_line(ANSI_ESCAPE1(ANSI_CTRL_BOLD), m_header);
 
-  llvm::StringRef help =
-      m_mode == PickerMode::SingleSelect
-          ? "  jk: navigate  Enter: select  s: sort  ESC: cancel"
-          : "  jk: navigate  Space: toggle  Enter: confirm  s: sort  "
-            "ESC: cancel";
-  write_line(ANSI_ESCAPE1(ANSI_CTRL_FAINT), help);
+  if (m_searching) {
+    std::string prompt = "  /" + m_query + "_";
+    prompt += ANSI_ESCAPE1(ANSI_CTRL_FAINT) "    Enter: apply  ESC: clear";
+    write_line("", prompt);
+  } else {
+    llvm::StringRef help =
+        m_mode == PickerMode::SingleSelect
+            ? "  jk: navigate  Enter: select  s: sort  /: search  ESC: cancel"
+            : "  jk: navigate  Space: toggle  Enter: confirm  s: sort  "
+              "/: search  ESC: cancel";
+    write_line(ANSI_ESCAPE1(ANSI_CTRL_FAINT), help);
+  }
 
   std::string column_names(GetPrefixWidth(), ' ');
   for (size_t i = 0; i < m_columns.size(); ++i) {
@@ -395,22 +404,133 @@ void IOHandlerPicker::Render() {
     write_line(is_cursor ? ANSI_ESCAPE1(ANSI_CTRL_IMAGE_NEGATIVE) : "", row);
   }
 
-  std::string footer =
-      m_mode == PickerMode::MultiSelect
-          ? llvm::formatv("  {0}/{1} selected", m_checked.count(),
-                          m_items.size())
-                .str()
-          : llvm::formatv("  {0}/{1}", m_cursor_index + 1, m_items.size())
-                .str();
+  std::string footer;
+  if (m_mode == PickerMode::MultiSelect)
+    footer =
+        llvm::formatv("  {0}/{1} selected", m_checked.count(), m_items.size())
+            .str();
+  else if (!m_visible_indices.empty())
+    footer =
+        llvm::formatv("  {0}/{1}", m_cursor_index + 1, 
m_visible_indices.size())
+            .str();
+  if (m_visible_indices.empty())
+    footer += "  no matches";
+  else if (!m_query.empty() && !m_searching)
+    footer += "  filter: " + m_query;
+  if (size_t hidden = m_items.size() - m_visible_indices.size())
+    footer += llvm::formatv("  ({0} hidden)", hidden).str();
   if (end < m_visible_indices.size())
     footer += "  [more below]";
   if (m_viewport_start > 0)
     footer += "  [more above]";
   write_line(ANSI_ESCAPE1(ANSI_CTRL_FAINT), footer);
 
+  // Filtering can shrink the list, so erase rows left over from the previous
+  // frame.
+  frame += ANSI_CSI_ED(0);
+
   GetOutputStreamFileSP()->Lock() << frame;
 }
 
+void IOHandlerPicker::HandleKey(KeyPress press) {
+  const size_t count = m_visible_indices.size();
+  switch (press.key) {
+  case Key::Up:
+    if (m_cursor_index > 0)
+      --m_cursor_index;
+    break;
+  case Key::Down:
+    if (m_cursor_index + 1 < count)
+      ++m_cursor_index;
+    break;
+  case Key::PageUp:
+    m_cursor_index -= std::min(m_cursor_index, GetViewportHeight());
+    break;
+  case Key::PageDown:
+    if (count)
+      m_cursor_index =
+          std::min(m_cursor_index + GetViewportHeight(), count - 1);
+    break;
+  case Key::Home:
+    m_cursor_index = 0;
+    break;
+  case Key::End:
+    if (count)
+      m_cursor_index = count - 1;
+    break;
+  case Key::Enter:
+    if (m_mode == PickerMode::SingleSelect) {
+      if (!count)
+        break;
+      m_result.selected_indices.push_back(m_visible_indices[m_cursor_index]);
+    } else {
+      // Items hidden by the filter stay checked.
+      for (unsigned i : m_checked.set_bits())
+        m_result.selected_indices.push_back(i);
+    }
+    SetIsDone(true);
+    break;
+  case Key::Escape:
+    Cancel();
+    break;
+  case Key::Char:
+    switch (press.ch) {
+    case 'k':
+      HandleKey({Key::Up});
+      break;
+    case 'j':
+      HandleKey({Key::Down});
+      break;
+    case 's':
+    case 'S':
+      CycleSort();
+      break;
+    case ' ':
+      if (m_mode == PickerMode::MultiSelect && count)
+        m_checked.flip(m_visible_indices[m_cursor_index]);
+      break;
+    case '/':
+      m_searching = true;
+      break;
+    }
+    break;
+  case Key::Backspace:
+  case Key::Abort:
+  case Key::Wakeup:
+  case Key::Unknown:
+    break;
+  }
+}
+
+void IOHandlerPicker::HandleSearchKey(KeyPress press) {
+  switch (press.key) {
+  case Key::Char:
+    m_query += press.ch;
+    UpdateVisibleIndices();
+    break;
+  case Key::Backspace:
+    if (m_query.empty()) {
+      m_searching = false;
+      break;
+    }
+    m_query.pop_back();
+    UpdateVisibleIndices();
+    break;
+  case Key::Enter:
+    m_searching = false;
+    break;
+  case Key::Escape:
+    m_searching = false;
+    m_query.clear();
+    UpdateVisibleIndices();
+    break;
+  default:
+    // Arrow keys keep navigating the matches while typing.
+    HandleKey(press);
+    break;
+  }
+}
+
 void IOHandlerPicker::Run() {
   if (!GetIsRealTerminal() || m_items.empty() || !EnterRawMode()) {
     m_result.was_canceled = true;
@@ -433,57 +553,20 @@ void IOHandlerPicker::Run() {
   Render();
 
   while (!GetIsDone()) {
-    switch (ReadKey()) {
-    case Key::Up:
-      if (m_cursor_index > 0)
-        --m_cursor_index;
-      break;
-    case Key::Down:
-      if (m_cursor_index + 1 < m_items.size())
-        ++m_cursor_index;
-      break;
-    case Key::PageUp:
-      m_cursor_index -= std::min(m_cursor_index, GetViewportHeight());
-      break;
-    case Key::PageDown:
-      m_cursor_index =
-          std::min(m_cursor_index + GetViewportHeight(), m_items.size() - 1);
-      break;
-    case Key::Home:
-      m_cursor_index = 0;
-      break;
-    case Key::End:
-      m_cursor_index = m_items.size() - 1;
-      break;
-    case Key::Sort:
-      CycleSort();
-      break;
-    case Key::Wakeup:
+    KeyPress press = ReadKey();
+    if (press.key == Key::Abort) {
+      Cancel();
+    } else if (press.key == Key::Wakeup) {
       // Unless Cancel() woke us up, the terminal was resized.
       if (!GetIsDone()) {
         UpdateLayout();
         // Rows may now be narrower than the previous frame, so wipe it.
         GetOutputStreamFileSP()->Lock() << ANSI_CSI_ERASE_VIEWPORT;
       }
-      break;
-    case Key::Space:
-      if (m_mode == PickerMode::MultiSelect)
-        m_checked.flip(m_visible_indices[m_cursor_index]);
-      break;
-    case Key::Enter:
-      if (m_mode == PickerMode::SingleSelect) {
-        m_result.selected_indices.push_back(m_visible_indices[m_cursor_index]);
-      } else {
-        for (unsigned i : m_checked.set_bits())
-          m_result.selected_indices.push_back(i);
-      }
-      SetIsDone(true);
-      break;
-    case Key::Escape:
-      Cancel();
-      break;
-    case Key::Unknown:
-      break;
+    } else if (m_searching) {
+      HandleSearchKey(press);
+    } else {
+      HandleKey(press);
     }
 
     if (!GetIsDone()) {
diff --git a/lldb/test/API/iohandler/picker/TestIOHandlerPicker.py 
b/lldb/test/API/iohandler/picker/TestIOHandlerPicker.py
index eaf42a52ebd2f..a290609f65128 100644
--- a/lldb/test/API/iohandler/picker/TestIOHandlerPicker.py
+++ b/lldb/test/API/iohandler/picker/TestIOHandlerPicker.py
@@ -105,3 +105,54 @@ def test_small_terminal_scrolls(self):
         self.child.expect_exact("[more above]")
         self.child.send("\r")
         self.finish("selected: 14")
+
+    def test_search_filters_rows(self):
+        """/ filters rows to those with a column containing the query."""
+        self.start_picker("test-picker single 26", "Select an item:")
+        # Matches quebec (17) and echo (5). Enter applies the filter.
+        self.child.send("/ec\r")
+        self.child.expect_exact("filter: ec  (24 hidden)")
+        self.child.send("j\r")
+        self.finish("selected: 5")
+
+    def test_search_typing_is_not_navigation(self):
+        """While searching, j/k/s/Space are part of the query and case is
+        ignored."""
+        self.start_picker("test-picker single 26", "Select an item:")
+        self.child.send("/jULIET\r\r")
+        self.finish("selected: 10")
+
+    def test_search_backspace(self):
+        """Backspace edits the query and brings back matches."""
+        self.start_picker("test-picker single 26", "Select an item:")
+        self.child.send("/ecx")
+        self.child.expect_exact("no matches  (26 hidden)")
+        self.child.send("\x7f\r\r")
+        self.finish("selected: 17")
+
+    def test_search_ignores_unhandled_sequences(self):
+        """Ignored escape sequences don't edit the query."""
+        self.start_picker("test-picker single 26", "Select an item:")
+        # Delete is "ESC [ 3 ~".
+        self.child.send("/ec\x1b[3~\r")
+        self.child.expect_exact("filter: ec  (24 hidden)")
+        self.child.send("j\r")
+        self.finish("selected: 5")
+
+    def test_search_escape_clears(self):
+        """ESC while searching clears the filter instead of canceling."""
+        self.start_picker("test-picker single 26", "Select an item:")
+        self.child.send("/zz")
+        self.child.expect_exact("/zz_")
+        self.child.send(self.escape_key)
+        self.child.expect_exact("/: search")
+        self.child.send("\r")
+        self.finish("selected: 26")
+
+    def test_search_multi_keeps_hidden_selection(self):
+        """Items hidden by the filter stay checked in multi-select mode."""
+        self.start_picker("test-picker multi 5", "Toggle items:")
+        # Matches echo (5) and charlie (3); check 5. 4 and 1 are hidden but
+        # stay pre-selected.
+        self.child.send("/ch\r \r")
+        self.finish("selected: 5", "selected: 4", "selected: 1")

_______________________________________________
llvm-branch-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits

Reply via email to