wig

package module
v0.0.0-...-79aad76 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 40 Imported by: 0

README

Wig (experimental text editor)

Hi! Welcome to my text editor page. wig is a modal, Vim-like text editor written in Go. I use it as my daily driver, btw.

Discord: https://discord.gg/p2Ym5EzH2

Note: wig currently supports go, c, odin and python. Do not edit files without backups. Wig is still in an early stage of development and may damage your files. But if you are using git that should not be a problem ;)

Features
  • LSP autocomplete, goto definition, hover info
  • Tree-sitter support
  • Color themes (borrowed from the Helix text editor)
  • Macros support
  • Whichkey helper
  • Git gutter, hunk editor
  • Something like Emacs org-mode: Open test.txt, place the cursor at line 15, and press "Ctrl-C Ctrl-C".

This project was written as a "speed run" — not for speed in terms of time, but rather as an exercise to explore the text editor problem space without overthinking or planning ahead. It’s a quick and "dirty" implementation, so to speak.


Running

make setup-runtime
make build-run

# then edit ~/.config/wig/config.toml

Keybindings

Most common Vim keybindings are implemented, providing minimal but enough (for me) support for daily source code editing. See config/config.go for all implemented keybindings.

To get started:

Key Description
Tab Next element in popup
Shift-Tab Prev element in popup
Space + f Find files in Git project
Space + b Buffers
Space + s + s Fuzzy text search
Ctrl-W + V Split window
Space + ` Toggle file
Space + / Search text in project

Plans

I plan to turn this "toy project" into a stable, fully-featured Vim-like text editor.


Contributors

Documentation

Overview

Movement and window related funcs

whichkey.go

Index

Constants

View Source
const IndentGuideGlyph = "│"

IndentGuideGlyph is the character used to draw vertical indent guides.

Variables

View Source
var AllCommands = map[string]CmdDefinition{}
View Source
var LastSearchPattern string
View Source
var MarksPopupFactory func(ctx Context, marks map[rune]Mark)

MarksPopupFactory allows the `ui` package to register a popup for marks without causing a circular import.

Functions

func ApplyBg

func ApplyBg(color string, style tcell.Style) tcell.Style

func ApplyTheme

func ApplyTheme(name string)

func BufferReloadFile

func BufferReloadFile(buf *Buffer) error

func CmdAppendLine

func CmdAppendLine(ctx Context)

func CmdAutocompleteTrigger

func CmdAutocompleteTrigger(ctx Context)

func CmdBackwardChar

func CmdBackwardChar(ctx Context) func(Context)

func CmdBackwardWord

func CmdBackwardWord(ctx Context)

func CmdBufferCycle

func CmdBufferCycle(ctx Context)

Cycle between last two buffers in jump list

func CmdBufferLast

func CmdBufferLast(ctx Context)

func CmdBufferNext

func CmdBufferNext(ctx Context)

func CmdBufferPrev

func CmdBufferPrev(ctx Context)

func CmdChangeBefore

func CmdChangeBefore(_ Context) func(Context)

func CmdChangeEndOfLine

func CmdChangeEndOfLine(ctx Context)

func CmdChangeInsideBlock

func CmdChangeInsideBlock(ctx Context)

func CmdChangeLine

func CmdChangeLine(ctx Context)

func CmdChangeTo

func CmdChangeTo(_ Context) func(Context)

func CmdChangeWORD

func CmdChangeWORD(ctx Context)

func CmdChangeWord

func CmdChangeWord(ctx Context)

func CmdCursorBeginningOfTheLine

func CmdCursorBeginningOfTheLine(ctx Context)

func CmdCursorCenter

func CmdCursorCenter(ctx Context)

func CmdCursorFirstNonBlank

func CmdCursorFirstNonBlank(ctx Context)

func CmdCursorLeft

func CmdCursorLeft(ctx Context)

func CmdCursorLineDown

func CmdCursorLineDown(ctx Context)

func CmdCursorLineUp

func CmdCursorLineUp(ctx Context)

func CmdCursorRight

func CmdCursorRight(ctx Context)

func CmdDeleteBefore

func CmdDeleteBefore(ctx Context) func(Context)

func CmdDeleteCharBackward

func CmdDeleteCharBackward(ctx Context)

func CmdDeleteCharForward

func CmdDeleteCharForward(ctx Context)

func CmdDeleteEndOfLine

func CmdDeleteEndOfLine(ctx Context)

func CmdDeleteLine

func CmdDeleteLine(ctx Context)

func CmdDeleteTo

func CmdDeleteTo(_ Context) func(Context)

func CmdDeleteWord

func CmdDeleteWord(ctx Context)

func CmdEnsureCursorVisible

func CmdEnsureCursorVisible(ctx Context)

func CmdEnterInsertMode

func CmdEnterInsertMode(ctx Context)

func CmdEnterInsertModeAppend

func CmdEnterInsertModeAppend(ctx Context)

func CmdExit

func CmdExit(ctx Context)

func CmdExitInsertMode

func CmdExitInsertMode(ctx Context)

func CmdForceExit

func CmdForceExit(ctx Context)

func CmdForwardBeforeChar

func CmdForwardBeforeChar(_ Context) func(Context)

func CmdForwardToChar

func CmdForwardToChar(_ Context) func(Context)

func CmdForwardWord

func CmdForwardWord(ctx Context)

func CmdGotoFile

func CmdGotoFile(ctx Context)

func CmdGotoFileOtherWindow

func CmdGotoFileOtherWindow(ctx Context)

func CmdGotoLine0

func CmdGotoLine0(ctx Context)

func CmdGotoLineEnd

func CmdGotoLineEnd(ctx Context)

func CmdGotoLineEndOfFile

func CmdGotoLineEndOfFile(ctx Context)

func CmdGotoMark

func CmdGotoMark(ctx Context)

CmdGotoMark opens the marks popup legend.

func CmdIndentLine

func CmdIndentLine(ctx Context)

Get number if "indents" in provided line Indent unit can be \t, or any number of spaces. eg. 2 or 4.

func CmdIndentLines

func CmdIndentLines(ctx Context, startLine, endLine int)

func CmdIndentOrComplete

func CmdIndentOrComplete(ctx Context)

func CmdJoinNextLine

func CmdJoinNextLine(ctx Context)

func CmdJumpBack

func CmdJumpBack(ctx Context)

func CmdJumpForward

func CmdJumpForward(ctx Context)

func CmdJumpToggle

func CmdJumpToggle(ctx Context)

CmdJumpToggle toggles between the previous and current jump locations (pingpong).

func CmdKillBuffer

func CmdKillBuffer(ctx Context)

func CmdLineOpenAbove

func CmdLineOpenAbove(ctx Context)

func CmdLineOpenBelow

func CmdLineOpenBelow(ctx Context)

func CmdMacroPlay

func CmdMacroPlay(ctx Context) func(Context)

func CmdMacroRecord

func CmdMacroRecord(ctx Context) func(Context)

func CmdMacroRepeat

func CmdMacroRepeat(ctx Context)

func CmdMatchPair

func CmdMatchPair(ctx Context)

func CmdNewBuffer

func CmdNewBuffer(ctx Context)

func CmdNormalMode

func CmdNormalMode(ctx Context)

func CmdPaste

func CmdPaste(ctx Context)

func CmdRedo

func CmdRedo(ctx Context)

func CmdReplaceChar

func CmdReplaceChar(ctx Context) func(Context)

func CmdSaveFile

func CmdSaveFile(ctx Context)

func CmdScrollDownLine

func CmdScrollDownLine(ctx Context)

func CmdScrollDownPage

func CmdScrollDownPage(ctx Context)

func CmdScrollUpLine

func CmdScrollUpLine(ctx Context)

func CmdScrollUpPage

func CmdScrollUpPage(ctx Context)

func CmdSearchNext

func CmdSearchNext(ctx Context)

func CmdSearchPrev

func CmdSearchPrev(ctx Context)

func CmdSelectionBlockDelete

func CmdSelectionBlockDelete(ctx Context)

CmdSelectionBlockDelete deletes the rectangular column range [minVisCol,maxVisCol] on every line in [minLine,maxLine], independently per line (ragged lines are clipped, never merged) — unlike SelectionDelete's single contiguous stream cut.

func CmdSelectionBlockYank

func CmdSelectionBlockYank(ctx Context)

CmdSelectionBlockYank captures the rectangular column range [minVisCol,maxVisCol] on every line in [minLine,maxLine] as a single block register entry, one line per row (independent per-line clipping, no stream join).

func CmdSelectionChange

func CmdSelectionChange(ctx Context)

func CmdSelectionDelete

func CmdSelectionDelete(ctx Context)

func CmdSelectionIndent

func CmdSelectionIndent(ctx Context)

func CmdSelectionUnindent

func CmdSelectionUnindent(ctx Context)

func CmdSetMark

func CmdSetMark(ctx Context) func(Context)

CmdSetMark waits for a character input and sets a mark at the current cursor position.

func CmdToggleComment

func CmdToggleComment(ctx Context)

TODO: implement correct toggle comment logic: check if all lines are commented - then uncomment. else, append comment to each uncommted line.

func CmdToggleIndentGuides

func CmdToggleIndentGuides(ctx Context)

CmdToggleIndentGuides flips the IndentGuides config flag at runtime so you can show/hide virtual indent guides without restarting. The initial value comes from the "indent_guides" key in config.toml (default: true).

func CmdUndo

func CmdUndo(ctx Context)

func CmdUnindentLine

func CmdUnindentLine(ctx Context)

func CmdUnindentLines

func CmdUnindentLines(ctx Context, startLine, endLine int)

func CmdVisitNextLine

func CmdVisitNextLine(ctx Context)

func CmdVisitPrevLine

func CmdVisitPrevLine(ctx Context)

func CmdVisualBlockInsert

func CmdVisualBlockInsert(ctx Context)

func CmdVisualBlockMode

func CmdVisualBlockMode(ctx Context)

func CmdVisualLineMode

func CmdVisualLineMode(ctx Context)

func CmdVisualMode

func CmdVisualMode(ctx Context)

func CmdWindowClose

func CmdWindowClose(ctx Context)

func CmdWindowCloseAndKillBuffer

func CmdWindowCloseAndKillBuffer(ctx Context)

func CmdWindowCloseOther

func CmdWindowCloseOther(ctx Context)

func CmdWindowMoveToWorkspace_0

func CmdWindowMoveToWorkspace_0(ctx Context)

func CmdWindowMoveToWorkspace_1

func CmdWindowMoveToWorkspace_1(ctx Context)

func CmdWindowMoveToWorkspace_2

func CmdWindowMoveToWorkspace_2(ctx Context)

func CmdWindowMoveToWorkspace_3

func CmdWindowMoveToWorkspace_3(ctx Context)

func CmdWindowMoveToWorkspace_4

func CmdWindowMoveToWorkspace_4(ctx Context)

func CmdWindowMoveToWorkspace_5

func CmdWindowMoveToWorkspace_5(ctx Context)

func CmdWindowMoveToWorkspace_6

func CmdWindowMoveToWorkspace_6(ctx Context)

func CmdWindowMoveToWorkspace_7

func CmdWindowMoveToWorkspace_7(ctx Context)

func CmdWindowMoveToWorkspace_8

func CmdWindowMoveToWorkspace_8(ctx Context)

func CmdWindowMoveToWorkspace_9

func CmdWindowMoveToWorkspace_9(ctx Context)

func CmdWindowNext

func CmdWindowNext(ctx Context)

func CmdWindowToggleLayout

func CmdWindowToggleLayout(ctx Context)

func CmdWindowVSplit

func CmdWindowVSplit(ctx Context)

func CmdWorkspaceSwitch_0

func CmdWorkspaceSwitch_0(ctx Context)

func CmdWorkspaceSwitch_1

func CmdWorkspaceSwitch_1(ctx Context)

func CmdWorkspaceSwitch_2

func CmdWorkspaceSwitch_2(ctx Context)

func CmdWorkspaceSwitch_3

func CmdWorkspaceSwitch_3(ctx Context)

func CmdWorkspaceSwitch_4

func CmdWorkspaceSwitch_4(ctx Context)

func CmdWorkspaceSwitch_5

func CmdWorkspaceSwitch_5(ctx Context)

func CmdWorkspaceSwitch_6

func CmdWorkspaceSwitch_6(ctx Context)

func CmdWorkspaceSwitch_7

func CmdWorkspaceSwitch_7(ctx Context)

func CmdWorkspaceSwitch_8

func CmdWorkspaceSwitch_8(ctx Context)

func CmdWorkspaceSwitch_9

func CmdWorkspaceSwitch_9(ctx Context)

func CmdYank

func CmdYank(ctx Context)

func CmdYankBeforeChar

func CmdYankBeforeChar(ctx Context) func(Context)

func CmdYankEol

func CmdYankEol(ctx Context)

func CmdYankPut

func CmdYankPut(ctx Context)

func CmdYankPutBefore

func CmdYankPutBefore(ctx Context)

func CmdYankToChar

func CmdYankToChar(_ Context) func(Context)

func Color

func Color(color string) tcell.Style

func CursorChClass

func CursorChClass(buf *Buffer, cur *Cursor) chClass

func CursorChar

func CursorChar(buf *Buffer, cur *Cursor) rune

Returns char under the cursor.

func CursorDec

func CursorDec(buf *Buffer, cur *Cursor) (moved bool)

func CursorInc

func CursorInc(buf *Buffer, cur *Cursor) (moved bool)

func CursorNumByLine

func CursorNumByLine(buf *Buffer, lookie *Element[Line]) int

func FindColor

func FindColor(color string) (s tcell.Style, found bool)

func HandleInsertKey

func HandleInsertKey(ctx Context, ev *tcell.EventKey)

func IndentGetNumber

func IndentGetNumber(line []rune, indentUnit []rune) int

func IndentGuideColumns

func IndentGuideColumns(lineRun []rune) []int

IndentGuideColumns returns the visual column positions (0-indexed from the start of the text content) where vertical indent guide lines should be drawn for the given line content.

A guide is placed at the first visual column of each tab-stop within the line's leading whitespace — one guide per indent level. For example, a line indented with two tabs (tab width 4) produces guides at visual columns 0 and 4 (i.e. "|\t|\tcode").

Lines with less than one tab-stop of leading whitespace produce no guides.

func IndentGuideSet

func IndentGuideSet(lineRun []rune) map[int]bool

IndentGuideSet returns a map of visual columns that have indent guides, suitable for O(1) lookup during per-character rendering. Returns nil if the line has no indent guides.

func IndentGuideStyle

func IndentGuideStyle() tcell.Style

IndentGuideStyle returns the tcell style for indent guide lines. Configure the color via the "ui.indentguide" key in your theme.

func MergeStyles

func MergeStyles(base tcell.Style, color string) tcell.Style

func ParseFileLocation

func ParseFileLocation(text string, cursor int) (filename string, line, ch int)

ParseFileLocation scans a line of text and extracts a filename under the cursor, optionally followed by :line or :line:column (both integers).

Example valid forms:

"main.go"
"src/foo/bar.go:42"
"app/server.go:101:8"

If line or column are missing, the returned values for line and ch will be -1.

func ReloadBufferContent

func ReloadBufferContent(ctx Context, content string)

ReloadBufferContent replaces the buffer's contents with the given text, recorded as a single undo/redo transaction. Use this instead of BufferReloadFile whenever the caller wants undo to work across the reload.

func RenderIndentGuidesForLine

func RenderIndentGuidesForLine(view View, lineRun []rune, textX, scrollX, screenY, viewWidth int, style tcell.Style)

RenderIndentGuidesForLine draws indent guide characters for a single rendered line. Call this AFTER the line's text content has been rendered, as it overwrites whitespace cells with the guide glyph.

style is supplied by the caller rather than computed here so that lines with a background already painted over them (e.g. the cursorline) can pass a blended style (see ApplyBg("ui.cursorline", IndentGuideStyle())). Using a flat, backgroundless style unconditionally would reset those cells back to the default background, punching a solid block out of the cursorline highlight instead of drawing a thin guide over it.

Parameters:

  • view: the render target
  • lineRun: the rune content of the line being rendered
  • textX: screen X where the first visible text column is drawn
  • scrollX: horizontal scroll offset in visual columns (0 = no scroll)
  • screenY: screen Y of this line
  • viewWidth: number of columns available for text
  • style: the style to draw the guide glyph with (see IndentGuideStyle)

func RuneIndexFromVisualCol

func RuneIndexFromVisualCol(line []rune, visCol int) int

RuneIndexFromVisualCol finds the rune index that corresponds to a given visual screen column.

func SearchNext

func SearchNext(ctx Context, pattern string)

Move cursor to the next search pattern match

func SearchPrev

func SearchPrev(ctx Context, pattern string)

func SelectionBlockBounds

func SelectionBlockBounds(sel *Selection) (minLine, maxLine, minChar, maxChar int)

SelectionBlockBounds returns the rectangular bounds of a block selection, independent per axis (unlike SelectionNormalize, which couples Line/Char).

func SelectionCursorInRange

func SelectionCursorInRange(sel *Selection, c Cursor) bool

func SelectionDelete

func SelectionDelete(ctx Context)

func SelectionStart

func SelectionStart(buf *Buffer, cur *Cursor)

func SelectionStop

func SelectionStop(buf *Buffer, cur *Cursor)

func SelectionToString

func SelectionToString(buf *Buffer, sel *Selection) string

func SnippetParse

func SnippetParse(s string) (str string, cursorPos int)

func TabstopActivate

func TabstopActivate(ctx Context, pos []SnippetTabstopLocation)

func TabstopNext

func TabstopNext(ctx Context)

func Tabstopped

func Tabstopped(ctx Context) bool

func TextDelete

func TextDelete(buf *Buffer, selection *Selection)

func TextInsert

func TextInsert(buf *Buffer, line *Element[Line], pos int, text string)

func TextObjectBlock

func TextObjectBlock(buf *Buffer, ch rune, include bool) (found bool, sel *Selection, cur Cursor)

Returns selection inside '(', '{', '[' as "Selection" range. This implementation is simple and does not check if open/close symbols are "balanced". TODO: rewrite

func TextObjectWord

func TextObjectWord(ctx Context, bigword bool) (start, end int)

func TreeSitterHighlighterGo

func TreeSitterHighlighterGo(e *Editor)

func VisitAtLine

func VisitAtLine(ctx Context, sourceBuf *Buffer, opts VisitOptions) error

func VisualCol

func VisualCol(line []rune, char int) int

VisualCol calculates the visual screen column of a given rune index.

func WindowCursorSet

func WindowCursorSet(win *Window, buf *Buffer, cur *Cursor)

func WithSelection

func WithSelection(fn func(Context)) func(Context)

Types

type AutocompleteFn

type AutocompleteFn func(Context) bool

type BlameInfo

type BlameInfo struct {
	Hash    string
	Author  string
	Display string
}

type Buffer

type Buffer struct {
	FilePath          string
	Lines             List[Line]
	Selection         *Selection
	Driver            Driver
	IndentCh          []rune
	Tx                *Transaction
	UndoRedo          *UndoRedo
	Highlighter       Highlighter
	KeyHandler        *KeyHandler
	GitSigns          map[int]rune
	BlameEnabled      bool
	BlameLines        map[int]BlameInfo
	BlameWidth        int
	VisualBlockInsert *VisualBlockInsertState

	OpenCount int

	Dirty bool
	// contains filtered or unexported fields
}

func BufferReadFile

func BufferReadFile(path string) (*Buffer, error)

func NewBuffer

func NewBuffer() *Buffer

func (*Buffer) Append

func (b *Buffer) Append(s string)

func (*Buffer) CountLines

func (b *Buffer) CountLines() int

func (*Buffer) GetName

func (b *Buffer) GetName() string

func (*Buffer) GetRootRir

func (buf *Buffer) GetRootRir() string

func (*Buffer) Mode

func (b *Buffer) Mode() Mode

func (*Buffer) ResetLines

func (b *Buffer) ResetLines()

Remove all lines

func (*Buffer) Save

func (b *Buffer) Save() error

func (*Buffer) SetMode

func (buf *Buffer) SetMode(m Mode)

func (*Buffer) String

func (b *Buffer) String() string

func (*Buffer) TxEnd

func (b *Buffer) TxEnd()

func (*Buffer) TxStart

func (b *Buffer) TxStart() (started bool)

type CmdDefinition

type CmdDefinition struct {
	Desc string
	Fn   interface{}
}

type CommitItem

type CommitItem struct {
	Hash    string
	Author  string
	Date    string
	Subject string
}

CommitItem represents a single commit entry in the git log.

type CompletionItems

type CompletionItems struct {
	IsIncomplete bool `json:"isIncomplete"`
	Items        []struct {
		Label               string              `json:"label"`
		InsertText          string              `json:"insertText"`
		Kind                int                 `json:"kind"`
		Detail              string              `json:"detail"`
		Documentation       Documentation       `json:"documentation"`
		Preselect           bool                `json:"preselect,omitempty"`
		SortText            string              `json:"sortText"`
		FilterText          string              `json:"filterText,omitempty"`
		InsertTextFormat    int                 `json:"insertTextFormat"`
		TextEdit            *CompletionTextEdit `json:"textEdit,omitempty"`
		AdditionalTextEdits []struct {
			Range struct {
				Start struct {
					Line      int `json:"line"`
					Character int `json:"character"`
				} `json:"start"`
				End struct {
					Line      int `json:"line"`
					Character int `json:"character"`
				} `json:"end"`
			} `json:"range"`
			NewText string `json:"newText"`
		} `json:"additionalTextEdits,omitempty"`
		Data interface{} `json:"data,omitempty"`
	} `json:"items"`
}

type CompletionTextEdit

type CompletionTextEdit struct {
	NewText string `json:"newText"`
	Insert  struct {
		Start struct {
			Line      int `json:"line"`
			Character int `json:"character"`
		} `json:"start"`
		End struct {
			Line      int `json:"line"`
			Character int `json:"character"`
		} `json:"end"`
	} `json:"insert"`
	Replace struct {
		Start struct {
			Line      int `json:"line"`
			Character int `json:"character"`
		} `json:"start"`
		End struct {
			Line      int `json:"line"`
			Character int `json:"character"`
		} `json:"end"`
	} `json:"replace"`
}

type ConfirmWidget

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

func ConfirmInit

func ConfirmInit(ctx Context, prompt string, onYes func(), onNo func(), onCancel func()) *ConfirmWidget

func (*ConfirmWidget) Keymap

func (u *ConfirmWidget) Keymap() *KeyHandler

func (*ConfirmWidget) Mode

func (u *ConfirmWidget) Mode() Mode

func (*ConfirmWidget) Plane

func (u *ConfirmWidget) Plane() RenderPlane

func (*ConfirmWidget) Render

func (u *ConfirmWidget) Render(view View)

type Context

type Context struct {
	Editor *Editor
	Buf    *Buffer
	Win    *Window
	Count  uint32
	Char   string
}

type Cursor

type Cursor struct {
	Line                 int
	Char                 int
	PreserveCharPosition int
	ScrollOffset         int
}

func ContextCursorGet

func ContextCursorGet(ctx Context) *Cursor

func CursorGet

func CursorGet(editor *Editor, buf *Buffer) *Cursor

func WindowCursorGet

func WindowCursorGet(win *Window, buf *Buffer) *Cursor

type Documentation

type Documentation struct {
	Kind  string `json:"kind"`
	Value string `json:"value"`
}

func (*Documentation) UnmarshalJSON

func (d *Documentation) UnmarshalJSON(data []byte) error

type Driver

type Driver interface {
	// Execute thing under cursor: line or seleciton
	Exec(*Editor, *Buffer, *Element[Line])
	// Execute whole buffer
	ExecBuffer()
}

Driver represents anything that can run selected text. it can be sql connection, or rest client.

type EditDiff

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

type Editor

type Editor struct {
	View                View
	Keys                *KeyHandler
	Buffers             []*Buffer
	UiComponents        []UiComponent
	ExitCh              chan int
	RedrawCh            chan int
	ScreenSyncCh        chan int
	Layout              Layout
	Yanks               List[yank]
	Projects            ProjectManager
	Message             string // display in echo area
	Lsp                 *LspManager
	Events              *EventsManager
	AutocompleteTrigger AutocompleteFn
	Snippets            *SnippetsManager
	Config              EditorConfig
	Workspaces          []Workspace
	ActiveWorkspace     int
}
var EditorInst *Editor

func NewEditor

func NewEditor(
	view View,
	keys *KeyHandler,
) *Editor

func (*Editor) ActiveBuffer

func (e *Editor) ActiveBuffer() *Buffer

Returns active window buffer. May return nil when the active workspace has no active window/buffer, e.g. transiently after ":q" closed the last window.

func (*Editor) ActiveWindow

func (e *Editor) ActiveWindow() *Window

func (*Editor) BufferFindByFilePath

func (e *Editor) BufferFindByFilePath(fp string, create bool) *Buffer

Find or create new buffer by its full file path

func (*Editor) EchoMessage

func (e *Editor) EchoMessage(msg string)

func (*Editor) EnsureBufferIsVisible

func (e *Editor) EnsureBufferIsVisible(b *Buffer)

func (*Editor) GetActiveWorkspace

func (e *Editor) GetActiveWorkspace() *Workspace

func (*Editor) GetWorkspace

func (e *Editor) GetWorkspace(num int) *Workspace

func (*Editor) HandleInput

func (e *Editor) HandleInput(ev *tcell.EventKey)

func (*Editor) LogError

func (e *Editor) LogError(err error, echo ...bool)

func (*Editor) LogMessage

func (e *Editor) LogMessage(msg ...string)

func (*Editor) NewContext

func (e *Editor) NewContext() Context

func (*Editor) OpenFile

func (e *Editor) OpenFile(path string) (*Buffer, error)

func (*Editor) PopUi

func (e *Editor) PopUi()

func (*Editor) PopUiComponent

func (e *Editor) PopUiComponent(c UiComponent)

PopUiComponent removes a specific UI component from the stack. This is required for WhichKey because commands executed from WhichKey can push their own UI components (Picker, CommandLine, etc.) before WhichKey.Close is called. Using PopUi in that case removes the newly pushed component instead of WhichKey, leaving WhichKey stuck on screen.

func (*Editor) PushUi

func (e *Editor) PushUi(c UiComponent)

func (*Editor) ReadConfigFile

func (e *Editor) ReadConfigFile()

func (*Editor) Redraw

func (e *Editor) Redraw()

func (*Editor) RuntimeDir

func (e *Editor) RuntimeDir(elems ...string) string

func (*Editor) ScreenSync

func (e *Editor) ScreenSync()

func (*Editor) SetActiveWindow

func (e *Editor) SetActiveWindow(w *Window)

func (*Editor) SetWindows

func (e *Editor) SetWindows(w []*Window)

func (*Editor) Windows

func (e *Editor) Windows() []*Window

type EditorConfig

type EditorConfig struct {
	Theme                string
	ShowLineNumbers      bool
	RelativeLineNumbers  bool
	CurrentLineAbsolute  bool // If true, shows absolute line number on current line when relative is on
	FormatOnSave         bool
	GitStatusView        string // "full" or "split"
	GitBlameView         string // "full" or "split"
	IndentGuides         bool
	FloatingWindowWidth  float64
	FloatingWindowHeight float64
}

type Element

type Element[T any] struct {
	Value T
	// contains filtered or unexported fields
}

func CursorLine

func CursorLine(buf *Buffer, cur *Cursor) *Element[Line]

func CursorLineByNum

func CursorLineByNum(buf *Buffer, num int) *Element[Line]

func (*Element[T]) Next

func (e *Element[T]) Next() *Element[T]

func (*Element[T]) Prev

func (e *Element[T]) Prev() *Element[T]

type Event

type Event struct {
	Msg any
	Wg  *sync.WaitGroup
}

type EventBufferModeChange

type EventBufferModeChange struct {
	Buf     *Buffer
	OldMode Mode
	NewMode Mode
}

type EventBufferReloaded

type EventBufferReloaded struct {
	Buf *Buffer
}

type EventKeyPressed

type EventKeyPressed struct {
	Key string
}

type EventTextChange

type EventTextChange struct {
	Buf     *Buffer
	Start   Position
	End     Position
	NewEnd  Position
	Text    string
	OldText string
}

type EventsManager

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

func NewEventsManager

func NewEventsManager() *EventsManager

func (*EventsManager) Broadcast

func (e *EventsManager) Broadcast(msg any)

this is very quick and dirty implementation. we need sync processing to not mess up lsp and treesitter. TODO: rewrite.

func (*EventsManager) Subscribe

func (e *EventsManager) Subscribe() <-chan Event

func (*EventsManager) Unsubscribe

func (e *EventsManager) Unsubscribe(ch <-chan Event)

type GitViewItem

type GitViewItem struct {
	Type     string // "header", "separator", "empty", "blank", "file", "branch", "stash"
	Label    string
	Status   string // "staged", "unstaged", "untracked", "last_commit", "branch", "active_branch", "stash"
	FilePath string
	Code     string
	StashRef string
}

GitViewItem represents a single line in the git status view panel.

type Highlighter

type Highlighter interface {
	// Full document build/re-build/init
	Build()
	TextChanged(EventTextChange)

	// Query syntax highlights for given range
	ForRange(startLine, endLine uint32) *HighlighterCursor
}

type HighlighterCursor

type HighlighterCursor struct {
	Cursor *Element[HighlighterNode]
}

func (*HighlighterCursor) Seek

func (c *HighlighterCursor) Seek(line, ch uint32) (node *Element[HighlighterNode], found bool)

type HighlighterNode

type HighlighterNode struct {
	NodeName  string
	StartLine uint32
	StartChar uint32
	EndLine   uint32
	EndChar   uint32
}

type Indent

type Indent struct {
	Unit     string `toml:"unit,omitempty"`
	TabWidth int    `toml:"tab-width,omitempty"`
}

type Jump

type Jump struct {
	FilePath string
	Cursor   Cursor
}

Jumps

type Jumps

type Jumps struct {
	List List[Jump]
	// contains filtered or unexported fields
}

func (*Jumps) JumpBack

func (j *Jumps) JumpBack()

func (*Jumps) JumpForward

func (j *Jumps) JumpForward()

func (*Jumps) Push

func (j *Jumps) Push(b *Buffer, cur *Cursor)

type KeyFallbackFn

type KeyFallbackFn func(ctx Context, ev *tcell.EventKey)

type KeyHandler

type KeyHandler struct {

	// enable suppor for repeat counter.
	EnableTimes bool

	Macros *MacrosManager
	// contains filtered or unexported fields
}

func DefaultKeyHandler

func DefaultKeyHandler(mergeKeys ModeKeyMap) *KeyHandler

func NewKeyHandler

func NewKeyHandler(mkeys ModeKeyMap) *KeyHandler

func (*KeyHandler) Fallback

func (k *KeyHandler) Fallback(fn func(ctx Context, ev *tcell.EventKey))

func (*KeyHandler) GetCount

func (k *KeyHandler) GetCount() int

func (*KeyHandler) GetFallback

func (k *KeyHandler) GetFallback() KeyFallbackFn

func (*KeyHandler) HandleKey

func (k *KeyHandler) HandleKey(editor *Editor, ev *tcell.EventKey, mode Mode)

func (*KeyHandler) Map

func (k *KeyHandler) Map(mode Mode, newMappings KeyMap)

Map/merge keymap by selected mode

func (*KeyHandler) SetContextFn

func (k *KeyHandler) SetContextFn(fn func(editor *Editor) Context)

type KeyMap

type KeyMap map[string]any

type LangConfig

type LangConfig struct {
	Languages       []Language                      `toml:"language,omitempty"`
	LanguageServers map[string]LanguageServerConfig `toml:"language-server,omitempty"`
}

func LoadLanguagesConfig

func LoadLanguagesConfig() LangConfig

type Language

type Language struct {
	Name            string `toml:"name"`
	FileTypes       []any  `toml:"file-types"`
	LanguageServers []any  `toml:"language-servers"`
	Indent          Indent `toml:"indent,omitempty"`
}

func (Language) GetFileTypes

func (l Language) GetFileTypes() (exts []string, globs []string)

func (Language) GetLanguageServers

func (l Language) GetLanguageServers() (servers []string)

type LanguageServerConfig

type LanguageServerConfig struct {
	Language Language
	Command  string   `toml:"command"`
	Args     []string `toml:"args"`
}

func LspConfigByFileName

func LspConfigByFileName(file string) (conf LanguageServerConfig, found bool)

type Layout

type Layout int
const (
	LayoutHorizontal Layout = 0
	LayoutVertical   Layout = 1
)

type Line

type Line []rune

func (Line) Bytes

func (l Line) Bytes() int

func (Line) IsEmpty

func (l Line) IsEmpty() bool

func (Line) Range

func (l Line) Range(from, to int) []rune

func (Line) String

func (l Line) String() string

type List

type List[T any] struct {
	Len int
	// contains filtered or unexported fields
}

the zero value is ready to use.

func FromSlice

func FromSlice[T any](slice []T) List[T]

Constructs a new List[T] from the given slice, returns the List[T].

func (*List[T]) First

func (l *List[T]) First() *Element[T]

func (*List[T]) Last

func (l *List[T]) Last() *Element[T]

func (*List[T]) PushBack

func (l *List[T]) PushBack(v T) *Element[T]

func (*List[T]) PushFront

func (l *List[T]) PushFront(v T) *Element[T]

func (*List[T]) Remove

func (l *List[T]) Remove(e *Element[T]) T

type Location

type Location struct {
	Text     string
	FilePath string
	Line     int
	Char     int
}

type LspManager

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

func NewLspManager

func NewLspManager(e *Editor) *LspManager

func (*LspManager) Completion

func (l *LspManager) Completion(buf *Buffer) (res CompletionItems)

func (*LspManager) CompletionItemResolve

func (l *LspManager) CompletionItemResolve(buf *Buffer, item any) (doc string, err error)

CompletionItemResolve requests the full documentation/detail for a completion item by calling completionItem/resolve on the language server. The item parameter should be the raw completion item (or a map containing at least label, kind, and data) received from a prior Completion call.

func (*LspManager) Definition

func (l *LspManager) Definition(buf *Buffer, cursor Cursor) (filePath string, cur Cursor)

func (*LspManager) Diagnostics

func (m *LspManager) Diagnostics(buf *Buffer, lineNum int) []protocol.Diagnostic

TODO: return copy of diagnostics

func (*LspManager) DidChange

func (l *LspManager) DidChange(event EventTextChange)

func (*LspManager) DidClose

func (l *LspManager) DidClose(buf *Buffer)

func (*LspManager) DidOpen

func (l *LspManager) DidOpen(buf *Buffer)

func (*LspManager) DidSave

func (l *LspManager) DidSave(buf *Buffer)

func (*LspManager) Hover

func (l *LspManager) Hover(buf *Buffer, cursor Cursor) (sign string)

func (*LspManager) Signature

func (l *LspManager) Signature(buf *Buffer, cursor Cursor) (sign string)

type MacrosManager

type MacrosManager struct {
	Register string
	// contains filtered or unexported fields
}

func NewMacrosManager

func NewMacrosManager(keyHandler *KeyHandler) *MacrosManager

func (*MacrosManager) Play

func (m *MacrosManager) Play(reg string)

func (*MacrosManager) Push

func (m *MacrosManager) Push(ev *tcell.EventKey)

func (*MacrosManager) Recording

func (m *MacrosManager) Recording() bool

func (*MacrosManager) Reset

func (m *MacrosManager) Reset()

func (*MacrosManager) Start

func (m *MacrosManager) Start(reg string)

func (*MacrosManager) StartRepeatRecording

func (m *MacrosManager) StartRepeatRecording()

func (*MacrosManager) Stop

func (m *MacrosManager) Stop()

func (*MacrosManager) StopRepeatRecording

func (m *MacrosManager) StopRepeatRecording()

type Mark

type Mark struct {
	Buf    *Buffer
	Cursor Cursor
}

Mark is a named cursor position bound to a specific buffer. When text is inserted or deleted in its buffer, the mark is adjusted so that it keeps pointing at the same text (vim-like behavior).

type Mode

type Mode int
const (
	MODE_NORMAL       Mode = 0
	MODE_INSERT       Mode = 1
	MODE_VISUAL       Mode = 2
	MODE_VISUAL_LINE  Mode = 3
	MODE_VISUAL_BLOCK Mode = 4
)

func (Mode) String

func (m Mode) String() string

type ModeKeyMap

type ModeKeyMap map[Mode]KeyMap

type Position

type Position struct {
	Line int
	Char int
}

type PositionCache

type PositionCache struct {
	Files map[string]PositionEntry `toml:"files"`
}

func LoadPositionCache

func LoadPositionCache() *PositionCache

func (*PositionCache) Save

func (c *PositionCache) Save()

type PositionEntry

type PositionEntry struct {
	Line      int   `toml:"line"`
	OpenCount int   `toml:"open_count"`
	Timestamp int64 `toml:"timestamp"`
}

type ProjectManager

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

func NewProjectManager

func NewProjectManager() ProjectManager

func (ProjectManager) Dir

func (p ProjectManager) Dir(buf *Buffer) (dir string)

Returns Dir of current buffer or working directory if buffer has no valid file path.

func (ProjectManager) FindRoot

func (p ProjectManager) FindRoot(buf *Buffer) (root string, err error)

Find project root by file path. Project root must have .git directory in it. otherwise "working directory" will be returned.

func (ProjectManager) GetRoot

func (p ProjectManager) GetRoot() (root string)

TODO: this must be also base on git dir

type Range

type Range struct {
	Start Position
	End   Position
}

type RenderPlane

type RenderPlane int
const (
	PlaneWin    RenderPlane = 0
	PlaneEditor RenderPlane = 1
)

type Selection

type Selection struct {
	Start Cursor
	End   Cursor
}

func SelectionNormalize

func SelectionNormalize(sel *Selection) Selection

type Snippet

type Snippet struct {
	Prefix string
	Body   string
}

type SnippetTabstopLocation

type SnippetTabstopLocation struct {
	Index    int
	Char     int
	Length   int
	Line     int
	Distance int
}

func SnippetParseLocations

func SnippetParseLocations(s string) (str string, pos []SnippetTabstopLocation)

type SnippetsManager

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

func NewSnippetsManager

func NewSnippetsManager() *SnippetsManager

func (*SnippetsManager) Complete

func (s *SnippetsManager) Complete(ctx Context) bool

func (*SnippetsManager) Expand

func (s *SnippetsManager) Expand(ctx Context, v Snippet, cursorChar int)

type Stack

type Stack[T any] struct {
	// contains filtered or unexported fields
}

func (*Stack[T]) IsEmpty

func (s *Stack[T]) IsEmpty() bool

func (*Stack[T]) Pop

func (s *Stack[T]) Pop() (T, bool)

func (*Stack[T]) Push

func (s *Stack[T]) Push(element T)

type Style

type Style struct {
	Fg        string
	Bg        string
	Underline struct {
		Color string
		Style string
	}
	Reversed bool
	Tcell    tcell.Style
}

type Theme

type Theme struct {
	Colors  map[string]Style
	Palette map[string]string
}

type Transaction

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

func NewTx

func NewTx(b *Buffer) *Transaction

func (*Transaction) End

func (tx *Transaction) End()

func (*Transaction) Start

func (tx *Transaction) Start()

type TreeSitterHighlighter

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

func TreeSitterHighlighterInitBuffer

func TreeSitterHighlighterInitBuffer(e *Editor, buf *Buffer) *TreeSitterHighlighter

func (*TreeSitterHighlighter) Build

func (h *TreeSitterHighlighter) Build()

func (*TreeSitterHighlighter) ForRange

func (h *TreeSitterHighlighter) ForRange(lineStart, lineEnd uint32) *HighlighterCursor

func (*TreeSitterHighlighter) TextChanged

func (h *TreeSitterHighlighter) TextChanged(event EventTextChange)

type UiComponent

type UiComponent interface {
	Mode() Mode
	Keymap() *KeyHandler
	Render(view View)
	Plane() RenderPlane
}

type UndoRedo

type UndoRedo struct {
	Buf      *Buffer
	History  []EditDiff
	Position int
	// SavedAtPosition stores the UndoRedo Position at the moment the file was saved.
	// If Position == SavedAtPosition, the buffer is not dirty.
	SavedAtPosition int
}

func NewUndoRedo

func NewUndoRedo(buf *Buffer) *UndoRedo

func (*UndoRedo) Push

func (u *UndoRedo) Push(edits EditDiff)

func (*UndoRedo) Redo

func (u *UndoRedo) Redo()

func (*UndoRedo) Undo

func (u *UndoRedo) Undo()

type View

type View interface {
	SetContent(x, y int, str string, st tcell.Style)
	Size() (width, height int)
	Resize(x, y, width, height int)
}

type VisitOptions

type VisitOptions struct {
	Movement      func(Context)
	Center        bool
	TargetWin     *Window
	ParseLocation bool
	Cursor        *Cursor
}

type VisualBlockInsertState

type VisualBlockInsertState struct {
	StartLine int
	EndLine   int
	Char      int
}

type WhichKey

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

func WhichKeyInit

func WhichKeyInit(e *Editor, keymap *KeyHandler, mode Mode, items KeyMap) *WhichKey

func (*WhichKey) Close

func (w *WhichKey) Close()

func (*WhichKey) Keymap

func (w *WhichKey) Keymap() *KeyHandler

func (*WhichKey) Mode

func (w *WhichKey) Mode() Mode

func (*WhichKey) Plane

func (w *WhichKey) Plane() RenderPlane

func (*WhichKey) Render

func (w *WhichKey) Render(view View)

func (*WhichKey) Update

func (w *WhichKey) Update(items KeyMap)

type Window

type Window struct {
	Marks map[rune]Mark
	Jumps *Jumps
	// contains filtered or unexported fields
}

func CreateWindow

func CreateWindow(parent *Window) *Window

Specify parent window to inherit cursors

func (*Window) Buffer

func (win *Window) Buffer() *Buffer

func (*Window) ShowBuffer

func (win *Window) ShowBuffer(buf *Buffer)

Show buffer. No history.

func (*Window) VisitBuffer

func (win *Window) VisitBuffer(ctx Context, cursor ...Cursor)

Jump to buffer and location. Records jump history.

type Workspace

type Workspace struct {
	Num          int
	Windows      []*Window
	ActiveWindow *Window
}

type WorkspaceCache

type WorkspaceCache struct {
	Workspaces      map[int]WorkspaceCacheEntry `json:"workspaces"`
	ActiveWorkspace int                         `json:"active_workspace"`
}

WorkspaceCache is the on-disk persistence store for workspace state. It is saved to ~/.config/wig/workspaces.json on exit and loaded on startup or when the workspace picker is opened.

func LoadWorkspaceCache

func LoadWorkspaceCache() *WorkspaceCache

LoadWorkspaceCache reads the workspace cache from disk. If the file does not exist or is corrupt, an empty cache is returned.

func (*WorkspaceCache) CaptureAll

func (c *WorkspaceCache) CaptureAll(editor *Editor)

CaptureAll captures the state of every workspace that has at least one window. Workspaces that were never used in this session are skipped so that their cached entries from a previous session are preserved.

func (*WorkspaceCache) CaptureWorkspace

func (c *WorkspaceCache) CaptureWorkspace(num int, ws *Workspace, editor *Editor)

CaptureWorkspace records the file paths open in a workspace into the cache. Only real file-backed buffers are stored; special buffers like [Messages] or [git] are skipped. Duplicate paths are deduplicated.

Previously-cached files are preserved only when they still exist on disk AND are still open in the editor (some buffer holds the path). This keeps files that the user temporarily hid by opening another file in the same window, while dropping files whose buffers were killed. Files are fully cleared from a workspace only via Delete in the picker, or when the computed list is empty (protected below).

func (*WorkspaceCache) RestoreWorkspace

func (c *WorkspaceCache) RestoreWorkspace(editor *Editor, num int)

RestoreWorkspace rebuilds the target workspace from cache if it is currently empty (no real file-backed buffers): every cached file gets its own window so the previous split layout is recreated. If the workspace already has file buffers, the cache is skipped to avoid duplicates.

func (*WorkspaceCache) Save

func (c *WorkspaceCache) Save()

Save writes the workspace cache to disk.

type WorkspaceCacheEntry

type WorkspaceCacheEntry struct {
	Files      []string `json:"files"`
	ActiveFile string   `json:"active_file"`
}

WorkspaceCacheEntry stores the file paths and active file for a single workspace so that the workspace layout can be restored in a later editor session.

type Yanks

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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