filefind

package
v1.17.1 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 20 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 filefind provides the file-finding primitives shared by any surface that offers "open a file by typing part of its name": fuzzy matching and scoring, the gitignore rules the scan honours, and a background project file cache that keeps its previous answer visible while it rescans.

Index

Constants

View Source
const (
	// MaxMatches caps how many fuzzy matches the finder keeps for a query.
	MaxMatches = 50

	// RegionItem is the prefix of the hit region ID registered for each
	// visible row; the row's index into Matches follows it (see ItemID and
	// ParseItemID).
	RegionItem = "quick-open"
)
View Source
const (
	// MaxFiles caps the file list (prevents OOM on huge repos).
	MaxFiles = 50000
	// MaxDirs caps the directory list (path auto-complete).
	MaxDirs = 10000
	// ScanTimeout is the most time one scan may spend walking.
	ScanTimeout = 2 * time.Second
)

Scan limits. They bound the walk so a huge or slow tree cannot stall the surface that asked for it: whatever the walk has by the deadline is what the caller gets, along with a message saying why it stopped early.

View Source
const DefaultMaxAge = 10 * time.Second

DefaultMaxAge is how long a file list is trusted without a rescan when its owner has not said otherwise.

A cache is told about changes by whoever owns it, and no owner sees every change: the Files plugin watches only the directories the tree has expanded, so a file an agent writes into a collapsed directory never marks the cache dirty, and a finder opened an hour later still answers from the list it walked before the file existed. That is how "use-cases" once found six near-misses and not USE-CASES.md. An age limit is the honest fallback, and it is cheap: an aged list is re-checked with one stat per directory the walk recorded (see DirStamp), and only a tree that actually moved pays the walk again. The old list stays on screen either way until the answer lands.

A cache whose scanner cannot stamp directories — a remote catalog — walks in full when it ages out, so an owner of one may want a longer MaxAge.

View Source
const PreferredWidth = 80

PreferredWidth is how wide the finder's box likes to be when the surface has room to spare.

Variables

This section is empty.

Functions

func FuzzySort

func FuzzySort(matches []Match)

FuzzySort orders matches best first: by score descending, then shorter path first, then by path, so equal candidates come out in the same order every time regardless of how the input was ordered.

func HighlightMatch

func HighlightMatch(text string, ranges []MatchRange) string

HighlightMatch applies the fuzzy-match highlight style to the matched character ranges of text, leaving the rest of it alone.

func ItemID

func ItemID(idx int) string

ItemID is the modal element ID of the row at idx into Matches.

func ParseItemID

func ParseItemID(id string) (int, bool)

ParseItemID reports whether id names a result row, and which one.

func RenderMatch

func RenderMatch(match Match, maxWidth int) string

RenderMatch renders a single match row: the path fitted to maxWidth with its matched characters highlighted.

func ScanPaths

func ScanPaths(root string, wantDirs bool) ([]string, string)

ScanPaths walks root collecting relative paths of either files or directories, respecting gitignore and bounded by a time and count limit. It returns the sorted paths plus a message describing why the scan stopped early, if it did.

Types

type Cache

type Cache struct {
	Files   []string // Paths relative to the root, sorted
	ErrText string   // Error message if the scan failed or hit a limit

	Scanning bool // A background scan is in flight
	OK       bool // A scan has completed at least once

	// Dirty is set when the disk moved under the cache, so its contents no
	// longer describe what is there. A scan clears it at its start, so a change
	// arriving while that scan is in flight re-sets it and the landing result
	// cannot pass itself off as current.
	Dirty bool

	// Scanned is when the list now held was last confirmed current, by a walk
	// landing or by a probe finding nothing moved. It is the zero time until a
	// scan has completed.
	Scanned time.Time

	// Stamps are the directories the last walk recorded (see DirStamp). Empty
	// when the scanner did not provide them, in which case an aged cache
	// walks in full.
	Stamps []DirStamp

	// MaxAge is how long the list is trusted after Scanned before Ensure walks
	// again. Zero means DefaultMaxAge; a negative value means the list never
	// ages out, for an owner that is told about every change.
	MaxAge time.Duration

	// Scan produces the path list. Nil walks this machine's filesystem, which
	// is every local caller. A surface bound to another machine binds its own
	// so the candidate list is that machine's files and this process never
	// walks a same-named path here.
	Scan func(root string, dirs bool) ([]string, string)
}

Cache holds a project's file (or directory) list plus the bookkeeping that keeps a rescan from being disruptive: the previous answer stays readable for the whole time the new scan runs.

The zero value is ready to use. Whether a cache holds files or directories is decided by which Ensure method its owner calls, so a cache built by a struct literal cannot end up scanning the wrong thing.

func (*Cache) Apply

func (c *Cache) Apply(msg ScannedMsg)

Apply stores a landed scan result. Callers are responsible for dropping stale results (see ScannedMsg.GetEpoch) before calling this.

func (*Cache) Ensure

func (c *Cache) Ensure(root string, epoch uint64) tea.Cmd

Ensure starts a background scan of root's files when the cache is missing or the disk has moved under it, and returns the command that runs it. It returns nil when a scan is already in flight or the cache is current. The existing contents are left in place until the result lands, so a UI keeps showing something usable.

func (*Cache) EnsureDirs

func (c *Cache) EnsureDirs(root string, epoch uint64) tea.Cmd

EnsureDirs is Ensure for a directory list (path auto-complete).

func (*Cache) Expired added in v1.15.0

func (c *Cache) Expired() bool

Expired reports whether the list has outlived MaxAge. A cache that has never scanned is not expired, merely empty; Ensure handles that on its own. Nor is a list nobody dated — one an owner filled in by hand rather than through Apply — because it has no age to compare.

func (*Cache) MarkDirty

func (c *Cache) MarkDirty()

MarkDirty records that the disk changed, so the next Ensure rescans.

func (*Cache) Reset

func (c *Cache) Reset()

Reset drops the cache contents and all bookkeeping. Use it when the root changes, e.g. on a project switch. The scanner goes with it: a cache that kept a remote scanner across a switch back to a local project would answer for the wrong machine.

type DirStamp added in v1.15.0

type DirStamp struct {
	Path    string
	ModTime time.Time
}

DirStamp is a directory a scan walked, with the modification time it had then. A directory's mtime moves whenever an entry is created, removed or renamed directly inside it, so the set of stamps a walk collected is enough to ask later, with one stat per directory and no readdir, whether the file list could have changed. Path is relative to the root; the root itself is ".". The root's .gitignore is stamped too, when it exists: editing it changes what the walk would list without moving any directory.

func ScanTreeContext added in v1.17.0

func ScanTreeContext(parent context.Context, root string, wantDirs bool, allow func(string, fs.DirEntry) bool) ([]string, []DirStamp, string)

ScanTreeContext uses the TUI's scan rules through a confined filesystem. allow can further refuse administrative paths or symlinks at a caller's boundary.

type FilterOptions added in v1.15.0

type FilterOptions struct {
	// Recent lists paths the user has been working with, most recent first.
	// With an empty query they lead the list, ahead of the shallowest paths in
	// the project; with a query each earns a small bonus, enough to break a
	// near-tie in favour of the file the user was just looking at but never
	// enough to outrank a clearly better match.
	Recent []string
}

FilterOptions tunes Filter beyond the query.

type Finder

type Finder struct {
	// Cache is the project file list the finder filters. It is a pointer
	// because a host may share one list with other surfaces (the Files plugin
	// filters the same cache for its tree search); pass nil to Open a finder
	// that owns its own.
	Cache *Cache
	// contains filtered or unexported fields
}

Finder is the "open a file by typing part of its name" surface: the file list, the query, the matches, the cursor, and the rendering and input handling for all of it. It renders at whatever size it is given, so the same type serves a full screen and a single pane.

func NewFinder

func NewFinder(cache *Cache, root string, epoch uint64) *Finder

NewFinder creates a finder over cache, rooted at root. A nil cache gives the finder one of its own. epoch is stamped on the scans it issues, so a scan for a root the host has since switched away from is dropped on arrival.

func (*Finder) Close added in v1.15.0

func (f *Finder) Close()

Close is Reset plus releasing the scan the finder may have in flight. A host that routes a landed scan to the finder that issued it has nowhere to deliver one that lands after the finder is gone, and a dropped result would leave the shared cache marked Scanning forever, with every later Ensure declining to walk. After Close the cache is free to scan again; whatever the abandoned scan returns is routed by the host or dropped, and either is fine.

func (*Finder) Cursor

func (f *Finder) Cursor() int

Cursor is the index into Matches of the highlighted row.

func (*Finder) HandleKey

func (f *Finder) HandleKey(msg tea.KeyPressMsg) (Result, tea.Cmd)

HandleKey processes a keypress.

func (*Finder) HandleMouse

func (f *Finder) 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 (*Finder) Matches

func (f *Finder) Matches() []Match

Matches are the current fuzzy matches, best first.

func (*Finder) Open

func (f *Finder) Open() tea.Cmd

Open clears the query and starts a background scan if the file list is missing or stale, returning the command that runs it.

func (*Finder) Query

func (f *Finder) Query() string

Query is the text typed so far.

func (*Finder) Refilter

func (f *Finder) Refilter()

Refilter recomputes the matches from the current query and file list, keeping the cursor in range. Hosts that apply scan results to a shared cache themselves call this afterwards; Update does it for them.

func (*Finder) Reset

func (f *Finder) Reset()

Reset drops the query, matches, and cursor. The file list survives, since it describes the project rather than this use of the finder.

func (*Finder) Root

func (f *Finder) Root() string

Root is the directory the finder searches.

func (*Finder) SetCursor

func (f *Finder) SetCursor(idx int)

SetCursor moves the highlighted row, clamped to the matches.

func (*Finder) SetFill

func (f *Finder) SetFill(fill bool)

SetFill switches the finder 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.

func (*Finder) SetPreferredWidth

func (f *Finder) SetPreferredWidth(width int)

SetPreferredWidth overrides how wide the box likes to be when it is sizing itself to its content. A host sets it when it knows something about where the box will land that the surface cannot: the Files plugin keeps the border off the column its pane divider occupies, so the box does not read as welded to the frame it is floating over. Zero restores the default.

func (*Finder) SetQuery

func (f *Finder) SetQuery(query string)

SetQuery replaces the typed text and recomputes the matches, for a host that seeds the finder from something other than typing.

func (*Finder) SetRecent added in v1.15.0

func (f *Finder) SetRecent(paths []string)

SetRecent tells the finder which paths (relative to its root) the user has been working with, most recent first. With nothing typed they lead the list; with a query they break near-ties. The host calls it before Open, or whenever its own notion of recency changes.

func (*Finder) SetRoot

func (f *Finder) SetRoot(root string, epoch uint64)

SetRoot points the finder at a different project. The cache is the host's to reset, since it may be shared.

func (*Finder) SetSize

func (f *Finder) SetSize(width, height int)

SetSize records the surface the finder will be rendered at. View does this too; call it directly when input may arrive before the first render.

func (*Finder) Update

func (f *Finder) Update(msg tea.Msg) tea.Cmd

Update handles the finder's own async traffic: a landed file scan. Scans for a different epoch, and directory scans (which belong to path auto-complete, not to the finder), are ignored.

func (*Finder) View

func (f *Finder) View(width, height int, handler *mouse.Handler) string

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

func (*Finder) WheelAtBoundary

func (f *Finder) WheelAtBoundary(msg tea.MouseWheelMsg) bool

WheelAtBoundary reports whether a wheel event is certainly a no-op for the finder. The wheel moves the match cursor wherever the pointer is, so only the cursor bounds matter. A scan still in flight can add matches, so it is never bounded.

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

type GitIgnore

type GitIgnore struct {
	// contains filtered or unexported fields
}

GitIgnore manages .gitignore patterns for file filtering.

func NewGitIgnore

func NewGitIgnore() *GitIgnore

NewGitIgnore creates a new GitIgnore instance.

func (*GitIgnore) ClearCache

func (gi *GitIgnore) ClearCache()

ClearCache clears the path cache.

func (*GitIgnore) IsIgnored

func (gi *GitIgnore) IsIgnored(path string, isDir bool) bool

IsIgnored checks if a path matches any gitignore pattern.

func (*GitIgnore) LoadBytes added in v1.16.0

func (gi *GitIgnore) LoadBytes(data []byte) error

LoadBytes parses patterns supplied by a caller with its own file boundary.

func (*GitIgnore) LoadFile

func (gi *GitIgnore) LoadFile(path string) error

LoadFile loads patterns from a .gitignore file.

type Index added in v1.17.0

type Index struct {
	// contains filtered or unexported fields
}

Index caches bounded file lists for API callers, sharing the TUI scan and freshness policy. Its zero value is ready to use. At most 32 roots are kept.

func (*Index) Paths added in v1.17.0

func (idx *Index) Paths(ctx context.Context, root string, allow func(string, fs.DirEntry) bool) ([]string, string, error)

Paths returns an immutable snapshot. Concurrent requests for one root share one scan; waiting, walking, and freshness checks honor caller cancellation.

type Match

type Match struct {
	Path        string       // Relative path from root
	Name        string       // Base filename
	Score       int          // Match score (higher = better)
	MatchRanges []MatchRange // Ranges for highlighting matched chars
}

Match represents a file matching the fuzzy query.

func Filter added in v1.15.0

func Filter(files []string, query string, maxResults int, opts FilterOptions) []Match

Filter is FuzzyFilter with options.

func FilterContext added in v1.17.0

func FilterContext(ctx context.Context, files []string, query string, maxResults int, opts FilterOptions) ([]Match, error)

FilterContext has exactly Filter's ranking and stops when its caller disconnects.

func FuzzyFilter

func FuzzyFilter(files []string, query string, maxResults int) []Match

FuzzyFilter filters and scores files against a query, returning the best maxResults matches in order. See FilterOptions for what an empty query shows.

type MatchRange

type MatchRange struct {
	Start int
	End   int
}

MatchRange represents a contiguous range of matched characters, as byte offsets into the matched path.

func FuzzyMatch

func FuzzyMatch(query, target string) (int, []MatchRange)

FuzzyMatch scores how well query matches target. It returns 0 and nil ranges when the query does not match; otherwise a positive score and the byte ranges of target that matched, in order, for highlighting.

The query is split on whitespace into terms, every one of which must match. Matching ignores case, and treats '-', '_' and ' ' as one another, so "use_cases" and "use cases" both find "USE-CASES.md".

type Outcome

type Outcome int

Outcome is what a key or mouse event asked the host to do. Everything the finder can do to itself it has already done by the time it returns; the outcome names only what it cannot decide, because that belongs to whatever surface is hosting it.

const (
	// OutcomeNone: the event was consumed (or ignored); the host has nothing
	// to do.
	OutcomeNone Outcome = iota
	// OutcomeCancelled: the user dismissed the finder.
	OutcomeCancelled
	// OutcomeOpen: the user chose a file. The host decides what "open" means.
	OutcomeOpen
)

type Result

type Result struct {
	Outcome Outcome
	// Path is relative to the finder's root.
	Path string
	// Line is the 1-based line to land on, or 0 for the top of the file. The
	// finder never selects a line itself; the field exists so hosts can treat
	// it and projectsearch.Result the same way.
	Line int
	// NewTab is set when the user asked for the file beside what they are
	// already looking at rather than in place.
	NewTab bool
}

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

type ScannedMsg

type ScannedMsg struct {
	Dirs    bool
	Files   []string // Paths relative to the scanned root, sorted
	ErrText string   // Non-empty when the scan failed or hit a limit
	Epoch   uint64

	// Stamps are the directories the walk descended into, with their
	// modification times, so the next Ensure can ask whether anything moved
	// without walking again. Nil when the scanner cannot provide them.
	Stamps []DirStamp

	// Unchanged is set when an aged cache was probed rather than walked and
	// nothing had moved: Files and Stamps are empty and the list already held
	// is still the answer. Only the clock moves.
	Unchanged bool
}

ScannedMsg carries the result of a background cache scan. Dirs distinguishes a directory scan (path auto-complete) from a file scan.

func (ScannedMsg) GetEpoch

func (m ScannedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage, so a scan issued for a project the caller has since switched away from can be dropped on arrival.

Jump to

Keyboard shortcuts

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