#pragma once #include #include #include #include namespace Bilicraft { // Pure in-memory, byte-at-a-time terminal editor. No terminal I/O or threads. // Only complete, valid UTF-8 codepoints are inserted; incomplete codepoints stay // buffered until complete or interrupted, and malformed input is discarded. // Cursor() is a byte offset, always on a codepoint boundary. History is local to // this instance, excludes blank/consecutive duplicate lines, and is never saved. class LineEditor { public: static constexpr std::size_t MaxLineBytes = 64 * 1024; static constexpr std::size_t MaxHistoryEntries = 200; // CR or LF returns the line and resets the editor. One LF immediately after // CR is swallowed, even across calls. Stop reading as soon as a line returns. // Ctrl-D on an empty line latches EOF; subsequent Feed calls do nothing. // Exceeding MaxLineBytes throws std::length_error without changing the line; // the caller can continue editing (e.g. backspace) and try again. std::optional Feed(char byte); const std::string &Text() const; std::size_t Cursor() const; bool IsEof() const; private: enum class EscapeState { None, Start, Intermediate, Csi, Ss3, String, StringEscape }; void FeedEscape(unsigned char byte); void FinishControlSequence(char finalByte); void ResetEscape(); void InsertByte(unsigned char byte); void InsertCodepoint(const std::string &codepoint); void HistoryUp(); void HistoryDown(); void DeleteAtCursor(); std::size_t PreviousBoundary() const; std::size_t NextBoundary() const; std::string Submit(); std::string text; std::size_t cursor = 0; bool eof = false; bool swallowLf = false; std::vector history; std::size_t historyIndex = 0; std::string draft; std::size_t draftCursor = 0; std::string utf8Pending; std::size_t utf8Expected = 0; EscapeState escapeState = EscapeState::None; std::string escapeParameters; std::size_t escapeLength = 0; bool escapeTooLong = false; }; } // namespace Bilicraft