editor

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package editor is the full-screen message editor used when a caller writes a post, reply, private mail or auto-signature. RunEditorWithMetadata is the entry point: it sizes an FSEditor to the caller's PTY, draws the FSEDITOR.ANS header and FSEDITORF.ANS footer from the menu set, and edits a MessageBuffer of up to MaxLines lines with word wrap, WordStar-style keys, an Escape command menu, and a split-pane quote picker. It returns the finished text and whether the caller chose to save it.

Index

Constants

View Source
const (
	// MaxLines is the maximum number of lines in a message (100 lines, 1-based indexing)
	MaxLines = 100
	// MaxLineLength is the maximum length of a line before word wrap (79 chars)
	MaxLineLength = 79
)
View Source
const (
	// WordStar navigation commands
	KeyCtrlE = 0x05 // Up
	KeyCtrlX = 0x18 // Down
	KeyCtrlS = 0x13 // Left
	KeyCtrlD = 0x04 // Right
	KeyCtrlW = 0x17 // Home (start of line)
	KeyCtrlP = 0x10 // End (end of line)
	KeyCtrlR = 0x12 // Page Up
	KeyCtrlC = 0x03 // Page Down

	// Command shortcuts (shown in footer: CTRL (A)Abort (Z)Save (Q)Quote)
	KeyCtrlA = 0x01 // Abort (formerly Word Left)
	KeyCtrlZ = 0x1A // Save
	KeyCtrlQ = 0x11 // Quote

	// Word navigation
	KeyCtrlF = 0x06 // Word Right

	// Edit commands
	KeyCtrlV = 0x16 // Toggle Insert/Overwrite
	KeyCtrlG = 0x07 // Delete character at cursor
	KeyCtrlT = 0x14 // Delete word
	KeyCtrlY = 0x19 // Delete line
	KeyCtrlK = 0x0B // Delete line (Mystic-style alias for Ctrl-Y)
	KeyCtrlJ = 0x0A // Join lines (also Enter/LF in some contexts)
	KeyCtrlN = 0x0E // Split line (new line)
	KeyCtrlB = 0x02 // Reformat paragraph
	KeyCtrlL = 0x0C // Redisplay screen
	KeyCtrlO = 0x0F // Autocorrect on/off

	// Special keys
	KeyEsc       = 0x1B // Escape
	KeyEnter     = 0x0D // Carriage Return
	KeyBackspace = 0x08 // Backspace
	KeyTab       = 0x09 // Tab
	KeyDelete    = 0x7F // Delete (DEL character)

	// Special internal codes for arrow keys (outside normal byte range)
	KeyArrowUp    = 0x100 // Internal code for up arrow
	KeyArrowDown  = 0x101 // Internal code for down arrow
	KeyArrowLeft  = 0x102 // Internal code for left arrow
	KeyArrowRight = 0x103 // Internal code for right arrow
	KeyPageUp     = 0x104 // Internal code for page up
	KeyPageDown   = 0x105 // Internal code for page down
	KeyHome       = 0x106 // Internal code for home
	KeyEnd        = 0x107 // Internal code for end
	KeyInsert     = 0x108 // Internal code for insert
	KeyDeleteKey  = 0x109 // Internal code for delete key
	KeyF1         = 0x10A // Internal codes for F1-F12, in order
	KeyF2         = 0x10B
	KeyF3         = 0x10C
	KeyF4         = 0x10D
	KeyF5         = 0x10E
	KeyF6         = 0x10F
	KeyF7         = 0x110
	KeyF8         = 0x111
	KeyF9         = 0x112
	KeyF10        = 0x113
	KeyF11        = 0x114
	KeyF12        = 0x115
	KeyBackTab    = 0x116 // Internal code for Shift-Tab
)

Special key codes for editor commands (using WordStar-style control characters)

View Source
const DefaultEscTimeout = 500 * time.Millisecond

DefaultEscTimeout is how long a lone ESC waits for the rest of an escape sequence before it counts as the Esc key (see ReadKey for why it is this long). The script engine's readkey uses the same window.

View Source
const MaxCSILength = 32

MaxCSILength caps the bytes read after "ESC [" while waiting for a CSI sequence's final byte. Every key in the table is far shorter; a sequence that runs past it is abandoned and reads as Esc, so a client streaming parameter bytes can't make the reader hold them without limit.

Variables

View Source
var ErrIdleTimeout = errors.New("idle timeout")

ErrIdleTimeout is returned by ReadKeyWithTimeout when no input arrives before the caller-supplied deadline. It is distinct from the internal inter-byte escape-sequence timeout so that callers can handle user-visible idle disconnects without false-positive matches on sequence parsing.

View Source
var ErrReadStopped = errors.New("input read stopped")

ErrReadStopped is returned by ReadUntil and ReadByteUntil when their stop channel closes before a byte arrives.

View Source
var ErrTimeLimit = fmt.Errorf("time limit reached: %w", ErrIdleTimeout)

ErrTimeLimit is returned by a session key read once the caller's time limit has passed (see SetSessionDeadline). It wraps ErrIdleTimeout, so every input loop that already logs the caller off on an idle timeout does the same when their time runs out.

Functions

func CSIKey added in v0.9.7

func CSIKey(params []byte, final byte) int

CSIKey returns the key for the CSI sequence "ESC [ params final", or 0 if it is not a key.

func ContinuesParagraph added in v0.9.6

func ContinuesParagraph(prev, next string, width int) bool

ContinuesParagraph reports whether next, the source line after prev, is a continuation of the same paragraph rather than the start of a new one. The source carries no paragraph marks, so this reads them off the layout: the author's editor wrapped next onto its own line only when its first word would not fit on prev, so a prev with room left for that word ended where it did on purpose. Blank lines, a change of quote depth or indent, and list items also break a paragraph. width is the wrap width of the source, in characters; ContinuesParagraphMeasured takes another measure.

func ContinuesParagraphMeasured added in v0.9.6

func ContinuesParagraphMeasured(prev, next string, width int, measure func(string) int) bool

ContinuesParagraphMeasured is ContinuesParagraph with lengths taken by measure, in the same unit as width. Where measure gives the next line's first character more than one column, it is double-width text, which an editor may break before any character, so that character alone is what did not fit.

func IsPrintable

func IsPrintable(key int) bool

IsPrintable returns true if the key is a printable character

func KeyName

func KeyName(key int) string

KeyName returns the name scripts use for a special key ("UP", "PGDN", "F1", "ESC", ...), or "" for any other key code.

func QuoteSourceWidth added in v0.9.6

func QuoteSourceWidth(lines []string) int

QuoteSourceWidth estimates the width the source message was wrapped at: its longest line, ignoring lines too long to have been wrapped at all. Lines are measured in characters; QuoteSourceWidthMeasured takes another measure.

func QuoteSourceWidthMeasured added in v0.9.6

func QuoteSourceWidthMeasured(lines []string, measure func(string) int) int

QuoteSourceWidthMeasured is QuoteSourceWidth with lines measured by measure, such as display columns, where double-width text takes two per character.

func ReadKeyOrEvent added in v0.9.5

func ReadKeyOrEvent[T any](ih *InputHandler, events <-chan T) (int, T, bool, error)

ReadKeyOrEvent is the exported form of readKeyOrEvent.

func RunEditorWithMetadata

func RunEditorWithMetadata(initialContent string, input io.Reader, output io.Writer, outputMode ansi.OutputMode,
	subject, recipient, fromName string, isAnon bool, quoteFrom, quoteTitle, quoteDate, quoteTime string, quoteIsAnon bool, quoteLines []string, ih *InputHandler, ctx ...EditorContext) (content string, saved bool, err error)

RunEditorWithMetadata is an extended version that accepts message metadata. fromName is the sender display name shown in the @F@ header field: the user's handle by default, their real name when the area requires it, or the configured anonymous string when the user chose to post anonymously.

ih is an optional pre-created *InputHandler to share with the caller's reader. Pass nil to create a new one internally. Passing a shared InputHandler prevents the editor's goroutine from consuming bytes after the editor exits.

func SS3Key added in v0.9.7

func SS3Key(b byte) int

SS3Key returns the key for the SS3 sequence "ESC O b", or 0 if it is not a key.

func SplitQuotePrefix added in v0.9.6

func SplitQuotePrefix(line string) (prefix, body string)

SplitQuotePrefix splits a cleaned source line into the quote prefix it already carries, normalized to single spaces ("Sh> "), and the text after it, indent included. A line with no prefix returns "" and the line unchanged.

func TranslateToWordStar

func TranslateToWordStar(key int) int

TranslateToWordStar translates arrow keys to WordStar equivalents

Types

type CommandHandler

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

CommandHandler handles special slash commands

func NewCommandHandler

func NewCommandHandler(screen *Screen, buffer *MessageBuffer, menuSetPath, yesNoHi, yesNoLo, yesText, noText, abortText string) *CommandHandler

NewCommandHandler creates a new command handler

func (*CommandHandler) HandleAbort

func (ch *CommandHandler) HandleAbort(inputHandler *InputHandler) bool

HandleAbort handles the Abort command (CTRL-A). Displays a lightbar Yes/No confirmation in the last footer row (PromptRow). Returns true to signal abort and exit; false restores the footer row and continues.

func (*CommandHandler) HandleHelp

func (ch *CommandHandler) HandleHelp(inputHandler *InputHandler)

HandleHelp handles the /H (help) command Displays the help screen

func (*CommandHandler) HandleQuote

func (ch *CommandHandler) HandleQuote(inputHandler *InputHandler, currentLine, currentCol int) (int, int)

HandleQuote handles the Quote command (CTRL-Q). Opens the split-pane quote picker: the message being composed stays on screen above a divider, the message being replied to is listed below it under a lightbar, and each selected line is inserted immediately. Everything paints inside the editing area, so the header and footer stay put. Returns the cursor position the editor should resume at.

func (*CommandHandler) HandleSave

func (ch *CommandHandler) HandleSave() bool

HandleSave handles the Save command (CTRL-Z). Returns true to signal save and exit; on false, an error is written to PromptRow.

func (*CommandHandler) HandleView

func (ch *CommandHandler) HandleView(inputHandler *InputHandler)

HandleView handles the /V (view) command Displays the current message (not fully implemented)

func (*CommandHandler) SetNetworkQuoteStrings added in v0.9.5

func (ch *CommandHandler) SetNetworkQuoteStrings(top, bottom string)

SetNetworkQuoteStrings marks the message as bound for a networked area and sets the banners used there. Unlike SetQuoteStrings, an empty value means no banner rather than the built-in default.

func (*CommandHandler) SetQuoteData

func (ch *CommandHandler) SetQuoteData(data *QuoteData)

SetQuoteData sets the message data to be used for the /Q quote command

func (*CommandHandler) SetQuoteStrings added in v0.8.1

func (ch *CommandHandler) SetQuoteStrings(top, bottom, prefix string)

SetQuoteStrings overrides the quote block styling from strings.json. Empty values keep the built-in defaults.

func (*CommandHandler) ShowEscapeMenu

func (ch *CommandHandler) ShowEscapeMenu(inputHandler *InputHandler) CommandType

ShowEscapeMenu displays a lightbar selection menu at PromptRow when Escape is pressed. Items: Save, Abort, Edit (continue), Help, Quote. Returns the selected CommandType, or CommandNone to continue editing.

type CommandType

type CommandType int

CommandType represents a special editor command

const (
	CommandNone  CommandType = iota // No command; keep editing
	CommandSave                     // /S - Save and exit
	CommandAbort                    // /A - Abort editing
	CommandQuote                    // /Q - Quote previous message
	CommandHelp                     // /H or /? - Show help
	CommandView                     // /V - View message (not implemented in this version)
)

Editor commands, chosen from the Escape lightbar menu or bound to CTRL keys (CTRL-A abort, CTRL-Z save, CTRL-Q quote) and run by the FSEditor. The slash forms noted beside each value are the original ViSiON/2 command letters.

type EditorContext

type EditorContext struct {
	NodeNumber int    // Current node number (@K@)
	NextMsgNum int    // Next message number in the area (@#@)
	ConfArea   string // "Conference > Area" combined string (@Z@)
	Networked  bool   // area is echoed off the BBS: quote with the quote*Net strings
	QuoteTo    string // who the quoted message was addressed to (^F in quote banners)

	// Autocorrect makes autocorrect available in this editor: the message
	// area (or, with no area, the board default) has it on. AutocorrectOff
	// is the caller's own choice to have it off; Ctrl-O can still turn it
	// back on while Autocorrect is set.
	Autocorrect    bool
	AutocorrectOff bool
	// SaveAutocorrect, if set, keeps the caller's choice when Ctrl-O
	// switches autocorrect; on is the new state.
	SaveAutocorrect func(on bool)
}

EditorContext carries optional display-only metadata for the editor header. Pass this to RunEditorWithMetadata to populate @K@ (node), @#@ (msg num), and @Z@ (conference > area) placeholders in FSEDITOR.ANS.

type FSEditor

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

FSEditor is the full-screen message editor

func NewFSEditor

func NewFSEditor(session ssh.Session, terminal io.Writer, outputMode ansi.OutputMode,
	termWidth, termHeight int, menuSetPath, yesNoHi, yesNoLo, yesText, noText, abortText string,
	ih *InputHandler) *FSEditor

NewFSEditor creates a new full-screen editor instance. ih is an optional pre-created InputHandler to reuse (pass nil to create a new one). Passing a shared InputHandler prevents the editor's background goroutine from racing with the caller's reader for bytes after the editor exits.

func (*FSEditor) EnableAutocorrect added in v0.9.7

func (e *FSEditor) EnableAutocorrect(configDir string, on bool, onToggle func(on bool))

EnableAutocorrect turns autocorrect on for this editor with the built-in list and configDir's autocorrect.txt. on is the caller's saved choice; onToggle, if set, is called with the new state when Ctrl-O changes it, so the caller's record can keep it.

func (*FSEditor) HandleResize

func (e *FSEditor) HandleResize(newWidth, newHeight int)

HandleResize applies a terminal size change and redraws the screen. Sizes below 80x24 are raised to it, as at startup. A size equal to the current one is ignored, so the initial window report that an SSH session queues does not cause a second full redraw.

HandleResize touches the Screen, so it must only be called from the goroutine running Run, or while Run is not running. RunEditorWithMetadata hands Run the session's window changes so Run calls it between keys.

func (*FSEditor) LoadContent

func (e *FSEditor) LoadContent(content string)

LoadContent loads initial content into the editor

func (*FSEditor) Run

func (e *FSEditor) Run() (string, bool, error)

Run starts the editor main loop

func (*FSEditor) SetAutocorrectColor added in v0.9.7

func (e *FSEditor) SetAutocorrectColor(code int)

SetAutocorrectColor sets the DOS colour code a fixed word is highlighted in (theme.json autocorrectHighlightColor).

func (*FSEditor) SetAutocorrectStrings added in v0.9.7

func (e *FSEditor) SetAutocorrectStrings(fixed, kept, on, off string)

SetAutocorrectStrings sets the notices' text; a blank one keeps the default.

func (*FSEditor) SetBoardName

func (e *FSEditor) SetBoardName(name string)

SetBoardName sets the BBS board name substituted into the footer @B@ placeholder.

func (*FSEditor) SetEditorContext

func (e *FSEditor) SetEditorContext(ctx EditorContext)

SetEditorContext sets optional context fields displayed in the editor header (node number, next message number, conference > area name).

func (*FSEditor) SetMetadata

func (e *FSEditor) SetMetadata(subject, recipient, fromName string, isAnon bool)

SetMetadata sets the message metadata (subject, recipient, sender, etc.)

func (*FSEditor) SetNetworkQuoteStrings added in v0.9.5

func (e *FSEditor) SetNetworkQuoteStrings(top, bottom string)

SetNetworkQuoteStrings sets the quote banners for a networked area, where an empty value leaves that banner out.

func (*FSEditor) SetQuoteData

func (e *FSEditor) SetQuoteData(data *QuoteData)

SetQuoteData sets message data to be used for the /Q quote command

func (*FSEditor) SetQuoteStrings added in v0.8.1

func (e *FSEditor) SetQuoteStrings(top, bottom, prefix string)

SetQuoteStrings overrides the quote block styling (banners and per-line prefix) with the values configured in strings.json.

func (*FSEditor) SetTimezone

func (e *FSEditor) SetTimezone(configTZ string)

SetTimezone configures the timezone used for date/time display in the editor header.

type InputHandler

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

InputHandler handles keyboard input and escape sequence parsing. A background goroutine continuously reads raw bytes from the underlying reader into a buffered channel. This makes select-based timeouts reliable regardless of whether the reader supports SetReadDeadline (e.g. ssh.Session).

func NewInputHandler

func NewInputHandler(input io.Reader) *InputHandler

NewInputHandler creates a new input handler. A goroutine is started to read from input; it exits when input returns an error.

func (*InputHandler) Close

func (ih *InputHandler) Close()

Close stops the background read loop for handlers backed by sessions that support SetReadInterrupt. It is safe to call multiple times.

func (*InputHandler) CloseAndTakeUnread added in v0.9.6

func (ih *InputHandler) CloseAndTakeUnread() (unread []byte, trailer bool)

CloseAndTakeUnread is CloseAndWait for an owner handing the session to another reader, such as a door: it also returns the bytes the handler read from the session that no one consumed, oldest first (pushed-back bytes, then queued ones), so they can go to whatever reads next. The LF or NUL of an Enter already read is not among them; trailer reports that such an Enter's LF or NUL has not arrived yet, so the session's next reader should drop a leading one (see ExpectEnterTrailer). Like other reads, it must only be called by the handler's owner.

For a session without SetReadInterrupt the background goroutine cannot be stopped and keeps reading; only the bytes already queued are returned.

func (*InputHandler) CloseAndWait

func (ih *InputHandler) CloseAndWait()

CloseAndWait stops the background goroutine and blocks until it has fully exited (including the deferred setReadInterrupt(nil) call). This eliminates the race where a door's SetReadInterrupt call is overwritten by the outgoing handler's deferred cleanup. For sessions without SetReadInterrupt support (e.g. telnet), it returns immediately after signaling close.

func (*InputHandler) DiscardPendingByte added in v0.9.4

func (ih *InputHandler) DiscardPendingByte(b byte, wait time.Duration) bool

DiscardPendingByte drops the next input byte if it equals b and is already queued or arrives within wait. Any other byte is left for the next read. It reports whether a byte was dropped.

func (*InputHandler) EscTimeout added in v0.9.7

func (ih *InputHandler) EscTimeout() time.Duration

EscTimeout is how long ReadKey waits after an ESC for the rest of a key's escape sequence before taking it as a lone Esc.

func (*InputHandler) ExpectEnterTrailer added in v0.9.6

func (ih *InputHandler) ExpectEnterTrailer()

ExpectEnterTrailer tells the handler that the session's previous reader took the CR of an Enter whose LF or NUL had not arrived, so the next byte read from the session is dropped if it is that LF or NUL. Like other reads, it must only be called by the handler's owner.

func (*InputHandler) Fail added in v0.9.5

func (ih *InputHandler) Fail(err error)

Fail makes every later key read return err. Code that reads the session while borrowing the handler, such as a script run in place of a string, uses it when the caller's session ended under it (idle timeout, time limit, hang-up): the handler's owner may not check the borrower's error, and its next read must not start a fresh idle interval and let the caller carry on.

func (*InputHandler) HoldToasts added in v0.9.6

func (ih *InputHandler) HoldToasts()

HoldToasts records that the toast hook used up its wake without being able to show what is waiting. Call it from the hook.

func (*InputHandler) Interrupt added in v0.9.7

func (ih *InputHandler) Interrupt()

Interrupt ends a WaitForInput in progress, or the next one, early, so a screen that is sent an event while a toast dwells can take it. It is safe to call from another goroutine.

func (*InputHandler) LastIdleTimeout added in v0.9.5

func (ih *InputHandler) LastIdleTimeout() time.Duration

LastIdleTimeout returns the session idle timeout that the last key read to end with ErrIdleTimeout ran out of, or 0 if none has. A screen may set its own timeout and put the session's back on the way out (chat does), so this is what to report once the call is ending, not the timeout set now.

func (*InputHandler) NoteActivity added in v0.9.5

func (ih *InputHandler) NoteActivity()

NoteActivity restarts the idle countdown of the key read waiting now, as a keystroke would, without supplying any input. Chat calls it from its event goroutine when the room has traffic, so a caller reading a conversation is not idle. Reads started later count from their own start as usual. Thread-safe.

func (*InputHandler) PendingByte added in v0.9.7

func (ih *InputHandler) PendingByte(d time.Duration) (b byte, ok bool, err error)

PendingByte waits up to d for input, as WaitForInput does, and returns the first byte waiting to be read without consuming it, so a caller can look at type-ahead (for a key that stops a long job, say) and leave it for the next read. ok is false when no byte came: the wait timed out or was ended early. err is io.EOF once the connection has closed, or the error a Fail latched, so a long job can end for a caller who is gone; the next read reports it too. Like the reads, it must be called from the goroutine that reads ih.

func (*InputHandler) Read

func (ih *InputHandler) Read(p []byte) (int, error)

Read implements io.Reader. It reads exactly one byte from the incoming channel, blocking until a byte is available or the channel is closed (EOF). This allows InputHandler to be wrapped by bufio.NewReader and shared between callers (e.g. menu loops and the full-screen editor) so that the background goroutine's bytes are not lost when the editor returns.

It is bounded like a key read: the session idle timeout and deadline end the wait with ErrIdleTimeout or ErrTimeLimit, so a prompt read through a bufio.Reader cannot hold a caller past either.

func (*InputHandler) ReadByteUntil added in v0.9.5

func (ih *InputHandler) ReadByteUntil(stop <-chan struct{}) (byte, error)

ReadByteUntil is ReadUntil for a single byte.

func (*InputHandler) ReadCursorReport added in v0.9.5

func (ih *InputHandler) ReadCursorReport(timeout time.Duration) (row, col int, ok bool)

ReadCursorReport waits up to timeout for the terminal's reply to a cursor position request (ESC[6n). Anything else that arrives first, such as keys the caller typed, is pushed back for the next read.

func (*InputHandler) ReadKey

func (ih *InputHandler) ReadKey() (int, error)

ReadKey reads a single key, handling escape sequences. Returns an integer code (may be > 255 for special keys).

func (*InputHandler) ReadKeyTranslated

func (ih *InputHandler) ReadKeyTranslated() (int, error)

ReadKeyTranslated reads a key and translates arrow keys to WordStar commands

func (*InputHandler) ReadKeyWithTimeout

func (ih *InputHandler) ReadKeyWithTimeout(idleTimeout time.Duration) (int, error)

ReadKeyWithTimeout is identical to ReadKey but waits at most idleTimeout for the very first byte. If no input arrives within that window it returns (0, ErrIdleTimeout). Inter-byte timeouts for escape-sequence parsing are unaffected. This is the extensible primitive for idle-disconnect logic.

func (*InputHandler) ReadUntil added in v0.9.5

func (ih *InputHandler) ReadUntil(p []byte, stop <-chan struct{}) (int, error)

ReadUntil reads the next key into p, waiting for its first byte, or returns ErrReadStopped once stop is closed. It applies no idle timeout, deadline or break-in, so code that borrows the handler (a script run in place of a string) can read through it without closing it under a caller that still holds it.

A key's escape sequence, or a CR with the LF or NUL of its Enter, is taken whole when already queued, for a reader that decodes keys per chunk. Other queued input is left alone: a borrower that reads ahead could not give it back. Stop wins over queued input, and a stop seen partway through a key hands every byte taken back to the handler.

func (*InputHandler) RetryHeldToasts added in v0.9.6

func (ih *InputHandler) RetryHeldToasts()

RetryHeldToasts makes the next key wait run the toast hook if HoldToasts was called since the last retry, for a screen that can show more than the one that held them. Call from the reading goroutine.

func (*InputHandler) ReturnInput added in v0.9.5

func (ih *InputHandler) ReturnInput(p []byte)

ReturnInput prepends unconsumed borrowed bytes in their original order. The borrower must stop all of its reads before returning input; like other input reads, this method must only be called by the handler's current owner.

func (*InputHandler) ScreenRedraw added in v0.9.6

func (ih *InputHandler) ScreenRedraw() func()

ScreenRedraw returns what SetScreenRedraw set.

func (*InputHandler) SetBreakIn added in v0.9.5

func (ih *InputHandler) SetBreakIn(ch <-chan struct{}, fn func())

SetBreakIn registers fn to run whenever ch fires while a read is waiting for the first byte of a key. fn runs on the reading goroutine with the session deadline suspended; the interrupted read then keeps waiting. Waits inside an escape sequence do not service it. Call before reads begin.

func (*InputHandler) SetEscTimeout

func (ih *InputHandler) SetEscTimeout(d time.Duration)

SetEscTimeout overrides the ESC disambiguation window used in ReadKey. Pass 0 to restore the default (500 ms). Thread-safe.

func (*InputHandler) SetScreenRedraw added in v0.9.6

func (ih *InputHandler) SetScreenRedraw(fn func())

SetScreenRedraw names how the screen waiting on the next read redraws itself, or clears it with nil. Only the screen's own goroutine may call it.

func (*InputHandler) SetSessionDeadline added in v0.9.5

func (ih *InputHandler) SetSessionDeadline(t time.Time)

SetSessionDeadline sets the time at which the caller's time limit runs out. Key reads waiting past it, or started after it, return ErrTimeLimit. Pass the zero time for no limit. Thread-safe.

func (*InputHandler) SetSessionIdleTimeout

func (ih *InputHandler) SetSessionIdleTimeout(d time.Duration)

SetSessionIdleTimeout sets the session-level idle timeout applied to every ReadKey call. Pass 0 to disable. Thread-safe.

func (*InputHandler) SetToastHook added in v0.9.6

func (ih *InputHandler) SetToastHook(ch <-chan struct{}, fn func(limit time.Duration))

SetToastHook registers fn to run whenever ch fires while a read is waiting for the first byte of a key, outside a break-in. Waits inside an escape sequence do not service it. fn must return within limit, the time left before the read's timeout, when limit is above zero, and fire ch again rather than keep going if it has more to do, so the read gets to check its timeouts. A WaitForInput inside fn ends early for a break-in or an Interrupt, and fn should return then, so the wait that ran it can service them. Call from the reading goroutine.

func (*InputHandler) SkipEnterTrailer added in v0.9.4

func (ih *InputHandler) SkipEnterTrailer()

SkipEnterTrailer is called after reading a CR. SSH clients often send Enter as CR LF and telnet NVT clients as CR NUL; the trailing byte must not reach the next reader as a keypress of its own (an empty answer to the next prompt, or a phantom key in a lightbar). A trailer already queued is dropped now; if none has arrived yet, it is dropped whenever it does, provided it is the very next byte. Any other byte is left for the next read.

func (*InputHandler) SuspendSessionDeadline added in v0.9.5

func (ih *InputHandler) SuspendSessionDeadline() (restore func())

SuspendSessionDeadline lifts the session deadline and returns a function that puts it back. Use it around input that must not be cut short, such as a message being written; if the deadline passed meanwhile, the next read after restoring returns ErrTimeLimit.

func (*InputHandler) WaitForInput added in v0.9.6

func (ih *InputHandler) WaitForInput(d time.Duration) bool

WaitForInput waits up to d for input, leaving it to be read, and reports whether any came. A closed connection counts: the next read reports it. The wait also ends early, reporting false, on a break-in or an Interrupt. The break-in is left for the read that is running this wait's caller to service, and an Interrupt sent before the wait began ends it at once.

type MessageBuffer

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

MessageBuffer manages the text content of the message being edited

func NewMessageBuffer

func NewMessageBuffer() *MessageBuffer

NewMessageBuffer creates a new message buffer

func (*MessageBuffer) Clear

func (mb *MessageBuffer) Clear()

Clear clears the buffer

func (*MessageBuffer) DeleteChar

func (mb *MessageBuffer) DeleteChar(lineNum, col int) bool

DeleteChar deletes a character at the specified position (1-based)

func (*MessageBuffer) DeleteLine

func (mb *MessageBuffer) DeleteLine(lineNum int) bool

DeleteLine deletes a line at the specified position (1-based)

func (*MessageBuffer) GetContent

func (mb *MessageBuffer) GetContent() string

GetContent returns the entire buffer content as a string, lines joined by "\n", soft wraps included. Trailing lines that are empty or hold only spaces are left off (see GetContentLineCount), so text loaded with LoadContent does not always come back byte for byte: trailing blank lines go, as do lines past MaxLines that LoadContent dropped.

func (*MessageBuffer) GetContentLineCount

func (mb *MessageBuffer) GetContentLineCount() int

GetContentLineCount returns the line count for content output, trimming trailing empty lines. Used by GetContent() for storage.

func (*MessageBuffer) GetLine

func (mb *MessageBuffer) GetLine(lineNum int) string

GetLine returns the content of a line (1-based)

func (*MessageBuffer) GetLineCount

func (mb *MessageBuffer) GetLineCount() int

GetLineCount returns the number of navigable lines (includes trailing blank lines created by the user). Used for cursor bounds and navigation.

func (*MessageBuffer) GetLineLength

func (mb *MessageBuffer) GetLineLength(lineNum int) int

GetLineLength returns the length of a line

func (*MessageBuffer) InsertChar

func (mb *MessageBuffer) InsertChar(lineNum, col int, ch rune) bool

InsertChar inserts a character at the specified position (1-based line and col)

func (*MessageBuffer) InsertLine

func (mb *MessageBuffer) InsertLine(lineNum int) bool

InsertLine inserts a new blank line at the specified position (1-based)

func (*MessageBuffer) IsHardNewline

func (mb *MessageBuffer) IsHardNewline(lineNum int) bool

IsHardNewline returns whether the line ends with a hard return (user-created).

func (*MessageBuffer) IsLineEmpty

func (mb *MessageBuffer) IsLineEmpty(lineNum int) bool

IsLineEmpty returns true if a line is empty or contains only whitespace

func (*MessageBuffer) IsWordSplit added in v0.9.6

func (mb *MessageBuffer) IsWordSplit(lineNum int) bool

IsWordSplit reports whether the soft wrap at the end of lineNum fell inside a word, so rejoining the line with the next must not add a space.

func (*MessageBuffer) JoinLines

func (mb *MessageBuffer) JoinLines(lineNum int) bool

JoinLines joins the current line with the next line. The combined line inherits hardNewline from the second line (lineNum+1), since the end of the combined line is where line lineNum+1 used to end, and its wordSplit flag for the same reason. Two lines of the same quote join as one: the second line's copy of the prefix is dropped.

func (*MessageBuffer) LoadContent

func (mb *MessageBuffer) LoadContent(content string)

LoadContent replaces the buffer with content, one buffer line per "\n"-separated line, each ending in a hard break. Only the first MaxLines lines are loaded: the rest is dropped without notice. Lines are not wrapped, so a line longer than MaxLineLength stays long until it is edited. Today the only caller is the auto-signature editor, which holds a few lines; a path that loads a whole message for editing must check the line count first.

func (*MessageBuffer) OverwriteChar

func (mb *MessageBuffer) OverwriteChar(lineNum, col int, ch rune) bool

OverwriteChar overwrites a character at the specified position (1-based)

func (*MessageBuffer) QuotePrefix added in v0.9.6

func (mb *MessageBuffer) QuotePrefix(lineNum int) string

QuotePrefix returns the quote prefix lineNum was written under, or "" for the caller's own text. A line whose text no longer starts with its prefix, because the caller edited it away, counts as their own text.

func (*MessageBuffer) SetHardNewline

func (mb *MessageBuffer) SetHardNewline(lineNum int, hard bool)

SetHardNewline sets or clears the hard-newline flag for a line.

func (*MessageBuffer) SetLine

func (mb *MessageBuffer) SetLine(lineNum int, content string)

SetLine sets the content of a line (1-based)

func (*MessageBuffer) SetQuotePrefix added in v0.9.6

func (mb *MessageBuffer) SetQuotePrefix(lineNum int, prefix string)

SetQuotePrefix records the quote prefix lineNum's text starts with. The quote picker sets it on the lines it writes, and WordWrapper on lines it rewraps.

func (*MessageBuffer) SetWordSplit added in v0.9.6

func (mb *MessageBuffer) SetWordSplit(lineNum int, split bool)

SetWordSplit sets or clears the word-split flag for a line. Only WordWrapper sets it, when it breaks a word that has no space to wrap at.

func (*MessageBuffer) SplitLine

func (mb *MessageBuffer) SplitLine(lineNum, col int) bool

SplitLine splits a line at the specified column (1-based). The split line (lineNum) gets hardNewline=false; the caller sets it to true for user-initiated splits (Enter, Ctrl+N). The new line (lineNum+1) inherits the original hardNewline and wordSplit values of lineNum. Both lines keep lineNum's quote prefix, which QuotePrefix reports only for a part whose text still starts with it. Returns true if successful.

type QuoteData

type QuoteData struct {
	From   string   // Message author
	To     string   // Who the message was addressed to
	Title  string   // Message subject/title
	Date   string   // Message date
	Time   string   // Message time
	IsAnon bool     // Anonymous flag
	Lines  []string // Message content lines
}

QuoteData holds message metadata for quoting

type Screen

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

Screen handles all screen rendering and ANSI control

func NewScreen

func NewScreen(terminal io.Writer, outputMode ansi.OutputMode, termWidth, termHeight int) *Screen

NewScreen creates a new screen manager

func (*Screen) ClearCache

func (s *Screen) ClearCache()

ClearCache clears the screen cache to force a full redraw on next refresh

func (*Screen) ClearEOL

func (s *Screen) ClearEOL()

ClearEOL clears from cursor to end of line

func (*Screen) ClearScreen

func (s *Screen) ClearScreen()

ClearScreen clears the entire screen and homes the cursor

func (*Screen) DisplayFooter

func (s *Screen) DisplayFooter()

DisplayFooter renders the footer template at the bottom of the terminal. It is called from FullRedraw and to restore the footer after a prompt has used its last row, so it clears its rows first: a footer row narrower than the prompt would otherwise leave the end of the prompt showing.

func (*Screen) DisplayHeader

func (s *Screen) DisplayHeader()

DisplayHeader displays the header template, then overlays dynamic row-4 fields.

func (*Screen) DisplayStatusLine

func (s *Screen) DisplayStatusLine(insertMode bool, currentLine, totalLines int)

DisplayStatusLine displays the status line at the bottom

func (*Screen) FullRedraw

func (s *Screen) FullRedraw(buffer *MessageBuffer, topLine, currentLine, currentCol int, insertMode bool)

FullRedraw performs a complete screen redraw

func (*Screen) GetEditingStartY

func (s *Screen) GetEditingStartY() int

GetEditingStartY returns the Y position where text editing begins

func (*Screen) GetScreenLines

func (s *Screen) GetScreenLines() int

GetScreenLines returns the number of available editing lines

func (*Screen) GoXY

func (s *Screen) GoXY(x, y int)

GoXY moves the cursor to the specified position (1-based)

func (*Screen) HasFooter

func (s *Screen) HasFooter() bool

HasFooter reports whether a footer template is loaded.

func (*Screen) LoadFooterTemplate

func (s *Screen) LoadFooterTemplate(menuSetPath string) error

LoadFooterTemplate loads and processes the FSEDITORF.ANS footer template. The footer is always 2 rows tall and is positioned at the bottom of the screen. Screen geometry (statusLineY) is adjusted to prevent the editing area from overwriting footer rows.

func (*Screen) LoadHeaderTemplate

func (s *Screen) LoadHeaderTemplate(menuSetPath, subject, recipient, fromName string, isAnon bool) error

LoadHeaderTemplate loads and processes the FSEDITOR.ANS template. fromName is the sender display name: handle, real name, or anonymous string.

func (*Screen) MarkWord added in v0.9.7

func (s *Screen) MarkWord(m *wordMark)

MarkWord draws m.word in m.sgr at its place in the text, from the next refresh until the line is redrawn without it: when UnmarkWord is called, when the line no longer holds the word there, or when the whole view is redrawn (scrolling, resize, Ctrl-L), which forgets the mark. Only the screen is changed.

func (*Screen) PromptRow

func (s *Screen) PromptRow() int

PromptRow returns the terminal row used for ephemeral command prompts (abort confirmation, save notice, quote range input, etc.). With a footer this is the last terminal row (the "ViSiON/3 Edit" tagline row), which is restored by DisplayFooter after the command completes. Without a footer it falls back to statusLineY.

func (*Screen) RefreshLine

func (s *Screen) RefreshLine(lineNum int, lineContent string, topLine int)

RefreshLine redraws a single line if it has changed

func (*Screen) RefreshScreen

func (s *Screen) RefreshScreen(buffer *MessageBuffer, topLine, currentLine, currentCol int, insertMode bool, forceStatusUpdate bool)

RefreshScreen redraws all visible lines (incremental update)

func (*Screen) Reposition

func (s *Screen) Reposition(currentLine, currentCol, topLine int)

Reposition moves cursor to the current editing position

func (*Screen) Resize

func (s *Screen) Resize(newWidth, newHeight int)

Resize handles terminal resize events

func (*Screen) UnmarkWord added in v0.9.7

func (s *Screen) UnmarkWord()

UnmarkWord forgets the highlighted word and has its line redrawn plain on the next refresh. The redraw writes the line as it now is, so a word that has since moved or changed is never written over other text.

func (*Screen) WriteArt added in v0.9.4

func (s *Screen) WriteArt(data []byte)

WriteArt writes ANSI art, making its line breaks explicit on terminals wider than the art (see ansi.FitArtToWidth).

func (*Screen) WriteDirect

func (s *Screen) WriteDirect(text string)

WriteDirect writes directly to the terminal (for special messages)

func (*Screen) WriteDirectProcessed

func (s *Screen) WriteDirectProcessed(text string)

WriteDirectProcessed writes directly to the terminal with pipe code processing

type WordWrapper

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

WordWrapper handles word wrapping and paragraph formatting

func NewWordWrapper

func NewWordWrapper(buffer *MessageBuffer) *WordWrapper

NewWordWrapper creates a new word wrapper

func (*WordWrapper) DeleteLine added in v0.9.6

func (ww *WordWrapper) DeleteLine(lineNum int) (int, int, bool)

DeleteLine deletes lineNum and closes up the paragraph around it. A line that ended its paragraph passes its hard break to the line above, so that line does not run on into the next paragraph. A line that held the middle of a split word leaves the parts either side of it as two words. Returns the cursor position for the start of the text that followed the deleted line, and whether a line was deleted.

func (*WordWrapper) DeleteWord

func (ww *WordWrapper) DeleteWord(lineNum, col int) (int, int, bool)

DeleteWord deletes the word to the right of the cursor and reflows. Returns new cursor position (line, col) and whether a change was made.

func (*WordWrapper) FindWordLeft

func (ww *WordWrapper) FindWordLeft(lineNum, col int) int

FindWordLeft finds the start of the word to the left

func (*WordWrapper) FindWordRight

func (ww *WordWrapper) FindWordRight(lineNum, col int) int

FindWordRight finds the start of the word to the right

func (*WordWrapper) HandleBackspace

func (ww *WordWrapper) HandleBackspace(lineNum, col int) (int, int, bool)

HandleBackspace handles backspace at the given position. Deletes the character before the cursor and reflows the paragraph, pulling words up from the lines below and onto the line above. At start-of-line, joins with the previous line and reflows. Returns new cursor position (line, col) and whether a change was made.

func (*WordWrapper) HandleDelete

func (ww *WordWrapper) HandleDelete(lineNum, col int) (int, int, bool)

HandleDelete handles delete at the given position. Deletes the character at the cursor and reflows, or joins with the next line if at end-of-line. Returns new cursor position (line, col) and whether a change was made.

func (*WordWrapper) ReflowRange

func (ww *WordWrapper) ReflowRange(startLine, cursorLine, cursorCol int) (int, int)

ReflowRange reflows soft-wrapped lines starting from startLine. It scans forward through consecutive soft-wrapped lines (hardNewline=false) and stops at the first hard newline, the end of the buffer, or a line under a different quote prefix. Text is collected, re-wrapped to MaxLineLength, and placed back into the buffer. A quoted paragraph is wrapped under its prefix: the prefix is taken off each line, the text rewrapped to the width left beside it, and the prefix put back on every line. cursorLine/cursorCol track the cursor through the reflow using a linear character offset, which is more robust than the old col-wrapPos arithmetic. Returns the adjusted cursor position (line, col).

func (*WordWrapper) ReformatParagraph

func (ww *WordWrapper) ReformatParagraph(startLine int) int

ReformatParagraph reformats a paragraph starting at the specified line. Uses ReflowRange to redistribute words across soft-wrapped lines. Stops at hard newlines or blank lines.

func (*WordWrapper) WrapAfterInsert

func (ww *WordWrapper) WrapAfterInsert(lineNum, cursorCol int) (int, int)

WrapAfterInsert handles word wrap after a character insertion. Fast path: only reflows if the current line exceeds MaxLineLength.

Directories

Path Synopsis
Package testterm provides an ANSI-interpreting virtual terminal for testing terminal output, plus a scripted session for driving interactive code.
Package testterm provides an ANSI-interpreting virtual terminal for testing terminal output, plus a scripted session for driving interactive code.

Jump to

Keyboard shortcuts

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