filebrowser

package
v0.74.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

Package filebrowser implements the file browser plugin with tree navigation, file preview, quick open, search, git integration, and file operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FuzzySort

func FuzzySort(matches []QuickOpenMatch)

FuzzySort sorts matches by score descending, then path length ascending.

func Highlight

func Highlight(content, extension, syntaxTheme string) (string, error)

Highlight returns a syntax highlighted string. Pattern from knipferrc/fm code/code.go

func LoadPreview

func LoadPreview(rootDir, path string, epoch uint64) tea.Cmd

LoadPreview creates a command to load file content.

func RelativeTime

func RelativeTime(t time.Time) string

RelativeTime formats a time as a relative duration string.

func RunGitBlame

func RunGitBlame(workDir, filePath string, epoch uint64) tea.Cmd

RunGitBlame runs git blame and returns the parsed output.

func RunProjectSearch

func RunProjectSearch(workDir string, state *ProjectSearchState, epoch uint64) tea.Cmd

RunProjectSearch executes ripgrep and returns results.

Types

type AttachToTmuxMsg

type AttachToTmuxMsg struct {
	SessionName string
}

AttachToTmuxMsg requests the app to suspend and attach to a tmux session.

type BlameLine

type BlameLine struct {
	CommitHash string
	Author     string
	AuthorTime time.Time
	LineNo     int
	Content    string
}

BlameLine represents a single line in git blame output.

type BlameLoadedMsg

type BlameLoadedMsg struct {
	Epoch uint64 // Epoch when request was issued (for stale detection)
	Lines []BlameLine
	Error error
}

BlameLoadedMsg is sent when blame data is loaded.

func (BlameLoadedMsg) GetEpoch

func (m BlameLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type BlameState

type BlameState struct {
	Lines        []BlameLine
	Cursor       int
	ScrollOffset int
	FilePath     string
	IsLoading    bool
	Error        error
}

BlameState holds the state for blame view.

type ContentMatch

type ContentMatch struct {
	LineNo   int // 0-indexed line number
	StartCol int // Start column (byte offset)
	EndCol   int // End column (byte offset)
}

ContentMatch represents a match position within file content.

type CreateSuccessMsg

type CreateSuccessMsg struct {
	Path  string
	IsDir bool
}

CreateSuccessMsg is sent when a file/directory is created.

type DeleteSuccessMsg

type DeleteSuccessMsg struct {
	Path string
}

DeleteSuccessMsg is sent when a file/directory is deleted.

type FileNode

type FileNode struct {
	Name       string
	Path       string // Relative path from root
	IsDir      bool
	IsExpanded bool
	IsIgnored  bool // Set by gitignore
	Children   []*FileNode
	Parent     *FileNode
	Depth      int
	Size       int64
	ModTime    time.Time
}

FileNode represents a file or directory in the tree.

type FileOpErrorMsg

type FileOpErrorMsg struct {
	Err error
}

FileOpErrorMsg is sent when a file operation fails.

type FileOpMode

type FileOpMode int

FileOpMode represents the current file operation mode.

const (
	FileOpNone FileOpMode = iota
	FileOpMove
	FileOpRename
	FileOpCreateFile
	FileOpCreateDir
	FileOpDelete
)

type FileOpSuccessMsg

type FileOpSuccessMsg struct {
	Src string
	Dst string
}

FileOpSuccessMsg is sent when a file operation succeeds.

type FileTab

type FileTab struct {
	Path      string
	Scroll    int
	Loaded    bool
	Result    PreviewResult
	IsPreview bool // Ephemeral preview tab, replaced on next j/k navigation

	// Edit state (persisted when switching away from inline editor)
	EditSession   string    // Tmux session name (empty if not in edit mode)
	EditOrigMtime time.Time // Original file mtime when editing started
	EditEditor    string    // Editor command used (vim, nano, etc.)
}

type FileTree

type FileTree struct {
	Root     *FileNode
	RootDir  string
	FlatList []*FileNode // Flattened visible nodes for cursor navigation

	SortMode    SortMode // Current sort mode
	ShowIgnored bool     // Whether to include ignored files in FlatList
	// contains filtered or unexported fields
}

FileTree manages the hierarchical file structure.

func NewFileTree

func NewFileTree(rootDir string) *FileTree

NewFileTree creates a new file tree rooted at the given directory.

func (*FileTree) Build

func (t *FileTree) Build() error

Build initializes the tree by loading the root directory's children.

func (*FileTree) Collapse

func (t *FileTree) Collapse(node *FileNode)

Collapse closes a directory node.

func (*FileTree) Expand

func (t *FileTree) Expand(node *FileNode) error

Expand opens a directory node, loading children if needed.

func (*FileTree) FindByPath

func (t *FileTree) FindByPath(path string) *FileNode

FindByPath returns the node with the given relative path, or nil if not found.

func (*FileTree) FindParentDir

func (t *FileTree) FindParentDir(node *FileNode) *FileNode

FindParentDir returns the parent directory node, or nil if at root.

func (*FileTree) Flatten

func (t *FileTree) Flatten() []*FileNode

Flatten rebuilds the FlatList from visible nodes.

func (*FileTree) GetExpandedPaths

func (t *FileTree) GetExpandedPaths() map[string]bool

GetExpandedPaths returns the paths of all expanded directories.

func (*FileTree) GetNode

func (t *FileTree) GetNode(index int) *FileNode

GetNode returns the node at the given index, or nil if out of bounds.

func (*FileTree) IndexOf

func (t *FileTree) IndexOf(node *FileNode) int

IndexOf returns the index of a node in the flat list, or -1 if not found.

func (*FileTree) Len

func (t *FileTree) Len() int

Len returns the number of visible nodes.

func (*FileTree) Refresh

func (t *FileTree) Refresh() error

Refresh reloads the tree from disk, preserving expanded state.

func (*FileTree) RestoreExpandedPaths

func (t *FileTree) RestoreExpandedPaths(paths map[string]bool)

RestoreExpandedPaths expands directories that were previously expanded.

func (*FileTree) SetSortMode

func (t *FileTree) SetSortMode(mode SortMode)

SetSortMode changes the sort mode and re-sorts the tree.

func (*FileTree) Toggle

func (t *FileTree) Toggle(node *FileNode) error

Toggle expands or collapses a directory node.

type FocusPane

type FocusPane int

FocusPane represents which pane is active.

const (
	PaneTree FocusPane = iota
	PanePreview
)

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 GitInfoMsg

type GitInfoMsg struct {
	Status     string
	LastCommit string
}

GitInfoMsg contains git status for a file.

type InlineEditExitedMsg

type InlineEditExitedMsg struct {
	FilePath string
}

InlineEditExitedMsg is sent when inline edit mode exits.

type InlineEditStartedMsg

type InlineEditStartedMsg struct {
	SessionName   string
	FilePath      string
	OriginalMtime time.Time // File mtime before editing (to detect changes)
	Editor        string    // Editor command used (vim, nano, emacs, etc.)
}

InlineEditStartedMsg is sent when inline edit mode starts successfully.

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 NavigateToFileMsg struct {
	Path string // Relative path from workdir
}

NavigateToFileMsg requests navigation to a specific file (from other plugins).

type PasteSuccessMsg

type PasteSuccessMsg struct {
	Src string
	Dst string
}

PasteSuccessMsg is sent when a file/directory is pasted.

type Plugin

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

Plugin implements file browser functionality.

func New

func New() *Plugin

New creates a new File Browser plugin.

func (*Plugin) Commands

func (p *Plugin) Commands() []plugin.Command

Commands returns the available commands.

func (*Plugin) ConsumesTextInput

func (p *Plugin) ConsumesTextInput() bool

ConsumesTextInput reports whether the file browser currently expects typed text input and should suppress app-level shortcut interception.

func (*Plugin) FocusContext

func (p *Plugin) FocusContext() string

FocusContext returns the current focus context.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the plugin identifier.

func (*Plugin) Icon

func (p *Plugin) Icon() string

Icon returns the plugin icon character.

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin with context.

func (*Plugin) IsFocused

func (p *Plugin) IsFocused() bool

IsFocused returns whether the plugin is focused.

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns the plugin display name.

func (*Plugin) SetFocused

func (p *Plugin) SetFocused(f bool)

SetFocused sets the focus state.

func (*Plugin) Start

func (p *Plugin) Start() tea.Cmd

Start begins plugin operation.

func (*Plugin) Stop

func (p *Plugin) Stop()

Stop cleans up plugin resources.

func (*Plugin) Update

func (p *Plugin) Update(msg tea.Msg) (plugin.Plugin, tea.Cmd)

Update handles messages.

func (*Plugin) View

func (p *Plugin) View(width, height int) string

View renders the plugin.

type PreviewLoadedMsg

type PreviewLoadedMsg struct {
	Epoch  uint64 // Epoch when request was issued (for stale detection)
	Result PreviewResult
	Path   string
}

PreviewLoadedMsg signals that file preview content is ready.

func (PreviewLoadedMsg) GetEpoch

func (m PreviewLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type PreviewResult

type PreviewResult struct {
	Content          string
	Lines            []string
	HighlightedLines []string // Syntax highlighted lines
	IsBinary         bool
	IsImage          bool // True if file is a recognized image format
	IsTruncated      bool
	TotalSize        int64
	ModTime          time.Time   // File modification time
	Mode             os.FileMode // File permissions
	Error            error
}

PreviewResult contains the loaded file content.

type ProjectSearchResultsMsg

type ProjectSearchResultsMsg struct {
	Epoch   uint64 // Epoch when request was issued (for stale detection)
	Results []SearchFileResult
	Error   error
}

ProjectSearchResultsMsg contains results from a search.

func (ProjectSearchResultsMsg) GetEpoch

func (m ProjectSearchResultsMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type ProjectSearchState

type ProjectSearchState 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

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

	// For future: multiple search tabs
	TabID int
}

ProjectSearchState holds the state for project-wide search.

func NewProjectSearchState

func NewProjectSearchState() *ProjectSearchState

NewProjectSearchState creates a new search state.

func (*ProjectSearchState) FileCount

func (s *ProjectSearchState) FileCount() int

FileCount returns the number of files with matches.

func (*ProjectSearchState) FirstMatchIndex

func (s *ProjectSearchState) FirstMatchIndex() int

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

func (*ProjectSearchState) FlatItem

func (s *ProjectSearchState) 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 (*ProjectSearchState) FlatLen

func (s *ProjectSearchState) FlatLen() int

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

func (*ProjectSearchState) GetSelectedFile

func (s *ProjectSearchState) 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 (*ProjectSearchState) NearestMatchIndex

func (s *ProjectSearchState) 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 (*ProjectSearchState) NextMatchIndex

func (s *ProjectSearchState) 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 (*ProjectSearchState) PrevMatchIndex

func (s *ProjectSearchState) 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 (*ProjectSearchState) ToggleFileCollapse

func (s *ProjectSearchState) ToggleFileCollapse()

ToggleFileCollapse toggles the collapsed state of the file at cursor.

func (*ProjectSearchState) TotalMatches

func (s *ProjectSearchState) TotalMatches() int

TotalMatches returns the total number of matches across all files.

type QuickOpenMatch

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

QuickOpenMatch represents a file matching the fuzzy query.

func FuzzyFilter

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

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

type RefreshMsg

type RefreshMsg struct{}

Message types

type RevealErrorMsg

type RevealErrorMsg struct {
	Err error
}

RevealErrorMsg is sent when reveal in file manager fails.

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 SortMode

type SortMode int

SortMode represents how files are sorted in the tree.

const (
	SortByName SortMode = iota
	SortBySize
	SortByTime
	SortByType
)

func (SortMode) Label

func (s SortMode) Label() string

SortModeLabel returns a short label for display.

func (SortMode) Next

func (s SortMode) Next() SortMode

NextSortMode cycles to the next sort mode.

type StateRestoredMsg

type StateRestoredMsg struct {
	State state.FileBrowserState
}

Message types

type TabOpenMode

type TabOpenMode int
const (
	TabOpenReplace TabOpenMode = iota
	TabOpenNew
	TabOpenPreview
)

type TreeBuiltMsg

type TreeBuiltMsg struct {
	Err error
}

Message types

type WatchEventMsg

type WatchEventMsg struct{}

Message types

type WatchStartedMsg

type WatchStartedMsg struct{ Watcher *Watcher }

Message types

type Watcher

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

Watcher monitors a single file for changes. Only watches the currently previewed file, not the entire directory tree.

func NewWatcher

func NewWatcher() (*Watcher, error)

NewWatcher creates a file watcher. Does not start watching anything until WatchFile is called.

func (*Watcher) Events

func (w *Watcher) Events() <-chan struct{}

Events returns a channel that signals when the watched file changes.

func (*Watcher) Stop

func (w *Watcher) Stop()

Stop shuts down the watcher.

func (*Watcher) WatchFile

func (w *Watcher) WatchFile(path string) error

WatchFile starts watching the specified file. Stops watching any previously watched file. Pass empty string to stop watching without watching a new file.

Jump to

Keyboard shortcuts

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