Implementation:Ollama Ollama Readline Buffer
| Knowledge Sources | |
|---|---|
| Domains | CLI, Terminal UI |
| Last Updated | 2025-02-15 00:00 GMT |
Overview
Implements the text editing buffer for the readline interactive input system, providing cursor movement, text insertion, deletion, and display management.
Description
The Buffer struct wraps an array list of runes with cursor position tracking (both logical position and display position to handle wide characters). Provides methods for cursor movement (left/right by character or word, start/end of line), text manipulation (add, delete, backspace, kill line, transpose, yank), and display rendering with line wrapping. Handles wide Unicode characters via runewidth for correct cursor positioning. Uses ANSI escape sequences to update the terminal display efficiently.
Usage
Core component of the interactive CLI prompt, managing the editable text area where users type prompts for the ollama run command.
Code Reference
Source Location
- Repository: Ollama
- File: readline/buffer.go
- Lines: 1-527
Signature
type Buffer struct {
DisplayPos int
Pos int
Buf *arraylist.List[rune]
LineHasSpace *arraylist.List[bool]
Prompt *Prompt
LineWidth int
Width int
Height int
}
func NewBuffer(prompt *Prompt) (*Buffer, error)
func (b *Buffer) MoveLeft()
func (b *Buffer) MoveRight()
func (b *Buffer) MoveLeftWord()
func (b *Buffer) MoveRightWord()
func (b *Buffer) MoveToStart()
func (b *Buffer) MoveToEnd()
func (b *Buffer) Add(r rune)
func (b *Buffer) Delete()
func (b *Buffer) String() string
Import
import "github.com/ollama/ollama/readline"
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| prompt | *Prompt | Yes | Prompt configuration for display width calculation |
Outputs
| Name | Type | Description |
|---|---|---|
| *Buffer | *Buffer | Initialized buffer with terminal dimensions |
| error | error | Non-nil if terminal size cannot be determined |
Usage Examples
prompt := &readline.Prompt{Prompt: ">>> "}
buf, err := readline.NewBuffer(prompt)
if err != nil {
log.Fatal(err)
}
buf.Add('H')
buf.Add('i')
fmt.Println(buf.String()) // "Hi"
buf.MoveToStart()
buf.Delete()
fmt.Println(buf.String()) // "i"