projectsearch

package
v1.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package projectsearch runs project-wide text search through ripgrep and holds the surface-neutral state a UI needs to present the results: the flattened file/match list, cursor and scroll bookkeeping, and the search options.

Index

Constants

View Source
const (
	ToggleRegexID = "project-search-toggle-regex"
	ToggleCaseID  = "project-search-toggle-case"
	ToggleWordID  = "project-search-toggle-word"
	OpenActionID  = "project-search-open"
)
View Source
const PreferredWidth = 120

PreferredWidth is how wide the search's box likes to be when the surface has room to spare. It is wider than the finder's because its rows are source lines rather than paths.

Variables

This section is empty.

Functions

func ParseFileID

func ParseFileID(id string) (int, bool)

ParseFileID reports whether id names a file header row, and which one.

func ParseMatchID

func ParseMatchID(id string) (int, int, bool)

ParseMatchID reports whether id names a match row, and which one.

func Run

func Run(workDir string, state *State, epoch uint64) tea.Cmd

Run executes ripgrep and returns results. It snapshots everything the run needs before returning, so the command it hands back touches no shared state.

func RunContext

func RunContext(ctx context.Context, workDir string, state *State, epoch uint64) tea.Cmd

RunContext is Run with a caller-owned context, so a host can kill the ripgrep process when its search surface closes or is superseded rather than leaving it to the timeout. Search.run does exactly that; see Search.Close.

func Schedule

func Schedule(version int, query string) tea.Cmd

Schedule schedules a debounced search. The returned command fires a DebounceMsg after the debounce delay; the caller runs the search only if the version still matches, so newer keystrokes cancel older ones.

Types

type DebounceMsg

type DebounceMsg struct {
	Version int
	Query   string
}

DebounceMsg is sent after debounce delay to trigger search.

type Outcome

type Outcome int

Outcome is what a key or mouse event asked the caller to do. Everything the search can do to itself it has already done by the time it returns; the outcome names only the things it cannot decide, because they belong to whatever surface is hosting it.

const (
	// OutcomeNone: the event was consumed (or ignored) and the host has
	// nothing to do.
	OutcomeNone Outcome = iota
	// OutcomeCancelled: the user dismissed the search. The host should drop it.
	OutcomeCancelled
	// OutcomeOpen: the user chose a result. The host decides what "open" means.
	OutcomeOpen
	// OutcomeOpenExternal: the user asked for the result in their editor
	// (ctrl+e, or a double-click on a row).
	OutcomeOpenExternal
)

type Result

type Result struct {
	Outcome Outcome
	// Path is relative to the search root.
	Path string
	// Line is the 1-based line of the match, or 0 for a file header.
	Line int
	// NewTab is set when the user asked for the result beside what they are
	// already looking at (shift+enter) rather than in place.
	NewTab bool
	// Query is the search text that produced the hit, so a host that wants to
	// highlight it in the opened file has it after the search is dropped.
	Query string
}

Result carries an Outcome plus everything the host needs to act on it.

type ResultsMsg

type ResultsMsg struct {
	Epoch uint64 // Epoch when request was issued (for stale detection)
	// Run is the State.RunToken the run was issued with. Apply drops a message
	// whose token is no longer the newest, so results cannot land out of order.
	// A zero token means "not issued by Run" (a host or a test building the
	// message by hand) and is always applied.
	Run     int
	Results []SearchFileResult
	// Truncated says the run hit the match cap and there were more hits behind
	// it, so the counts row can say so rather than present a cut set as the
	// whole answer.
	Truncated bool
	Error     error
}

ResultsMsg contains results from a search.

func (ResultsMsg) GetEpoch

func (m ResultsMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type Search struct {
	// State is the search's data. It is exported because hosts legitimately
	// inspect it (footer counts, tests) and because the ripgrep runner takes it.
	State *State
	// contains filtered or unexported fields
}

Search is a project-wide search surface: the state, the modal that presents it, and the input handling that drives both. It renders at whatever size it is given, so the same type serves a full screen and a single pane.

It knows nothing about what opening a result means; see Outcome.

func New

func New(root string, epoch uint64) *Search

New creates a search rooted at root. epoch is stamped on the commands it issues, so results for a root the host has since switched away from can be dropped on arrival (see Update).

func (*Search) Apply

func (s *Search) Apply(msg ResultsMsg)

Apply stores a landed results message. Update calls it after the epoch check; a host that does its own staleness filtering can call it directly.

A message from a superseded run is dropped here rather than in Update, because a host that filters staleness itself calls Apply directly and must not be able to opt out of it: two runs in one epoch (the debounced one and the immediate one an option toggle issues) can land in either order.

func (*Search) Close

func (s *Search) Close()

Close releases the search: it kills the ripgrep process still running for it, if any. Hosts call it when they drop the surface — the search is dismissed by dropping the pointer to it, which on its own leaves rg running to its timeout. It is safe to call more than once, and on a search that never ran.

func (*Search) HandleKey

func (s *Search) HandleKey(msg tea.KeyPressMsg) (Result, tea.Cmd)

HandleKey processes a keypress. The returned command is the search's own async work (a debounce tick, a ripgrep run, a modal cursor blink).

func (*Search) HandleMouse

func (s *Search) HandleMouse(msg tea.MouseMsg, handler *mouse.Handler) (Result, tea.Cmd)

HandleMouse processes a mouse event against the regions the last View registered on handler.

func (*Search) Root

func (s *Search) Root() string

Root is the directory this search runs in.

func (*Search) SetFill

func (s *Search) SetFill(fill bool)

SetFill switches the search between the two placements its hosts need. Off (the default) it draws a box sized to its own content, which a host centres on a screen or in a roomy pane with the surface behind it dimmed. On, it draws a box that is exactly the surface it was given, for a pane with no room to show anything useful behind the modal. filefind.Finder.SetFill is the same switch, because the two are one component in two modes.

func (*Search) SetFocus

func (s *Search) SetFocus(id string)

SetFocus focuses one of the modal's elements by ID (ToggleRegexID and friends, or a row ID from ParseFileID/ParseMatchID).

func (*Search) SetPreferredWidth

func (s *Search) SetPreferredWidth(width int)

SetPreferredWidth overrides how wide the box likes to be when it is sizing itself to its content, for a host that knows where the box will land — see filefind.Finder.SetPreferredWidth. Zero restores the default.

func (*Search) SetRoot

func (s *Search) SetRoot(root string, epoch uint64)

SetRoot changes the directory searched. Pending results for the old root are dropped by the epoch check in Update.

func (*Search) SetSize

func (s *Search) SetSize(width, height int)

SetSize records the surface the search will be rendered at. View does this too; call it directly when input may arrive before the first render, as it does on the keystroke that opens the search.

func (*Search) ToggleOption

func (s *Search) ToggleOption(option *bool) tea.Cmd

ToggleOption flips one of the search options and re-runs the search immediately if there is a query. option must point into the search's own State (see State.UseRegex and friends).

func (*Search) Update

func (s *Search) Update(msg tea.Msg) tea.Cmd

Update handles the search's own async traffic: the debounce tick and the ripgrep results. Messages stamped with a different epoch are dropped.

func (*Search) View

func (s *Search) View(width, height int, handler *mouse.Handler) string

View renders the search at the given size and registers its hit regions on handler. The result is the modal alone; the caller composites it over its own background (ui.OverlayModal for a screen, panemodal.Render for a pane).

func (*Search) WheelAtBoundary

func (s *Search) WheelAtBoundary(msg tea.MouseWheelMsg) bool

WheelAtBoundary reports whether a wheel event is certainly a no-op for the search. The wheel moves the result cursor wherever the pointer is, so the modal body never scrolls and only the cursor bounds matter. A run still in flight can grow the list, so it is never bounded.

True means "certain no-op"; false means the cursor can move, or the answer is unknown. It performs no loads and mutates nothing.

type SearchFileResult

type SearchFileResult struct {
	Path      string
	Matches   []SearchMatch
	Collapsed bool
}

SearchFileResult represents a file with search matches.

type SearchMatch

type SearchMatch struct {
	LineNo   int    // 1-indexed line number
	LineText string // Full line content
	ColStart int    // Match start column (0-indexed)
	ColEnd   int    // Match end column (0-indexed)
}

SearchMatch represents a single match within a file.

type State

type State struct {
	Query   string
	Results []SearchFileResult

	// Search options (toggle with keyboard shortcuts)
	UseRegex      bool
	CaseSensitive bool
	WholeWord     bool

	// UI state
	Cursor         int  // Index in flattened results (files + matches)
	ScrollOffset   int  // For scrolling
	IsSearching    bool // True while ripgrep is running
	Error          string
	ResultsFocused bool // When true, j/k/g/G navigate results instead of typing
	// Truncated is set when the run hit the match cap; the counts row says so.
	Truncated bool

	// Debounce: only run search when version matches
	DebounceVersion int

	// RunToken names the newest ripgrep run this state has issued. Every run
	// stamps it on the ResultsMsg it produces, and a result carrying an older
	// token is dropped: two runs inside one epoch can finish out of order (a
	// slow debounced run and the immediate re-run an option toggle issues), and
	// the epoch alone cannot tell them apart.
	RunToken int

	// For future: multiple search tabs
	TabID int
}

State holds the state for project-wide search.

func NewState

func NewState() *State

NewState creates a new search state.

func (*State) FileCount

func (s *State) FileCount() int

FileCount returns the number of files with matches.

func (*State) FirstMatchIndex

func (s *State) FirstMatchIndex() int

FirstMatchIndex returns the flat index of the first match (skipping file headers). Returns 0 if no matches exist.

func (*State) FlatIndexForFile

func (s *State) FlatIndexForFile(fileIdx int) int

FlatIndexForFile returns the flattened-list index of a file header, or -1 when there is no such file.

func (*State) FlatIndexForMatch

func (s *State) FlatIndexForMatch(fileIdx, matchIdx int) int

FlatIndexForMatch returns the flattened-list index of one match, or -1 when it is not visible (no such match, or its file is collapsed).

func (*State) FlatItem

func (s *State) FlatItem(idx int) (fileIdx int, matchIdx int, isFile bool)

FlatItem returns the item at the given flat index. Returns (fileIndex, matchIndex, isFile). matchIndex is -1 if this is a file header.

func (*State) FlatLen

func (s *State) FlatLen() int

FlatLen returns the length of the flattened results list. Each file is 1 item, plus its matches if not collapsed.

func (*State) GetSelectedFile

func (s *State) GetSelectedFile() (path string, lineNo int)

GetSelectedFile returns the currently selected file path and line number. If a match is selected, returns file path and line number. If a file header is selected, returns file path and line 0.

func (*State) LastMatchIndex

func (s *State) LastMatchIndex() int

LastMatchIndex returns the flat index of the last visible match. Skips file headers. Returns 0 if no matches are visible.

func (*State) NearestMatchIndex

func (s *State) NearestMatchIndex(fromIdx int) int

NearestMatchIndex returns the flat index of the nearest match to the given index. Searches forward first, then backward. Returns 0 if no matches exist.

func (*State) NextMatchIndex

func (s *State) NextMatchIndex() int

NextMatchIndex returns the flat index of the next match after current cursor. Skips file headers. Returns current cursor if no next match exists.

func (*State) PrevMatchIndex

func (s *State) PrevMatchIndex() int

PrevMatchIndex returns the flat index of the previous match before current cursor. Skips file headers. Returns current cursor if no previous match exists.

func (*State) ToggleFileCollapse

func (s *State) ToggleFileCollapse()

ToggleFileCollapse toggles the collapsed state of the file at cursor.

func (*State) TotalMatches

func (s *State) TotalMatches() int

TotalMatches returns the total number of matches across all files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL