filefind

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 19 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 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 sorts matches by score descending, then path length ascending.

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
}

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) 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.

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) 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) 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) LoadFile

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

LoadFile loads patterns from a .gitignore file.

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 FuzzyFilter

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

FuzzyFilter filters and scores files against a query. Returns top maxResults matches sorted by score.

type MatchRange

type MatchRange struct {
	Start int
	End   int
}

MatchRange represents a contiguous range of matched characters.

func FuzzyMatch

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

FuzzyMatch scores how well query matches target string. Returns score (0 = no match) and ranges for highlighting. Scoring:

  • Consecutive matches: bonus per consecutive char
  • Word start matches (after /, _, -, .): large bonus
  • Shorter targets: small bonus

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
}

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